bat-cli 0.38.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
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
//! 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::types::EvmParam;
use crate::batbelt::evm::miro::EvmMiroError;
use crate::batbelt::miro::client::{ArrowEnd, ConnectorStroke, ConnectorStyle, MiroClient};
use crate::batbelt::miro::layout::{GraphLayout, PlacedNode};

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 only this contract's frame — "what does X talk to", on its own.
    ///
    /// The map is one frame per top caller, and most readings are about one of them. Drawing
    /// the whole block to look at one contract costs the board a dozen frames nobody asked for.
    pub contract: Option<String>,
    /// List which contracts are the hierarchy's two ends and stop, touching no board.
    ///
    /// The top callers are the frames the map has; the foundations are what everything else
    /// needs in order to exist. Both are read off the relations, and neither is something the
    /// auditor can get by reading the file tree.
    pub hierarchy: bool,
    /// Contracts to draw filled for this run, on top of the ones `bat-cli mark` recorded.
    pub mark: Vec<String>,
    /// Draw a leaf for EVERY method called on an outside box, reads included.
    ///
    /// By default only the ones that can change something: a `view` leaf says nothing left and
    /// nothing changed, and seventeen `balanceOf` boxes crowd out the one `safeTransfer` that
    /// matters. The flag is for reading a boundary in full.
    pub all_methods: bool,
    /// Leave out the contracts with no source in this repository.
    ///
    /// They are drawn by default. They used to be a text panel on the grounds that giving
    /// somebody else's token the same shape as the code under review is misleading — but what
    /// the audit actually asks is "what does this thing touch that I cannot read", and a name
    /// in a list beside the picture is not an answer to that. They are boxes now, grey ones,
    /// and the flag is for the rare read where only this repository matters.
    pub no_boundaries: bool,
    /// Print each frame as an indented tree of what it draws, and stop.
    ///
    /// The picture in words. A preview PNG cannot carry the names at map scale, so this is the
    /// only way to check that a leaf has the children it should without opening the board.
    pub tree: 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,
    /// Every call from one to the other is a READ — `view` or `pure`. The relation is real and
    /// nothing moves across it, so the map draws the box and stops there: what the far contract
    /// does on its own is not something this caller can set off.
    Reads,
}

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",
            Self::Reads => "reads",
        }
    }
}

/// `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"
        )));
    }
    // The hierarchy, and nothing else: which contracts the map makes a frame for, and which
    // ones everything else needs in order to exist. Answered from the relations, before any
    // layout, because it is a question about the system and not about a picture.
    if options.hierarchy {
        for line in hierarchy(&metadata, &relations(&metadata), options.no_boundaries) {
            println!("{line}");
        }
        return Ok(());
    }
    let mut prepared = prepare(&metadata, &options)?;
    // One contract's frame, when that is what was asked for. Named rather than silently
    // ignored: a flag that matches nothing and draws everything is worse than an error.
    if let Some(wanted) = options.contract.as_deref() {
        prepared.keep_only(wanted)?;
    }
    let edges = prepared.edges.clone();
    mark("working out the relations, laying out and rendering", &mut phase);

    // The picture in words, and nothing else: the report's lists answer other questions, and a
    // tree with four screens of preamble above it is a tree nobody reads to the end.
    if options.tree {
        for line in prepared.tree() {
            println!("{line}");
        }
        prepared.discard();
        return Ok(());
    }

    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 — in the strip at the right, \
             apart from the diagram:",
            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}");
        }
    }
    // The handover: every call site whose party the code cannot name, where it is written and
    // the key that records the answer. A reader (or an assistant reading the code) traces the
    // value once; the map draws it from then on like any other party.
    if !prepared.unnamed.is_empty() {
        println!();
        println!(
            "{} call site(s) handing an address the code cannot name ({} of them with a key to \
             record) — trace one and record it:",
            prepared.unnamed.len(),
            prepared.unnamed.iter().filter(|party| party.key.is_some()).count()
        );
        for party in &prepared.unnamed {
            println!("  {}", located(party));
            match &party.key {
                Some(key) => println!(
                    "      {}({}) → bat-cli resolve {key} <Contract>",
                    party.call, party.argument
                ),
                None => println!(
                    "      {}({}) — the scan did not record the expression; open the line",
                    party.call, party.argument
                ),
            }
        }
    }
    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;

    // A preview does NOT touch the board. Its own help says "instead of looking at it on the
    // board", and it was drawing the PNG and then deploying anyway — so asking to see a change
    // before showing it to anyone published it.
    if let Some(path) = options.preview.as_deref() {
        preview(&prepared, path)?;
        prepared.discard();
        return Ok(());
    }
    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);

    // What was drawn goes into the registry, and the clusters get their cards — both only for
    // a FULL map: `--contract` draws one frame, and rewriting every cluster's cards from it
    // would leave each cluster pointing at the one frame that happened to be redrawn.
    if let Ok(drawn) = outcome.as_ref() {
        let whole_map = options.contract.is_none();
        match record_map(drawn.clone(), whole_map, &client).await {
            Ok(cards) if whole_map => {
                println!("    {} {cards} card(s) on the clusters", "✓".green())
            }
            Ok(_) => {}
            // The picture is on the board either way; a registry that could not be written is
            // worth a line, not a failed command.
            Err(report) => println!(
                "    {} the map is drawn, but the registry was not updated: {}",
                "note:".yellow(),
                report.current_context()
            ),
        }
        // The one frame listing what is marked, checked here as well as in `mark --apply`: both
        // are moments the reader is looking at the board, and a list that is only right after
        // one of two commands is a list nobody trusts.
        {
            let mut registry = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
            let listed: BTreeSet<String> = registry.marked_contracts.iter().cloned().collect();
            match ensure_marked_frame(&mut registry, &client, &listed).await {
                Ok((0, _)) => {}
                Ok((boxes, fresh)) => println!(
                    "    {} `marked`: {boxes} contract(s){}",
                    "✓".green(),
                    if fresh { " — drag the frame where you want it; it stays there" } else { "" }
                ),
                Err(report) => println!("    {} `marked`: {report:?}", "skipped:".yellow()),
            }
        }
        mark("recording it", &mut phase);
    }

    let (retries, waits, retry_seconds) = client.stats();
    // What was SENT, beside what was planned. They are different numbers and only the first one
    // spends the budget: a read costs 50 credits and the plan counts no reads at all.
    let (sent, credits) = client.sent();
    // Three causes, three numbers. A budget wait is arithmetic — this much work does not fit in
    // a minute's credits — and a brake wait is the board itself pushing back. One counter for
    // both read as "Miro is throttling us" on a run where Miro never said a word.
    // What the board's pushback COST, not just that there was some. A `Retry-After` from Miro
    // is a minute, so two retries are two minutes of a run that otherwise took seconds — and
    // without this the line read as "drawing 59 items took 126 seconds".
    let braked = match retry_seconds {
        0 => String::new(),
        seconds => format!(", {seconds}s waiting one out"),
    };
    println!(
        "    {:>6.1}s  in total  ({sent} request(s) for {} planned, {credits} credits, {retries} retr(ies){braked})",
        started.elapsed().as_secs_f64(),
        calls.total()
    );
    let _ = waits;
    outcome.map(|_| ())
}

/// What a card is: how far above the cluster's label it sits, and how big.
///
/// Above the shape, because the shape is the group's anchor — read from the board every run,
/// since the auditor moves it — and because the column under it is where the deployments go.
/// Sized to be read at the zoom where a whole group fits, which is the only zoom anybody looks
/// at a cluster's heading from. The first try was 2 600 × 260 with 90-point text — legible with
/// the board at 100%, a chip at any useful distance, next to a name shape 1 200 units tall.
const CARD_HEIGHT: f64 = 560.0;
const CARD_WIDTH: f64 = 4_600.0;
const CARD_GAP: f64 = 200.0;
const CARD_FONT: usize = 180;
const CARD_FILL: &str = "#ffffff";
/// The one colour on the board that means "go there".
const CARD_BORDER: &str = "#1a73e8";
/// At most this many cards over one cluster; past it the last one counts the rest.
const MAX_CARDS: usize = 4;

/// Record what the map drew, and give every cluster a card per frame that shows its contract.
///
/// Returns how many cards were created.
///
/// Three rules the auditor set, and they are the whole design:
/// - a card per FRAME, because the frame is where the hierarchy is read — parents and children
///   are in the picture, so the card only has to take you there;
/// - the cluster must NOT depend on the map: no record, no cards, no error;
/// - a redrawn map replaces its own cards rather than stacking new ones on the old.
async fn record_map(
    frames: Vec<crate::batbelt::evm::metadata::bat_metadata::MapFrameRef>,
    whole_map: bool,
    client: &MiroClient,
) -> Result<usize, EvmMiroError> {
    use crate::batbelt::evm::metadata::bat_metadata::{MapCardRef, MapFrameRef};

    let mut metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    if !whole_map {
        // One frame redrawn: keep it in the registry by its root, and leave the cards alone —
        // they describe a map this run did not replace.
        let mut kept: Vec<MapFrameRef> = metadata
            .miro
            .map
            .iter()
            .filter(|old| !frames.iter().any(|new| new.root == old.root))
            .cloned()
            .collect();
        kept.extend(frames);
        metadata.miro.map = kept;
        metadata.save_metadata().change_context(EvmMiroError)?;
        return Ok(0);
    }

    // The cards this tool put up last time, gone before new ones go up: a card pointing at a
    // frame that no longer exists is worse than no card, and they would otherwise stack.
    //
    // Found on the BOARD and not only in the registry. The registry is a convenience and it can
    // be lost — a binary that did not know the `miro.map` field rewrote `BatMetadata.json`
    // without it, and the next run drew a second set of cards on top of the first, which is
    // exactly what the auditor saw. A card carries its own signature in its text, so the board
    // can always be asked.
    let mut stale: Vec<String> = metadata
        .miro
        .map
        .iter()
        .flat_map(|frame| frame.cards.iter().map(|card| card.item_id.clone()))
        .collect();
    // The board is only asked when the registry has NOTHING to say.
    //
    // The registry knows the id of every card this tool put up, so when it has them the sweep
    // finds the same ones again — and it is not a cheap question: `list_loose_shapes` pages
    // every shape on the board that is not inside a frame, fifty at a time, and a board with a
    // few thousand of them answers in dozens of requests. Recording five cards took 74.7
    // seconds, longer than drawing all nine frames.
    //
    // The sweep stays for the case it was written for: a registry that lost the `miro.map`
    // field, where going by the registry alone would stack a second set of cards on the first.
    // That case says exactly "no cards recorded", which is the condition here.
    if stale.is_empty() {
        if let Ok(loose) = client.list_loose_shapes().await {
            stale.extend(
                loose
                    .into_iter()
                    .filter(|(_, content)| is_map_card(content))
                    .map(|(id, _)| id),
            );
        }
    }
    stale.sort();
    stale.dedup();
    let mut removing = tokio::task::JoinSet::new();
    for id in stale {
        let client = client.clone();
        removing.spawn(async move { client.delete_item(&id).await });
    }
    while removing.join_next().await.is_some() {}

    // Where each cluster's cards go: above its label shape, which is read from the board
    // because the auditor drags groups around. Every geometry asked for at once.
    let columns: Vec<(String, String)> = metadata
        .miro
        .auto
        .columns
        .iter()
        .filter(|column| !column.label_id.is_empty())
        .map(|column| (column.contract.clone(), column.label_id.clone()))
        .collect();
    let made = draw_cards(&columns, &frames, client).await;
    metadata.miro.map = frames
        .into_iter()
        .map(|mut frame| {
            frame.cards = made
                .iter()
                .filter(|(_, root, _)| *root == frame.root)
                .map(|(contract, _, id)| MapCardRef {
                    contract: contract.clone(),
                    item_id: id.clone(),
                })
                .collect();
            frame
        })
        .collect();
    metadata.save_metadata().change_context(EvmMiroError)?;
    Ok(made.len())
}

/// Put one card per frame over each of these clusters, and say which card is whose.
///
/// Returns `(cluster contract, frame root, item id)` per card made. Everything it can ask for
/// at once it asks for at once: the geometries in one wave, the cards in batches of twenty.
async fn draw_cards(
    columns: &[(String, String)],
    frames: &[crate::batbelt::evm::metadata::bat_metadata::MapFrameRef],
    client: &MiroClient,
) -> Vec<(String, String, String)> {
    // Only the columns that will actually GET a card.
    //
    // The geometry is read from the board because the auditor drags groups around, and it is
    // one request per column: a board with forty-five deployments was answering forty-five of
    // them to place five cards. `frames_showing` decides which columns those are and it was
    // being applied after the asking rather than before it.
    let mut asking = tokio::task::JoinSet::new();
    for (contract, label_id) in columns
        .iter()
        .filter(|(contract, _)| !frames_showing(frames, contract).is_empty())
    {
        let client = client.clone();
        let (contract, label_id) = (contract.clone(), label_id.clone());
        asking.spawn(async move { (contract, client.item_geometry(&label_id).await) });
    }
    let mut anchors: BTreeMap<String, (f64, f64)> = BTreeMap::new();
    while let Some(Ok((contract, geometry))) = asking.join_next().await {
        if let Some((x, y, _, height)) = geometry {
            anchors.insert(contract, (x, y - height / 2.0));
        }
    }

    struct Planned {
        contract: String,
        root: String,
        item: serde_json::Value,
    }
    let mut planned: Vec<Planned> = Vec::new();
    for (contract, (centre, top)) in &anchors {
        let showing = frames_showing(frames, contract);
        if showing.is_empty() {
            continue;
        }
        let drawn = showing.len().min(MAX_CARDS);
        let span = drawn as f64 * CARD_WIDTH + (drawn as f64 - 1.0) * CARD_GAP;
        for (index, frame) in showing.iter().take(MAX_CARDS).enumerate() {
            let x = centre - span / 2.0 + CARD_WIDTH / 2.0 + index as f64 * (CARD_WIDTH + CARD_GAP);
            let y = top - CARD_GAP - CARD_HEIGHT / 2.0;
            // The words carry the fact, the anchor carries the jump. A map can be deleted and
            // the card still says which frame showed this contract — `linkedTo` is not
            // reachable from the REST API, so the link has always been an `<a href>` in the
            // text (see CLAUDE.md).
            let left = showing.len().saturating_sub(MAX_CARDS);
            let text = if index + 1 == MAX_CARDS && left > 0 {
                format!("map · {} (+{left} more)", frame.root)
            } else {
                format!("map · {}", frame.root)
            };
            planned.push(Planned {
                contract: contract.clone(),
                root: frame.root.clone(),
                item: MiroClient::link_card_item(
                    &text,
                    &client.frame_url(&frame.frame_id),
                    x,
                    y,
                    CARD_WIDTH,
                    CARD_HEIGHT,
                    CARD_FONT,
                    CARD_FILL,
                    CARD_BORDER,
                ),
            });
        }
    }

    const BATCH: usize = 20;
    let mut making = tokio::task::JoinSet::new();
    for chunk in planned.chunks(BATCH) {
        let client = client.clone();
        let keys: Vec<(String, String)> = chunk
            .iter()
            .map(|card| (card.contract.clone(), card.root.clone()))
            .collect();
        let items: Vec<serde_json::Value> = chunk.iter().map(|card| card.item.clone()).collect();
        making.spawn(async move { (keys, client.create_items_bulk(items).await) });
    }
    let mut made: Vec<(String, String, String)> = Vec::new();
    while let Some(joined) = making.join_next().await {
        if let Ok((keys, Ok(ids))) = joined {
            for ((contract, root), id) in keys.into_iter().zip(ids) {
                made.push((contract, root, id));
            }
        }
    }
    made
}

/// Is this loose shape one of the map's cards?
///
/// Its own signature and nothing looser: the `map · ` prefix the card is written with AND a link
/// to a frame. A shape an auditor wrote by hand does not carry both, and deleting one of theirs
/// would be unforgivable — this is the only place this tool removes something it is not holding
/// an id for.
fn is_map_card(content: &str) -> bool {
    content.contains("map · ") && content.contains("moveToWidget=")
}

/// The frames that draw this contract — the ones its cluster gets a card for.
fn frames_showing<'a>(
    frames: &'a [crate::batbelt::evm::metadata::bat_metadata::MapFrameRef],
    contract: &str,
) -> Vec<&'a crate::batbelt::evm::metadata::bat_metadata::MapFrameRef> {
    frames
        .iter()
        .filter(|frame| frame.contracts.iter().any(|name| name == contract))
        .collect()
}

/// Give ONE cluster its cards, from the map already in the registry.
///
/// Called by `deploy` when a group is drawn, because a cluster deployed after the map had no
/// way to get them: `map` draws the cards, and when it last ran this column did not exist.
/// Treasury's group went up with none.
///
/// Silent and harmless when there is no map: a cluster must never depend on one.
pub async fn cards_for(contract: &str, client: &MiroClient) -> Result<usize, EvmMiroError> {
    use crate::batbelt::evm::metadata::bat_metadata::MapCardRef;

    let mut metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    if metadata.miro.map.is_empty() {
        return Ok(0);
    }
    let Some(label_id) = metadata
        .miro
        .auto
        .columns
        .iter()
        .find(|column| column.contract == contract)
        .map(|column| column.label_id.clone())
        .filter(|id| !id.is_empty())
    else {
        return Ok(0);
    };

    // This cluster's own old cards, and only its own: another column's are none of this
    // deployment's business.
    let mut removing = tokio::task::JoinSet::new();
    for frame in &metadata.miro.map {
        for card in frame.cards.iter().filter(|card| card.contract == contract) {
            let (client, id) = (client.clone(), card.item_id.clone());
            removing.spawn(async move { client.delete_item(&id).await });
        }
    }
    while removing.join_next().await.is_some() {}

    let frames = metadata.miro.map.clone();
    let made = draw_cards(&[(contract.to_string(), label_id)], &frames, client).await;
    for frame in &mut metadata.miro.map {
        frame.cards.retain(|card| card.contract != contract);
        frame.cards.extend(
            made.iter()
                .filter(|(_, root, _)| root == &frame.root)
                .map(|(contract, _, id)| MapCardRef {
                    contract: contract.clone(),
                    item_id: id.clone(),
                }),
        );
    }
    metadata.save_metadata().change_context(EvmMiroError)?;
    Ok(made.len())
}

/// Repaint the boxes of the map already on the board, so changing which contracts stand out
/// costs no frames.
///
/// `bat-cli map` never replaces: a redraw would leave another generation of frames for the
/// auditor to delete, and the only thing that changed is a fill. The frames are in the registry;
/// their boxes are found by the name they carry, which is the same trick the cards use.
///
/// Contracts only. An outside leaf and a method leaf are not marked — the reader's list is of
/// contracts, and those boxes carry their interface's colour on the border, which this does not
/// touch.
pub async fn repaint(client: &MiroClient) -> Result<(usize, usize), EvmMiroError> {
    let mut metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    // The list as a THING on the board, before the fills: a reader who marked twelve contracts
    // wants to see the twelve, and a fill spread over eight frames is not a list.
    let listed: BTreeSet<String> = metadata.marked_contracts.iter().cloned().collect();
    match ensure_marked_frame(&mut metadata, client, &listed).await {
        Ok((0, _)) => {}
        Ok((boxes, fresh)) => println!(
            "    {} `marked`: {boxes} contract(s){}",
            "✓".green(),
            if fresh { " — drag the frame where you want it; it stays there" } else { "" }
        ),
        Err(report) => println!("    {} `marked`: {report:?}", "skipped:".yellow()),
    }
    if metadata.miro.map.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("no map recorded for this project")
            .attach(crate::Suggestion("draw one first: `bat-cli map`".to_string())));
    }
    let marked: BTreeSet<&str> = metadata
        .marked_contracts
        .iter()
        .map(String::as_str)
        .collect();

    // Every frame's boxes at once, each paired with the contracts THAT frame draws — which the
    // registry already knows. Only those are repainted: an interface's box carries its colour
    // too (as a fill on a map drawn before 0.33, as a border after), and a repaint that painted
    // every box it could name would wipe it.
    let mut asking = tokio::task::JoinSet::new();
    for frame in &metadata.miro.map {
        let (client, id) = (client.clone(), frame.frame_id.clone());
        // By ENTITY on the registry's side too, so a frame recorded before this was fixed —
        // where the names went in as `cohortTreasury%Treasury` — repaints without redrawing it.
        let contracts: BTreeSet<String> = frame
            .contracts
            .iter()
            .map(|name| drawn_entity(name).to_string())
            .collect();
        asking.spawn(async move { (contracts, client.shapes_in_frame(&id).await) });
    }
    let mut boxes: Vec<(String, String)> = Vec::new();
    let mut looked_at = 0usize;
    let mut unreadable = 0usize;
    let mut why_unreadable = String::new();
    while let Some(joined) = asking.join_next().await {
        match joined {
            Ok((contracts, Ok(found))) => {
                looked_at += found.len();
                boxes.extend(found.into_iter().filter(|(_, content)| {
                    shape_name(content).is_some_and(|name| contracts.contains(&name))
                }));
            }
            // A frame the board would not answer for is not "nothing to repaint": the run said
            // `0 of 0` and left the reader to guess whether the map was wrong, the list was
            // wrong, or Miro had simply refused. WITH the reason, because the three are fixed
            // in three different places — a 429 is waited out, a 404 is a frame somebody
            // deleted and a registry that should be cleaned.
            Ok((_, Err(report))) => {
                unreadable += 1;
                if why_unreadable.is_empty() {
                    why_unreadable = why(&report);
                }
            }
            Err(error) => {
                unreadable += 1;
                if why_unreadable.is_empty() {
                    why_unreadable = error.to_string();
                }
            }
        }
    }
    if unreadable > 0 {
        println!(
            "    {} {unreadable} frame(s) the board would not read back: {why_unreadable}",
            "skipped:".yellow()
        );
    }
    if boxes.is_empty() && looked_at > 0 {
        println!(
            "    {looked_at} shape(s) in {} frame(s), none of them a contract this map records",
            metadata.miro.map.len()
        );
    }

    // What each one should be, from its WORDS: a box says the contract it stands for, and a
    // contract is marked or it is not. An interface leaf is left alone — its border carries its
    // colour and its text is the interface's name, which is not in the reader's list anyway.
    let mut painting = tokio::task::JoinSet::new();
    let mut touched = 0usize;
    for (id, content) in &boxes {
        let Some(name) = shape_name(content) else { continue };
        let fill = if marked.contains(name.as_str()) { MARK_FILL } else { BOX_FILL };
        touched += 1;
        let (client, id) = (client.clone(), id.clone());
        painting.spawn(async move { client.recolour_shape(&id, fill).await });
    }
    let mut repainted = 0usize;
    while let Some(joined) = painting.join_next().await {
        if matches!(joined, Ok(Ok(()))) {
            repainted += 1;
        }
    }
    Ok((repainted, touched))
}

/// The ONE frame that lists what is marked, created or brought up to date.
///
/// A marked list is an audit's scope, and the scope is a thing a reader wants to see as a thing
/// — not spread over eight frames as a fill on whichever boxes happen to be drawn there. This is
/// that list: one box per marked contract, in a grid, with no arrows. It answers "what did I say
/// I was looking at", which is a different question from "what does this contract talk to", and
/// a diagram would answer neither better than a list does.
///
/// There is exactly one on the board and the auditor owns WHERE it is. So the frame's id is kept
/// in the registry and the frame is updated in place — its position is never written back, only
/// its size, which has to follow the number of names. A tool that cannot find its own frame
/// again can only draw a second one somewhere else, which is how the cards came to stack.
///
/// Checked by `map` and by `mark --apply` alike: both of them already know the list and both are
/// moments when the reader is looking at the board.
pub async fn ensure_marked_frame(
    metadata: &mut EvmBatMetadata,
    client: &MiroClient,
    marked: &BTreeSet<String>,
) -> Result<(usize, bool), EvmMiroError> {
    /// Columns in the grid, so the frame is wider than it is tall at any plausible scope.
    const COLUMNS: usize = 4;
    const PAD: f64 = 200.0;
    const GAP: f64 = 120.0;
    const TITLE_BAND: f64 = 400.0;

    // Nothing marked is not a reason to leave a stale frame listing what used to be.
    let names: Vec<&str> = marked.iter().map(String::as_str).collect();
    let existing = metadata.miro.marked_frame.clone();
    if names.is_empty() {
        if !existing.is_empty() {
            let _ = client.delete_item(&existing).await;
            metadata.miro.marked_frame.clear();
            metadata.save_metadata().change_context(EvmMiroError)?;
        }
        return Ok((0, false));
    }

    let widest = names.iter().map(|name| node_width(name)).fold(0.0_f64, f64::max);
    let rows = names.len().div_ceil(COLUMNS);
    let columns = names.len().min(COLUMNS);
    let width = 2.0 * PAD + columns as f64 * widest + (columns as f64 - 1.0) * GAP;
    let height =
        2.0 * PAD + TITLE_BAND + rows as f64 * NODE_HEIGHT + (rows as f64 - 1.0) * GAP;

    // Where it already is, if it is still there. Its position is the auditor's and is read, not
    // chosen; only when there is no frame at all does this pick a corner.
    let placed = match existing.is_empty() {
        true => None,
        false => client.item_geometry(&existing).await,
    };
    let (frame_id, fresh) = match placed {
        Some((x, y, _, _)) => {
            client
                .update_frame(&existing, MARKED_FRAME_TITLE, x, y, width, height)
                .await
                .change_context(EvmMiroError)?;
            (existing.clone(), false)
        }
        None => {
            // Above everything, where the maps are not: the maps march leftwards and down.
            let id = client
                .create_frame(MARKED_FRAME_TITLE, 0.0, -height - 2000.0, width, height, None)
                .await
                .change_context(EvmMiroError)?;
            (id, true)
        }
    };

    // Its own boxes, gone before the new ones go in: the list changes and a stale name in it is
    // a lie about the scope. Only the frame's own children, so nothing else is touched.
    if !fresh {
        if let Ok(inside) = client.shapes_in_frame(&frame_id).await {
            let mut removing = tokio::task::JoinSet::new();
            for (id, _) in inside {
                let client = client.clone();
                removing.spawn(async move { client.delete_item(&id).await });
            }
            while removing.join_next().await.is_some() {}
        }
    }

    // A child's position is measured from the frame's own corner, the way every other box on
    // this map is placed — not from its centre. Centred coordinates are negative, and Miro
    // answers those with `new position is outside of parent boundaries`.
    let left = PAD + widest / 2.0;
    let top = PAD + TITLE_BAND + NODE_HEIGHT / 2.0;
    let items: Vec<serde_json::Value> = names
        .iter()
        .enumerate()
        .map(|(at, name)| {
            let (row, column) = (at / COLUMNS, at % COLUMNS);
            MiroClient::label_item(
                name,
                left + column as f64 * (widest + GAP),
                top + row as f64 * (NODE_HEIGHT + GAP),
                widest,
                NODE_HEIGHT,
                NODE_FONT,
                MARK_FILL,
                BOX_BORDER,
                BORDER_WIDTH,
                BOX_BORDER,
                "normal",
                &frame_id,
            )
        })
        .collect();
    let mut made = 0usize;
    for chunk in items.chunks(ITEMS_PER_CALL.max(1)) {
        made += client
            .create_items_bulk(chunk.to_vec())
            .await
            .change_context(EvmMiroError)?
            .len();
    }

    metadata.miro.marked_frame = frame_id;
    metadata.save_metadata().change_context(EvmMiroError)?;
    Ok((made, fresh))
}

/// The one frame listing the marked contracts. Matched by id, not by title — the auditor may
/// rename it — but a name it can be found by in the board's search is worth having.
const MARKED_FRAME_TITLE: &str = "marked";

/// Which contracts this frame draws more than one DEPLOYMENT of.
///
/// By address and not by box: a contract drawn twice on two branches is one deployment and one
/// name, while `cohortTreasury` and `opexTreasury` are two. `this` counts as the contract
/// itself — a frame rooted at `AscendLaunchpad` and a `launchpad (AscendLaunchpad)` reached
/// through the desk are the same launchpad, which is the whole reason this is measured.
fn drawn_more_than_once(edges: &[Edge]) -> BTreeSet<String> {
    let mut addresses: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for id in edges.iter().flat_map(|edge| [edge.from.as_str(), edge.to.as_str()]) {
        if is_outside(id) || method_of(id).is_some() {
            continue;
        }
        let held = drawn_entity(id);
        let named = original_of(id)
            .split_once(VARIABLE_MARK)
            .map(|(variable, _)| variable)
            .unwrap_or("");
        addresses.entry(held).or_default().insert(named);
    }
    addresses
        .into_iter()
        // By the VARIABLES, not by the boxes. A box with no variable is the contract itself —
        // the frame's root, or a cast the code never named — and it is the same address as the
        // one variable that holds it, when there is only one. Counting it as a second name is
        // what kept `launchpad (AscendLaunchpad)` labelled on the launchpad's own frame.
        .filter(|(_, named)| named.iter().filter(|name| !name.is_empty()).count() > 1)
        .map(|(held, _)| held.to_string())
        .collect()
}

/// The plain name a box's HTML carries: `<p><b>YieldRouter</b></p>` → `YieldRouter`.
fn shape_name(content: &str) -> Option<String> {
    let text: String = {
        let mut out = String::new();
        let mut inside_tag = false;
        for ch in content.chars() {
            match ch {
                '<' => inside_tag = true,
                '>' => inside_tag = false,
                _ if !inside_tag => out.push(ch),
                _ => {}
            }
        }
        out.trim().to_string()
    };
    if text.is_empty() {
        return None;
    }
    // An ACCOUNT is never filled, however the reader's list reads: it is an address, not code,
    // and a fresh map draws it the same way. Left alone, like a legend row.
    if text.ends_with("(address)") {
        return None;
    }
    // A party box says the role before the entity — `to: StakerDistributor` — and it stands for
    // that contract exactly as the contract's own box does. Without this, marking a contract
    // painted its box and left its four party copies white, while a redrawn map painted all
    // five.
    let name = text.split_once(ROLE_MARK).map(|(_, entity)| entity).unwrap_or(&text).trim();
    // A box is named after the VARIABLE that holds it — `opexTreasury (Treasury)` — and what it
    // stands for is the contract in the brackets. Reading the whole text as the name made every
    // such box fail to match the registry's list, which stores real contract names: `mark
    // --apply` repainted nothing at all and said "0 of 0", on every map drawn since boxes
    // started carrying their variable.
    let name = match name.rsplit_once(" (") {
        Some((_, held)) => held.strip_suffix(')').unwrap_or(held).trim(),
        None => name,
    };
    // A legend row, a strip heading or a method leaf is not a contract: a contract's box carries
    // exactly its name, and anything with a space left in it is one of the others.
    (!name.is_empty() && !name.contains(' ')).then(|| name.to_string())
}

/// 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.
/// MEASURED, not guessed: at 320 with a 120 font the box was 62% air, and ascend's biggest
/// frame 64 700 units tall. 260 with 100 of padding put the words against the border — the
/// preview showed it — so 280 and 140 is where the margin is still visible and the frame is
/// 7% shorter. The width is dominated by the column gap, not by the padding, which is why
/// tightening the padding further buys nothing.
const NODE_HEIGHT: f64 = 320.0;
/// What a box that is NOT this repository's code takes: THE SAME as any other box.
///
/// It used to be half the height and half the type, on the grounds that an interface leaf is
/// the most numerous box and the least important. That stopped being true the day the parties
/// were drawn: the numerous boxes are now the destinations, at full size, and the half-size
/// ones sat between them as unreadable dust — three sizes in one row, and the two that name
/// what crosses the boundary were the ones nobody could read. One size, one font; a box is as
/// wide as its words and no wider.
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 = 140.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";
/// The invisible square a leg lands on, as the deploy sizes it.
const MARKER_SIZE: f64 = 8.0;

/// The one colour an arrow has.
///
/// Colour used to carry two things at once — what KIND of relation, and how SURE the scan
/// was — and four hues for five kinds was one too many to tell apart at the zoom where the
/// whole map fits, which is the only zoom it is for. The kind is the stroke now (`stroke_of`),
/// and colour is kept for the one thing worth a colour: an arrow that runs backwards.
const EDGE_COLOUR: &str = "#1a1a1a";
/// A cycle. Two contracts that each depend on the other is where re-entrancy and ordering
/// bugs live, so the arrow that closes the loop is the one mark on the map that is itself a
/// finding candidate — and it gets the only colour.
const CYCLE_COLOUR: &str = "#f24726";
/// `new X(...)`: this contract DEPLOYED that one, which is a different fact from calling it —
/// the address exists because of this line. It carried the word "creates" on the leg; a colour
/// says the same thing with nothing to read.
///
/// Yellow. A dark green read as a black line at the zoom where a whole frame fits, and a bright
/// one was still lost among the ordinary calls — the colour only earns its place if it is seen
/// before the line it is drawn on.
const CREATES_COLOUR: &str = "#fac710";
const BOX_FILL: &str = "#ffffff";
const BOX_BORDER: &str = "#1a1a1a";

/// A box that is NOT this repository's code, drawn only under `--with-boundaries`: grey, so
/// a token nobody here can read is never mistaken for a contract they can.
const OUTSIDE_FILL: &str = "#e6e6e6";

/// The background of a contract the reader asked to see (`bat-cli mark`).
///
/// A strong, warm fill: it has to be found before anything else on the frame, which is the whole
/// request. Nothing else on the map uses it — the interfaces' tints are pale and the repeated
/// contracts use borders.
const MARK_FILL: &str = "#ffe066";

/// One fill per INTERFACE, per frame.
///
/// Every caller gets its own copy of what it calls outside, which is what keeps the arrows
/// short — but then four boxes reading `IERC20` are four boxes, and nothing says they are the
/// same thing. A colour does: within a frame, every copy of one interface carries one fill and
/// no two interfaces carry the same. Per FRAME and not per map, because a reader compares what
/// is in front of them; across frames the name is the identity.
///
/// Light tints on purpose — the name is read off the box, so the fill sits under black text
/// without competing with the arrows.
/// Saturated, because these are a BORDER and a NAME now, not a fill.
///
/// They started as pale tints for a filled box, which is what they were good at; once the fill
/// went to the marked contracts and the interfaces moved to a dotted border with their name in
/// colour, the same tints became a label nobody could read against white.
const OUTSIDE_FILLS: &[&str] = &[
    "#1a73e8", "#c2185b", "#00897b", "#e8710a", "#6a1b9a", "#00838f", "#5d4037", "#827717",
    "#2e7d32", "#ad1457", "#283593", "#4e342e",
];

/// One border per CONTRACT that this frame draws more than once.
///
/// A frame is a tree, so a contract reached two ways is two boxes — which is what keeps the
/// arrows short, and leaves the reader with two boxes reading `Treasury` and nothing saying they
/// are the same address. The interfaces answer that with their fill; a contract cannot use the
/// fill too, or the two codes collide on a box that is both. So: a contract drawn ONCE keeps the
/// plain border, and one drawn twice or more takes a colour of its own, carried by every copy.
///
/// Saturated, because a 4-unit border has to carry the colour on its own — and neither green nor
/// red, which already mean `creates` and `a cycle` on the arrows.
/// How thick a border is drawn, plain and coloured.
///
/// A coloured border is a SIGNAL, and at 4 units it was invisible at the zoom where a whole
/// frame fits — which is the only zoom the map is read at. The plain one stays thin, because a
/// black border that thick reads as weight rather than as an edge. Miro's ceiling is 24.
const BORDER_WIDTH: usize = 4;
const REPEAT_BORDER_WIDTH: usize = 23;

/// Mid-tone, not deep: at the zoom where a whole frame fits, a 23-unit border of `#1a237e` or
/// `#3e2723` is a thick black line, and a reader comparing two of them across a frame is
/// comparing two blacks. The palette was reached for by hue alone and half of it came out at a
/// lightness the eye reads as "dark" before it reads as "blue" — which is the one job the
/// colour has. These sit around the middle of the scale: light enough to be a colour at a
/// glance, dark enough to hold against white.
///
/// Still neither green nor red, which already mean `creates` and `a cycle` on the arrows, and
/// still sixteen: past that a reader cannot tell two of them apart anyway.
const REPEAT_BORDERS: &[&str] = &[
    "#42a5f5", "#ab47bc", "#26a69a", "#ffa726", "#ec407a", "#8d6e63", "#7e57c2", "#c0ca33",
    "#26c6da", "#ff7043", "#5c6bc0", "#9ccc65", "#4fc3f7", "#f06292", "#a1887f", "#ffca28",
];
/// The strip's own boxes: present, apart, and visibly not part of the diagram.
const STRIP_FILL: &str = "#f4f4f4";
/// Vertical distance between two arrows meeting the same side of one box. Five arrows into
/// one contract used to land on one point of its border and read as one.
const ANCHOR_PITCH: f64 = 40.0;
/// Kept clear at the top and bottom of a box's side, so no arrow grazes a corner.
const ANCHOR_INSET: f64 = 40.0;

/// The id of the strip's heading, which is a box like the others and must never be confused
/// with a contract that happens to carry that name.
const STRIP_HEADING: &str = "\u{0}not connected in scope";
/// Length of the sample leg beside a legend row.
const LEGEND_SAMPLE: f64 = 700.0;
/// How far under the lowest box a cycle's corridor runs, and how far apart two of them sit.
const CYCLE_GAP: f64 = 240.0;
const CYCLE_PITCH: f64 = 160.0;

/// How far under its box a contract's leaves sit, which is the room the arrows into them need.
const BADGE_GAP: f64 = 30.0;
/// The height a leaf's row takes under its caller, used when a frame is measured.
const BADGE_HEIGHT: f64 = 150.0;

/// Half the gap between rows: where an arrow entering a lane from above crosses.
const ROW_GAP_HALF: f64 = 75.0;

/// The widest a box may be. Past it a name wraps instead of widening its column.
const WIDTH_CEILING: f64 = 2_600.0;

fn node_width(id: &str) -> f64 {
    // Measured from the TEXT the box actually carries, not from its id: a method leaf is sized
    // for `safeTransfer()` and not for the `IERC20` its id starts with, which is how a leaf ended
    // up narrower or wider than its own words.
    text_width(&box_text(id))
}

/// How wide a box has to be for its words: MEASURED, not counted.
///
/// A character count times a constant is a guess that is wrong in both directions — `l` and `W`
/// are not the same width — and the legend's long rows ran out of their boxes because of it.
/// The font is the one the screenshots use, which is wider than the board's own, so a box this
/// says fits is a box that fits. Falls back to the count when the font is not installed.
fn text_width(text: &str) -> f64 {
    // The font handle is not `Sync` — it holds a FreeType face — so it lives per thread, and
    // the widths are kept because a layout measures the same names many times over.
    thread_local! {
        static FONT: Option<silicon::font::FontCollection> =
            silicon::font::FontCollection::new(&[("Hack", NODE_FONT as f32)]).ok();
        static MEASURED: std::cell::RefCell<BTreeMap<String, f64>> =
            std::cell::RefCell::new(BTreeMap::new());
    }
    let cached = MEASURED.with(|cache| cache.borrow().get(text).copied());
    if let Some(width) = cached {
        return width;
    }
    // A FLOOR, because what the reader sees first is the box and only then its name: `swap()`
    // beside `to: the counterparty the owner names (address)` was a fifth of its width and read
    // as a lesser kind of thing, which it is not. Wide enough for a twelve-character name — the
    // length of most contract names here — so the short ones stop looking like dust while the
    // long ones still get the room they need.
    const FLOOR: f64 = 1100.0;
    // And a CEILING, because width is the expensive direction. A column is as wide as its
    // widest name, so one long box — `to: the counterparty the owner names (address)`, 5 294
    // units — made its whole column that wide and every box in it mostly empty. Past the
    // ceiling the name wraps onto a second line: the box grows DOWN, where the cost is one
    // row, instead of sideways, where the cost is a column.
    let measured = (FONT.with(|font| match font {
        Some(font) => font.get_text_len(text) as f64,
        None => text.chars().count() as f64 * NODE_CHAR,
    }) + NODE_PAD * 2.0)
        .clamp(FLOOR, WIDTH_CEILING);
    MEASURED.with(|cache| cache.borrow_mut().insert(text.to_string(), measured));
    measured
}

/// A box's words, broken onto a second line when they do not fit the widest box allowed.
///
/// Width is the expensive direction on this layout — a column is as wide as its widest name, so
/// a single long box inflates every box beside it — and height is the cheap one. So a name past
/// the ceiling wraps at a space rather than making its column wider. Broken at a SPACE, never
/// mid-word, and never more than twice: a box is a label, not a paragraph.
fn wrapped(text: &str) -> String {
    if text_width(text) < WIDTH_CEILING {
        return text.to_string();
    }
    let words: Vec<&str> = text.split(' ').collect();
    if words.len() < 2 {
        return text.to_string();
    }
    // The break nearest the middle, so neither line is a stub.
    let mut best = 1;
    let mut closest = f64::MAX;
    for at in 1..words.len() {
        let left = text_width(&words[..at].join(" "));
        let right = text_width(&words[at..].join(" "));
        let off = (left - right).abs();
        if off < closest {
            closest = off;
            best = at;
        }
    }
    format!("{}\n{}", words[..best].join(" "), words[best..].join(" "))
}

/// The box every node gets: one height, whatever it stands for.
///
/// They are the most numerous boxes on a frame — every caller carries its own copy — and the
/// least important: a reader does not scan for `IERC20` from across the board, they read it once
/// they have found the contract that calls it. At the contracts' own size they were most of the
/// frame's area.
fn node_height(id: &str) -> f64 {
    // Two lines when the name had to wrap, so the words have the room the box promised them.
    match wrapped(&box_text(id)).contains('\n') {
        true => NODE_HEIGHT * 1.6,
        false => NODE_HEIGHT,
    }
}

fn node_font(_id: &str) -> usize {
    NODE_FONT
}

/// How a kind of relation is drawn: its stroke, and — where one word earns its cost — a
/// caption on the leg that carries the head. Three strokes a reader can tell apart at any
/// zoom: solid is a fact, dashed is a question, dotted is wiring nobody calls through.
fn stroke_of(relation: Relation) -> (ConnectorStroke, Option<&'static str>) {
    match relation {
        Relation::Calls => (ConnectorStroke::Solid, None),
        // No caption: a word hung on a leg is a word to read, and `new X(...)` is rare enough
        // that a colour of its own carries it. Green, which nothing else on the map uses.
        Relation::Creates => (ConnectorStroke::Solid, None),
        // Only ever drawn for a pair that is wired and NOT called — a call outranks it — so
        // the word marks the odd case worth a second look.
        Relation::WiresAtConstruction => (ConnectorStroke::Dotted, Some("wired")),
        Relation::Unresolved => (ConnectorStroke::Dashed, Some("?")),
        // The grey box at the far end already says it is outside; the arrow is a call.
        Relation::Boundary => (ConnectorStroke::Solid, None),
        // Dotted like the other relation nothing flows through, and captioned because dotted
        // alone would read as `wired`.
        Relation::Reads => (ConnectorStroke::Dotted, Some("reads")),
    }
}

/// The style of one arrow: its relation's stroke in the one colour, or red when it runs
/// backwards.
fn style_of(relation: Relation, backwards: bool) -> ConnectorStyle {
    let (stroke, caption) = stroke_of(relation);
    let colour = match (backwards, relation) {
        (true, _) => CYCLE_COLOUR,
        (false, Relation::Creates) => CREATES_COLOUR,
        (false, _) => EDGE_COLOUR,
    };
    ConnectorStyle {
        stroke_color: colour.to_string(),
        stroke_width: EDGE_WIDTH.to_string(),
        stroke,
        caption: caption.map(str::to_string),
        arrow: ArrowEnd::End,
    }
}

/// What a legend row shows beside its words.
#[derive(Debug, Clone)]
enum Sample {
    /// A short leg in this style: two markers and one connector, like any arrow.
    Leg(ConnectorStyle),
    /// A box with this fill, border and border style, like any box.
    Box { fill: &'static str, border: &'static str, style: &'static str },
}

/// One row of the legend: a box with the words, and beside it the thing the words name.
///
/// The old legend was five boxes each FILLED with its relation's colour, which made sense
/// while colour was the code. With one colour and three strokes a filled box says nothing;
/// the sample is a real leg in the real style, so the reader matches a line to a line.
#[derive(Debug, Clone)]
struct LegendRow {
    text: &'static str,
    sample: Sample,
    /// Frame-local centre of the words' box, and its width.
    x: f64,
    y: f64,
    width: f64,
    /// The sample's two ends, for a `Leg`; the words' own box doubles as the sample for a
    /// `Box` row.
    sample_from: (f64, f64),
    sample_to: (f64, f64),
}

/// The legend, placed: one row per thing a reader can see on the map, in the frame's
/// top-left corner above the first column.
fn legend_rows() -> Vec<LegendRow> {
    let rows: [(&'static str, Sample); 11] = [
        ("calls", Sample::Leg(style_of(Relation::Calls, false))),
        ("yellow: creates it — `new X(...)`", Sample::Leg(style_of(Relation::Creates, false))),
        ("wired at construction, never called", Sample::Leg(style_of(Relation::WiresAtConstruction, false))),
        ("unresolved binding — a question", Sample::Leg(style_of(Relation::Unresolved, false))),
        ("runs backwards — a cycle", Sample::Leg(style_of(Relation::Calls, true))),
        // Every box on a map is this repository's code now: what leaves it is the grey line
        // under a box, and a contract with a frame of its own is a card.
        ("dotted, named in colour: no source here", Sample::Box { fill: BOX_FILL, border: OUTSIDE_FILLS[0], style: "dotted" }),
        ("filled: a contract you marked to see", Sample::Box { fill: MARK_FILL, border: BOX_BORDER, style: "normal" }),
        ("coloured border: the same contract, drawn twice", Sample::Box { fill: BOX_FILL, border: REPEAT_BORDERS[0], style: "normal" }),
        ("dotted `reads`: every call that way is a view — nothing moves, nothing follows", Sample::Leg(style_of(Relation::Reads, false))),
        ("dashed: an address only the deploy script names — `bat-cli resolve C.var X`", Sample::Box { fill: BOX_FILL, border: BOX_BORDER, style: "dashed" }),
        ("`drawn in this frame`: the same address, drawn in full on another branch", Sample::Box { fill: BOX_FILL, border: BOX_BORDER, style: "normal" }),
    ];
    rows.into_iter()
        .enumerate()
        .map(|(index, (text, sample))| {
            let width = text_width(text);
            let left = MAP_MARGIN / 2.0;
            let y = MAP_MARGIN / 2.0 + index as f64 * (NODE_HEIGHT + 60.0);
            let (sample_from, sample_to) = match sample {
                Sample::Leg(_) => ((left + width + 100.0, y), (left + width + 100.0 + LEGEND_SAMPLE, y)),
                Sample::Box { .. } => ((left, y), (left + width, y)),
            };
            LegendRow { text, sample, x: left + width / 2.0, y, width, sample_from, sample_to }
        })
        .collect()
}

/// One legend row per thing on the map — pinned by a test to `legend_rows()`, because the
/// layout reserves this many rows of height above the first column.
const LEGEND_ROWS: usize = 11;

/// One arrow as it will be drawn: which relation it is (if any — the legend's samples are
/// arrows too), its markers and legs, and its style.
pub(crate) struct RoutedArrow {
    /// Index into the drawn edges; `None` for a legend sample.
    pub(crate) edge: Option<usize>,
    pub(crate) plan: crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow,
    pub(crate) style: ConnectorStyle,
}

/// The nearest height to `y` that crosses no box of `layer`.
///
/// A box is a rectangle and an arrow is a line: the line is clear when it passes above the
/// top or below the bottom of every box in the column, with a margin so it does not graze one.
fn clear_of_the_layer(nodes: &[PlacedNode], layer: usize, y: f64) -> f64 {
    /// Enough to read as a gap rather than as a line touching a border.
    const CLEARANCE: f64 = 24.0;

    let blocked: Vec<(f64, f64)> = nodes
        .iter()
        .filter(|node| node.layer == layer)
        .map(|node| {
            (
                node.y - node.height / 2.0 - CLEARANCE,
                node.y + node.height / 2.0 + CLEARANCE,
            )
        })
        .collect();
    let hits = |y: f64| blocked.iter().any(|(top, bottom)| y > *top && y < *bottom);
    if !hits(y) {
        return y;
    }
    // Every box's two edges are the candidates: the answer is always flush against one of
    // them, so there is no search to run — just the nearest of a short list.
    blocked
        .iter()
        .flat_map(|(top, bottom)| [*top, *bottom])
        .filter(|candidate| !hits(*candidate))
        .min_by(|a, b| {
            (a - y)
                .abs()
                .partial_cmp(&(b - y).abs())
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .unwrap_or(y)
}

/// Where every arrow meets its boxes, and where it runs in between: lanes, corridors and
/// 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: &GraphLayout, with_legend: bool) -> Vec<RoutedArrow> {
    use crate::batbelt::evm::miro::auto_deploy::{plan_lane_chain, LaneEnd, LaneSide, PlannedLaneArrow};
    use crate::batbelt::miro::client::RelativeAnchor;
    use crate::batbelt::miro::layout::{assign_lanes, LANE_PITCH};

    struct Forward<'a> {
        index: usize,
        edge: &'a Edge,
        from: &'a PlacedNode,
        to: &'a PlacedNode,
        /// The gutters crossed, caller's side first.
        gutters: Vec<usize>,
        /// The corridor heights, in the same order: the first is the column beside the caller.
        corridors: Vec<f64>,
    }

    let mut forward: Vec<Forward> = Vec::new();
    let mut backwards: Vec<(usize, &Edge, &PlacedNode, &PlacedNode)> = Vec::new();
    for (index, edge) in edges.iter().enumerate() {
        let (Some(from), Some(to)) = (layout.node(&edge.from), layout.node(&edge.to)) else {
            continue;
        };
        if to.layer <= from.layer {
            // A cycle: the layout had to reverse it, and it runs back towards the frame's own
            // contract. Drawn red, box to box, routed by Miro — the one arrow allowed to look
            // different is the one that is a finding. It used to be dropped here without a word.
            backwards.push((index, edge, from, to));
            continue;
        }
        // The corridors, CALLER FIRST — which is now the order `insert_bend_points` produces,
        // because the caller is the one in the lower layer. Walking them the other way round
        // put every arrow that skipped two columns through the wrong column's corridor at the
        // wrong height, which is to say through the boxes.
        let corridors: Vec<f64> = layout
            .routes
            .get(index)
            .map(|bends| bends.iter().map(|(_, y)| *y).collect())
            .unwrap_or_default();
        // One gutter per corridor, plus the last drop into the callee — rather than one per
        // column the arrow spans. They are the same number whenever the layout bent the arrow,
        // and they are NOT when it declined to: `rejoin` makes a box with two parents, the
        // layout's depth-first pass can call one of those edges a back edge, and the layers it
        // then assigns can still come out forward. That arrow reached here asking for three
        // lanes with no corridor to run them at, and the router indexed past its own turns.
        let gutters: Vec<usize> = (from.layer..=(from.layer + corridors.len())).collect();
        // A corridor is the height an arrow crosses the NEXT column at, and it has to be
        // clear of that whole column. The bend point it comes from only claims a slot in its
        // own sub-column: a layer tall enough to be split into two keeps packing the second
        // one from the top, so the gap the bend reserved sat beside a box rather than above
        // or below it, and the arrow ran straight through `AscendCtoReceiver`'s name.
        //
        // Slid to the nearest height the whole layer leaves free. Nearest, so an arrow is
        // moved as little as the picture allows and the ordering the layout settled on — which
        // is what keeps the crossing count at zero — survives the move.
        let corridors: Vec<f64> = corridors
            .iter()
            .enumerate()
            .map(|(step, y)| clear_of_the_layer(&layout.nodes, from.layer + step + 1, *y))
            .collect();
        forward.push(Forward { index, edge, from, to, gutters, corridors });
    }

    // Where each arrow meets its two boxes. Every arrow used to leave from the caller's
    // mid-height and land on the callee's, so five arrows into one contract were one point
    // on its border. Spread along the side instead, in the order they head off: an arrow
    // going up leaves from the upper part of the side, one going down from the lower, so none
    // crosses another in the first hundred units of its life.
    let spread = |mut ends: Vec<(usize, f64)>, height: f64| -> BTreeMap<usize, f64> {
        ends.sort_by(|a, b| {
            a.1.partial_cmp(&b.1)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(a.0.cmp(&b.0))
        });
        let count = ends.len();
        let step = if count > 1 {
            // The BOX's own height, not a constant: an outside leaf is half as tall, and five
            // arrows spread over a contract's height would have left its border.
            ANCHOR_PITCH.min((height - 2.0 * ANCHOR_INSET).max(0.0) / (count - 1) as f64)
        } else {
            0.0
        };
        ends.into_iter()
            .enumerate()
            .map(|(rank, (index, _))| (index, (rank as f64 - (count as f64 - 1.0) / 2.0) * step))
            .collect()
    };
    let mut leaving: BTreeMap<&str, (f64, Vec<(usize, f64)>)> = BTreeMap::new();
    let mut landing: BTreeMap<&str, (f64, Vec<(usize, f64)>)> = BTreeMap::new();
    for arrow in &forward {
        let heads_to = arrow.corridors.first().copied().unwrap_or(arrow.to.y);
        let comes_from = arrow.corridors.last().copied().unwrap_or(arrow.from.y);
        leaving
            .entry(arrow.from.id.as_str())
            .or_insert_with(|| (arrow.from.height, Vec::new()))
            .1
            .push((arrow.index, heads_to));
        landing
            .entry(arrow.to.id.as_str())
            .or_insert_with(|| (arrow.to.height, Vec::new()))
            .1
            .push((arrow.index, comes_from));
    }
    let mut start_offset: BTreeMap<usize, f64> = BTreeMap::new();
    for (height, ends) in leaving.into_values() {
        start_offset.extend(spread(ends, height));
    }
    let mut end_offset: BTreeMap<usize, f64> = BTreeMap::new();
    for (height, ends) in landing.into_values() {
        end_offset.extend(spread(ends, height));
    }

    // Which gutters each arrow crosses, and the y it enters and leaves each one at.
    let mut crossing: BTreeMap<usize, Vec<((usize, usize), f64, f64)>> = BTreeMap::new();
    for arrow in &forward {
        let start_y = arrow.from.y + start_offset.get(&arrow.index).copied().unwrap_or(0.0);
        let end_y = arrow.to.y + end_offset.get(&arrow.index).copied().unwrap_or(0.0);
        let mut enters = start_y;
        for (step, gutter) in arrow.gutters.iter().enumerate() {
            let leaves = arrow.corridors.get(step).copied().unwrap_or(end_y);
            crossing
                .entry(*gutter)
                .or_default()
                .push(((arrow.index, step), enters, leaves));
            enters = leaves;
        }
    }

    // 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);
        // Unchanged by the flip: a gutter still runs between column `g` and column `g + 1`,
        // and a lane is still measured from the left of the two.

        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<RoutedArrow> = Vec::new();
    for arrow in &forward {
        let lanes: Vec<f64> = arrow
            .gutters
            .iter()
            .enumerate()
            .filter_map(|(step, _)| lane_of.get(&(arrow.index, step)).copied())
            .collect();
        if lanes.is_empty() {
            continue;
        }
        let start_y = arrow.from.y + start_offset.get(&arrow.index).copied().unwrap_or(0.0);
        let end_y = arrow.to.y + end_offset.get(&arrow.index).copied().unwrap_or(0.0);

        // A box that is NOT the leftmost of its column sits in a second or third lane, with
        // another box between it and the gutter. Entering it from the left means crossing that
        // box — 33 arrows over a box the first time lanes were tried. So the arrow runs up the
        // gutter, crosses in the ROW GAP above the leaf's row, and drops into its TOP side:
        // the crossing happens in a gap where no box is, and the drop stays inside the leaf's
        // own width, so it cannot touch anything by construction.
        let leftmost = layout
            .nodes
            .iter()
            .filter(|node| node.layer == arrow.to.layer)
            .map(|node| node.x - node.width / 2.0)
            .fold(f64::MAX, f64::min);
        let in_a_lane = arrow.to.x - arrow.to.width / 2.0 > leftmost + 1.0;
        let (to_end, lanes, corridors) = match in_a_lane {
            false => (
                LaneEnd::Point { x: arrow.to.x - arrow.to.width / 2.0, y: end_y },
                lanes.clone(),
                arrow.corridors.clone(),
            ),
            true => {
                let above = arrow.to.y - arrow.to.height / 2.0 - ROW_GAP_HALF;
                let mut lanes = lanes.clone();
                let mut corridors = arrow.corridors.clone();
                corridors.push(above);
                lanes.push(arrow.to.x);
                (
                    LaneEnd::Point { x: arrow.to.x, y: arrow.to.y - arrow.to.height / 2.0 },
                    lanes,
                    corridors,
                )
            }
        };
        planned.push(RoutedArrow {
            edge: Some(arrow.index),
            plan: plan_lane_chain(
                &LaneEnd::Point { x: arrow.from.x + arrow.from.width / 2.0, y: start_y },
                &to_end,
                &lanes,
                &corridors,
            ),
            style: style_of(arrow.edge.relation, false),
        });
    }
    // A cycle goes back the SHORT way: out of the caller's left, one row down, across to the
    // lane outside the callee's column, up, and in at the callee's left.
    //
    // Two versions came before it. Miro's own routing drew it through the middle of the frame
    // and over two boxes. Sending it under the WHOLE diagram cleared the boxes and drew a lap
    // of the entire frame — it left the top-left box, crossed the full width twice and the full
    // height once, to reach a contract two rows above. The corridor only has to clear the
    // caller's own row, and the lane outside the callee's column is empty by construction.
    for (rank, (index, edge, from, to)) in backwards.into_iter().enumerate() {
        // Just under the caller's row, inside the gutter the layout already leaves there
        // (`gutter_y` is one and a half boxes), so nothing is crossed and nothing moves.
        let corridor = from.y + from.height / 2.0 + CYCLE_GAP + rank as f64 * CYCLE_PITCH;
        let anchor = RelativeAnchor::new(0.5, 0.5);
        // Out of the LEFT, because the callee is to the left: leaving right meant crossing the
        // caller's own column before turning round.
        let down_x = from.x - from.width / 2.0 - CYCLE_GAP;
        let up_x = to.x - to.width / 2.0 - CYCLE_GAP;
        planned.push(RoutedArrow {
            edge: Some(index),
            plan: PlannedLaneArrow {
                points: vec![
                    (from.x - from.width / 2.0, from.y),
                    (down_x, from.y),
                    (down_x, corridor),
                    (up_x, corridor),
                    (up_x, to.y),
                    (to.x - to.width / 2.0, to.y),
                ],
                legs: vec![
                    (LaneSide::Marker(0), anchor, LaneSide::Marker(1), anchor, false),
                    (LaneSide::Marker(1), anchor, LaneSide::Marker(2), anchor, false),
                    (LaneSide::Marker(2), anchor, LaneSide::Marker(3), anchor, false),
                    (LaneSide::Marker(3), anchor, LaneSide::Marker(4), anchor, false),
                    (LaneSide::Marker(4), anchor, LaneSide::Marker(5), anchor, true),
                ],
            },
            style: style_of(edge.relation, true),
        });
    }
    // The legend's samples are arrows like any other, so they are counted, drawn and
    // previewed by the same code — a legend drawn by its own path is a legend that drifts.
    // Only on the legend's own frame: appended to every frame, they drew five loose strokes
    // over the top-left corner of each contract's diagram.
    for row in legend_rows().into_iter().filter(|_| with_legend) {
        let Sample::Leg(style) = row.sample else { continue };
        planned.push(RoutedArrow {
            edge: None,
            plan: PlannedLaneArrow {
                points: vec![row.sample_from, row.sample_to],
                legs: vec![(
                    LaneSide::Marker(0),
                    RelativeAnchor::new(1.0, 0.5),
                    LaneSide::Marker(1),
                    RelativeAnchor::new(0.0, 0.5),
                    true,
                )],
            },
            style,
        });
    }

    // Every arrow, with its zero-length legs collapsed — see `tighten`.
    planned
        .into_iter()
        .map(|arrow| RoutedArrow { plan: tighten(arrow.plan), ..arrow })
        .collect()
}

/// Drop the zero-length legs of a planned arrow, and the markers they would have joined.
///
/// A lane chain places two markers per gutter — where the arrow enters it and where it leaves.
/// When the arrow runs level, those two are the same point, and two markers at identical
/// coordinates come back from the bulk endpoint as ONE item; Miro then refuses the connector
/// with `"The startitem id and enditem id cannot be the same"`. Four relations of a real board
/// were lost that way, silently until the failure learned to quote the API.
///
/// Merging them is also the right picture: a leg of no length is a leg nobody can see.
fn tighten(
    plan: crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow,
) -> crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow {
    use crate::batbelt::evm::miro::auto_deploy::{LaneSide, PlannedLaneArrow};

    let same = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 0.5 && (a.1 - b.1).abs() < 0.5;
    // Each old marker keeps its own new index, unless an EARLIER one already sits on that point.
    let mut points: Vec<(f64, f64)> = Vec::new();
    let mut moved: Vec<usize> = Vec::new();
    for point in &plan.points {
        match points.iter().position(|kept| same(*kept, *point)) {
            Some(index) => moved.push(index),
            None => {
                points.push(*point);
                moved.push(points.len() - 1);
            }
        }
    }
    let at = |side: &LaneSide| match side {
        LaneSide::Marker(index) => LaneSide::Marker(moved.get(*index).copied().unwrap_or(*index)),
        LaneSide::Item(id) => LaneSide::Item(id.clone()),
    };
    let mut legs: Vec<_> = plan
        .legs
        .iter()
        .map(|(from, from_anchor, to, to_anchor, head)| {
            (at(from), *from_anchor, at(to), *to_anchor, *head)
        })
        .filter(|(from, _, to, _, _)| match (from, to) {
            (LaneSide::Marker(a), LaneSide::Marker(b)) => a != b,
            _ => true,
        })
        .collect();
    // The head rides on the last leg: dropping the one that carried it would leave an arrow
    // with no point on it.
    if !legs.is_empty() && !legs.iter().any(|leg| leg.4) {
        let last = legs.len() - 1;
        legs[last].4 = true;
    }
    PlannedLaneArrow { points, legs }
}

/// Draw the planned map into a local PNG: every frame's border and title, its boxes, 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::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]));

    for frame in &prepared.frames {
        // Frame-local, exactly as Miro reads a child item's position, plus where the frame sits
        // in the block.
        let at = |x: f64, y: f64| {
            (
                ((frame.left + x) * scale) as i64,
                ((frame.top + y) * scale) as i64,
            )
        };
        let border = parse_colour(BOX_BORDER);
        let (frame_left, frame_top) = at(0.0, 0.0);
        let (frame_right, frame_bottom) = at(frame.width, frame.height);
        for (from, to) in [
            ((frame_left, frame_top), (frame_right, frame_top)),
            ((frame_right, frame_top), (frame_right, frame_bottom)),
            ((frame_right, frame_bottom), (frame_left, frame_bottom)),
            ((frame_left, frame_bottom), (frame_left, frame_top)),
        ] {
            draw_stroke(&mut canvas, from, to, border, ConnectorStroke::Solid);
        }

        // Every box with the fill and border the board will give it — what a box IS and what it
        // DOES are the two things a reader takes from it before reading its name, so the preview
        // has to show them or it is previewing a different picture.
        // Carrying the STYLE and the text colour as well, because the board does. A preview
        // that draws every border solid and every name black is answering a question about a
        // picture nobody is going to see: two colour schemes were judged fine from PNGs where
        // the dotted boxes, the dashed accounts and the coloured interface names were all
        // invisible, and both failed on the board.
        let mut boxes: Vec<(f64, f64, f64, f64, &str, &str, usize, String, &str, &str)> =
            Vec::new();
        for node in &frame.layout.nodes {
            let (repeat_border, thickness) = frame.border_of(&node.id);
            let (fill, outside_border, style) = frame.paint_of(&node.id, &prepared.marked);
            // A repeated contract's own colour outranks the plain border; an outside leaf has
            // no repeat colour, so its interface colour is what shows.
            let border = if repeat_border == BOX_BORDER { outside_border } else { repeat_border };
            boxes.push((
                node.x,
                node.y,
                node.width,
                node.height,
                fill,
                border,
                thickness,
                wrapped(&frame.text_of(&node.id)),
                style,
                // An outside box carries its interface's colour in the NAME, which is the one
                // thing the preview never showed.
                if is_outside(&node.id) { outside_border } else { BOX_BORDER },
            ));
        }
        for node in &frame.strip {
            boxes.push((
                node.x,
                node.y,
                node.width,
                node.height,
                STRIP_FILL,
                BOX_BORDER,
                BORDER_WIDTH,
                box_text(&node.id),
                "normal",
                BOX_BORDER,
            ));
        }
        if frame.is_legend() {
            for row in legend_rows() {
                let (fill, border, style) = match row.sample {
                    Sample::Leg(_) => (BOX_FILL, BOX_BORDER, "normal"),
                    Sample::Box { fill, border, style } => (fill, border, style),
                };
                let thickness = if border == BOX_BORDER { BORDER_WIDTH } else { REPEAT_BORDER_WIDTH };
                boxes.push((
                    row.x,
                    row.y,
                    row.width,
                    NODE_HEIGHT,
                    fill,
                    border,
                    thickness,
                    row.text.to_string(),
                    style,
                    BOX_BORDER,
                ));
            }
        }
        for (x, y, box_width, box_height, fill, box_border, thickness, words, style, ink) in boxes
        {
            let (left, top) = at(x - box_width / 2.0, y - box_height / 2.0);
            let (right, bottom) = at(x + box_width / 2.0, y + box_height / 2.0);
            fill_rect(&mut canvas, (left, top), (right, bottom), parse_colour(fill));
            let edge = parse_colour(box_border);
            // Drawn as nested rectangles, one per unit of thickness at this scale, so a border
            // the board draws thick is thick in the preview too — otherwise the preview answers
            // a question about the picture that the picture answers differently.
            let stroke = match style {
                "dotted" => ConnectorStroke::Dotted,
                "dashed" => ConnectorStroke::Dashed,
                _ => ConnectorStroke::Solid,
            };
            let rings = ((thickness as f64 * scale).round() as i64).max(1);
            for ring in 0..rings {
                for (from, to) in [
                    ((left + ring, top + ring), (right - ring, top + ring)),
                    ((right - ring, top + ring), (right - ring, bottom - ring)),
                    ((right - ring, bottom - ring), (left + ring, bottom - ring)),
                    ((left + ring, bottom - ring), (left + ring, top + ring)),
                ] {
                    draw_stroke(&mut canvas, from, to, edge, stroke);
                }
            }
            // The WORDS, at the size the board will give them. Without them the preview shows
            // boxes whose proportions nobody can judge — a name that overflows its box and a
            // name lost in it look exactly alike, which is how three different box sizes
            // reached the board before anybody saw them.
            write_words(&mut canvas, &words, (left, top), (right, bottom), scale, parse_colour(ink));
        }

        // Every leg of every arrow, in its stroke and colour, from the markers the plan places.
        for arrow in &frame.arrows {
            let colour = parse_colour(&arrow.style.stroke_color);
            for (from, _, to, _, _) in &arrow.plan.legs {
                let point = |side: &LaneSide| match side {
                    LaneSide::Marker(index) => arrow.plan.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_stroke(&mut canvas, at(from_x, from_y), at(to_x, to_y), colour, arrow.style.stroke);
            }
        }
    }

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

/// A box's words, centred, at the font the board uses scaled to the preview.
///
/// Rendered with the same font machinery the screenshots use, so a name that does not fit its
/// box does not fit here either. Below a few pixels nothing legible can be drawn and nothing
/// is: the preview is then a picture of the layout, which is what it was before.
fn write_words(
    canvas: &mut image::RgbaImage,
    words: &str,
    (left, top): (i64, i64),
    (right, bottom): (i64, i64),
    scale: f64,
    // The board colours an outside box's NAME after its interface, so a preview that writes
    // every name in black is previewing a different picture.
    ink: image::Rgba<u8>,
) {
    let size = (NODE_FONT as f64 * scale).round() as f32;
    if size < 5.0 || words.is_empty() {
        return;
    }
    let Ok(font) = silicon::font::FontCollection::new(&[("Hack", size)]) else {
        return;
    };
    // One line per line: a wrapped name is two lines on the board, and a preview that ran them
    // together would be previewing a box that fits where the real one does not.
    let lines: Vec<&str> = words.split('\n').collect();
    let height = font.get_font_height() as i64;
    let block = height * lines.len() as i64;
    let first = top + ((bottom - top) - block).max(0) / 2;
    for (at, line) in lines.iter().enumerate() {
        let width = font.get_text_len(line) as i64;
        let x = left + ((right - left) - width).max(0) / 2;
        let y = first + at as i64 * height;
        if x < 0 || y < 0 {
            continue;
        }
        font.draw_text_mut(
            canvas,
            ink,
            x as u32,
            y as u32,
            silicon::font::FontStyle::BOLD,
            line,
        );
    }
}

/// A line in one of the three strokes, so the preview tells a question from a fact the way
/// the board will. Lengths are in pixels of the scaled canvas: a dash long enough to read as
/// a dash at a sixth of board scale, a dot that is not a dash.
fn draw_stroke(
    canvas: &mut image::RgbaImage,
    from: (i64, i64),
    to: (i64, i64),
    colour: image::Rgba<u8>,
    stroke: ConnectorStroke,
) {
    let (on, off) = match stroke {
        ConnectorStroke::Solid => (usize::MAX, 0),
        ConnectorStroke::Dashed => (12, 8),
        ConnectorStroke::Dotted => (3, 6),
    };
    let mut walked = 0usize;
    for (x, y) in bresenham(from, to) {
        if walked % (on.saturating_add(off)) < on {
            for dy in -1..=1 {
                for dx in -1..=1 {
                    let (px, py) = (x + dx, y + dy);
                    if px >= 0 && py >= 0 && (px as u32) < canvas.width() && (py as u32) < canvas.height() {
                        canvas.put_pixel(px as u32, py as u32, colour);
                    }
                }
            }
        }
        walked += 1;
    }
}

/// Every pixel of the line from `from` to `to`, in order.
fn bresenham(from: (i64, i64), to: (i64, i64)) -> Vec<(i64, i64)> {
    let mut pixels = Vec::new();
    let (mut x, mut y) = from;
    let dx = (to.0 - x).abs();
    let dy = -(to.1 - y).abs();
    let step_x = if x < to.0 { 1 } else { -1 };
    let step_y = if y < to.1 { 1 } else { -1 };
    let mut error = dx + dy;
    loop {
        pixels.push((x, y));
        if x == to.0 && y == to.1 {
            break;
        }
        let double = 2 * error;
        if double >= dy {
            error += dy;
            x += step_x;
        }
        if double <= dx {
            error += dx;
            y += step_y;
        }
    }
    pixels
}

fn fill_rect(canvas: &mut image::RgbaImage, top_left: (i64, i64), bottom_right: (i64, i64), colour: image::Rgba<u8>) {
    for y in top_left.1.max(0)..bottom_right.1.min(canvas.height() as i64) {
        for x in top_left.0.max(0)..bottom_right.0.min(canvas.width() as i64) {
            canvas.put_pixel(x as u32, y as u32, colour);
        }
    }
}

/// `#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 the map. Local: no client, no board, no renders.
///
/// One frame per top caller, plus a small frame for the legend and whatever is connected to
/// nothing — see `partition_frames`. The frames are packed into a block here, in frame-local
/// coordinates, so the only thing the board decides is where that block starts.
pub fn prepare(metadata: &EvmBatMetadata, options: &MapOptions) -> Result<PreparedMap, EvmMiroError> {
    let all = relations(metadata);
    // The reader's own list, from the registry and from this run's flag. Names only: what it
    // means — an audit's scope, a subsystem — is theirs, and bat stays agnostic.
    let marked: BTreeSet<String> = metadata
        .marked_contracts
        .iter()
        .cloned()
        .chain(options.mark.iter().cloned())
        .collect();

    let mut edges = drawn_edges(metadata, &all, options.no_boundaries);
    let (leaves, unnamed) = method_leaves(metadata, &edges, options.all_methods);
    edges.extend(leaves);
    if edges.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("no relations between contracts — run `bat-cli sonar` first"));
    }


    let mut frames: Vec<PreparedFrame> = partition_frames(&edges, options.contract.as_deref())
        .into_iter()
        .map(|plan| {
            // No localizing: a frame is a tree, so nothing inside it is shared and nothing can
            // cross. The crossing count is still reported, as the certificate that it stays so.
            let mine = plan.edges;
            let layout = layout_tree(&plan.root, &mine);
            let arrows = route_arrows(&mine, &layout, false);
            // Tall enough for what the arrows actually use: a cycle's corridor runs under the
            // lowest box, and a frame measured from the boxes alone would cut it off.
            let used = arrows
                .iter()
                .flat_map(|arrow| arrow.plan.points.iter())
                .map(|(_, y)| *y)
                .fold(0.0_f64, f64::max);
            PreparedFrame {
                title: frame_title(&plan.root),
                root: plan.root.clone(),
                fills: PreparedFrame::outside_fills(&mine),
                borders: PreparedFrame::repeat_borders(metadata, &mine),
                width: layout.frame_width,
                height: layout.frame_height.max(used + MAP_MARGIN),
                crossings: layout.crossings,
                over_boxes: arrows_over_boxes(&arrows, &mine, &layout),
                many: drawn_more_than_once(&mine),
                edges: mine,
                layout,
                arrows,
                strip: Vec::new(),
                left: 0.0,
                top: 0.0,
            }
        })
        .collect();
    // The legend FIRST: it is the frame a reader opens to learn how to read the others, so it
    // takes the top-left of the block and is the first one created. It used to be appended, so
    // it landed wherever the packing had room — usually last, at the bottom right.
    frames.insert(0, legend_frame(&unconnected(metadata, &edges)));
    pack_frames(&mut frames);

    let width = frames
        .iter()
        .map(|frame| frame.left + frame.width)
        .fold(0.0_f64, f64::max);
    let height = frames
        .iter()
        .map(|frame| frame.top + frame.height)
        .fold(0.0_f64, f64::max);
    let calls = ApiCalls {
        frames: frames.len(),
        boxes: frames
            .iter()
            .map(|frame| frame.layout.nodes.len() + frame.boxes_of_its_own())
            .sum(),
        markers: frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .map(|arrow| arrow.plan.points.len())
            .sum(),
        connectors: frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .map(|arrow| arrow.plan.legs.len())
            .sum(),
    };

    Ok(PreparedMap { edges, frames, marked, width, height, calls, unnamed })
}

/// A frame's title: whose frame it is. One phrasing, used by the title, by `--contract` and by
/// the card that points at it, so the three can never drift apart.
fn frame_title(root: &str) -> String {
    format!("map: what {root} talks to")
}

/// The legend, and the contracts no relation touches, on a frame of their own.
///
/// One copy for the whole map rather than one per frame: seven rows repeated on every frame is
/// seven rows of noise per frame, and the reader needs them once.
fn legend_frame(alone: &[String]) -> PreparedFrame {
    let rows = legend_rows();
    let mut strip = strip_of(alone, rows.last().map(|row| row.y).unwrap_or(0.0) + NODE_HEIGHT * 2.0);
    let width = rows
        .iter()
        .map(|row| row.x + row.width / 2.0 + LEGEND_SAMPLE + MAP_MARGIN)
        .chain(strip.iter().map(|node| node.x + node.width / 2.0 + MAP_MARGIN))
        .fold(0.0_f64, f64::max);
    let height = rows
        .iter()
        .map(|row| row.y)
        .chain(strip.iter().map(|node| node.y))
        .fold(0.0_f64, f64::max)
        + NODE_HEIGHT / 2.0
        + MAP_MARGIN;
    // Its samples are arrows like any other, drawn and previewed by the same code.
    let arrows = route_arrows(&[], &crate::batbelt::miro::layout::GraphLayout {
        nodes: Vec::new(),
        routes: Vec::new(),
        back_edges: Vec::new(),
        bbox_width: 0.0,
        bbox_height: 0.0,
        frame_width: width,
        frame_height: height,
        crossings: 0,
    }, true);
    strip.shrink_to_fit();
    PreparedFrame {
        title: "map: legend".to_string(),
        root: String::new(),
        fills: BTreeMap::new(),
        borders: BTreeMap::new(),
        many: BTreeSet::new(),
        edges: Vec::new(),
        layout: crate::batbelt::miro::layout::GraphLayout {
            nodes: Vec::new(),
            routes: Vec::new(),
            back_edges: Vec::new(),
            bbox_width: width,
            bbox_height: height,
            frame_width: width,
            frame_height: height,
            crossings: 0,
        },
        arrows,
        strip,
        width,
        height,
        crossings: 0,
        over_boxes: 0,
        left: 0.0,
        top: 0.0,
    }
}

/// Place the frames in rows, left to right, wrapping at a width that keeps the block roughly
/// as wide as it is tall.
///
/// Miro refuses a frame that overlaps another with a 500, so this is not cosmetic. Rows rather
/// than one long line because a map of eight frames in a row is a map nobody can see at once —
/// the whole reason there are frames at all.
fn pack_frames(frames: &mut [PreparedFrame]) {
    let area: f64 = frames.iter().map(|frame| frame.width * frame.height).sum();
    let widest = frames.iter().map(|frame| frame.width).fold(0.0_f64, f64::max);
    // Two of the widest frames side by side, at least: `sqrt(area)` alone is the width of the
    // single widest frame whenever one frame dominates, which lays every other frame out in a
    // column one frame wide and makes the block a mile tall.
    let target = area.sqrt().max(widest * 2.0 + MAP_MARGIN);
    let (mut x, mut y, mut row_height) = (0.0_f64, 0.0_f64, 0.0_f64);
    for frame in frames.iter_mut() {
        if x > 0.0 && x + frame.width > target {
            x = 0.0;
            y += row_height + MAP_MARGIN;
            row_height = 0.0;
        }
        frame.left = x;
        frame.top = y;
        x += frame.width + MAP_MARGIN;
        row_height = row_height.max(frame.height);
    }
}

/// The strip's boxes: a heading, then one box per unconnected contract, stacked in a column
/// under the legend's rows.
fn strip_of(names: &[String], top: f64) -> Vec<PlacedNode> {
    if names.is_empty() {
        return Vec::new();
    }
    let heading = strip_heading_text();
    let width = names
        .iter()
        .map(|name| node_width(name))
        .fold(node_width(heading), f64::max);
    std::iter::once(STRIP_HEADING.to_string())
        .chain(names.iter().cloned())
        .enumerate()
        .map(|(row, id)| PlacedNode {
            id,
            layer: 0,
            x: MAP_MARGIN / 2.0 + width / 2.0,
            y: top + row as f64 * (NODE_HEIGHT + 60.0),
            width,
            height: NODE_HEIGHT,
        })
        .collect()
}

/// The words on the strip's heading box.
fn strip_heading_text() -> &'static str {
    STRIP_HEADING.trim_start_matches('\u{0}')
}

/// The words a box carries: a contract's name, or the strip's heading.
fn box_text(id: &str) -> String {
    if id == STRIP_HEADING {
        return strip_heading_text().to_string();
    }
    // A destination says WHO, and nothing else: the method it came from is the box beside it.
    if let Some(to) = destination_of(id) {
        // An address nobody has named reads as one. Without the word the box looked like a
        // contract called `yieldSink`, and the reader went looking for its source.
        // The mark is on the whole name, so it comes off before the variable is read out.
        let (to, unnamed) = match to.strip_suffix(ADDRESS_MARK) {
            Some(point) => (point, true),
            None => (to, false),
        };
        let to = match to.split_once(VARIABLE_MARK) {
            // The variable first, because that is what tells one deployment from another; the
            // contract after it, because that is the code to open.
            Some((variable, held)) => format!("{variable} ({held})"),
            None => to.to_string(),
        };
        return match unnamed {
            true => format!("{to} (address)"),
            false => to,
        };
    }
    // A box that names the variable holding it: `opexTreasury (Treasury)`, one of five
    // deployments of one contract.
    if let Some((variable, held)) = original_of(id).split_once(VARIABLE_MARK) {
        return format!("{variable} ({held})");
    }
    // A method leaf says the METHOD, written as Solidity writes one: `vault()`, not `vault`.
    // Without the parentheses a getter's box reads as a destination — `ICLPoolManager → vault`
    // looked like a second contract rather than the call that asks for its address.
    match method_of(id) {
        // `call{value}` already says it is a call; `call{value}()` reads like a method named
        // after an option block.
        Some(method) if method.ends_with('}') => method.to_string(),
        Some(method) => format!("{method}()"),
        None => original_of(id).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;
    // By ENTITY on both ends: a box named after the variable holding it (`burnSink%BurnSink`)
    // and a party at the end of a call (`…=>to: BurnSink`) are that contract drawn. Comparing
    // the literal names listed `BurnSink` as touching nothing while the router wires it and
    // pays it.
    let drawn: BTreeSet<&str> = edges
        .iter()
        .flat_map(|edge| [drawn_entity(&edge.from), drawn_entity(&edge.to)])
        .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, with nothing on the board yet.
///
/// The same split `storage` and `effects` have, and for the same two reasons: a frame has to be
/// created at its final size, 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 {
    /// Every relation, before any frame copied one: what the terminal reports.
    edges: Vec<Edge>,
    /// The contracts the reader asked to see (`bat-cli mark`), drawn with a filled background.
    marked: BTreeSet<String>,
    /// One per top caller, plus the legend's. Their `left`/`top` are inside the block.
    frames: Vec<PreparedFrame>,
    pub width: f64,
    pub height: f64,
    pub calls: ApiCalls,
    /// The call-site arguments the map could not turn into an entity: where to look, and the
    /// key that records the answer. Reported, never guessed.
    pub unnamed: Vec<UnnamedParty>,
}

/// One frame of the map: what one contract talks to, laid out on its own.
pub struct PreparedFrame {
    title: String,
    /// The contract this frame is about — the tree's root, which a cycle's frame cannot get
    /// from the edges because every member of a cycle is pointed at.
    root: String,
    /// This frame's relations, with the copies `localize` made — not the map's.
    edges: Vec<Edge>,
    layout: GraphLayout,
    arrows: Vec<RoutedArrow>,
    /// One fill per interface drawn here, so every copy of one interface looks like the others
    /// and no two interfaces look alike.
    fills: BTreeMap<String, &'static str>,
    /// One border per contract drawn here MORE THAN ONCE, so its copies read as one address.
    borders: BTreeMap<String, &'static str>,
    /// Only the legend frame has these: the contracts no relation touches.
    strip: Vec<PlacedNode>,
    width: f64,
    height: f64,
    /// Arrow pairs that still cross after localizing — the certificate, printed per frame so a
    /// change to the layout is judged by a number instead of by looking at a PNG.
    crossings: usize,
    /// And the other half of that certificate: arrows running across a box they do not touch.
    over_boxes: usize,
    /// The contracts this frame draws MORE THAN ONE deployment of.
    ///
    /// What a box has to say depends on its company. One `AscendLaunchpad` on a frame needs no
    /// variable in front of it — there is nothing to tell it apart from — and putting one there
    /// made the root and a box reached through `listingDesk.launchpad` read as two different
    /// contracts. Six `Treasury`s on one frame need theirs, every one, or the six are one.
    many: BTreeSet<String>,
    /// Inside the block, before the board says where the block starts.
    left: f64,
    top: f64,
}

impl PreparedFrame {
    /// What a box SAYS on THIS frame.
    ///
    /// The variable in front of a contract's name is there to tell one deployment from another,
    /// so it is worth printing only when the frame holds more than one of them. With one, it is
    /// noise that reads as a difference: the root of `map: what AscendLaunchpad talks to` said
    /// `AscendLaunchpad` and the same launchpad reached through `listingDesk.launchpad` said
    /// `launchpad (AscendLaunchpad)`, and nothing on the picture said they were one address.
    fn text_of(&self, id: &str) -> String {
        let text = box_text(id);
        let held = drawn_entity(id);
        // An ACCOUNT's brackets say `(address)`, which is not a contract in brackets and is the
        // whole point of that box: `to: the pool creator (address)` became `to: the pool
        // creator`, which reads as a contract by that name.
        if held.is_empty() || self.many.contains(held) || text.ends_with("(address)") {
            return text;
        }
        // `opexTreasury (Treasury)` → `Treasury`, and `to: opexTreasury (Treasury)` keeps its
        // role: it is the ROLE that makes a party box worth reading.
        match text.rsplit_once(" (") {
            Some((before, _)) => match before.rsplit_once(ROLE_MARK) {
                Some((role, _)) => format!("{role}{ROLE_MARK}{held}"),
                None => held.to_string(),
            },
            None => text,
        }
    }

    /// Whose frame this is, read back off its title.
    fn root(&self) -> &str {
        self.title
            .strip_prefix("map: what ")
            .and_then(|rest| rest.strip_suffix(" talks to"))
            .unwrap_or(&self.title)
    }

    /// Every contract drawn here, by its real name and once: a frame draws a contract twice on
    /// purpose, and for "where is this shown" the two copies are one frame.
    fn contracts_shown(&self) -> Vec<String> {
        let mut names: BTreeSet<&str> = BTreeSet::new();
        for node in &self.layout.nodes {
            if !is_outside(&node.id) {
                // The CONTRACT, not the box's id. A box is named after the variable holding it
                // and its id says so — `cohortTreasury%Treasury` — but what a reader asks for
                // is `Treasury`: it is the name they mark, and the name the board's own text
                // carries in its brackets. Writing the ids here meant `mark --apply` compared
                // `Treasury` against `cohortTreasury%Treasury` and matched only the handful of
                // contracts nothing holds in a variable: 13 of 154 boxes on one frame.
                names.insert(drawn_entity(&node.id));
            }
        }
        names.into_iter().map(str::to_string).collect()
    }

    /// One fill per interface this frame draws, by the order the names sort in — so the same
    /// frame drawn twice gives the same colours, and two interfaces never share one.
    fn outside_fills(edges: &[Edge]) -> BTreeMap<String, &'static str> {
        let names: BTreeSet<&str> = edges
            .iter()
            .filter(|edge| is_outside(&edge.to))
            .map(|edge| original_of(&edge.to))
            .collect();
        names
            .into_iter()
            .enumerate()
            .map(|(index, name)| {
                // Past the palette, grey: a ninth colour nobody can tell from the first is
                // worse than a box that plainly says "outside and not colour-coded".
                // Past the palette, BLACK. It used to fall back to a pale grey, which was a
                // fill colour and became an invisible label the moment this channel turned into
                // a border and a name: `IWrappedHype` was the ninth interface of a frame and
                // could not be read at all. A plain black dotted box still says "outside"; it
                // just does not say which one by colour.
                (name.to_string(), OUTSIDE_FILLS.get(index).copied().unwrap_or(BOX_BORDER))
            })
            .collect()
    }

    /// One border per contract this frame draws more than once, by the order the names sort in.
    fn repeat_borders(metadata: &EvmBatMetadata, edges: &[Edge]) -> BTreeMap<String, &'static str> {
        use crate::batbelt::evm::types::EvmContractType;
        // A CONTRACT of this repository, and nothing else. An interface already carries its own
        // colour in its name, an account is dashed, and a boundary box is one per caller — so
        // colouring those spent the palette on boxes that do not need it: ascend's biggest
        // frame had 28 repeated entities and only 7 of them were contracts.
        let deployable: BTreeSet<&str> = metadata
            .contracts
            .iter()
            .filter(|contract| {
                !contract.vendored && contract.contract_type == EvmContractType::Contract
            })
            .map(|contract| contract.name.as_str())
            .collect();
        // Count the distinct BOXES per contract: `Treasury` and `Treasury#2` are two, while two
        // arrows into the same box are one.
        let mut boxes: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for edge in edges {
            for id in [edge.from.as_str(), edge.to.as_str()] {
                // A DESTINATION is an entity drawn here like any other, and it is the box most
                // often repeated — `StakingFeeConverter` as a party under four different
                // methods. Its id starts with the interface the call went through, so reading
                // the name off the front counted them all as copies of `IERC20` and coloured
                // none of them.
                if (!is_outside(id) || destination_of(id).is_some())
                    && deployable.contains(drawn_entity(id))
                {
                    boxes.entry(addressed_as(id)).or_default().insert(id);
                }
            }
        }
        // `this (X)` is the box it hangs under. Which box that is cannot be known in general —
        // two deployments of X and the name says nothing — but it CAN be known when this frame
        // holds exactly one variable of that contract: then `this` is that address, and the
        // two names merge instead of reading as two things.
        let mut merged: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for (key, copies) in &boxes {
            let held = held_entity(key);
            // Any other name for that contract in this frame — a variable holding it, or the
            // contract's own box. `this (YieldRouter)` under the router's own subtree is the
            // router, and leaving the plain key out of the candidates split it into two colours.
            let variables: Vec<&&str> = boxes
                .keys()
                .filter(|other| held_entity(other) == held && !other.starts_with("this"))
                .collect();
            // The same for a box with NO variable at all: the frame's own root, or a cast the
            // code never named. `map --contract AscendLaunchpad` draws the launchpad as its
            // root and again as `listingDesk.launchpad`, and the two took different colours
            // while being one address — which is the thing the colour exists to say.
            let anonymous = key.starts_with("this") || !key.contains(VARIABLE_MARK);
            let under = match (anonymous, variables.as_slice()) {
                (true, [only]) => **only,
                _ => key,
            };
            merged.entry(under).or_default().extend(copies.iter().copied());
        }
        merged
            .into_iter()
            .filter(|(_, copies)| copies.len() > 1)
            .enumerate()
            .filter_map(|(index, (name, _))| {
                // Past the palette, the plain border: a seventeenth colour nobody can tell from
                // the first says less than saying nothing.
                REPEAT_BORDERS.get(index).map(|colour| (name.to_string(), *colour))
            })
            // A box looks its colour up under its OWN name, so every other name the merge
            // folded in has to carry it: `this (X)` and the bare contract alike.
            .flat_map(|(name, colour)| {
                let held = held_entity(&name).to_string();
                match name.contains(VARIABLE_MARK) {
                    true => vec![
                        (name, colour),
                        (format!("this{VARIABLE_MARK}{held}"), colour),
                        (held, colour),
                    ],
                    false => vec![(name, colour)],
                }
            })
            .collect()
    }

    /// The border a box of this frame gets, and how thick: its contract's own colour, drawn
    /// thick enough to read at the zoom where the frame fits, when that contract is drawn here
    /// more than once — and the plain thin one otherwise.
    fn border_of(&self, id: &str) -> (&'static str, usize) {
        // A PARTY hangs off an outside box, so its id carries the `@` — and reading that as
        // "this is the outside" sent it back with the plain border while the contract it names
        // stood beside it in colour. The two are one address; they carry one colour.
        if is_outside(id) && destination_of(id).is_none() {
            return (BOX_BORDER, BORDER_WIDTH);
        }
        match self.borders.get(addressed_as(id)) {
            Some(colour) => (colour, REPEAT_BORDER_WIDTH),
            None => (BOX_BORDER, BORDER_WIDTH),
        }
    }

    /// How a box is painted: its fill, its text colour and whether its border is dotted.
    ///
    /// Three channels, one meaning each, and the loudest goes to what the reader asked for:
    ///
    /// - a MARKED contract gets the FILL, because a background is what carries at the zoom where
    ///   a whole frame fits — a border does not, which the cards and the repeat borders both
    ///   proved;
    /// - an OUTSIDE leaf gives up the fill and takes a dotted border with its name in the
    ///   interface's colour: it is read once the reader has found the contract that calls it, so
    ///   it can afford the quieter channel, and the coloured text still ties its copies together;
    /// - a contract drawn TWICE keeps its solid coloured border (see `border_of`).
    fn paint_of(&self, id: &str, marked: &BTreeSet<String>) -> (&'static str, &'static str, &'static str) {
        // A destination is an ENTITY, not a type the caller declared: it is drawn like a
        // contract, in black, at a contract's size. The one it carries an address for and
        // nobody has named is dashed — the map's own stroke for a question.
        if let Some(to) = destination_of(id) {
            if to.ends_with(ADDRESS_MARK) {
                return (BOX_FILL, BOX_BORDER, "dashed");
            }
            if marked.contains(entity_named(to)) {
                return (MARK_FILL, BOX_BORDER, "normal");
            }
            return (BOX_FILL, BOX_BORDER, "normal");
        }
        if is_outside(id) {
            let colour = self.fills.get(original_of(id)).copied().unwrap_or(BOX_BORDER);
            return (BOX_FILL, colour, "dotted");
        }
        if marked.contains(original_of(id)) {
            return (MARK_FILL, BOX_BORDER, "normal");
        }
        (BOX_FILL, BOX_BORDER, "normal")
    }

    /// Boxes this frame draws that are not its laid-out contracts: the legend's rows and the
    /// strip.
    fn boxes_of_its_own(&self) -> usize {
        self.strip.len() + if self.is_legend() { LEGEND_ROWS } else { 0 }
    }

    /// Is this the legend's frame? It carries no relations of its own.
    fn is_legend(&self) -> bool {
        self.edges.is_empty()
    }
}

impl PreparedMap {
    /// How many drawn relations run against the hierarchy — the red arrows.
    fn backwards(&self) -> usize {
        self.frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .filter(|arrow| arrow.edge.is_some() && arrow.style.stroke_color == CYCLE_COLOUR)
            .count()
    }

    /// Keep only the frame of one contract, and the legend.
    ///
    /// The frames were all measured, which costs nothing but arithmetic; what is expensive is
    /// drawing them, and that is what this prevents. The block is repacked, so a single frame
    /// opens where a single frame belongs rather than in the corner of a block-sized hole.
    pub fn keep_only(&mut self, contract: &str) -> Result<(), EvmMiroError> {
        let wanted = frame_title(contract);
        if !self.frames.iter().any(|frame| frame.title == wanted) {
            let known: Vec<&str> = self
                .frames
                .iter()
                .filter(|frame| !frame.is_legend())
                .filter_map(|frame| frame.title.strip_prefix("map: what "))
                .filter_map(|rest| rest.strip_suffix(" talks to"))
                .collect();
            return Err(Report::new(EvmMiroError)
                .attach_printable(format!(
                    "no frame for `{contract}`: no relation of this map leaves it"
                ))
                .attach_printable(format!("the map has frames for: {}", known.join(", "))));
        }
        self.frames.retain(|frame| frame.title == wanted || frame.is_legend());
        pack_frames(&mut self.frames);
        self.width = self.frames.iter().map(|frame| frame.left + frame.width).fold(0.0, f64::max);
        self.height = self.frames.iter().map(|frame| frame.top + frame.height).fold(0.0, f64::max);
        self.calls = ApiCalls {
            frames: self.frames.len(),
            boxes: self
                .frames
                .iter()
                .map(|frame| frame.layout.nodes.len() + frame.boxes_of_its_own())
                .sum(),
            markers: self
                .frames
                .iter()
                .flat_map(|frame| frame.arrows.iter())
                .map(|arrow| arrow.plan.points.len())
                .sum(),
            connectors: self
                .frames
                .iter()
                .flat_map(|frame| frame.arrows.iter())
                .map(|arrow| arrow.plan.legs.len())
                .sum(),
        };
        Ok(())
    }

    /// Nothing is rendered any more, so there is nothing to throw away — kept so a dry run and
    /// a failure path read the same as the deploy's.
    pub fn discard(&self) {}

    /// What a real run would cost, in the terminal, before it costs it.
    /// Every frame as an indented TREE of what it draws: the picture, in words.
    ///
    /// A preview PNG cannot carry the names — a map is thirty thousand board units wide and a
    /// name comes out three pixels tall — so the only way to check that a leaf has the children
    /// it should is to read them. This is that reading: one line per box, indented under the box
    /// that points at it, with what the arrow means when it is not a plain call.
    pub fn tree(&self) -> Vec<String> {
        let mut lines = Vec::new();
        for frame in &self.frames {
            if frame.is_legend() {
                continue;
            }
            lines.push(String::new());
            lines.push(frame.title.clone());
            let mut children: BTreeMap<&str, Vec<&Edge>> = BTreeMap::new();
            for edge in &frame.edges {
                children.entry(edge.from.as_str()).or_default().push(edge);
            }
            let mut walked: BTreeSet<&str> = BTreeSet::new();
            // The path from the root, so a box that comes round again can say WHICH kind of
            // again it is: on the path is a cycle, anywhere else is the one box two branches
            // share. `rejoin` makes the second kind on purpose, and calling it a cycle told
            // the reader the system loops where it does not.
            let mut path: Vec<&str> = Vec::new();
            let mut stack: Vec<(&str, usize, Option<Relation>)> =
                vec![(frame.root.as_str(), 0, None)];
            while let Some((id, depth, relation)) = stack.pop() {
                path.truncate(depth);
                let note = match relation {
                    Some(Relation::Creates) => "  (creates)",
                    // Not "never called": value reaches it as a PARTY of somebody else's
                    // call — `AscendLaunchpad` pays six treasuries it never calls a method on.
                    Some(Relation::WiresAtConstruction) => "  (wired at construction)",
                    Some(Relation::Unresolved) => "  (unresolved binding)",
                    // The tree stops under a read, and without the word it read as an ordinary
                    // call whose callee happens to do nothing.
                    Some(Relation::Reads) => "  (reads)",
                    _ => "",
                };
                // A back edge closes a cycle: printed where it lands, said so, and not
                // followed, or the walk would never end.
                let seen = !walked.insert(id);
                // An ECHO is read off the frame, not off this walk: the walk's order is not the
                // layout's, so "the one I met second" marked whichever branch happened to come
                // first here and left the cut one looking like a contract that calls nothing.
                let note = match path.contains(&id) {
                    true => "  (again — a cycle)",
                    false => note,
                };
                path.push(id);
                lines.push(format!(
                    "{:indent$}{}{note}",
                    "",
                    frame.text_of(id),
                    indent = depth * 2 + 2
                ));
                if seen {
                    continue;
                }
                let mut below = children.get(id).cloned().unwrap_or_default();
                below.sort_by(|a, b| b.to.cmp(&a.to));
                for edge in below {
                    stack.push((edge.to.as_str(), depth + 1, Some(edge.relation)));
                }
            }
        }
        lines
    }

    pub fn estimate(&self) -> Vec<String> {
        let mut lines = vec![format!(
            "{} frame(s), {} box(es), {} relation(s) ({} backwards), {} crossing(s) left, {} arrow(s) over a box",
            self.frames.len(),
            self.calls.boxes,
            self.edges.len(),
            self.backwards(),
            self.frames.iter().map(|frame| frame.crossings).sum::<usize>(),
            self.frames.iter().map(|frame| frame.over_boxes).sum::<usize>(),
        )];
        // Per frame, because "which frame is still a mesh" is the question a total cannot
        // answer, and the only one worth asking of a map that has been redrawn five times.
        for frame in &self.frames {
            if frame.is_legend() {
                continue;
            }
            lines.push(format!(
                "  {:<46} {} box(es), {} relation(s), {} crossing(s), {} over a box",
                frame.title,
                frame.layout.nodes.len(),
                frame.edges.len(),
                frame.crossings,
                frame.over_boxes
            ));
        }
        // An arrow whose chain collapsed draws NOTHING: a relation the report counts and the
        // board does not show, which is the worst kind of missing — nobody looks for a line
        // that was never promised. Counted here so a redraw cannot hide one.
        let mute: Vec<String> = self
            .frames
            .iter()
            .flat_map(|frame| frame.arrows.iter().map(move |arrow| (frame, arrow)))
            .filter(|(_, arrow)| arrow.edge.is_some() && arrow.plan.legs.is_empty())
            .map(|(frame, arrow)| format!("  {}: {}", frame.title, arrow_name(frame, arrow)))
            .collect();
        if !mute.is_empty() {
            lines.push(format!("{} relation(s) with no leg to draw:", mute.len()));
            lines.extend(mute);
        }
        lines.push(format!(
            "block: {} × {} board units — {} frames + {} boxes + {} markers + {} connectors = {} writes in {} request(s)",
            self.width.round(),
            self.height.round(),
            self.calls.frames,
            self.calls.boxes,
            self.calls.markers,
            self.calls.connectors,
            self.calls.total(),
            self.calls.requests()
        ));
        lines.push(format!(
            "       {:.1}s at the {} writes a second this paces itself to, if nothing else limits it",
            self.calls.seconds_at_the_ceiling(),
            crate::batbelt::miro::client::WRITES_PER_SECOND
        ));
        lines.push("placement: needs the board, which a dry run does not read".to_string());
        lines
    }
}

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

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

    /// The REQUESTS those writes become, which is a smaller number than the writes.
    ///
    /// Boxes and markers go through `/items/bulk`, twenty to a call; a frame and a connector go
    /// one at a time, because bulk takes items only. 290 boxes and 1 044 markers are 1 334
    /// things to create and 67 requests to create them with — and printing the first number as
    /// "API calls" said 2 103 where the run sent 899.
    pub fn requests(&self) -> usize {
        self.frames + self.connectors + (self.boxes + self.markers).div_ceil(ITEMS_PER_CALL)
    }

    /// 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 {
        // The rate the client actually paces itself at, not a number written here as well: an
        // estimate quoting a ceiling the code no longer uses is an estimate that drifts.
        self.total() as f64 / crate::batbelt::miro::client::WRITES_PER_SECOND
    }
}

/// The two ends of the hierarchy, as lines for the terminal.
///
/// A TOP CALLER is a contract nothing in scope depends on: where a reader starts, and what the
/// map makes a frame for. A FOUNDATION is one that depends on nothing: what has to exist before
/// any of the others, which is the order the board reads left to right.
///
/// Neither is in the file tree, and neither is a guess — both fall straight out of the
/// relations.
pub fn hierarchy(metadata: &EvmBatMetadata, all: &[Edge], no_boundaries: bool) -> Vec<String> {
    // The TOP CALLERS are read off the same edges the map frames, so the list and the frames
    // cannot disagree: a contract whose only relation leaves the repository is still a contract
    // nothing in scope depends on, and it still gets a frame.
    let framed = drawn_edges(metadata, all, no_boundaries);
    // The FOUNDATIONS are read off this repository's own relations: what leaves the code is a
    // leaf of whoever calls it, never a rung of the hierarchy, and listing `IERC20` as
    // something "everything else needs" said nothing true about the system.
    let edges: Vec<Edge> = all
        .iter()
        .filter(|edge| edge.relation != Relation::Boundary)
        .cloned()
        .collect();
    let names: BTreeSet<&str> = edges
        .iter()
        .flat_map(|edge| [held_entity(&edge.from), held_entity(&edge.to)])
        .collect();
    // By ENTITY, like the frames: `vault%AscendYieldVault` is the vault, and reading these off
    // the raw ids made every contract reached only through a variable look like a top caller.
    let called: BTreeSet<&str> = edges.iter().map(|edge| held_entity(&edge.to)).collect();
    let calls: BTreeSet<&str> = edges.iter().map(|edge| held_entity(&edge.from)).collect();
    let out = |name: &str| edges.iter().filter(|edge| held_entity(&edge.from) == name).count();
    let into = |name: &str| edges.iter().filter(|edge| held_entity(&edge.to) == name).count();

    let framed_names: BTreeSet<&str> = framed.iter().map(|edge| held_entity(&edge.from)).collect();
    let framed_called: BTreeSet<&str> = framed.iter().map(|edge| held_entity(&edge.to)).collect();
    let mut tops: Vec<&str> = framed_names
        .iter()
        .copied()
        .filter(|name| !framed_called.contains(name))
        .collect();
    tops.sort_by(|a, b| out(b).cmp(&out(a)).then(a.cmp(b)));
    let mut foundations: Vec<&str> = names.iter().copied().filter(|n| !calls.contains(n)).collect();
    foundations.sort_by(|a, b| into(b).cmp(&into(a)).then(a.cmp(b)));

    let mut lines = vec![format!(
        "{} top caller(s) — nothing in scope depends on them, and the map gives each one a frame:",
        tops.len()
    )];
    for name in &tops {
        lines.push(format!("  {name:<28} talks to {} contract(s)   bat-cli map --contract {name}", out(name)));
    }
    lines.push(String::new());
    lines.push(format!(
        "{} foundation(s) — they depend on nothing, so they exist before the rest:",
        foundations.len()
    ));
    for name in &foundations {
        lines.push(format!("  {name:<28} {} contract(s) depend on it", into(name)));
    }
    lines
}

/// Split the whole graph into one frame per TOP CALLER, the way a deployment is one frame per
/// entry point.
///
/// Sixteen contracts and twenty relations on one frame is a mesh whichever way it is laid out,
/// and no amount of colour fixes it: the reader cannot follow a single arrow. The entry-point
/// diagrams hit this years ago and the answer there (`docs/diagram-deploy-design.md` §4) was to
/// partition and REPEAT — a callee drawn in two frames is drawn twice on purpose, because a
/// repeated box is cheap and a crossing arrow is not.
///
/// A top caller is a contract nothing in scope depends on: the place a reader starts. Its
/// frame holds everything it reaches, so the frame answers one question — "what does this
/// contract talk to" — and a contract everyone uses appears in each frame that uses it.
///
/// Anything left over (a cycle nothing points into) gets a frame of its own rather than being
/// dropped, picked by the contract with the most relations.
fn partition_frames(edges: &[Edge], asked_for: Option<&str>) -> Vec<FramePlan> {
    let names: BTreeSet<&str> = edges
        .iter()
        .flat_map(|edge| [edge.from.as_str(), edge.to.as_str()])
        .collect();
    // By ENTITY: `vault%AscendYieldVault` is the vault, so the vault is not a contract nothing
    // points at, and it does not deserve a frame of its own. Reading this off the ids turned six
    // frames into thirteen the moment a box could be named after the variable holding it.
    // Who something in scope DEPENDS on — which a destination does not say. `to: this` is a
    // contract paying itself, and `to: burnSink` is an address being handed over, not a call:
    // counting them cost `AscendCtoRegistry` and `ReferralPot` their place as top callers,
    // each because of one `safeTransferFrom(…, address(this))`. They were then picked up by
    // the leftover loop, which is the same frames in a worse order. `--hierarchy` was already
    // right about this — it drops the boundary relations before it looks — and the two
    // answers disagreeing is how the difference stayed invisible.
    let called: BTreeSet<&str> = edges
        .iter()
        .filter(|edge| destination_of(&edge.to).is_none())
        .map(|edge| held_entity(&edge.to))
        .collect();
    let out_degree = |name: &str| edges.iter().filter(|edge| edge.from == name).count();
    // How many relations a frame rooted here would DRAW — the transitive closure, not the
    // relations leaving this contract. They pick different roots and the difference showed:
    // `AscendLaunchpad` has thirteen relations of its own and `AscendCtoRegistry` has three,
    // but the registry's frame reaches the launchpad's whole system, so choosing by out-degree
    // gave the launchpad its frame first, then the receiver's, and the registry then drew both
    // of them again — ninety-one boxes of a frame that was entirely inside another one.
    let reaches = |name: &str| {
        let mut seen: BTreeSet<&str> = [held_entity(name)].into_iter().collect();
        let mut walking = vec![held_entity(name)];
        let mut relations = 0;
        while let Some(at) = walking.pop() {
            for edge in edges.iter().filter(|edge| edge.from == at) {
                relations += 1;
                if seen.insert(held_entity(&edge.to)) {
                    walking.push(held_entity(&edge.to));
                }
            }
        }
        relations
    };
    let mut roots: Vec<String> = names
        .iter()
        .copied()
        .filter(|name| !called.contains(held_entity(name)))
        .map(str::to_string)
        .collect();
    // Deterministic, and the busiest first so the frame a reader opens first says the most.
    roots.sort_by(|a, b| out_degree(b).cmp(&out_degree(a)).then(a.cmp(b)));

    let mut frames: Vec<FramePlan> = Vec::new();
    let mut covered: BTreeSet<(String, String)> = BTreeSet::new();
    let mut plan = |root: &str, frames: &mut Vec<FramePlan>, covered: &mut BTreeSet<(String, String)>| {
        let mine = rejoin(unfold(root, edges), root);
        for edge in &mine {
            covered.insert((
                held_entity(original_of(&edge.from)).to_string(),
                held_entity(original_of(&edge.to)).to_string(),
            ));
        }
        if !mine.is_empty() {
            frames.push(FramePlan { root: root.to_string(), edges: mine });
        }
    };
    for root in &roots {
        plan(root, &mut frames, &mut covered);
    }
    // A cycle with nothing above it has no top caller, and is every bit as much part of the
    // system: it gets a frame of its own rather than being dropped. `StakingFeeConverter` is
    // one — `StakingFeeTreasury` calls back into it, so nothing in scope sits above it.
    let mut tried: BTreeSet<String> = roots.iter().cloned().collect();
    // Compared by ORIGINAL name on both ends, because a drawn edge carries the id of a copy
    // (`IERC20@YieldRouter`, `Treasury#2`) and the raw relation carries the name. Comparing the
    // two made every call that leaves the repository look undrawn, and every contract that
    // makes one became a root of its own: fourteen frames for five systems.
    while let Some(orphan) = edges
        .iter()
        .filter(|edge| {
            !covered.contains(&(
                held_entity(original_of(&edge.from)).to_string(),
                held_entity(original_of(&edge.to)).to_string(),
            ))
        })
        // The CONTRACT, not the box: `IStakingSwapRouter@StakingFeeConverter` is that
        // converter's own copy of an interface, and choosing by reach handed it a frame of
        // its own titled after a copy. A frame is rooted at something a reader can open.
        .map(|edge| held_entity(original_of(&edge.from)).to_string())
        // Every contract whose own relations are still undrawn is a candidate, and already
        // being somebody's root disqualifies it, or the loop re-roots the same contract for
        // ever. Among the rest the root is THE ONE THAT CALLS THE MOST, not the first one the
        // relations happen to list: a cycle has no top caller, so some member has to be picked,
        // and the member with the most outgoing relations is the one whose frame tells the most
        // of the story. Ties go to the name, so the same system always draws the same frames.
        .filter(|name| !tried.contains(name))
        .max_by(|a, b| reaches(a).cmp(&reaches(b)).then_with(|| b.cmp(a)))
    {
        tried.insert(orphan.clone());
        plan(&orphan, &mut frames, &mut covered);
    }

    // And whatever the reader ASKED for, even when nothing above would have given it a frame.
    //
    // The frames are one per top caller plus whatever they did not cover, which is the right
    // set to draw by default — but it is not the set a reader is allowed to ask about.
    // `AscendLaunchpad` is drawn inside `AscendCtoRegistry`'s frame, two levels down and
    // surrounded by what the registry does; "show me the launchpad on its own" is a fair
    // question and the answer was "it is not a top caller". The walk starts anywhere, so it
    // starts here too.
    if let Some(wanted) = asked_for {
        let is_drawn = frames.iter().any(|frame| frame.root == wanted);
        let exists = edges
            .iter()
            .any(|edge| held_entity(original_of(&edge.from)) == wanted);
        if !is_drawn && exists {
            let mine = rejoin(unfold(wanted, edges), wanted);
            if !mine.is_empty() {
                frames.push(FramePlan { root: wanted.to_string(), edges: mine });
            }
        }
    }
    frames
}


/// A frame is a TREE: everything its contract reaches, with anything shared DRAWN AGAIN rather
/// than pointed at from two places.
///
/// The rule this replaced cut a contract two frames both reached into a frame of its own and
/// left a card behind. It optimised the right thing — no box drawn twice — and the wrong goal:
/// `ListingDesk` is an intermediate contract, not a system worth opening on its own, and a
/// reader asking what `AscendCtoRegistry` does was sent through three frames to find out. Fewer
/// frames, each self-contained, is worth more than fewer boxes.
///
/// Unfolding a shared graph into a tree is also what makes a frame readable with no localizing
/// machinery at all: nothing is shared, so nothing can cross. It can in principle blow up — a
/// diamond is drawn twice, a diamond of diamonds four times — so it is bounded. On the systems
/// this is pointed at today (16 contracts, 20 relations) it does not come close; when it does,
/// that is the moment to start recycling a box, which is intense logic for a problem nobody has.
fn unfold(root: &str, edges: &[Edge]) -> Vec<Edge> {
    /// Enough for any audit this has been pointed at, and a wall rather than a hang.
    const MAX_BOXES: usize = 400;

    let mut drawn: Vec<Edge> = Vec::new();
    let mut copies: BTreeMap<String, usize> = [(root.to_string(), 1)].into_iter().collect();
    // (name, the id of the copy being expanded): the path from the root, which is what tells a
    // cycle from a share — a node already on the path is a loop, one seen anywhere else is not.
    let mut path: Vec<(String, String)> = vec![(root.to_string(), root.to_string())];
    // An explicit stack of (depth, which child is next), because the recursion depth here is the
    // audit's own call depth and a frame is not worth a blown stack.
    let mut stack: Vec<(usize, usize)> = vec![(0, 0)];

    while let Some((depth, next)) = stack.pop() {
        let (name, id) = path[depth].clone();
        // What a box calls is a property of the CONTRACT, and a box may be named after the
        // variable holding it — `opexTreasury%Treasury` calls whatever `Treasury` calls. The
        // caller's own copy of an outside box (`IERC20@YieldRouter`) keeps its id: its children
        // are that caller's methods and nobody else's.
        let from = held_entity(&name);
        // A DESTINATION is a leaf: it says where this call's value went, and the box it names
        // has its own place on the map. Expanding it drew `StakerDistributor`'s whole subtree
        // under an `approve()` leaf.
        let outgoing: Vec<&Edge> = match destination_of(&name).is_some() {
            true => Vec::new(),
            false => edges.iter().filter(|edge| edge.from == from).collect(),
        };
        let Some(edge) = outgoing.get(next) else {
            path.truncate(depth + 1);
            continue;
        };
        stack.push((depth, next + 1));
        // A DESTINATION is a leaf that says who this call pays, not a step in the walk: it
        // never closes a cycle. Treated as one, `approve()`'s party came out as the ancestor's
        // box — `StakingFeeConverter (again — a cycle)` — with the role it fills thrown away.
        let continues = destination_of(&edge.to).is_none();
        if let Some((_, ancestor)) = path
            .iter()
            .take(depth + 1)
            // By the box's own name, minus the copy number: two DEPLOYMENTS of one contract
            // calling each other (`opexTreasury → kntqTreasury`) are not a cycle, and reading
            // them by type said they were — the second one's whole subtree went undrawn.
            .find(|(on_path, _)| {
                continues && same_box(on_path) == same_box(&edge.to)
            })
        {
            // Back to something this path came through: a cycle, drawn as the one red arrow
            // rather than unfolded for ever.
            drawn.push(Edge { from: id, to: ancestor.clone(), relation: edge.relation });
            continue;
        }
        if copies.values().sum::<usize>() >= MAX_BOXES {
            continue;
        }
        // `this (X)` is the box whose subtree this leaf hangs in — which the walk knows and a
        // name cannot: a frame with seven `Treasury`s has seven `this`, one per subtree. The
        // nearest ancestor of that contract is the answer, so the party and the box it belongs
        // to read as one address instead of the party standing alone.
        let landed = match edge.to.split_once(&format!("this{VARIABLE_MARK}")) {
            Some((before, held)) => {
                let held = held.split(COPY_MARK).next().unwrap_or(held);
                match path
                    .iter()
                    .take(depth + 1)
                    .rev()
                    .find(|(on_path, _)| held_entity(on_path) == held)
                {
                    Some((named, _)) => format!("{before}{named}"),
                    None => edge.to.clone(),
                }
            }
            None => edge.to.clone(),
        };
        let edge = &Edge { from: edge.from.clone(), to: landed, relation: edge.relation };
        let seen = copies.entry(edge.to.clone()).or_insert(0);
        *seen += 1;
        let child = if *seen == 1 {
            edge.to.clone()
        } else {
            format!("{}{COPY_MARK}{}", edge.to, seen)
        };
        drawn.push(Edge { from: id, to: child.clone(), relation: edge.relation });
        // A READ is where the walk stops. The relation is real — this contract asks that one a
        // question — but nothing the far contract does on its own follows from it, and hanging
        // its whole subtree here drew a graph the caller cannot set off. `YieldRouter` reaches
        // `AscendLaunchpad` through two getters and was given the launchpad's every branch.
        // A READ and a WIRING both say the two are connected and neither says this contract
        // sets the other one off. Drawing the far contract's whole subtree under either was a
        // graph of things that cannot happen from here.
        if matches!(edge.relation, Relation::Reads | Relation::WiresAtConstruction) {
            path.truncate(depth + 1);
            continue;
        }
        path.truncate(depth + 1);
        path.push((edge.to.clone(), child));
        stack.push((depth + 1, 0));
    }
    drawn
}

/// Two branches reaching the SAME ENTITY are drawn as two arrows into one box.
///
/// `unfold` makes a tree, so nothing is shared and nothing can cross. That is the right default
/// for a leaf — a shared `IERC20` pulled seven long arrows across a frame, which is why the
/// unfolding exists. It is the wrong default for a SUBTREE: `AscendCtoRegistry` creates
/// `AscendCtoReceiver`, both of them call `launchpad`, and the launchpad's hundred-odd boxes
/// were drawn twice in one frame. The reader cannot tell a second launchpad from the same one.
///
/// And what the merge says is the thing the duplicate hides: these two contracts talk to ONE
/// address. Which is why it merges by entity and not by type — `launchpad%AscendLaunchpad` is
/// not any `AscendLaunchpad`, it is that deployment, the same key the repeated-border colour
/// is keyed by.
///
/// Three conditions, and the first is the one that keeps small things duplicated:
/// - the subtree saved is at least `WORTH_SHARING` boxes — sharing a leaf only lengthens arrows;
/// - the copy is not inside the keeper's own subtree, or the merge would close a cycle;
/// - the keeper is the copy with the MOST below it, so the branch that is kept is the full one.
///
/// The layout needs no tree: `layout_graph` assigns a layer by the LONGEST path, so a box with
/// two parents lands below both of them, and it reports the crossings it ended up with.
fn rejoin(drawn: Vec<Edge>, root: &str) -> Vec<Edge> {
    /// Below this, saying "already drawn" costs more than drawing it.
    ///
    /// It was 8 while the second mention was MERGED into the first, because sharing a box pulls
    /// an arrow across the frame and a long arrow for two saved boxes is a bad trade. Cutting
    /// the subtree instead costs no arrow at all — the box stays where its own branch puts it —
    /// so the only question left is whether the words "already drawn" are shorter than what
    /// they replace. Two boxes are.
    const WORTH_SHARING: usize = 2;

    let mut children: BTreeMap<String, Vec<usize>> = BTreeMap::new();
    for (at, edge) in drawn.iter().enumerate() {
        children.entry(edge.from.clone()).or_default().push(at);
    }
    // How many boxes hang below each one, and who is below whom. Both are read off the tree,
    // which has no cycles, so a plain walk settles it.
    let subtree = |id: &str| -> BTreeSet<String> {
        let mut below = BTreeSet::new();
        let mut walking = vec![id.to_string()];
        while let Some(at) = walking.pop() {
            for edge in children.get(&at).into_iter().flatten().map(|at| &drawn[*at]) {
                if below.insert(edge.to.clone()) {
                    walking.push(edge.to.clone());
                }
            }
        }
        below
    };
    // Which entity a box stands for, for the purpose of grouping its copies.
    //
    // The box's own name minus the copy number — EXCEPT that the frame's root is the same
    // entity as any box named after a variable holding it. A frame titled "what AscendLaunchpad
    // talks to" has the launchpad as its root, and `listingDesk.launchpad` is that launchpad:
    // the ids read `AscendLaunchpad` and `launchpad%AscendLaunchpad`, which share no prefix, so
    // the launchpad's entire system was drawn a second time inside its own frame.
    //
    // Only against the ROOT, and only inside that root's frame. Two variables of one type are
    // two addresses — six `Treasury`s are six — and nothing here says which of them a bare
    // `Treasury` would be. The root is the one box whose identity the frame itself asserts.
    let identity = |id: &str| -> String {
        match drawn_entity(id) == drawn_entity(root) {
            true => drawn_entity(root).to_string(),
            false => same_box(id).to_string(),
        }
    };

    // What a subtree SAYS, as relations between entities rather than between box ids. A merge
    // is only allowed when everything the copy says is said by the box that stays — otherwise
    // the picture loses a relation, which is the one thing a map may never do to save room.
    let says = |id: &str| -> BTreeSet<(String, String)> {
        let mut said = BTreeSet::new();
        let mut walking = vec![id.to_string()];
        let mut walked: BTreeSet<String> = [id.to_string()].into_iter().collect();
        while let Some(at) = walking.pop() {
            for edge in children.get(&at).into_iter().flatten().map(|at| &drawn[*at]) {
                said.insert((identity(&edge.from), identity(&edge.to)));
                if walked.insert(edge.to.clone()) {
                    walking.push(edge.to.clone());
                }
            }
        }
        said
    };

    // The copies of one entity. The ROOT is put in first: it is never the far end of an arrow,
    // so reading the boxes off the arrows' destinations leaves it out of its own group — and
    // then the copy of it further down has nobody to be a copy OF.
    let mut copies: BTreeMap<String, Vec<String>> = BTreeMap::new();
    copies.insert(identity(root), vec![root.to_string()]);
    for edge in &drawn {
        let group = copies.entry(identity(&edge.to)).or_default();
        if !group.contains(&edge.to) {
            group.push(edge.to.clone());
        }
    }

    // How far from the root each box sits: which copy keeps its subtree is decided by this, so
    // the full version is the one a reader meets first and every later mention points back.
    let mut depth: BTreeMap<&str, usize> = [(root, 0usize)].into_iter().collect();
    let mut walking = vec![root];
    while let Some(at) = walking.pop() {
        let here = depth.get(at).copied().unwrap_or(0);
        for edge in children.get(at).into_iter().flatten().map(|at| &drawn[*at]) {
            if !depth.contains_key(edge.to.as_str()) {
                depth.insert(edge.to.as_str(), here + 1);
                walking.push(edge.to.as_str());
            }
        }
    }

    // Who each copy is redirected to. Built first, applied after, so a merge never reads a
    // subtree another merge has already moved.
    let mut keeper: BTreeMap<String, String> = BTreeMap::new();
    let mut dropped: BTreeSet<String> = BTreeSet::new();
    for (_, group) in copies.iter().filter(|(_, group)| group.len() > 1) {
        let sizes: BTreeMap<&String, BTreeSet<String>> =
            group.iter().map(|id| (id, subtree(id))).collect();
        let Some(keep) = group
            .iter()
            // Nearest the root first, so the full version is the one met first and every later
            // mention says "already drawn" about something above it. Then the fullest, then the
            // name, so the same system always draws the same frame.
            .min_by(|a, b| {
                depth
                    .get(a.as_str())
                    .unwrap_or(&usize::MAX)
                    .cmp(depth.get(b.as_str()).unwrap_or(&usize::MAX))
                    .then_with(|| sizes[b].len().cmp(&sizes[a].len()))
                    .then_with(|| a.cmp(b))
            })
        else {
            continue;
        };
        if sizes[keep].len() < WORTH_SHARING {
            continue;
        }
        let kept_says = says(keep);
        for copy in group.iter().filter(|id| *id != keep) {
            // What must not happen is cutting the branch the KEEPER is on: everything below the
            // copy goes, and if the keeper is down there it goes with it.
            //
            // This used to be the other way round — a copy inside the keeper's reach was
            // skipped — which was right while the second mention was MERGED into the first,
            // because that would have closed a loop. Cutting a subtree closes nothing, and the
            // old test excluded the frame's own root from ever keeping anything, since every
            // box is inside the root's reach. That is how a frame titled "what AscendLaunchpad
            // talks to" drew the launchpad's whole system a second time.
            if sizes[copy].contains(keep) || copy.as_str() == root {
                continue;
            }
            // And a copy that reaches somewhere the keeper does not keeps its own branch:
            // framing cuts a subtree differently in two places, and the fuller of the two is
            // not always the one with more boxes in it.
            if !says(copy).is_subset(&kept_says) {
                continue;
            }
            keeper.insert(copy.clone(), keep.clone());
            dropped.insert(copy.clone());
            dropped.extend(sizes[copy].iter().cloned());
        }
    }
    if keeper.is_empty() {
        return drawn;
    }
    // A box below a merged copy is reachable from the keeper too, so only the ones that are
    // NOT are really gone. Keeping that distinction is what stops the merge from deleting a
    // branch the keeper never had.
    let kept: BTreeSet<String> = keeper
        .values()
        .flat_map(|keep| subtree(keep).into_iter().chain([keep.clone()]))
        .collect();

    // A merge that would run BACKWARDS is not made.
    //
    // The layout lays a frame out in the order the walk reached things, so when the branch that
    // keeps the box comes after the branch that loses it, the arrow into the shared box points
    // back up the frame — and an arrow that runs backwards is drawn red, which the legend reads
    // as "a cycle". The map was then claiming a loop where there is only a shortcut: on
    // `AscendLaunchpad`'s frame a shared `safeTransfer()` came out as a long red line to a box
    // three screens above it.
    if keeper.is_empty() {
        return drawn;
    }

    // The copy KEEPS ITS BOX and loses its subtree.
    //
    // Three ways to draw the same entity reached twice, and this is the third. Drawing it in
    // full twice is a frame that says one thing twice — the launchpad's hundred-odd boxes, over
    // again. Pointing the second arrow at the first box shares it, but the shared box is
    // wherever the first branch put it, and an arrow that does not move right is drawn red,
    // which the legend reads as a cycle: the map then claims a loop that is not there.
    //
    // So: the box stays where its own branch puts it, and what hangs off it does not. The
    // reader sees that the branch reaches that contract, sees its name, and is told the rest is
    // drawn above rather than being shown it again. It costs one box instead of a hundred and
    // it invents no arrow at all.
    //
    // Which is only possible because a box is an ENTITY — `launchpad%AscendLaunchpad` is that
    // deployment. "Already drawn" about a type would be a lie the moment a system holds six
    // deployments of one contract, which is the normal case here.
    let mut rejoined: Vec<Edge> = Vec::new();
    for edge in drawn {
        // Under a copy whose subtree is cut: gone, unless it hangs off the keeper too.
        if dropped.contains(&edge.from) && !kept.contains(&edge.from) {
            continue;
        }
        // The copy's own box is kept; only what it points AT is cut.
        if keeper.contains_key(&edge.from) {
            continue;
        }
        rejoined.push(edge);
    }
    // And each cut copy points at ONE leaf saying where the rest went.
    //
    // As a leaf and not as a second line inside the box, so every box that stands for a
    // contract looks like every other one — same size, same shape, the name and nothing else.
    // A note written into the box made it wider than its neighbours and, when the name was
    // long, pushed the words out past the border.
    for copy in keeper.keys().filter(|id| {
        // Only off a box that COULD have had children. A destination says who was paid and a
        // method leaf is a call; neither has a subtree to have lost, and hanging the note on
        // one put the box's raw id into the picture.
        destination_of(id).is_none() && method_of(id).is_none()
    }) {
        rejoined.push(Edge {
            from: copy.clone(),
            to: format!("{copy}{DESTINATION_MARK}{DRAWN_ELSEWHERE}"),
            relation: Relation::Calls,
        });
    }
    rejoined
}

/// What the leaf under a cut copy says.
const DRAWN_ELSEWHERE: &str = "drawn in this frame";


/// How many times an arrow runs ACROSS a box it has nothing to do with.
///
/// `crossings` counts arrows crossing each OTHER, and a frame can score zero on it while a line
/// runs straight through a contract's name — which is what `AscendCtoRegistry`'s arrow did to
/// `AscendCtoReceiver`. A certificate that says "0 crossings" over a picture with a line
/// through a box is a certificate measuring the wrong thing, so this is the second number.
///
/// Measured off the arrow's own corners, which are the turns it will actually be drawn with:
/// every segment between two consecutive points, against every box that is not one of its two
/// ends. A box is hit when the segment passes through its rectangle, with a small inset so an
/// arrow that lands exactly on a border does not count as running over it.
fn arrows_over_boxes(arrows: &[RoutedArrow], edges: &[Edge], layout: &GraphLayout) -> usize {
    use crate::batbelt::evm::miro::auto_deploy::LaneSide;
    /// Touching a border is landing on it, not crossing it.
    const INSET: f64 = 8.0;

    let mut over = 0;
    for arrow in arrows {
        let Some(index) = arrow.edge else { continue };
        let Some(edge) = edges.get(index) else { continue };
        // The LEGS, not the points: a point is a corner, and two corners in the list are not
        // necessarily the two ends of one line. Reading them pairwise measured diagonals the
        // picture never draws, and reported eight crossings on a frame that had none.
        let at = |side: &LaneSide| -> Option<(f64, f64)> {
            match side {
                LaneSide::Marker(index) => arrow.plan.points.get(*index).copied(),
                LaneSide::Item(id) => layout.node(id).map(|node| (node.x, node.y)),
            }
        };
        for (from, _, to, _, _) in &arrow.plan.legs {
            let (Some((ax, ay)), Some((bx, by))) = (at(from), at(to)) else { continue };
            let (low_x, high_x) = (ax.min(bx), ax.max(bx));
            let (low_y, high_y) = (ay.min(by), ay.max(by));
            for node in &layout.nodes {
                if node.id == edge.from || node.id == edge.to {
                    continue;
                }
                let left = node.x - node.width / 2.0 + INSET;
                let right = node.x + node.width / 2.0 - INSET;
                let top = node.y - node.height / 2.0 + INSET;
                let bottom = node.y + node.height / 2.0 - INSET;
                if low_x <= right && high_x >= left && low_y <= bottom && high_y >= top {
                    over += 1;
                }
            }
        }
    }
    over
}

/// One frame before it is laid out: whose frame it is, what it draws, and which of its boxes
/// are cards standing for a frame of their own.
#[derive(Debug)]
pub struct FramePlan {
    root: String,
    edges: Vec<Edge>,
}

/// How many items go in one call to Miro, where the endpoint allows a batch.
///
/// Miro's bulk endpoint takes twenty, and one was tried against it on the same map, because
/// timing the waves separately made the batch look like the problem: 68 bulk calls carrying
/// 1 334 items took 110s, while 760 connectors — one item a call — took 39s. A bulk of twenty
/// does come back in about 1.6 seconds whatever is in it, so sending the items one at a time
/// did make that wave faster: **78s**.
///
/// And it made everything else worse. The same map, measured:
///
/// |                  | 20 per call | 1 per call |
/// |------------------|-------------|------------|
/// | boxes, markers   | 110.5s      | **78.7s**  |
/// | connectors       | **39.5s**   | 100.6s     |
/// | retries          | **0**       | 54         |
/// | total            | **198s**    | 234s       |
///
/// The 1 266 extra requests saturated the board, and the connector wave — which is not batched
/// and cannot be — paid for it. So the batch does not buy latency, it buys REQUESTS NOT SPENT,
/// and requests are what Miro actually rations.
///
/// Batching has a price, paid elsewhere: the bulk endpoint COLLAPSES identical items, which is
/// why two markers on one point are made distinct before they are sent, and a leg finds its
/// marker by the position of its id in the answer, which holds only while the endpoint answers
/// in the order it was asked. Both are worth it.
const ITEMS_PER_CALL: usize = 20;

/// A contract drawn more than once in one frame: `Treasury#2` is a second box for `Treasury`.
const COPY_MARK: char = '#';
/// A box for something OUTSIDE the repository, private to the contract that calls it:
/// `IERC20@YieldRouter` is `YieldRouter`'s own copy of `IERC20`.
const OUTSIDE_MARK: char = '@';

/// The original a box stands for, which is its own name unless it is a copy.
fn original_of(id: &str) -> &str {
    id.split([COPY_MARK, OUTSIDE_MARK]).next().unwrap_or(id)
}

/// The entity a box stands for: a destination's party, or the contract a copy copies.
/// The box's own name without the variable in front of it: `opexTreasury%Treasury` is
/// `Treasury`, and `IERC20@YieldRouter` is left alone — that `@` says whose copy it is, which
/// is part of the box's identity, not of the contract's.
fn held_entity(id: &str) -> &str {
    id.split_once(VARIABLE_MARK).map(|(_, held)| held).unwrap_or(id)
}

/// The box itself, minus which copy of it this is: `Treasury#2` is `Treasury`, and
/// `opexTreasury%Treasury` stays apart from `kntqTreasury%Treasury` because they are two
/// addresses. What a cycle is about.
fn same_box(id: &str) -> &str {
    id.split(COPY_MARK).next().unwrap_or(id)
}

/// The ADDRESS a box stands for, as the code names it: the variable that holds it and the
/// contract behind it — `distributor%StakerDistributor`, `opexTreasury%Treasury`.
///
/// This is what the repeat colour groups by, and it is a different question from
/// `drawn_entity`: seven `Treasury`s are one TYPE and seven ADDRESSES, and one colour over all
/// of them said they were one thing. What it cannot merge is two NAMES for one address — `this`
/// inside a contract and somebody else's variable holding it — because only a deployment knows
/// that; the box says `this (…)`, so the reader is unhelped there rather than misled.
fn addressed_as(id: &str) -> &str {
    match destination_of(id) {
        Some(destination) => {
            let entity = destination
                .split_once(ROLE_MARK)
                .map(|(_, entity)| entity)
                .unwrap_or(destination);
            entity.strip_suffix(ADDRESS_MARK).unwrap_or(entity)
        }
        None => original_of(id),
    }
}

fn drawn_entity(id: &str) -> &str {
    match destination_of(id) {
        Some(destination) => entity_named(destination),
        None => {
            let original = original_of(id);
            original.split_once(VARIABLE_MARK).map(|(_, held)| held).unwrap_or(original)
        }
    }
}

/// Is this box something with no source in this repository?
fn is_outside(id: &str) -> bool {
    id.contains(OUTSIDE_MARK)
}

/// What separates an outside box from the METHOD called on it: `IERC20@YieldRouter::safeTransfer`.
const METHOD_MARK: &str = "::";
/// And what separates that method from WHO it hands the value to:
/// `IERC20@YieldRouter::safeTransfer=>burnSink`.
const DESTINATION_MARK: &str = "=>";

/// The method this box stands for, when it is one.
fn method_of(id: &str) -> Option<&str> {
    id.split_once(METHOD_MARK)
        // `IListingLaunchpad@X::collect#3` is the THIRD copy of that leaf, and a box reading
        // `collect#3` tells the reader about our bookkeeping instead of about the method.
        .map(|(_, method)| method.split(COPY_MARK).next().unwrap_or(method))
        .map(|method| method.split(DESTINATION_MARK).next().unwrap_or(method))
}

/// A destination the deploy script decides and the code never names: `=>yieldSink~` is the
/// ADDRESS that variable holds, not a contract. Marked so the box can say so — an unnamed
/// address drawn like a contract is a contract the reader will go looking for.
const ADDRESS_MARK: char = '~';

/// How the scan writes a ternary argument: `recipient|burnSink`, one party per branch.
use crate::batbelt::evm::parser::call_resolver::TERNARY_MARK;

/// Who the value goes to, when this box is a destination.
fn destination_of(id: &str) -> Option<&str> {
    id.split_once(DESTINATION_MARK)
        .map(|(_, to)| to.split(COPY_MARK).next().unwrap_or(to))
}

/// The box a native-value transfer gets: the EVM's own, with no interface and no code to read.
const NATIVE_BOX: &str = "native HYPE";

/// And the box for a low-level call with no value: `router.call(data)`, where the method is in
/// the payload and the only thing the code says is who it goes to.
const LOW_LEVEL_BOX: &str = "low-level call";

/// What separates the VARIABLE that holds an address from the contract at it:
/// `to: opexTreasury (Treasury)`. One contract, several deployments, and the variable is the
/// only thing that tells them apart.
const VARIABLE_MARK: char = '%';

/// What separates the PARAMETER a party fills from the party itself: `to: StakerDistributor`.
const ROLE_MARK: &str = ": ";

/// The entity a destination names, without the role it fills or the address mark.
fn entity_named(destination: &str) -> &str {
    let entity = destination
        .split_once(ROLE_MARK)
        .map(|(_, entity)| entity)
        .unwrap_or(destination);
    // `opexTreasury%Treasury` stands for `Treasury`: that is what the reader's list names and
    // what every copy of it shares.
    let entity = entity.strip_suffix(ADDRESS_MARK).unwrap_or(entity);
    entity.split_once(VARIABLE_MARK).map(|(_, held)| held).unwrap_or(entity)
}

/// Is this box a destination whose entity nobody has named yet — a bare state `address`?
fn is_wiring_point(id: &str) -> bool {
    destination_of(id).is_some_and(|to| to.ends_with(ADDRESS_MARK))
}

/// The PARTIES a call hands an address to, resolved to the entities they name.
///
/// General, and about every method rather than about transfers: a parameter whose type is an
/// address or a contract is another party in that interaction, whoever declared the method. The
/// declaration says which parameters those are; the call site says what was passed; and only
/// what resolves to an ENTITY is drawn — `msg.sender` is whoever called, a bare parameter is a
/// name from another function, and neither is a contract this map can place.
///
/// Two places hold the declaration, and the second is why `safeTransfer` works at all:
/// - the type itself, its bases, or whoever implements it — arguments line up one to one;
/// - a library bound with `using X for Y`, where the receiver is the FIRST parameter, so the
///   call site's argument `i` is parameter `i + 1`. `token.safeTransfer(to, amount)` is sugar
///   for `SafeERC20.safeTransfer(token, to, amount)`, and without that shift the recipient would
///   be read as the token.
fn parties_of(
    metadata: &EvmBatMetadata,
    caller: &ContractMetadata,
    function: &crate::batbelt::evm::metadata::bat_metadata::FunctionMetadata,
    type_name: &str,
    method: &str,
    arguments: &[String],
) -> (Vec<String>, Vec<UnnamedParty>) {
    let Some((params, offset)) = declaration_of(metadata, caller, type_name, method) else {
        return (Vec::new(), Vec::new());
    };
    let mut parties = Vec::new();
    let mut unnamed = Vec::new();
    for (role, argument) in addressed_arguments(metadata, params, offset, arguments) {
        let param = EvmParam { name: role, type_name: String::new(), storage_location: None };
        let argument = &argument;
        // A ternary is TWO possible parties and the transaction picks one, so each branch is
        // its own question and its own box. `recipient|burnSink` is not a name.
        for argument in argument.trim().split(TERNARY_MARK) {
            let argument = argument.trim();
            // The scan writes `…` where the expression was too compound to record. There is no
            // key for it and no name to trace from here — it is reported as a line to open,
            // not as a question with a blank to fill.
            let recorded = argument != "…";
            match entity_of(metadata, caller, &function.name, argument) {
                // One answer may name SEVERAL contracts — a function called from two places
                // with two destinations — and each of them is a party.
                Some(entity) => {
                    for named in entity.split(',').map(str::trim).filter(|name| !name.is_empty()) {
                        // A state address already carries the mark from `entity_of`; marking it
                        // again drew `POOL~ (address)`, with the bookkeeping in the box.
                        let named = named.strip_suffix(ADDRESS_MARK).unwrap_or(named);
                        // WHICH parameter it fills. `transferFrom(from, to, amount)` hands two
                        // addresses to two different roles, and two boxes with only the names
                        // in them do not say which is paying and which is being paid. An
                        // interface that declares no parameter names says nothing here either,
                        // and then the box keeps the entity alone.
                        let role = match param.name.trim() {
                            "" => String::new(),
                            name => format!("{name}{ROLE_MARK}"),
                        };
                        // An answer that is not a contract of this repository is an ACCOUNT —
                        // the launch creator, the caller, a multisig. Named, and drawn as the
                        // address it is: dashed, not as code somebody can go and read.
                        let held = named.split_once(VARIABLE_MARK).map(|(_, h)| h).unwrap_or(named);
                        let account = !metadata.contracts.iter().any(|c| c.name == held)
                            && !named.starts_with("address(")
                            && !named.starts_with("payable(");
                        let party = match account {
                            true => format!("{role}{named}{ADDRESS_MARK}"),
                            false => format!("{role}{named}"),
                        };
                        if !parties.contains(&party) {
                            parties.push(party);
                        }
                    }
                }
                // A party the map cannot place vanished silently, and an audit cannot discard a
                // party it was never shown. Reported instead, with the key that answers it.
                None => unnamed.push(UnnamedParty {
                    contract: caller.name.clone(),
                    file: caller.file_path.clone(),
                    function: function.name.clone(),
                    line: function.line,
                    end_line: function.end_line,
                    call: format!("{type_name}.{method}"),
                    argument: argument.to_string(),
                    key: recorded
                        .then(|| format!("{}.{}.{argument}", caller.name, function.name)),
                }),
            }
        }
    }
    (parties, unnamed)
}

/// Where a call site is, as `src/YieldRouter.sol:142  YieldRouter.pay`.
///
/// The scan records a function's line range but not a call's line, and the reader has to open
/// the file either way — so the line is looked up HERE, within the function's own lines, by the
/// method name. When the file is not where the metadata says, or the call is written in a shape
/// this does not match, the function's own line is printed: a worse answer, never a wrong one.
fn located(party: &UnnamedParty) -> String {
    let method = party.call.rsplit('.').next().unwrap_or_default();
    let line = call_line(&party.file, party.line, party.end_line, method).unwrap_or(party.line);
    format!("{}:{line}  {}.{}", party.file, party.contract, party.function)
}

/// The line a method is called on, inside a function, read from the file itself.
fn call_line(file: &str, from: usize, to: usize, method: &str) -> Option<usize> {
    let source = std::fs::read_to_string(file).ok()?;
    let needle = format!(".{method}(");
    source
        .lines()
        .enumerate()
        .skip(from.saturating_sub(1))
        .take(to.saturating_sub(from) + 1)
        .find(|(_, line)| line.contains(&needle))
        .map(|(index, _)| index + 1)
}

/// One call-site argument the map could not turn into an entity: where it is written, what it
/// says, and the key `bat-cli resolve` takes to answer it.
///
/// This is the whole handover. bat says where to look and stops guessing; a reader (or an
/// assistant reading the code) traces the value and records what it found; the map then draws
/// it like any other party. Nothing here is inferred from a name.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct UnnamedParty {
    pub contract: String,
    pub file: String,
    pub function: String,
    /// The function's own lines, which bound the search for the call's line.
    pub line: usize,
    pub end_line: usize,
    /// The call it is an argument of, as `IERC20.transfer`.
    pub call: String,
    /// The argument as the source writes it: `msg.sender`, `to`, `recipient`.
    pub argument: String,
    /// What to pass to `bat-cli resolve <KEY> <CONTRACT>` — `None` when the scan could not
    /// write the argument's expression down, and there is nothing to key on.
    pub key: Option<String>,
}

/// Every argument that hands over an address, with the role it fills.
///
/// Two shapes. A parameter whose own type is an address or a contract — `transfer(to, amount)`.
/// And a STRUCT parameter, which is where an address hides from a signature:
/// `exactInput(ExactInputParams(path, address(this), deadline, …))` declares no address and
/// hands one over all the same. The struct's declaration says which of its fields are
/// addresses, and the construction says what was passed, so the two line up by position and the
/// role reads `params.recipient`.
fn addressed_arguments(
    metadata: &EvmBatMetadata,
    params: &[EvmParam],
    offset: usize,
    arguments: &[String],
) -> Vec<(String, String)> {
    let mut found = Vec::new();
    for (index, argument) in arguments.iter().enumerate() {
        let Some(param) = params.get(index + offset) else {
            continue;
        };
        if is_address_like(metadata, &param.type_name) {
            found.push((param.name.clone(), argument.clone()));
            continue;
        }
        let Some(fields) = struct_fields(metadata, &param.type_name) else {
            continue;
        };
        let Some(built) = construction_arguments(argument) else {
            continue;
        };
        for (field, inner) in fields.iter().zip(built) {
            if is_address_like(metadata, &field.type_name) {
                found.push((format!("{}.{}", param.name, field.name), inner));
            }
        }
    }
    found
}

/// The fields of the struct this type names, wherever it is declared.
fn struct_fields<'a>(metadata: &'a EvmBatMetadata, type_name: &str) -> Option<&'a [EvmParam]> {
    let clean = type_name.trim().trim_end_matches("[]");
    // `IStakingSwapRouter.ExactInputParams` names its owner; `ExactInputParams` alone does not.
    let (owner, name) = match clean.split_once('.') {
        Some((owner, name)) => (Some(owner), name),
        None => (None, clean),
    };
    metadata
        .contracts
        .iter()
        .filter(|contract| owner.is_none_or(|owner| contract.name == owner))
        .flat_map(|contract| contract.structs.iter())
        .find(|declared| declared.name == name)
        .map(|declared| declared.fields.as_slice())
}

/// The arguments of a struct construction, as the scan wrote them: `Name(a, b, c)` → the three.
///
/// Split at the commas of the OUTER list only, so a nested construction or a call stays whole.
fn construction_arguments(argument: &str) -> Option<Vec<String>> {
    let inner = argument.trim().strip_suffix(')')?;
    let (_, inner) = inner.split_once('(')?;
    let mut out = Vec::new();
    let mut depth = 0usize;
    let mut current = String::new();
    for character in inner.chars() {
        match character {
            '(' | '[' => {
                depth += 1;
                current.push(character);
            }
            ')' | ']' => {
                depth = depth.saturating_sub(1);
                current.push(character);
            }
            ',' if depth == 0 => out.push(std::mem::take(&mut current).trim().to_string()),
            _ => current.push(character),
        }
    }
    let last = current.trim().to_string();
    if !last.is_empty() {
        out.push(last);
    }
    Some(out)
}

/// Is this type an address — plainly, or because it names a contract or an interface?
fn is_address_like(metadata: &EvmBatMetadata, type_name: &str) -> bool {
    let clean = type_name.trim().trim_end_matches("[]");
    clean == "address"
        || clean == "address payable"
        || metadata.contracts.iter().any(|contract| contract.name == clean)
}

/// The parameters of `method` as declared, and how far the call site's arguments are shifted.
fn declaration_of<'a>(
    metadata: &'a EvmBatMetadata,
    caller: &ContractMetadata,
    type_name: &str,
    method: &str,
) -> Option<(&'a [crate::batbelt::evm::types::EvmParam], usize)> {
    let family = type_family(metadata, type_name);
    // The declaration that NAMES its parameters, where there is one: a vendored `IERC20` may
    // write `approve(address, uint256)` and another copy `approve(address spender, uint256
    // value)`, and the box is the poorer for picking the first. Falls back to any declaration.
    let declarations = || {
        metadata
            .contracts
            .iter()
            .filter(|contract| family.contains(contract.name.as_str()))
            .flat_map(|contract| contract.functions.iter())
            .filter(|function| function.name == method)
    };
    let declared = declarations()
        .find(|function| function.params.iter().all(|param| !param.name.trim().is_empty()))
        .or_else(|| declarations().next());
    if let Some(function) = declared {
        return Some((function.params.as_slice(), 0));
    }
    // Attached by `using X for Y`: the receiver is the library's first parameter. The same
    // preference for a declaration that NAMES its parameters, so the box can say which role
    // each party fills.
    let attached = || {
        metadata
            .contracts
            .iter()
            .filter(|contract| caller.using_libraries.iter().any(|lib| lib == &contract.name))
            .flat_map(|contract| contract.functions.iter())
            .filter(|function| function.name == method && !function.params.is_empty())
    };
    attached()
        .find(|function| function.params.iter().all(|param| !param.name.trim().is_empty()))
        .or_else(|| attached().next())
        .map(|function| (function.params.as_slice(), 1))
}

/// Every contract this one INHERITS from, transitively and in scope.
///
/// A base's functions are this contract's: `StakingFeeTreasury is Treasury` has `sweep`, and
/// `sweep` moves its whole balance. The scan records a function under the contract that
/// DECLARES it, so without this a child showed only what it declared itself and the treasuries
/// came out with no way to pay anything out.
fn inherited(metadata: &EvmBatMetadata, contract: &ContractMetadata) -> Vec<String> {
    let mut found: Vec<String> = Vec::new();
    let mut walking: Vec<String> = contract.base_contracts.clone();
    while let Some(base) = walking.pop() {
        if found.contains(&base) || base == contract.name {
            continue;
        }
        if let Some(declared) = metadata
            .contracts
            .iter()
            .find(|candidate| !candidate.vendored && candidate.name == base)
        {
            walking.extend(declared.base_contracts.iter().cloned());
        }
        found.push(base);
    }
    found
}

/// The methods this call's own body invokes on `msg.sender` — the ones that come back here.
///
/// Read off the declaration the call lands on, the same family `declaration_of` walks, and only
/// where there is a BODY to read: an interface declares `lock(bytes)` and says nothing, while
/// the implementation (vendored or not) says `ILockCallback(msg.sender).lockAcquired(data)`.
fn calls_back(
    metadata: &EvmBatMetadata,
    caller: &ContractMetadata,
    type_name: &str,
    method: &str,
) -> Vec<String> {
    let family = type_family(metadata, type_name);
    let mut found: Vec<String> = Vec::new();
    for contract in metadata.contracts.iter().filter(|c| family.contains(c.name.as_str())) {
        for function in contract.functions.iter().filter(|f| f.name == method) {
            for back in &function.callbacks {
                if !found.contains(back) {
                    found.push(back.clone());
                }
            }
        }
    }
    // The caller has to be able to receive it; a contract that does not declare the callback
    // never gets called back, whatever the callee does with some other `msg.sender`.
    found.retain(|back| {
        caller.functions.iter().any(|f| f.name == *back)
            || caller.base_contracts.iter().any(|base| {
                metadata
                    .contracts
                    .iter()
                    .any(|c| c.name == *base && c.functions.iter().any(|f| f.name == *back))
            })
    });
    found
}

/// The call a library WRAPPER really makes, with the arguments of the call site substituted in.
///
/// `token.safeTransfer(to, amount)` is sugar for `SafeERC20.safeTransfer(token, to, amount)`, and
/// that function's body is `abi.encodeCall(token.transfer, (to, value))` — so what crosses the
/// boundary is `transfer`, and `safeTransfer` is how this code decides to make it. A box reading
/// `IERC20 → safeTransfer()` names a method that interface does not have.
///
/// Returns the real method and its arguments, both as the call site would have written them:
/// the wrapper's parameters are replaced by what was passed. `to` is parameter 1 of the library,
/// so it is argument 0 of the call site; `value` is parameter 2, argument 1.
///
/// `None` when this is not a wrapper, when its body makes no call on the receiver, or when it
/// makes more than one — `forceApprove` calls `approve` twice, which is one relation, but a
/// wrapper that calls two DIFFERENT methods is not something to flatten into one box.
fn unwrap_library_call(
    metadata: &EvmBatMetadata,
    caller: &ContractMetadata,
    method: &str,
    arguments: &[String],
) -> Option<(String, Vec<String>)> {
    let wrapper = metadata
        .contracts
        .iter()
        .filter(|contract| caller.using_libraries.iter().any(|lib| lib == &contract.name))
        .flat_map(|contract| contract.functions.iter())
        .find(|function| function.name == method && !function.params.is_empty())?;

    // The receiver is the wrapper's first parameter: every call its body makes ON that name is a
    // call on the thing the caller wrote.
    let receiver = wrapper.params.first()?.name.clone();
    let inner: Vec<_> = wrapper
        .unknown_external_calls
        .iter()
        .filter(|call| call.receiver == receiver)
        .collect();
    let (first, rest) = inner.split_first()?;
    if rest.iter().any(|call| call.method != first.method) {
        return None;
    }

    // The wrapper's parameters, in order, as the call site filled them: parameter `i + 1` holds
    // argument `i`.
    let filled: BTreeMap<&str, &str> = wrapper
        .params
        .iter()
        .skip(1)
        .zip(arguments.iter())
        .map(|(param, argument)| (param.name.as_str(), argument.as_str()))
        .collect();
    let substituted = first
        .arguments
        .iter()
        .map(|written| {
            filled
                .get(written.as_str())
                .map(|argument| argument.to_string())
                .unwrap_or_else(|| written.clone())
        })
        .collect();
    Some((first.method.clone(), substituted))
}

/// A type, everything it inherits from, and everything that declares it as a base./// A type, everything it inherits from, and everything that declares it as a base.
fn type_family<'a>(metadata: &'a EvmBatMetadata, type_name: &'a str) -> BTreeSet<&'a str> {
    let mut family: BTreeSet<&str> = [type_name].into_iter().collect();
    let mut walking = vec![type_name];
    while let Some(name) = walking.pop() {
        for contract in metadata.contracts.iter().filter(|c| c.name == name) {
            for base in &contract.base_contracts {
                if family.insert(base.as_str()) {
                    walking.push(base.as_str());
                }
            }
        }
    }
    for contract in metadata.contracts.iter() {
        if contract.base_contracts.iter().any(|base| base == type_name) {
            family.insert(contract.name.as_str());
        }
    }
    family
}

/// Which ENTITY an argument names, when it names one at all.
///
/// `this` is the contract doing the calling — the one thing here the language settles on its
/// own. A state variable typed as a contract or an interface names that. Anything else —
/// `msg.sender`, a parameter, a local computed elsewhere — is an address this map cannot place,
/// and is left undrawn rather than guessed at.
fn entity_of(
    metadata: &EvmBatMetadata,
    caller: &ContractMetadata,
    function: &str,
    argument: &str,
) -> Option<String> {
    let name = argument.trim();
    // `address(this)` is the caller, and saying only the contract's name left the reader asking
    // whether `to: StakerDistributor` was this one or another of the same kind.
    if name == "this" {
        return Some(format!("this{VARIABLE_MARK}{}", caller.name));
    }
    // `address(0)` is an entity and a famous one — value sent there is burnt. It is written
    // down in full, so there is nothing to trace and nothing to ask: it is its own name.
    if name.starts_with("address(") || name.starts_with("payable(") {
        return Some(name.to_string());
    }
    // What somebody RECORDED outranks the declared type: `treasury` is declared `Treasury` and
    // holds a `StakingFeeTreasury` in this deployment, which only a reader can say. The
    // VARIABLE stays in front of it — `treasury` and `stakerYieldTreasury` are two
    // `StakingFeeTreasury`s, one per converter, and an answer that drops the name merged two
    // addresses into one box.
    if let Some(recorded) = wired_to(metadata, caller, name) {
        let answer = elsewhere(metadata, caller, &recorded);
        let holds = caller.state_variables.iter().any(|state| state.name == name);
        return Some(match holds && !answer.contains(VARIABLE_MARK) && !answer.contains(',') {
            true => format!("{name}{VARIABLE_MARK}{answer}"),
            false => answer,
        });
    }
    let Some(variable) = caller.state_variables.iter().find(|variable| variable.name == name)
    else {
        // Not state: a parameter, `msg.sender`, a local assigned elsewhere. Static analysis is
        // done here — the value comes from the caller, one transaction at a time — but a READER
        // can trace it, and once they have, it is a fact about this call site and belongs
        // written down: `bat-cli resolve <Contract>.<function>.<argument> <Contract>`.
        return wired_at(metadata, caller, function, name);
    };
    match classify_type(metadata, Some(caller.name.as_str()), &variable.type_name) {
        // WHICH one. `AscendLaunchpad` holds five `Treasury`s — `treasury`, `ecosystemTreasury`,
        // `kntqTreasury`, `opexTreasury`, `stakerYieldTreasury` — and they are five deployed
        // addresses, not one. Named by the type alone the five transfers out of
        // `_routeProtocolFees` came out as five identical boxes. The variable is the identity;
        // the contract stays on the box because it is what the reader opens.
        TypeTarget::Contract(entity) => Some(format!("{name}{VARIABLE_MARK}{entity}")),
        // An interface nobody in scope implements is still an entity — the box the map already
        // draws for what leaves the repository.
        TypeTarget::Outside(entity) => Some(entity),
        // Several candidates, or not a contract at all. A plain `address` held in STATE is
        // still a party, and a fixed one: `feeSink` is decided once, at deployment, and never
        // changes. The code never says WHICH contract it is — only the deploy script does — so
        // the box carries the variable's name and says that much, which is the difference
        // between "value leaves here, to this wiring point" and silence. `bat-cli resolve`
        // turns it into a named contract when somebody can say so.
        TypeTarget::Open(_) | TypeTarget::NotAContract => {
            let plain = variable.type_name.trim();
            if plain != "address" && plain != "address payable" {
                return None;
            }
            // Nobody has said what this slot holds — `bat-cli resolve YieldRouter.burnSink
            // BurnSink` is the only way that fact can get here, since the compiler sees twenty
            // bytes written by a deploy script — so the box says the variable and says it is
            // an address.
            Some(format!("{name}{ADDRESS_MARK}"))
        }
    }
}

/// What the `wiring` table says this state address holds, if anybody has said.
///
/// Keyed by the contract that HOLDS the variable, which is what makes it unambiguous — two
/// contracts with a `vault` each are two entries. A variable declared in a base is looked up
/// under the base as well, so the fact is recorded once where it is written.
fn wired_to(metadata: &EvmBatMetadata, caller: &ContractMetadata, variable: &str) -> Option<String> {
    std::iter::once(caller.name.as_str())
        .chain(caller.base_contracts.iter().map(String::as_str))
        .find_map(|holder| metadata.wiring.get(&format!("{holder}.{variable}")))
        .cloned()
}

/// Does calling this library function send native value, and which argument says where to?
///
/// A library has no address: its code runs in the caller, so a low-level `call` in its body is
/// the CALLER paying out. Solmate's `safeTransferETH` is one, written entirely in assembly, and
/// `Treasury.sweep` moves its whole balance through it. The destination is the function's first
/// `address` parameter, which the call site fills.
fn sends_native(metadata: &EvmBatMetadata, type_name: &str, method: &str) -> Option<usize> {
    use crate::batbelt::evm::types::EvmContractType;
    let library = metadata.contracts.iter().find(|contract| {
        contract.name == type_name && contract.contract_type == EvmContractType::Library
    })?;
    let declared = library.functions.iter().find(|function| function.name == method)?;
    let low_level = declared.unknown_external_calls.iter().any(|call| {
        matches!(call.method.trim_end_matches("{value}"), "call" | "delegatecall")
    });
    if !low_level {
        return None;
    }
    // A library that acts on a TOKEN is not sending native value, whatever its body does:
    // solmate writes `safeTransfer(ERC20 token, …)` in assembly too, and that is the token's
    // own transfer — drawn on the token's box by `through_library`. Native value is the one
    // whose first parameter is the address itself.
    let first = declared.params.first()?;
    matches!(first.type_name.trim(), "address" | "address payable").then_some(0)
}

/// The type a LIBRARY function acts on: its first parameter, which is the receiver `using X for
/// Y` would have made explicit. `None` when this is not a library call by name.
///
/// A plain `address` first parameter means native value — `safeTransferETH(to, amount)` — and
/// the caller draws that in its own box, so it is not re-aimed here.
fn through_library(metadata: &EvmBatMetadata, type_name: &str, method: &str) -> Option<String> {
    use crate::batbelt::evm::types::EvmContractType;
    let library = metadata
        .contracts
        .iter()
        .find(|contract| contract.name == type_name && contract.contract_type == EvmContractType::Library)?;
    let first = library
        .functions
        .iter()
        .find(|function| function.name == method)?
        .params
        .first()?;
    let acts_on = first.type_name.trim();
    match acts_on == "address" || acts_on == "address payable" {
        true => None,
        false => Some(acts_on.to_string()),
    }
}

/// Where a call's arguments are decided, and what they are there.
///
/// A contract's own function decides them itself: one site, the arguments as written. A
/// LIBRARY's function does not — its parameters are filled by each host, so `VaultPay.pay(vault,
/// …)` is as many sites as there are calls to it, and the library's parameter names are
/// substituted by what that host passed. The reader is then pointed at the host's line, which
/// is where the answer can be traced, and an answer recorded for one host never leaks to
/// another.
type CallSite<'a> = (
    &'a ContractMetadata,
    &'a crate::batbelt::evm::metadata::bat_metadata::FunctionMetadata,
    Vec<String>,
);

fn call_sites<'a>(
    host: &'a ContractMetadata,
    source: &'a ContractMetadata,
    function: &'a crate::batbelt::evm::metadata::bat_metadata::FunctionMetadata,
    arguments: &[String],
) -> Vec<CallSite<'a>> {
    if source.name == host.name {
        return vec![(host, function, arguments.to_vec())];
    }
    let declared: Vec<&str> = source
        .functions
        .iter()
        .find(|declared| declared.name == function.name)
        .map(|declared| declared.params.iter().map(|param| param.name.as_str()).collect())
        .unwrap_or_default();
    let mut sites = Vec::new();
    for caller in &host.functions {
        for call in &caller.unknown_external_calls {
            if call.method != function.name {
                continue;
            }
            let filled: Vec<String> = arguments
                .iter()
                .map(|argument| {
                    match declared.iter().position(|param| *param == argument.as_str()) {
                        // `using X for Y` passes the receiver as the first parameter, so the
                        // call site's argument `i` is the library's parameter `i + 1`.
                        Some(0) => call.receiver.clone(),
                        Some(index) => call
                            .arguments
                            .get(index - 1)
                            .cloned()
                            .unwrap_or_else(|| argument.clone()),
                        None => argument.clone(),
                    }
                })
                .collect();
            sites.push((host, caller, filled));
        }
    }
    // Nobody in this host calls it directly — `VaultPay.pay` is called by `VaultPay.buyExactIn`
    // — so the arguments stand as the library writes them and they are read in the LIBRARY's
    // context. Reading them in the host's would be worse than useless: `VaultPay.pay`'s own
    // parameter `vault` would resolve against `YieldRouter.vault`, a different contract that
    // happens to share the name.
    if sites.is_empty() {
        sites.push((source, function, arguments.to_vec()));
    }
    sites
}

/// A recorded answer, as a party: `ListingDesk.listingTreasury` names that contract's variable,
/// so the box reads like every other one holding that address (`listingTreasury (Treasury)`).
/// Anything else is taken as written — a contract's name, or an account the reader named.
fn elsewhere(metadata: &EvmBatMetadata, caller: &ContractMetadata, recorded: &str) -> String {
    recorded
        .split(',')
        .map(str::trim)
        .map(|answer| {
            // `this` in an answer is the contract the answer is about, same as in the source.
            if answer == "this" {
                return format!("this{VARIABLE_MARK}{}", caller.name);
            }
            let Some((owner, variable)) = answer.split_once('.') else {
                return answer.to_string();
            };
            let held = metadata
                .contracts
                .iter()
                .filter(|contract| contract.name == owner)
                .flat_map(|contract| contract.state_variables.iter())
                .find(|state| state.name == variable);
            match held {
                // What that slot HOLDS, if somebody has said: `YieldRouter.burnSink` is declared
                // `address`, and `burnSink (address)` names no contract at all — the recorded
                // answer for the slot is the whole point of pointing at it.
                Some(state) => {
                    let held = metadata
                        .wiring
                        .get(&format!("{owner}.{variable}"))
                        .map(String::as_str)
                        .unwrap_or(state.type_name.trim());
                    format!("{variable}{VARIABLE_MARK}{held}")
                }
                None => answer.to_string(),
            }
        })
        .collect::<Vec<_>>()
        .join(",")
}

/// What the `wiring` table says about ONE call site's argument: `YieldRouter.pay.to`.
///
/// The key carries the function, because the answer is about that call and not about the name:
/// `to` in one function is not `to` in another, and a bare name would bind both.
fn wired_at(
    metadata: &EvmBatMetadata,
    caller: &ContractMetadata,
    function: &str,
    argument: &str,
) -> Option<String> {
    metadata
        .wiring
        .get(&format!("{}.{function}.{argument}", caller.name))
        .map(|recorded| elsewhere(metadata, caller, recorded))
}

/// Lay a frame out as a TREE: each contract at the height of the children it talks to.
///
/// The layered engine packs every column from the top, which is right when a column holds
/// unrelated boxes — and wrong here. A frame IS a tree now, and packing from the top put a
/// contract's own callees level with somebody else's: following one arrow meant scrolling up
/// and down a frame whose answer was two boxes apart. Reingold–Tilford instead: leaves take the
/// next free row, a parent sits at the middle of its children, so a box is always beside the
/// boxes it points at.
///
/// It costs what the deploy rejected it for — a parent's band is its whole subtree, so a light
/// sibling after a heavy one starts low. On a map that is cheap: the boxes are a name each, and
/// the outside leaves are half-height.
///
/// Every edge of a tree joins adjacent columns, so there are no bend points and nothing to
/// route through a corridor; crossings are 0 by construction, which the certificate still
/// reports rather than assumes.
fn layout_tree(root: &str, edges: &[Edge]) -> GraphLayout {
    /// Between two boxes stacked in the same column.
    const ROW_GAP: f64 = 150.0;
    /// Between one column and the next: room for the arrows' lanes.
    const COLUMN_GAP: f64 = 300.0;
    /// Between two LANES of the same column — tighter than between columns, because no arrow
    /// runs down between them: a leaf's only arrow comes from the parent on its left.
    const LANE_GAP: f64 = 120.0;

    // The tree: the first arrow into a box is the one that owns it. Anything else is a back
    // edge — `unfold` only emits one when it reaches a box already on the path — and takes no
    // part in the placement.
    let mut children: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    let mut parented: BTreeSet<&str> = BTreeSet::new();
    let mut order: Vec<&str> = Vec::new();
    for edge in edges {
        for id in [edge.from.as_str(), edge.to.as_str()] {
            if !order.contains(&id) {
                order.push(id);
            }
        }
    }
    for edge in edges {
        // Never the root: the frame of a cycle has an arrow back INTO its own root, and taking
        // that one for the tree made the root somebody's child — so no box was left without a
        // parent, the layout found no root at all, and the whole frame came out empty. It
        // reached the board as a titled frame with nothing in it.
        if edge.to == root || parented.contains(edge.to.as_str()) {
            continue;
        }
        parented.insert(edge.to.as_str());
        children.entry(edge.from.as_str()).or_default().push(edge.to.as_str());
    }
    let Some(root) = order.iter().copied().find(|id| *id == root).or_else(|| {
        // The caller's root is normally one of the boxes; if it somehow is not, anything
        // without a parent will do before drawing nothing at all.
        order.iter().copied().find(|id| !parented.contains(id))
    }) else {
        return GraphLayout {
            nodes: Vec::new(),
            routes: vec![Vec::new(); edges.len()],
            back_edges: Vec::new(),
            bbox_width: 0.0,
            bbox_height: 0.0,
            frame_width: MAP_MARGIN * 2.0,
            frame_height: MAP_MARGIN * 2.0,
            crossings: 0,
        };
    };

    // Depth per box, and the widest box of each depth: a column is as wide as its widest name.
    let mut depth: BTreeMap<&str, usize> = BTreeMap::new();
    let mut stack = vec![(root, 0usize)];
    while let Some((id, at)) = stack.pop() {
        depth.insert(id, at);
        for child in children.get(id).into_iter().flatten() {
            stack.push((child, at + 1));
        }
    }
    let deepest = depth.values().copied().max().unwrap_or(0);

    // LEAVES OF ONE PARENT GO IN A GRID, not in a single file.
    //
    // A frame is as tall as its most crowded column, and the most crowded column is always
    // leaves: `safeTransfer()` hands eleven addresses to eleven boxes, each taking a row that
    // the other columns then have to span. On `AscendLaunchpad` that column held 33 of the 76
    // boxes while the other four held 1, 13, 23 and 6 — the frame was 27 000 units tall and
    // **13.9% of its area was box**, the rest air.
    //
    // A leaf has no children, so nothing hangs off it and nothing has to line up beneath it:
    // the only reason they were in a column is that the walk put them there one after another.
    // Side by side they cost width that the column already has — the lanes are as wide as the
    // widest name in that column either way.
    /// How many lanes a parent's leaves are spread over.
    ///
    /// Three past eight, because a frame is as tall as its most crowded column and that column
    /// is always leaves: eleven `to:` boxes under one `safeTransfer()` were eleven rows that
    /// every other column then had to span. Three lanes of four beats eleven rows and keeps the
    /// frame wider than tall, which is the shape a screen is.
    /// How many lanes a parent's leaves are spread over.
    ///
    /// Two past three leaves, three past eight. A frame is as tall as its most crowded column
    /// and that column is always leaves — eleven `to:` boxes under one `safeTransfer()` were
    /// eleven rows every other column had to span.
    ///
    /// The arrows are what made this fail the first time: sent out of the parent's right side
    /// and into the leaf's left, an arrow to the second lane runs straight through the leaf in
    /// the first. They now enter a lane past the first FROM ABOVE — see `route_arrows`.
    let lanes_for = |count: usize| -> usize {
        match count {
            0..=3 => 1,
            4..=8 => 2,
            _ => 3,
        }
    };
    let mut lane: BTreeMap<&str, usize> = BTreeMap::new();
    for (parent, mine) in &children {
        let all_leaves = mine.iter().all(|child| !children.contains_key(child));
        if !all_leaves {
            continue;
        }
        let lanes = lanes_for(mine.len());
        if lanes < 2 {
            continue;
        }
        let _ = parent;
        for (at, child) in mine.iter().enumerate() {
            lane.insert(child, at % lanes);
        }
    }

    // A column is as wide as its widest name, times the lanes it needs.
    let mut column_width = vec![0.0_f64; deepest + 1];
    let mut column_lanes = vec![1usize; deepest + 1];
    for (id, at) in &depth {
        column_width[*at] = column_width[*at].max(node_width(id));
        column_lanes[*at] = column_lanes[*at].max(lane.get(id).copied().unwrap_or(0) + 1);
    }
    let mut column_x = vec![0.0_f64; deepest + 1];
    let mut left = MAP_MARGIN;
    for (at, width) in column_width.iter().enumerate() {
        column_x[at] = left + width / 2.0;
        let lanes = column_lanes[at] as f64;
        left += width * lanes + LANE_GAP * (lanes - 1.0) + COLUMN_GAP;
    }

    // Rows, by the CONTOUR of each subtree rather than one cursor for the whole frame.
    //
    // The cursor version gave every leaf a row of its own across every column: a leaf two
    // columns deep pushed the next box in column 1 down as well, though nothing sits beside it
    // there. `AscendLaunchpad` came out 47 rows tall while its most crowded column holds 33 —
    // fourteen rows of air nothing asked for, and the reason the frame was tall and narrow with
    // the text looking tiny inside it.
    //
    // This is the step Reingold–Tilford specifies and this code was missing. Each subtree is
    // laid out in its OWN coordinates starting at zero, carrying the contour it occupies — per
    // column, its topmost and bottommost edge. Siblings are then stacked by sliding each one
    // down only until its contour clears the one before it, column by column: a branch that is
    // deep but narrow costs the rows it actually uses, not the rows the widest branch used.
    //
    // Two passes over an explicit stack, because the depth here is the audited system's own
    // call depth and a frame is not worth a blown stack.
    type Contour = BTreeMap<usize, (f64, f64)>;
    // Per subtree: where each of its boxes sits relative to the subtree's own zero, and the
    // span it occupies in every column it touches.
    let mut spread: BTreeMap<&str, (BTreeMap<&str, f64>, Contour)> = BTreeMap::new();

    let mut walk: Vec<(&str, bool)> = vec![(root, false)];
    while let Some((id, done)) = walk.pop() {
        let mine = children.get(id).cloned().unwrap_or_default();
        let at = depth.get(id).copied().unwrap_or(0);
        let height = node_height(id);
        if mine.is_empty() {
            let mut own = BTreeMap::new();
            own.insert(id, 0.0);
            let mut shape: Contour = BTreeMap::new();
            shape.insert(at, (0.0, height));
            spread.insert(id, (own, shape));
            continue;
        }
        if !done {
            walk.push((id, true));
            for child in mine.iter().rev() {
                walk.push((child, false));
            }
            continue;
        }

        // Stack the children: each one slides down until it clears the contour of the ones
        // already placed, in every column the two of them share.
        let mut placed: BTreeMap<&str, f64> = BTreeMap::new();
        let mut shape: Contour = BTreeMap::new();
        let (mut first_mid, mut last_mid) = (0.0_f64, 0.0_f64);
        // Leaves spread over lanes share a ROW: the second and third lane sit beside the first,
        // not under it, so they take the slide the first one took. Without this the lanes cost
        // width and saved no height at all — which is the whole reason they exist.
        let mut row_slide = 0.0_f64;
        for (nth, child) in mine.iter().enumerate() {
            let Some((below, child_shape)) = spread.get(child) else { continue };
            let beside = lane.get(child.as_ref() as &str).copied().unwrap_or(0) > 0;
            let mut slide = match beside {
                true => row_slide,
                false => 0.0,
            };
            if !beside {
                for (column, (top, _)) in child_shape {
                    if let Some((_, taken)) = shape.get(column) {
                        slide = slide.max(taken + ROW_GAP - top);
                    }
                }
                row_slide = slide;
            }
            for (box_id, spot) in below {
                placed.insert(box_id, spot + slide);
            }
            for (column, (top, bottom)) in child_shape {
                let entry = shape.entry(*column).or_insert((top + slide, bottom + slide));
                entry.0 = entry.0.min(top + slide);
                entry.1 = entry.1.max(bottom + slide);
            }
            let mid = placed.get(child.as_ref() as &str).copied().unwrap_or(slide)
                + node_height(child) / 2.0;
            if nth == 0 {
                first_mid = mid;
            }
            last_mid = mid;
        }

        // The parent sits at the midpoint of its first and last child. If that puts it above
        // the subtree's own zero, the whole subtree moves down instead — a box may not sit at
        // a negative offset, and the parent is the one thing that cannot be slid alone.
        let parent_top = (first_mid + last_mid) / 2.0 - height / 2.0;
        let lift = (-parent_top).max(0.0);
        if lift > 0.0 {
            for spot in placed.values_mut() {
                *spot += lift;
            }
            for (_, span) in shape.iter_mut() {
                span.0 += lift;
                span.1 += lift;
            }
        }
        let parent_top = parent_top + lift;
        placed.insert(id, parent_top);
        let entry = shape.entry(at).or_insert((parent_top, parent_top + height));
        entry.0 = entry.0.min(parent_top);
        entry.1 = entry.1.max(parent_top + height);
        spread.insert(id, (placed, shape));
    }

    // Absolute at last: the root's own layout, shifted off the frame's margin.
    let mut y: BTreeMap<&str, f64> = BTreeMap::new();
    if let Some((placed, _)) = spread.get(root) {
        for (box_id, top) in placed {
            y.insert(box_id, MAP_MARGIN + top + node_height(box_id) / 2.0);
        }
    }

    let nodes: Vec<PlacedNode> = order
        .iter()
        .filter_map(|id| {
            Some(PlacedNode {
                id: id.to_string(),
                layer: *depth.get(id)?,
                x: column_x[*depth.get(id)?]
                    + lane.get(id).copied().unwrap_or(0) as f64
                        * (column_width[*depth.get(id)?] + LANE_GAP),
                y: *y.get(id)?,
                width: node_width(id),
                height: node_height(id),
            })
        })
        .collect();
    if std::env::var("SPACE_DEBUG").is_ok() {
        let ink: f64 = nodes.iter().map(|n| n.width * n.height).sum();
        let w = nodes.iter().map(|n| n.x + n.width / 2.0).fold(0.0, f64::max) + MAP_MARGIN;
        let h = nodes.iter().map(|n| n.y + n.height / 2.0).fold(0.0, f64::max) + MAP_MARGIN;
        let widest = nodes.iter().map(|n| n.width).fold(0.0, f64::max);
        let mut per_layer: std::collections::BTreeMap<usize, (usize, f64)> = Default::default();
        for n in &nodes {
            let e = per_layer.entry(n.layer).or_insert((0, 0.0));
            e.0 += 1;
            e.1 = e.1.max(n.width);
        }
        eprintln!(
            "SPACE {} boxes, ink {:.0}, frame {:.0}x{:.0} = {:.0}, filled {:.1}%, widest box {:.0}",
            nodes.len(), ink, w, h, w * h, 100.0 * ink / (w * h), widest
        );
        for (layer, (count, widest)) in per_layer {
            eprintln!("  layer {layer}: {count} box(es), widest {widest:.0}");
        }
    }
    let width = nodes
        .iter()
        .map(|node| node.x + node.width / 2.0)
        .fold(0.0_f64, f64::max)
        + MAP_MARGIN;
    let height = nodes
        .iter()
        .map(|node| node.y + node.height / 2.0)
        .fold(0.0_f64, f64::max)
        + MAP_MARGIN;
    // A corridor for every column an arrow SKIPS.
    //
    // This layout was written when a frame was a tree, where every arrow is one column long and
    // there is nothing to skip, so it returned no corridors at all and the router drew those
    // arrows as one straight line from caller to callee. `rejoin` ended that: a box two
    // branches share sits below both of them, so the shorter branch's arrow spans two columns
    // or more — and one of them ran clean through `AscendCtoReceiver`'s name while the frame
    // reported no crossings, because an arrow crossing a BOX was not a thing being counted.
    //
    // The height is the callee's own, slid to the nearest gap that column leaves free. Its own
    // height, because that is where the arrow is heading and a corridor at any other height is
    // two more turns; the nearest gap, because the layout's ordering is what keeps the crossing
    // count at zero and moving an arrow further than it has to be moved puts that at risk.
    let routes: Vec<Vec<(f64, f64)>> = edges
        .iter()
        .map(|edge| {
            let (Some(from), Some(to)) = (
                nodes.iter().find(|node| node.id == edge.from),
                nodes.iter().find(|node| node.id == edge.to),
            ) else {
                return Vec::new();
            };
            if to.layer <= from.layer + 1 {
                return Vec::new();
            }
            (from.layer + 1..to.layer)
                .map(|layer| (0.0, clear_of_the_layer(&nodes, layer, to.y)))
                .collect()
        })
        .collect();

    GraphLayout {
        nodes,
        routes,
        back_edges: Vec::new(),
        bbox_width: width - MAP_MARGIN * 2.0,
        bbox_height: height - MAP_MARGIN * 2.0,
        frame_width: width,
        frame_height: height,
        crossings: 0,
    }
}

/// 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, with what leaves the repository given a box of its
/// own — one PER CALLER.
///
/// A call out of the code is a call, and an audit's question about it ("what does this touch
/// that I cannot read") deserves an arrow like any other. What it must not be is a SHARED node:
/// `IERC20` is reached by seven contracts, and one box for all of them pulled seven long arrows
/// across the frame and was, alone, the busiest thing on the map. So every caller gets its own
/// copy, which is §5's localize taken to the end — an outside box has no chain under it, so a
/// copy costs one box and saves a crossing every time.
fn drawn_edges(metadata: &EvmBatMetadata, edges: &[Edge], no_boundaries: bool) -> Vec<Edge> {
    // WHOSE copy is a question about the TARGET, not about the relation: an outside box that is
    // only read, or only held, is still one copy per caller. Keyed on the relation alone, those
    // two went back to being one shared box the moment `reads` and `wired` stopped being
    // flattened into `leaves the code`.
    let outside = |name: &str| {
        matches!(classify_type(metadata, None, held_entity(name)), TypeTarget::Outside(_))
    };
    edges
        .iter()
        .filter(|edge| !no_boundaries || !outside(&edge.to))
        .map(|edge| match outside(&edge.to) {
            true => Edge {
                from: edge.from.clone(),
                to: format!("{}{OUTSIDE_MARK}{}", edge.to, edge.from),
                relation: edge.relation,
            },
            false => edge.clone(),
        })
        .collect()
}

/// Does this method of that type only READ?
///
/// Read from the DECLARATION, never from a vocabulary of names: `view`/`pure` is the one thing
/// the language itself guarantees, it holds in any protocol, and the scan already has it —
/// interfaces under `lib/` are scanned with their functions like anything else.
///
/// Unknown counts as "no". If the type is declared nowhere this scan can see, a boundary that
/// might move value is drawn rather than hidden: an audit can discard a box, it cannot discard a
/// transfer it was never shown.
fn reads_only(metadata: &EvmBatMetadata, type_name: &str, method: &str) -> bool {
    use crate::batbelt::evm::types::EvmMutability;
    // The type itself, and whoever declares it as a base. An interface in this repository often
    // declares only part of its surface — `IListingLaunchpad` declares five methods and the code
    // calls `poolCreator`, which is written with `view` in the contract that implements it. Same
    // rule, wider search, and still the language's own word rather than a guess at a name.
    // The type, everything it INHERITS from (transitively), and everything that declares it as
    // a base. `ICLPoolManager` declares eleven methods and `vault` is not one of them — it comes
    // from the interface it extends, and a getter drawn as if it moved value is exactly the
    // noise this filter exists to remove.
    let mut family: BTreeSet<&str> = [type_name].into_iter().collect();
    let mut walking = vec![type_name];
    while let Some(name) = walking.pop() {
        for contract in metadata.contracts.iter().filter(|c| c.name == name) {
            for base in &contract.base_contracts {
                if family.insert(base.as_str()) {
                    walking.push(base.as_str());
                }
            }
        }
    }
    let declares = |contract: &ContractMetadata| {
        family.contains(contract.name.as_str())
            || contract.base_contracts.iter().any(|base| base == type_name)
    };
    metadata
        .contracts
        .iter()
        .filter(|contract| declares(contract))
        .flat_map(|contract| contract.functions.iter())
        .filter(|function| function.name == method)
        .map(|function| matches!(function.mutability, EvmMutability::View | EvmMutability::Pure))
        // Several declarations of one name (a vendored copy and ours, an interface and its
        // implementer): a single one that writes is enough to keep the leaf.
        .reduce(|a, b| a && b)
        // Searching for the NAME in unrelated contracts was the other candidate and it is a
        // guess: `poolCreator` is `view` on `IAscendLaunchpad` while the call is typed
        // `IListingLaunchpad`, which declares no such thing. What settles that is the auditor
        // resolving the interface (`bat-cli resolve`), not this function picking a declaration
        // that looks similar. Until then the leaf is drawn.
        .unwrap_or(false)
}

/// A leaf under each outside box: the METHODS this caller actually calls on it.
///
/// A box reading `IERC20` says the code touches a token; `IERC20 → safeTransfer` says value
/// leaves here, and `IERC20 → balanceOf` says nothing leaves at all. That difference is most of
/// what an audit wants from a boundary, and the scan already records it — the map was throwing
/// it away. Thirteen interfaces in ascend, 44 distinct (interface, method) pairs, but a single
/// caller's copy carries only the two or three methods IT calls.
///
/// Attached to the CALLER'S OWN copy of the interface, so the methods never pool on one shared
/// box, which is the thing that made a shared `IERC20` the busiest node on the map.
fn method_leaves(
    metadata: &EvmBatMetadata,
    drawn: &[Edge],
    all_methods: bool,
) -> (Vec<Edge>, Vec<UnnamedParty>) {
    // Which outside boxes exist, by (caller, interface) — the methods are hung on those and on
    // nothing else, so folding (`hosts`) and the ignore list are respected without repeating
    // their rules here.
    let boxes: BTreeSet<(&str, &str)> = drawn
        .iter()
        .filter(|edge| edge.relation == Relation::Boundary)
        .map(|edge| (edge.from.as_str(), original_of(&edge.to)))
        .collect();

    // A library's code runs as the contract that uses it, and the relations already say so —
    // the method leaves did not. `VaultPay.buyExactIn` calls `pm.swap` and `vault.sync`, and
    // because the library's own box is folded away, those leaves were dropped: the
    // `ICLPoolManager` box under `YieldRouter` came out with no methods at all.
    let hosted = hosts(metadata);
    let mut found: BTreeSet<Edge> = BTreeSet::new();
    let mut unnamed: BTreeSet<UnnamedParty> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        let running: Vec<&ContractMetadata> = std::iter::once(contract)
            .chain(
                hosted
                    .get(&contract.name)
                    .into_iter()
                    .flatten()
                    .chain(inherited(metadata, contract).iter())
                    .filter_map(|name| {
                        metadata.contracts.iter().find(|c| !c.vendored && c.name == *name)
                    }),
            )
            .collect();
        // `source` declares the function — its state and its name are what an answer is keyed
        // by; `contract` is the box the leaf hangs under.
        for (source, function) in running
            .iter()
            .flat_map(|source| source.functions.iter().map(move |function| (*source, function)))
        {
            let calls = function
                .unknown_external_calls
                .iter()
                // A call recorded for its VALUE is the same call as the one beside it, and the
                // `native HYPE` box already draws it: `IKinetiqStaking` showed `stake()` and
                // `stake{value}` as two leaves of one call.
                .filter(|call| !call.method.ends_with("{value}"))
                .map(|call| {
                    // A library wrapper is drawn as the call it actually makes: what crosses the
                    // boundary is `transfer`, not the `safeTransfer` that decides to make it —
                    // and `IERC20` has no `safeTransfer` to show.
                    let (method, arguments) =
                        unwrap_library_call(metadata, source, &call.method, &call.arguments)
                            .unwrap_or_else(|| (call.method.clone(), call.arguments.clone()));
                    // A LIBRARY's parameters are filled by whoever calls it, and each host
                    // fills them differently: `VaultPay.buyExactIn(…, to)` takes
                    // `l.receiver` from the router and `d.devBuyRecipient` from the launchpad.
                    // Resolving the library's own parameter names made one set of destinations
                    // and hung it on every host — the router's `take()` showed the launchpad's
                    // recipients and the launchpad showed the router's.
                    let mut parties = Vec::new();
                    let mut gaps = Vec::new();
                    for (whose, at, arguments) in
                        call_sites(contract, source, function, &arguments)
                    {
                        let (found, missing) = parties_of(
                            metadata,
                            whose,
                            at,
                            &call.inferred_type,
                            &method,
                            &arguments,
                        );
                        for party in found {
                            if !parties.contains(&party) {
                                parties.push(party);
                            }
                        }
                        gaps.extend(missing);
                    }
                    (call.inferred_type.clone(), method, parties, gaps)
                })
                .chain(function.unresolved_calls.iter().map(|call| {
                    (call.inferred_type.clone(), call.method.clone(), Vec::new(), Vec::new())
                }));
            for (type_name, method, parties, gaps) in calls {
                if type_name.is_empty() || method.is_empty() {
                    continue;
                }
                // A library call by name is drawn as what it DOES to its first argument:
                // `SafeTransferLib.safeTransfer(ERC20(token), to, amount)` is a transfer on
                // that token, and `safeTransferETH(to, amount)` is native value leaving. The
                // library itself is no box — its code runs here — so without this the call had
                // nowhere to land.
                // A library call is aimed at its first parameter, and that parameter is then
                // the BOX: `SafeTransferLib.safeTransfer(ERC20(token), to, amount)` draws
                // `ERC20 → safeTransfer() → to: …`, and listing `token:` as a party of itself
                // is the box's own name said twice.
                let through = through_library(metadata, &type_name, &method);
                let parties = match through.is_some() {
                    true => parties.iter().skip(1).cloned().collect::<Vec<_>>(),
                    false => parties.clone(),
                };
                let type_name = through.unwrap_or_else(|| type_name.clone());
                let TypeTarget::Outside(outside) =
                    classify_type(metadata, Some(contract.name.as_str()), &type_name)
                else {
                    continue;
                };
                if !boxes.contains(&(contract.name.as_str(), outside.as_str())) {
                    continue;
                }
                if !all_methods && reads_only(metadata, &outside, &method) {
                    continue;
                }
                // `IStakingSwapRouter.ExactInputParams(path, …)` is a STRUCT, written with the
                // interface that declares it in front — it is not a call on that interface and
                // it never crossed anything. The scan records the struct, so this is read off
                // the declaration rather than guessed from the capital letter.
                if declares_struct(metadata, &outside, &method) {
                    continue;
                }
                // `vault.pay(currency, amount)` is `VaultPay.pay(IVault, …)` attached with
                // `using VaultPay for IVault`: the code runs HERE, and the vault has no `pay`
                // to show. What crosses is what the library's own body does — `sync`,
                // `safeTransfer`, `settle` — which is drawn already, so the leaf was a method
                // of somebody else's contract that does not exist.
                if attached_elsewhere(metadata, &outside, &method) {
                    continue;
                }
                let leaf = format!("{outside}{OUTSIDE_MARK}{}", contract.name);
                let method_leaf = format!("{leaf}{METHOD_MARK}{method}");
                found.insert(Edge {
                    from: leaf.clone(),
                    to: method_leaf.clone(),
                    relation: Relation::Boundary,
                });
                // And the other PARTIES of that call: every address it is handed that names a
                // contract. A map that says `safeTransfer` says half of it; this is the half
                // that tells an audit where the value went.
                for party in &parties {
                    found.insert(Edge {
                        from: method_leaf.clone(),
                        to: format!("{method_leaf}{DESTINATION_MARK}{party}"),
                        relation: Relation::Boundary,
                    });
                }
                // Only the gaps of a call that IS drawn: a report about a box nobody can see is
                // a report about nothing.
                unnamed.extend(gaps);
                // And the control that comes BACK. A method whose body calls on `msg.sender`
                // calls its caller: `Vault.lock` ends in `ILockCallback(msg.sender)
                // .lockAcquired(data)`, so `lock()` hands the thread back here. Nothing in the
                // signature says it — `lock(bytes)` — and it is a fact about the code, not a
                // guess from a name.
                for back in calls_back(metadata, source, &type_name, &method) {
                    found.insert(Edge {
                        from: method_leaf.clone(),
                        to: format!(
                            "{method_leaf}{DESTINATION_MARK}calls back {back}{ROLE_MARK}{}",
                            contract.name
                        ),
                        relation: Relation::Boundary,
                    });
                }
            }
            // Native HYPE leaving the contract: `to.call{value: amount}("")`. There is no
            // interface and no method name here — the EVM's own transfer is the whole call —
            // so it gets a boundary box of its own, with the receiver as its party. It used to
            // be reported as an untyped receiver and drawn nowhere, which is how the one leg of
            // `StakerDistributor._pay` that moves native value stayed invisible.
            for call in &function.unknown_external_calls {
                // A library that ends in a low-level call moves value from WHOEVER calls it,
                // and says so only in assembly: `SafeTransferLib.safeTransferETH(to, amount)`
                // is `Treasury.sweep` paying out, with nothing in the signature to show for it.
                // Its first address parameter is where the value goes, filled by this call.
                let through = sends_native(metadata, &call.inferred_type, &call.method);
                let sends_value = call.method.ends_with("{value}") || through.is_some();
                let low_level = matches!(
                    call.method.trim_end_matches("{value}"),
                    "call" | "delegatecall"
                );
                if !(sends_value || low_level) || call.receiver == "assembly" {
                    continue;
                }
                // Whose address the value goes to: the receiver of a low-level call, or the
                // argument that filled the library's address parameter.
                let receiver = match through {
                    Some(at) => match call.arguments.get(at) {
                        Some(argument) => argument.clone(),
                        None => continue,
                    },
                    None => call.receiver.clone(),
                };
                // Value makes it a transfer of native HYPE; without value it is a call into
                // whatever that address is — `router.call(data)` in an aggregator, which is as
                // much a boundary as any interface and was drawn nowhere.
                let box_name = match sends_value {
                    true => NATIVE_BOX,
                    false => LOW_LEVEL_BOX,
                };
                let leaf = format!("{box_name}{OUTSIDE_MARK}{}", contract.name);
                let method_leaf = format!("{leaf}{METHOD_MARK}{}", call.method);
                found.insert(Edge {
                    from: contract.name.clone(),
                    to: leaf.clone(),
                    relation: Relation::Boundary,
                });
                found.insert(Edge {
                    from: leaf.clone(),
                    to: method_leaf.clone(),
                    relation: Relation::Boundary,
                });
                match entity_of(metadata, source, &function.name, &receiver) {
                    Some(entity) => {
                        // The cast at the call site names what is being paid, where the
                        // variable's own type is a bare `address`: `IKinetiqStaking(
                        // stakingManager).stake{value: v}()` pays a staking manager.
                        let entity = match (&call.inferred_type, entity.ends_with(ADDRESS_MARK)) {
                            (cast, true) if !cast.is_empty() => {
                                format!("{}{VARIABLE_MARK}{cast}", entity.trim_end_matches(ADDRESS_MARK))
                            }
                            _ => entity,
                        };
                        for named in entity.split(',').map(str::trim).filter(|n| !n.is_empty()) {
                            // The same rule as any other party: the mark goes on the whole
                            // name, and whether it is an account is a question about the
                            // CONTRACT, not about the variable in front of it. Marking the
                            // variable form drew `distributor (StakerDistributor~)`.
                            let named = named.strip_suffix(ADDRESS_MARK).unwrap_or(named);
                            let held = held_entity(named);
                            let account = !metadata.contracts.iter().any(|c| c.name == held)
                                && !named.starts_with("address(")
                                && !named.starts_with("payable(");
                            let party = match account {
                                true => format!("to{ROLE_MARK}{named}{ADDRESS_MARK}"),
                                false => format!("to{ROLE_MARK}{named}"),
                            };
                            found.insert(Edge {
                                from: method_leaf.clone(),
                                to: format!("{method_leaf}{DESTINATION_MARK}{party}"),
                                relation: Relation::Boundary,
                            });
                        }
                    }
                    None => {
                        unnamed.insert(UnnamedParty {
                            contract: source.name.clone(),
                            file: source.file_path.clone(),
                            function: function.name.clone(),
                            line: function.line,
                            end_line: function.end_line,
                            call: format!("{box_name}.{}", call.method),
                            argument: receiver.clone(),
                            key: Some(format!(
                                "{}.{}.{receiver}",
                                source.name, function.name
                            )),
                        });
                    }
                }
            }
        }
    }
    (found.into_iter().collect(), unnamed.into_iter().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(name),
        })
        .collect();
    // The frame's own contract first, and the chain growing rightwards from it.
    //
    // The edges used to be fed REVERSED, so that the contract everything needs — `Treasury` —
    // landed leftmost and the deployment order read left to right. That was the right rule for
    // one frame of the whole system. It is the wrong one now that a frame is one contract's
    // story: its subject ended up at the far RIGHT, every arrow ran right to left, and the
    // reader started at the end. The hierarchy of the system is answered by `--hierarchy` and
    // by which contracts have a frame at all, not by where a box sits inside one.
    let laid_edges: Vec<LayoutEdge> = edges
        .iter()
        .map(|edge| LayoutEdge {
            from: edge.from.clone(),
            to: edge.to.clone(),
            from_line_fraction: 0.5,
        })
        .collect();

    // The root is the frame's own contract: what nothing here calls.
    let called: BTreeSet<&str> = edges.iter().map(|edge| edge.to.as_str()).collect();
    let root = names
        .iter()
        .find(|name| !called.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,
        // No room reserved for a legend: it has a frame of its own now, and reserving its
        // height here left every contract's frame opening with a screen of nothing.
        padding_y: MAP_MARGIN,
        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);
    let mut layout = if wanted <= LayoutConfig::default().gutter_x {
        first
    } else {
        layout_graph(&root, &nodes, &laid_edges, config(wanted))
    };
    order_hub_column(&mut layout, edges);
    layout
}

/// Put the most-called contracts of the first column in the MIDDLE of it, and the rest
/// outwards from there.
///
/// The first column is what calls nothing in scope: the contracts everything else depends on.
/// The barycentre sweep orders it to cut crossings between the first two columns, which is
/// the right rule everywhere else — but the thing a reader asks of this column is "which one
/// does everybody write to", and the answer should be where the eye lands first. A hub in the
/// middle also takes its arrows from above and below, half each, instead of all of them
/// running the height of the frame to reach a box the sweep left at the top.
///
/// Only the first column, and only by swapping the y's it already has: every box is one
/// height, so the slots are interchangeable and nothing else in the layout moves.
fn order_hub_column(layout: &mut GraphLayout, edges: &[Edge]) {
    // Column 0 is the frame's own contract now — one box — so this returns immediately on a
    // map and stays only for the case of a frame whose root is a cycle with several entries.

    let mut incoming: BTreeMap<&str, usize> = BTreeMap::new();
    for edge in edges {
        *incoming.entry(edge.to.as_str()).or_default() += 1;
    }
    let mut members: Vec<usize> = (0..layout.nodes.len())
        .filter(|&index| layout.nodes[index].layer == 0)
        .collect();
    if members.len() < 2 {
        return;
    }
    let mut slots: Vec<f64> = members.iter().map(|&index| layout.nodes[index].y).collect();
    slots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    // Most called first, then by name so two equally popular contracts always come out the
    // same way round.
    members.sort_by(|&a, &b| {
        let calls = |index: usize| incoming.get(layout.nodes[index].id.as_str()).copied().unwrap_or(0);
        calls(b).cmp(&calls(a)).then_with(|| layout.nodes[a].id.cmp(&layout.nodes[b].id))
    });
    for (rank, index) in members.into_iter().enumerate() {
        layout.nodes[index].y = slots[centre_out(rank, slots.len())];
    }
}

/// The slot the `rank`-th item takes when `count` slots are filled from the middle outwards:
/// the middle, then one below, one above, two below, two above.
fn centre_out(rank: usize, count: usize) -> usize {
    let middle = (count - 1) / 2;
    let distance = (rank + 1) / 2;
    if rank % 2 == 1 {
        (middle + distance).min(count - 1)
    } else {
        middle.saturating_sub(distance)
    }
}

/// 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: every frame, then every box and marker, then every leg.
async fn draw(
    client: &MiroClient,
    prepared: PreparedMap,
    left: f64,
    top: f64,
) -> Result<Vec<crate::batbelt::evm::metadata::bat_metadata::MapFrameRef>, EvmMiroError> {
    use crate::batbelt::evm::miro::auto_deploy::LaneSide;
    use crate::batbelt::miro::MiroError;

    // Each WAVE timed on its own.
    //
    // A wave does not start until the one before it has finished to the last request, so one
    // slow call holds up everything behind it and the run looks frozen and then sudden. "Drawing
    // it: 201s" cannot tell which wave that was, and whether a frame 55 000 units wide costs
    // more to create than a small one is a question only this answers.
    let mut wave_started = std::time::Instant::now();
    let mut wave_time = |what: &str, sent: u32| {
        println!(
            "      {:>5.1}s  {what} ({sent} request(s))",
            wave_started.elapsed().as_secs_f64()
        );
        wave_started = std::time::Instant::now();
    };
    let before = client.sent().0;

    // The frames first and together: everything else is a child of one of them, and a frame is
    // the one thing here nothing can be issued before.
    let mut frames_wave: tokio::task::JoinSet<(usize, String, std::result::Result<String, Report<MiroError>>)> =
        tokio::task::JoinSet::new();
    for (index, frame) in prepared.frames.iter().enumerate() {
        let client = client.clone();
        let title = frame.title.clone();
        let (x, y) = (
            left + frame.left + frame.width / 2.0,
            top + frame.top + frame.height / 2.0,
        );
        let (width, height) = (frame.width, frame.height);
        frames_wave.spawn(async move {
            let made = client.create_frame(&title, x, y, width, height, None).await;
            (index, title, made)
        });
    }
    let mut frame_ids: BTreeMap<usize, String> = BTreeMap::new();
    let mut failures: Vec<String> = Vec::new();
    while let Some(joined) = frames_wave.join_next().await {
        match joined {
            Ok((index, _, Ok(id))) => {
                frame_ids.insert(index, id);
            }
            Ok((_, title, Err(report))) => {
                failures.push(format!("frame {title}: {}", why(&report)))
            }
            Err(error) => failures.push(format!("a frame: {error}")),
        }
    }
    wave_time("the frames", client.sent().0 - before);
    let before = client.sent().0;
    if frame_ids.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("not one frame of the map could be created")
            .attach_printable(failures.join("; ")));
    }

    // ONE wave for everything whose only reference is a frame: the boxes, the badges, the
    // legend's rows, the strip and every marker of every arrow. A marker's position came from
    // the plan, not from a box's id, so nothing about it waits on a box.
    //
    // And sent in BATCHES of twenty, which is the part that matters. One item per request, 226
    // requests at 48 in flight, took 75 seconds against a budget that allows 16.7 writes a
    // second — so the wall was never the budget, it was waiting for a round trip per item.
    // Miro's bulk endpoint takes twenty items a call; connectors it does not take, so the legs
    // below still go one by one.
    enum Made {
        Boxes(usize),
        Markers(Vec<(usize, usize, usize)>, Vec<String>),
    }
    type Outcome = (String, std::result::Result<Made, Report<MiroError>>);
    let mut wave: tokio::task::JoinSet<Outcome> = tokio::task::JoinSet::new();
    /// How many items go in one call.
    ///
    /// Miro's bulk endpoint takes twenty, and twenty was the obvious answer until the waves
    /// were timed separately: 68 bulk calls carrying 1 334 items took **110s**, while the 760
    /// connectors of the same map — one item per call — took **39s**. A bulk of twenty comes
    /// back in about 1.6 seconds and a single item comes back in a twentieth of that, so the
    /// batch buys nothing: latency per call is what sets the pace, not items per call.
    ///
    /// It also costs. A bulk call collapses items that are identical, which is why the markers
    /// have to be made distinct before they are sent; and the legs find their markers by the
    /// POSITION of each id in the answer, which only works while the endpoint answers in the
    /// order it was asked.
    ///
    /// Settable so the next person can measure rather than take this on faith.
    const BATCH: usize = ITEMS_PER_CALL;
    // Every item of every frame, in one list, so a batch is full even when a frame holds three
    // boxes: batching per frame would have sent eight half-empty calls.
    let mut plain: Vec<(String, serde_json::Value)> = Vec::new();
    let mut marker_items: Vec<((usize, usize, usize), serde_json::Value)> = Vec::new();

    for (index, frame) in prepared.frames.iter().enumerate() {
        let Some(frame_id) = frame_ids.get(&index) else {
            continue;
        };
        type Box<'a> = (String, String, f64, f64, f64, f64, usize, &'a str, &'a str, usize, &'a str, &'a str);
        let mut boxes: Vec<Box> = Vec::new();
        if frame.is_legend() {
            for row in legend_rows() {
                let (fill, border, style) = match row.sample {
                    Sample::Leg(_) => (BOX_FILL, BOX_BORDER, "normal"),
                    Sample::Box { fill, border, style } => (fill, border, style),
                };
                // The legend's own sample of a repeated contract has to look like one.
                let thickness = if border == BOX_BORDER { BORDER_WIDTH } else { REPEAT_BORDER_WIDTH };
                boxes.push((
                    format!("legend: {}", row.text),
                    row.text.to_string(),
                    row.x,
                    row.y,
                    row.width,
                    NODE_HEIGHT,
                    NODE_FONT,
                    fill,
                    border,
                    thickness,
                    BOX_BORDER,
                    style,
                ));
            }
        }
        for node in &frame.layout.nodes {
            let (repeat_border, thickness) = frame.border_of(&node.id);
            let (fill, colour, style) = frame.paint_of(&node.id, &prepared.marked);
            let border = if repeat_border == BOX_BORDER { colour } else { repeat_border };
            boxes.push((
                format!("box {}", box_text(&node.id)),
                wrapped(&frame.text_of(&node.id)),
                node.x,
                node.y,
                node.width,
                node.height,
                node_font(&node.id),
                fill,
                border,
                thickness,
                // The name carries the interface's colour; a contract's stays black.
                if is_outside(&node.id) && destination_of(&node.id).is_none() { colour } else { BOX_BORDER },
                style,
            ));
        }
        for node in &frame.strip {
            boxes.push((
                format!("strip: {}", box_text(&node.id)),
                box_text(&node.id).to_string(),
                node.x,
                node.y,
                node.width,
                node.height,
                NODE_FONT,
                STRIP_FILL,
                BOX_BORDER,
                BORDER_WIDTH,
                BOX_BORDER,
                "normal",
            ));
        }
        for (what, text, x, y, width, height, font, fill, border, thickness, text_colour, style) in boxes {
            plain.push((
                what,
                MiroClient::label_item(
                    &text,
                    x,
                    y,
                    width,
                    height,
                    font,
                    fill,
                    border,
                    thickness,
                    text_colour,
                    style,
                    frame_id,
                ),
            ));
        }
        for (arrow_index, arrow) in frame.arrows.iter().enumerate() {
            for (point, (x, y)) in arrow.plan.points.iter().enumerate() {
                marker_items.push((
                    (index, arrow_index, point),
                    MiroClient::marker_item(*x, *y, MARKER_SIZE, frame_id),
                ));
            }
        }
    }

    for batch in plain.chunks(BATCH) {
        let client = client.clone();
        // Named by its first item: a batch that fails has to say what is missing, and listing
        // twenty names in one line says nothing a reader can use.
        let what = format!("a batch of {} item(s) from {}", batch.len(), batch[0].0);
        let items: Vec<serde_json::Value> = batch.iter().map(|(_, item)| item.clone()).collect();
        let count = items.len();
        wave.spawn(async move {
            let made = client.create_items_bulk(items).await.map(|_| Made::Boxes(count));
            (what, made)
        });
    }
    for batch in marker_items.chunks(BATCH) {
        let client = client.clone();
        let what = format!("a batch of {} marker(s)", batch.len());
        let keys: Vec<(usize, usize, usize)> = batch.iter().map(|(key, _)| *key).collect();
        let items: Vec<serde_json::Value> = batch.iter().map(|(_, item)| item.clone()).collect();
        wave.spawn(async move {
            let made = client
                .create_items_bulk(items)
                .await
                .map(|ids| Made::Markers(keys, ids));
            (what, made)
        });
    }

    // Every task 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
    // frames' URLs are never printed, so the auditor is left with a half-drawn board and no
    // idea what is on it. A failure costs its own item and is named.
    let mut markers: BTreeMap<(usize, usize, usize), String> = BTreeMap::new();
    let mut boxes_made = 0usize;
    while let Some(joined) = wave.join_next().await {
        match joined {
            Ok((_, Ok(Made::Boxes(count)))) => boxes_made += count,
            Ok((what, Ok(Made::Markers(keys, ids)))) => {
                // The bulk endpoint answers in the order it was sent, which is what lets a
                // marker be found again by the leg that lands on it. If it ever does not, the
                // legs of those arrows are named as skipped rather than drawn somewhere wrong.
                if ids.len() != keys.len() {
                    failures.push(format!("{what}: {} item(s) back for {} sent", ids.len(), keys.len()));
                }
                for (key, id) in keys.into_iter().zip(ids) {
                    markers.insert(key, id);
                }
            }
            Ok((what, Err(report))) => failures.push(format!("{what}: {}", why(&report))),
            Err(error) => failures.push(format!("a task: {error}")),
        }
    }
    wave_time("the boxes and markers", client.sent().0 - before);
    let before = client.sent().0;
    println!(
        "    {} {} frame(s), {boxes_made} box(es), {} marker(s)",
        "✓".green(),
        frame_ids.len(),
        markers.len()
    );

    // Then every leg of every arrow, together: each one's two ends already exist. The caption
    // rides on the leg that carries the head, and on that one only — a word on every leg of a
    // five-leg chain is five words.
    let mut legs_wave = tokio::task::JoinSet::new();
    let mut skipped: Vec<String> = Vec::new();
    for (index, frame) in prepared.frames.iter().enumerate() {
        if !frame_ids.contains_key(&index) {
            continue;
        }
        for (arrow_index, arrow) in frame.arrows.iter().enumerate() {
            for (from_side, from_anchor, to_side, to_anchor, head) in &arrow.plan.legs {
                let resolve = |side: &LaneSide| match side {
                    LaneSide::Marker(point) => markers.get(&(index, arrow_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!("{}: a leg whose marker failed", arrow_name(frame, arrow)));
                    continue;
                };
                let mut leg = arrow.style.clone();
                leg.arrow = if *head { ArrowEnd::End } else { ArrowEnd::None };
                if !*head {
                    leg.caption = None;
                }
                let (from_anchor, to_anchor) = (*from_anchor, *to_anchor);
                let what = arrow_name(frame, arrow);
                let client = client.clone();
                legs_wave.spawn(async move {
                    let made = client
                        // STRAIGHT, not elbowed. Every leg of a map's arrow is already
                        // horizontal or vertical — the chain is planned that way — so `elbowed`
                        // handed a segment we had already computed to Miro's own router, which
                        // added its own elbows on top and drew a staircase where a line was
                        // asked for. The deploy keeps `elbowed`, where a leg can be diagonal
                        // and a straight one would cut across a screenshot.
                        .create_connector_shaped(
                            &from_id, from_anchor, &to_id, to_anchor, leg, "straight",
                        )
                        .await;
                    (what, made)
                });
            }
        }
    }
    let mut legs = 0usize;
    while let Some(joined) = legs_wave.join_next().await {
        match joined {
            Ok((_, Ok(_))) => legs += 1,
            Ok((what, Err(report))) => failures.push(format!("leg of {what}: {}", why(&report))),
            Err(error) => failures.push(format!("a leg: {error}")),
        }
    }
    wave_time("the connectors", client.sent().0 - before);
    for line in skipped.iter().chain(failures.iter()) {
        println!("    {} {line}", "skipped:".yellow());
    }
    println!(
        "    {} {} relation(s) drawn, {legs} leg(s)",
        "✓".green(),
        prepared
            .frames
            .iter()
            .flat_map(|frame| frame.arrows.iter())
            .filter(|arrow| arrow.edge.is_some())
            .count()
    );
    // One URL per frame, named: the whole point of several frames is that the auditor goes to
    // the one contract they are reading about.
    for (index, frame) in prepared.frames.iter().enumerate() {
        if let Some(id) = frame_ids.get(&index) {
            println!("  {:<46} {}", frame.title, client.frame_url(id).blue());
        }
    }
    // What was drawn, for the registry: which frame shows which contracts. A cluster cannot
    // point at the map without it, and the ids live nowhere else once this run ends.
    let drawn_frames: Vec<crate::batbelt::evm::metadata::bat_metadata::MapFrameRef> = prepared
        .frames
        .iter()
        .enumerate()
        .filter(|(_, frame)| !frame.is_legend())
        .filter_map(|(index, frame)| {
            Some(crate::batbelt::evm::metadata::bat_metadata::MapFrameRef {
                root: frame.root().to_string(),
                frame_id: frame_ids.get(&index)?.clone(),
                contracts: frame.contracts_shown(),
                cards: Vec::new(),
            })
        })
        .collect();
    if !failures.is_empty() {
        // NAMED, in the error itself. The `skipped:` lines above say the same thing, but they
        // scroll past behind a thousand API calls and the error is what the reader is left
        // holding — "33 items could not be drawn" is a number nobody can act on.
        const SHOWN: usize = 12;
        let named = failures
            .iter()
            .take(SHOWN)
            .map(|failure| format!("\n  · {failure}"))
            .collect::<String>();
        let rest = match failures.len() > SHOWN {
            true => format!("\n  · … and {} more", failures.len() - SHOWN),
            false => String::new(),
        };
        return Err(Report::new(EvmMiroError).attach_printable(format!(
            "{} item(s) of this map could not be drawn — the frames above have the rest{named}{rest}",
            failures.len()
        )));
    }
    Ok(drawn_frames)
}

/// Why a call failed, in one line: the attachments the client hung on the report — which is
/// where the HTTP status and Miro's own message live.
///
/// Printing `current_context()` alone printed "Miro error" and nothing else, which told the
/// reader a thing failed and not one fact about why. The body is already carried; it was simply
/// never shown.
fn why(report: &Report<crate::batbelt::miro::MiroError>) -> String {
    let detail: Vec<String> = report
        .frames()
        .filter_map(|frame| frame.downcast_ref::<String>().map(|line| line.trim().to_string()))
        .collect();
    if detail.is_empty() {
        report.current_context().to_string()
    } else {
        detail.join(" — ")
    }
}

/// What an arrow is, for a message about it.
fn arrow_name(frame: &PreparedFrame, arrow: &RoutedArrow) -> String {
    match arrow.edge.and_then(|index| frame.edges.get(index)) {
        Some(edge) => format!("{} → {}", box_text(&edge.from), box_text(&edge.to)),
        None => "a legend sample".to_string(),
    }
}

/// 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.
            //
            // An ignored contract is not a destination either. The auditor declared it out of
            // the audit, and `ignored` used to be read only for the contract an edge leaves
            // FROM — so a contract nobody was going to look at still took a box and an arrow
            // the moment somebody called it.
            // `opexTreasury%Treasury` is a deployment of `Treasury`: what is folded, ignored or
            // the caller itself is a question about the contract, never about which copy.
            let entity = to.split_once(VARIABLE_MARK).map(|(_, held)| held).unwrap_or(to);
            // A call written as a cast — `StakingQuoteOracle(oracle_).quoteAsset()` in a
            // constructor — names no variable, and drawing it beside `oracle (StakingQuoteOracle)`
            // is two boxes for one address. When the contract holds exactly ONE variable of that
            // type, that is which one it is; holding several (five `Treasury`s) it stays the
            // plain type, because then the code really does not say.
            // Only for this repository's own contracts: a boundary box is the TYPE the caller
            // sees (`IERC20`, `ERC20`), one copy per caller, and naming it after a variable
            // would say which deployment we cannot know.
            let singular: Option<&str> = match to.contains(VARIABLE_MARK) || !in_scope.contains(entity) {
                true => None,
                false => {
                    // By what the type MEANS, not by how it is written: `IAscendLaunchpad
                    // launchpad` holds an `AscendLaunchpad`, and comparing the raw names drew
                    // the wiring as `launchpad (AscendLaunchpad)` and the call as a second,
                    // plain `AscendLaunchpad` box in the same frame.
                    let mut held = contract.state_variables.iter().filter(|state| {
                        matches!(
                            classify_type(metadata, Some(contract.name.as_str()), &state.type_name),
                            TypeTarget::Contract(ref held) if held == entity
                        )
                    });
                    held.next().filter(|_| held.next().is_none()).map(|state| state.name.as_str())
                }
            };
            // And the variable only sticks to a DEPLOYABLE contract of this repository. An
            // interface or a vendored type is a boundary box, drawn once per caller with its
            // methods hanging off it (`IStakingSwapRouter@YieldRouter`); renaming it after the
            // variable broke that pairing and the methods lost their box.
            let deployable = metadata.contracts.iter().any(|c| {
                !c.vendored
                    && c.name == entity
                    && c.contract_type == crate::batbelt::evm::types::EvmContractType::Contract
            });
            let to = &match (deployable, singular) {
                (false, _) => entity.to_string(),
                (true, Some(variable)) => format!("{variable}{VARIABLE_MARK}{entity}"),
                (true, None) => to.to_string(),
            };
            if entity.is_empty()
                || entity == contract.name
                || folded.contains(entity)
                || ignored(entity, "")
            {
                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)> {
            // `opexTreasury%Treasury`: which deployment, and of what. The type decides where the
            // arrow lands; the variable only survives when the answer is that type itself.
            let (held_by, type_name) = match type_name.split_once(VARIABLE_MARK) {
                Some((variable, held)) => (Some(variable), held),
                None => (None, type_name),
            };
            match classify_type(metadata, Some(contract.name.as_str()), type_name) {
                TypeTarget::Contract(target) => Some((
                    match held_by {
                        Some(variable) if target == type_name => {
                            format!("{variable}{VARIABLE_MARK}{target}")
                        }
                        _ => 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,
                    // A boundary that is only READ is a read: `IERC20Metadata.decimals()`,
                    // `IStakingPriceFeed.latestRoundData()`. Called a plain boundary it came
                    // out as a box with nothing under it — every method filtered as a view —
                    // saying "this is touched" and leaving the reader to wonder what for.
                    match relation {
                        // A boundary only READ, and a boundary only HELD, keep what they are:
                        // flattening both to "leaves the code" made `IMirrorFactory` — one
                        // `view` call and an immutable — a box with nothing under it and
                        // nothing said about it.
                        Relation::Reads => Relation::Reads,
                        Relation::WiresAtConstruction => Relation::WiresAtConstruction,
                        _ => 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()
                .chain(inherited(metadata, contract).iter())
                .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) {
                record(&created, Relation::Creates);
            }
            // WHICH deployment the call goes to, when the receiver is a state variable:
            // `listingDesk.collect()` is a call on the address `listingDesk` holds, which is
            // the box its creation already drew. Without this the same deployment got two
            // boxes — one named by its variable, one by its type.
            let held_by = |receiver: &str| -> Option<&str> {
                let name = receiver.trim();
                contract
                    .state_variables
                    .iter()
                    .find(|state| state.name == name)
                    .map(|state| state.name.as_str())
            };
            for call in &function.resolved_calls {
                if in_scope.contains(call.contract.as_str()) {
                    // A call that only READS is a relation that sets nothing off. `YieldRouter`
                    // reaches `AscendLaunchpad` through `poolManager()` and `emaSqrtPrice()`
                    // and nothing else — and the frame hung the launchpad's whole mutating
                    // subtree under that arrow, a graph the router cannot trigger.
                    let kind = match reads_only(metadata, &call.contract, &call.method) {
                        true => Relation::Reads,
                        false => Relation::Calls,
                    };
                    let to = match held_by(&call.receiver) {
                        Some(variable) => format!("{variable}{VARIABLE_MARK}{}", call.contract),
                        None => call.contract.clone(),
                    };
                    record(&to, kind);
                }
            }
            let typed = function
                .unresolved_calls
                .iter()
                .map(|call| (call.receiver.as_str(), call.inferred_type.as_str(), call.method.as_str()))
                .chain(function.unknown_external_calls.iter().map(|call| {
                    (call.receiver.as_str(), call.inferred_type.as_str(), call.method.as_str())
                }));
            for (receiver, type_name, method) in typed {
                // A library call by name is a call on its first parameter — the receiver
                // `using X for Y` would have made explicit. Classified as the library itself it
                // was folded or ignored away, and with it went `Treasury.sweep`'s token leg.
                let aimed_type = through_library(metadata, type_name, method);
                let type_name = aimed_type.as_deref().unwrap_or(type_name);
                let kind = match reads_only(metadata, type_name, method) {
                    true => Relation::Reads,
                    false => Relation::Calls,
                };
                let aimed = match held_by(receiver) {
                    Some(variable) => format!("{variable}{VARIABLE_MARK}{type_name}"),
                    None => type_name.to_string(),
                };
                if let Some((to, relation)) = aim(&aimed, kind) {
                    // `aim` keeps the relation it was given unless the far end is unresolved or
                    // outside, which are facts about the TARGET and outrank how it was reached.
                    record(&to, relation);
                }
            }
        }

        for wired in sources.iter().flat_map(|source| wired_at_construction(source, &metadata.wiring)) {
            if let Some((to, relation)) = aim(&wired, Relation::WiresAtConstruction) {
                record(&to, relation);
            }
        }
    }

    // One arrow per pair — two between the same boxes is the noise this map exists to avoid —
    // and the one kept is the one that SAYS THE MOST.
    //
    // `creates` outranks `calls`: that an address exists because of this line is the rare fact,
    // and it is the one nothing else on the board shows. That it also calls what it made is
    // taken for granted — `AscendYieldVault` both creates `YieldExitReserve` in `_checkpoint`
    // and calls it, and the map used to draw only the call, which read as two contracts that
    // happened to find each other.
    //
    // Below that, what a scan is SURER of wins: a call it pinned over wiring it inferred, and
    // either over a binding it could not pin at all.
    let rank = |relation: Relation| match relation {
        Relation::Creates => 0,
        Relation::Calls => 1,
        // A call that leaves the code is still a CALL: one `safeTransfer` outranks any number
        // of `decimals()`. Ranked under the reads, a single view call turned a mutating
        // boundary into a read and took its methods with it — 105 leaves became 62.
        Relation::Boundary => 2,
        Relation::Unresolved => 3,
        // A read outranks only the wiring: `YieldRouter` holds the vault AND asks it for the
        // rate, and "wired, never called" was the wrong half of that.
        Relation::Reads => 4,
        Relation::WiresAtConstruction => 5,
    };
    let mut best: BTreeMap<(String, String), Relation> = BTreeMap::new();
    for edge in found {
        best.entry((edge.from.clone(), edge.to.clone()))
            .and_modify(|existing| {
                if rank(edge.relation) < rank(*existing) {
                    *existing = 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();
        // `using VaultPay for IVault` is the other way a contract runs a library's code, and
        // the call site reads `poolVault.buyExactIn(…)` — no `VaultPay.` anywhere for the
        // callee scan to find. Without this, `VaultPay`'s `pm.swap` and `vault.sync` belonged
        // to nobody and the `ICLPoolManager` box under `YieldRouter` came out with no methods.
        used.extend(
            contract
                .using_libraries
                .iter()
                .filter(|library| folded.contains_key(library.as_str()))
                .cloned(),
        );
        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: &crate::batbelt::evm::metadata::bat_metadata::FunctionMetadata,
) -> Vec<String> {
    // WHERE each one was put. `AscendLaunchpad`'s constructor runs `new Treasury(owner_)` five
    // times into five variables: five addresses, and keyed by the type alone the map drew one
    // arrow to one box. The variable names the box — the same box its transfers point at, so
    // this costs the board nothing it was not already drawing.
    callees_of(metadata, &function.metadata_id)
        .iter()
        .filter_map(|callee| callee.strip_suffix(".constructor"))
        .filter_map(|name| metadata.contract_in_scope(name, &caller.file_path))
        .filter(|target| !target.vendored)
        .flat_map(|target| {
            let variables: Vec<&str> = function
                .creations
                .iter()
                .filter(|(variable, created)| {
                    created == &target.name
                        && caller.state_variables.iter().any(|state| state.name == *variable)
                })
                .map(|(variable, _)| variable.as_str())
                .collect();
            match variables.is_empty() {
                // Not stored in state: a local, a return value. Nothing names it but its type.
                true => vec![target.name.clone()],
                false => variables
                    .into_iter()
                    .map(|variable| format!("{variable}{VARIABLE_MARK}{}", target.name))
                    .collect(),
            }
        })
        .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,
    wiring: &std::collections::HashMap<String, String>,
) -> 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.
        // The variable comes along: `opexTreasury` and `kntqTreasury` are two addresses of one
        // type, and the wiring arrow has to land on the same box its creation did instead of
        // adding a generic `Treasury` beside the six named ones. `aim` drops the variable
        // again when the TYPE is what decides the far end (an interface collapsing into its
        // implementer, a struct that is no relation at all).
        .map(|variable| {
            // A recorded answer outranks the declared type here as well: `treasury` is declared
            // `Treasury` and holds a `StakingFeeTreasury` in this deployment.
            let held = wiring
                .get(&format!("{}.{}", contract.name, variable.name))
                .map(String::as_str)
                .unwrap_or(variable.type_name.trim());
            format!("{}{VARIABLE_MARK}{held}", variable.name)
        })
        .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, scope: Option<&str>, 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.resolution_for(scope, 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()),
        // Nobody declares `is IListingLaunchpad` — but it EXTENDS `IAscendLaunchpad`, and
        // `AscendLaunchpad` declares that base and every function the child adds. That is
        // what satisfying an interface means in Solidity, and a reader can see it; the map
        // called it somebody else's code, which hid the desk/launchpad cycle and drew a
        // destination that does not exist.
        (None, _) if is_interface => match satisfied_by(metadata, name) {
            Some(only) => TypeTarget::Contract(only),
            None => 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 one in-scope contract that satisfies this interface without declaring it, if exactly
/// one does.
///
/// An interface that extends another — `IListingLaunchpad is IAscendLaunchpad` — is satisfied
/// by a contract that declares the BASE and defines every function the child adds. Both halves
/// are checked, because the base alone proves nothing (two contracts can declare it and only
/// one carry the extra methods), and the function list alone proves nothing either.
///
/// Several candidates is a question, not an answer: it stays the outside and
/// `bat-cli resolve` is the reader's word on it.
fn satisfied_by(metadata: &EvmBatMetadata, interface: &str) -> Option<String> {
    use crate::batbelt::evm::types::EvmContractType;
    let declared: Vec<&ContractMetadata> =
        metadata.contracts.iter().filter(|c| c.name == interface).collect();
    let bases: BTreeSet<&str> = declared
        .iter()
        .flat_map(|c| c.base_contracts.iter())
        .map(String::as_str)
        .collect();
    if bases.is_empty() {
        return None;
    }
    let wanted: BTreeSet<&str> = declared
        .iter()
        .flat_map(|c| c.functions.iter())
        .map(|function| function.name.as_str())
        .collect();
    let mut found = metadata
        .contracts
        .iter()
        .filter(|c| !c.vendored && c.contract_type == EvmContractType::Contract)
        .filter(|c| {
            let family = inherited(metadata, c);
            bases.iter().any(|base| {
                c.base_contracts.iter().any(|own| own == base) || family.iter().any(|up| up == base)
            })
        })
        .filter(|c| {
            let family: Vec<&ContractMetadata> = std::iter::once(*c)
                .chain(
                    inherited(metadata, c)
                        .iter()
                        .filter_map(|name| metadata.contracts.iter().find(|up| up.name == *name))
                        .collect::<Vec<_>>(),
                )
                .collect();
            // A `public` state variable IS a function: Solidity writes its getter, and
            // `listingDesk()` and `owner()` of `IListingLaunchpad` are exactly that. Counting
            // only the declared functions left the interface unsatisfied by the contract that
            // satisfies it.
            let own: BTreeSet<&str> = family
                .iter()
                .flat_map(|contract| contract.functions.iter())
                .map(|function| function.name.as_str())
                .chain(
                    family
                        .iter()
                        .flat_map(|contract| contract.state_variables.iter())
                        .filter(|state| {
                            state.visibility == crate::batbelt::evm::types::EvmVisibility::Public
                        })
                        .map(|state| state.name.as_str()),
                )
                .collect();
            wanted.iter().all(|method| own.contains(method))
        });
    match (found.next(), found.next()) {
        (Some(only), None) => Some(only.name.clone()),
        _ => None,
    }
}

/// 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 {
                // A call on a value type or a library runs HERE: `PoolId.unwrap(id)` is a cast
                // the compiler erases and `LaunchpadKey.keyOf(...)` is this contract's own code
                // by another name. Neither crosses anything, so neither is a receiver the scan
                // failed to type — listing them asked the reader to resolve a non-question.
                if runs_locally(metadata, receiver) {
                    continue;
                }
                // A native-value call IS drawn now, in its own boundary box with the receiver
                // as its party — reporting it as something the map left out is a lie.
                if (method.ends_with("{value}")
                    || matches!(method.as_str(), "call" | "delegatecall"))
                    && receiver != "assembly"
                {
                    continue;
                }
                // A call on a STRUCT or a mapping entry cannot leave this contract: it is a
                // library attached with `using … for`, running here. `pendingCap[].update` is
                // not a receiver the scan failed to type — it is not a receiver at all.
                if holds_no_code(metadata, inferred_type) {
                    continue;
                }
                if classify_type(metadata, Some(contract.name.as_str()), 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()
}

/// Is this method a LIBRARY's, attached to that type with `using … for`, rather than the
/// type's own?
///
/// Only when the type is one this scan knows: a type it has never seen declares nothing, and
/// drawing the call is better than hiding it. The library's first parameter is the receiver —
/// that is what `using X for T` means — so the shape is checked, not the name.
///
/// And only when the library's body says what DOES cross: `VaultPay.pay(IVault vault, …)` calls
/// `vault.sync()` and `vault.settle()`, which are drawn on their own, so the `pay()` leaf was a
/// method the vault does not have. `SafeTransferLib.safeTransfer(ERC20 token, …)` writes its
/// call in assembly and never names `token` again — dropping that leaf dropped the transfer
/// itself, and left a bare `ERC20` box reaching nothing. Nothing else drawn means the leaf
/// stays: a call this map cannot relocate is a call it still has to show.
fn attached_elsewhere(metadata: &EvmBatMetadata, type_name: &str, method: &str) -> bool {
    use crate::batbelt::evm::types::EvmContractType;
    let known = metadata.contracts.iter().any(|contract| contract.name == type_name);
    if !known {
        return false;
    }
    let family = type_family(metadata, type_name);
    let declares = metadata
        .contracts
        .iter()
        .filter(|contract| family.contains(contract.name.as_str()))
        .any(|contract| contract.functions.iter().any(|function| function.name == method));
    if declares {
        return false;
    }
    metadata
        .contracts
        .iter()
        .filter(|contract| contract.contract_type == EvmContractType::Library)
        .flat_map(|contract| contract.functions.iter())
        .any(|function| {
            function.name == method
                && function
                    .params
                    .first()
                    .is_some_and(|first| first.type_name.trim() == type_name)
                // What the body does to the receiver is what replaces this leaf. A body that
                // never calls the receiver by name — solmate's assembly — replaces it with
                // nothing, and then hiding the leaf hides the call.
                && function.params.first().is_some_and(|receiver| {
                    function
                        .unknown_external_calls
                        .iter()
                        .any(|call| call.receiver == receiver.name)
                })
        })
}

/// Is `name` a struct this type declares — so `Type.name(…)` is building one, not calling?
fn declares_struct(metadata: &EvmBatMetadata, type_name: &str, name: &str) -> bool {
    use crate::batbelt::evm::types::EvmFileItemKind;
    metadata.file_items.iter().any(|item| {
        item.kind == EvmFileItemKind::Struct
            && item.name == name
            && item.owner == type_name
    })
}

/// Is this type a value rather than an address: a struct, an enum, a mapping, a value type?
///
/// A call on one of those is a library attached with `using … for`, which runs in the calling
/// contract. There is nothing to type and nothing to resolve.
fn holds_no_code(metadata: &EvmBatMetadata, type_name: &str) -> bool {
    use crate::batbelt::evm::types::EvmFileItemKind;
    let clean = type_name.trim().trim_end_matches("[]");
    if clean.is_empty() {
        return false;
    }
    if clean.starts_with("mapping(") {
        return true;
    }
    metadata.file_items.iter().any(|item| {
        item.name == clean
            && matches!(
                item.kind,
                EvmFileItemKind::Struct | EvmFileItemKind::Enum | EvmFileItemKind::TypeAlias
            )
    })
}

/// Does a call on this receiver run in the calling contract?
///
/// Two shapes, one answer. A user-defined value type (`type PoolId is bytes32`) only ever
/// carries `wrap`/`unwrap` and whatever `using … for` attaches, and all of it is erased at
/// compile time. A LIBRARY's code runs as the contract that calls it — which the map already
/// knows, since it folds libraries into their callers rather than drawing them.
fn runs_locally(metadata: &EvmBatMetadata, receiver: &str) -> bool {
    use crate::batbelt::evm::types::{EvmContractType, EvmFileItemKind};
    let name = receiver.trim();
    metadata
        .file_items
        .iter()
        .any(|item| item.name == name && item.kind == EvmFileItemKind::TypeAlias)
        || metadata
            .contracts
            .iter()
            .any(|c| c.name == name && c.contract_type == EvmContractType::Library)
}

/// 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, &metadata.wiring));
        for type_name in referenced {
            if let TypeTarget::Outside(name) =
                classify_type(metadata, Some(contract.name.as_str()), &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());
        }
        // The terminal shows the id, minus the bookkeeping: `=>feeSink~` is an address, and
        // the tilde is how the drawing knows, not something to read.
        let to = edge.to.replace(ADDRESS_MARK, "");
        lines.push(format!("  → {:<28} {}", 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, FunctionDependency, 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(),
            structs: 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(),
            callbacks: Vec::new(),
            creations: 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()
    }

    /// A pair that is both CREATED and called keeps the creation. One arrow per pair, and the
    /// one kept is the one that says the most: that an address exists because of this line is
    /// the rare fact and the one nothing else on the board shows. `AscendYieldVault` creates
    /// `YieldExitReserve` in `_checkpoint` and calls it, and the map used to draw only the
    /// call, which read as two contracts that happened to find each other.
    #[test]
    fn a_created_and_called_pair_keeps_the_creation() {
        let mut vault = contract("AscendYieldVault", EvmContractType::Contract, &[], false);
        vault.functions.push(calling("YieldExitReserve"));
        let maker = vault.functions[0].metadata_id.clone();
        let metadata = EvmBatMetadata {
            contracts: vec![
                vault,
                contract("YieldExitReserve", EvmContractType::Contract, &[], false),
            ],
            function_dependencies: vec![FunctionDependency {
                function_metadata_id: maker,
                callees: vec!["YieldExitReserve.constructor".to_string()],
            }],
            ..Default::default()
        };
        assert_eq!(
            pairs(&relations(&metadata)),
            vec![(
                "AscendYieldVault".to_string(),
                "YieldExitReserve".to_string(),
                Relation::Creates
            )]
        );
    }

    /// `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, None, "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, None, "IVault"), TypeTarget::Open("IVault".to_string()));
        assert_eq!(
            pairs(&drawn_edges(&metadata, &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, None, "Limits"), TypeTarget::NotAContract);
        assert_eq!(classify_type(&metadata, None, "CurveStep[]"), TypeTarget::NotAContract);
        assert_eq!(classify_type(&metadata, None, "mapping(Id => PendingUint192)"), TypeTarget::NotAContract);
        // With boundaries on, which is where the structs used to leak through as "outside".
        assert_eq!(
            pairs(&relations(&metadata)),
            // The variable comes with it: two feeds of one type are two addresses.
            vec![(
                "AscendYieldVault".to_string(),
                "pricefeed%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, None, "ERC20"), TypeTarget::Outside("ERC20".to_string()));
        // Only HELD, in this fixture: the box is the outside either way, and the arrow says
        // which of the two facts it is — here, an immutable and not one call.
        assert_eq!(
            pairs(&relations(&metadata)),
            vec![(
                "AscendCoreToken".to_string(),
                "ERC20".to_string(),
                Relation::WiresAtConstruction
            )]
        );
        // Drawn, as a leaf of its own caller: `ERC20@AscendCoreToken` is that contract's own
        // copy, so no two callers share a box for it.
        let drawn = drawn_edges(&metadata, &relations(&metadata), false);
        assert_eq!(drawn.len(), 1);
        assert_eq!(drawn[0].to, "ERC20@AscendCoreToken");
        assert_eq!(super::box_text(&drawn[0].to), "ERC20");
        assert!(
            drawn_edges(&metadata, &relations(&metadata), true).is_empty(),
            "--no-boundaries draws none"
        );
    }

    /// 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, None, "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(&metadata, &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"));
    }

}

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

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

    /// The hierarchy names both ends and nothing in between: a top caller is what the map
    /// frames, a foundation is what everything else needs in order to exist.
    #[test]
    fn the_hierarchy_names_the_tops_and_the_foundations() {
        let edges = vec![
            edge("Launchpad", "Desk", Relation::Calls),
            edge("Desk", "Treasury", Relation::Calls),
            edge("Router", "Treasury", Relation::Calls),
        ];
        // Nothing is outside in this fixture: the shape of the hierarchy is the whole point.
        let metadata =
            crate::batbelt::evm::metadata::bat_metadata::EvmBatMetadata::default();
        let lines = hierarchy(&metadata, &edges, false);
        let tops: Vec<&String> = lines
            .iter()
            .take_while(|line| !line.is_empty())
            .filter(|line| line.starts_with("  "))
            .collect();
        assert_eq!(tops.len(), 2, "Launchpad and Router: {tops:?}");
        assert!(tops.iter().all(|line| line.contains("Launchpad") || line.contains("Router")));
        let foundations: Vec<&String> = lines
            .iter()
            .skip_while(|line| !line.is_empty())
            .filter(|line| line.starts_with("  "))
            .collect();
        assert_eq!(foundations.len(), 1, "only Treasury depends on nothing: {foundations:?}");
        assert!(foundations[0].contains("Treasury") && foundations[0].contains('2'));
    }

    /// The hierarchy is about this repository's contracts: what leaves the code is a badge,
    /// never a rung of the hierarchy, whichever way the flag is set.
    #[test]
    fn the_outside_is_never_part_of_the_hierarchy() {
        let edges = vec![
            edge("Vault", "IERC20", Relation::Boundary),
            edge("Vault", "Oracle", Relation::Calls),
        ];
        let metadata =
            crate::batbelt::evm::metadata::bat_metadata::EvmBatMetadata::default();
        for no_boundaries in [true, false] {
            assert!(hierarchy(&metadata, &edges, no_boundaries)
                .iter()
                .all(|line| !line.contains("IERC20")));
        }
        assert!(hierarchy(&metadata, &edges, false).iter().any(|line| line.contains("Oracle")));
    }
}

#[cfg(test)]
mod visual_test {
    use super::{
        centre_out, legend_rows, order_hub_column, route_arrows, strip_of, style_of, Edge,
        Relation, Sample, CYCLE_COLOUR, EDGE_COLOUR, LEGEND_ROWS, NODE_HEIGHT, STRIP_HEADING,
    };
    use crate::batbelt::evm::miro::auto_deploy::LaneSide;
    use crate::batbelt::miro::client::ConnectorStroke;
    use crate::batbelt::miro::layout::{GraphLayout, PlacedNode};

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

    fn node(id: &str, layer: usize, x: f64, y: f64) -> PlacedNode {
        PlacedNode { id: id.to_string(), layer, x, y, width: 1_000.0, height: NODE_HEIGHT }
    }

    /// A layout as `layout_graph` would hand it back: columns 1 000 wide at a 2 000 pitch,
    /// every route listed from the CALLEE's column outwards.
    fn layout(nodes: Vec<PlacedNode>, routes: Vec<Vec<(f64, f64)>>) -> GraphLayout {
        GraphLayout {
            nodes,
            routes,
            back_edges: Vec::new(),
            bbox_width: 8_000.0,
            bbox_height: 4_000.0,
            frame_width: 9_200.0,
            frame_height: 5_200.0,
            crossings: 0,
        }
    }

    /// The legs of one arrow as point-to-point segments.
    fn segments(arrow: &super::RoutedArrow) -> Vec<((f64, f64), (f64, f64))> {
        arrow
            .plan
            .legs
            .iter()
            .filter_map(|(from, _, to, _, _)| {
                let at = |side: &LaneSide| match side {
                    LaneSide::Marker(index) => arrow.plan.points.get(*index).copied(),
                    LaneSide::Item(_) => None,
                };
                Some((at(from)?, at(to)?))
            })
            .collect()
    }

    /// The layout bends an edge from the callee's column outwards, and the chain is drawn from
    /// the caller: consumed as listed, an arrow skipping two columns ran its corridor legs at
    /// the wrong columns' heights — through the boxes. The corridor beside the caller comes
    /// first.
    #[test]
    fn corridors_are_walked_from_the_callers_side() {
        let laid = layout(
            // The caller is column 0 — its frame's own contract — and the chain grows right.
            vec![node("Caller", 0, 500.0, 3_000.0), node("Callee", 3, 6_500.0, 1_000.0)],
            // Column 1's corridor at y = 2 400, column 2's at y = 1 700: caller-first order.
            vec![vec![(2_000.0, 2_400.0), (4_000.0, 1_700.0)]],
        );
        let routed = route_arrows(&[edge("Caller", "Callee", Relation::Calls)], &laid, false);
        let arrow = routed.iter().find(|arrow| arrow.edge == Some(0)).expect("the arrow");
        let legs = segments(arrow);
        // Leg 1 leaves the caller; leg 2 runs up the first lane to the FIRST corridor the
        // arrow meets, which is the column beside the caller.
        let first_drop = legs[1];
        assert_eq!(first_drop.0 .1, 3_000.0, "from the caller's row: {legs:?}");
        assert_eq!(first_drop.1 .1, 2_400.0, "to the corridor of the column beside the caller: {legs:?}");
        // Two skipped columns: at most 2s + 2 markers and 2s + 3 legs — fewer when two of them
        // land on the same point, which `tighten` collapses rather than asking Miro to draw a
        // connector from an item to itself.
        assert!(arrow.plan.points.len() <= 6 + 2, "{:?}", arrow.plan.points);
        assert!(arrow.plan.legs.len() <= 7);
        assert!(arrow.plan.legs.last().expect("a leg").4, "the last leg still carries the head");
    }

    /// Five arrows into one contract used to meet its border at one point. They land spread
    /// along the side, in the order they arrive from, so none crosses another at the box.
    #[test]
    fn arrows_meeting_one_box_are_spread_along_its_side() {
        let laid = layout(
            vec![
                node("Top", 0, 500.0, 500.0),
                node("Mid", 0, 500.0, 2_000.0),
                node("Low", 0, 500.0, 3_500.0),
                node("Hub", 1, 2_500.0, 2_000.0),
            ],
            vec![Vec::new(), Vec::new(), Vec::new()],
        );
        let edges = [
            edge("Low", "Hub", Relation::Calls),
            edge("Top", "Hub", Relation::Calls),
            edge("Mid", "Hub", Relation::Calls),
        ];
        let routed = route_arrows(&edges, &laid, false);
        let landing = |index: usize| {
            let arrow = routed.iter().find(|arrow| arrow.edge == Some(index)).expect("drawn");
            segments(arrow).last().expect("the head leg").1 .1
        };
        let (low, top, mid) = (landing(0), landing(1), landing(2));
        assert!(top < mid && mid < low, "landings follow where the arrows come from: {top} {mid} {low}");
        assert!((low - top) <= NODE_HEIGHT - 2.0 * super::ANCHOR_INSET, "and stay on the box's side");
        assert_eq!(mid, 2_000.0, "the middle one lands on the middle");
    }

    /// The first column is ordered by how many contracts point at each box, from the middle
    /// outwards: the hub in the middle, where its arrows split above and below it.
    #[test]
    fn the_hub_column_puts_the_most_called_in_the_middle() {
        let mut laid = layout(
            vec![
                node("A", 0, 500.0, 500.0),
                node("B", 0, 500.0, 1_000.0),
                node("Hub", 0, 500.0, 1_500.0),
                node("D", 0, 500.0, 2_000.0),
                node("E", 0, 500.0, 2_500.0),
                node("Caller", 1, 2_500.0, 500.0),
            ],
            Vec::new(),
        );
        let edges = [
            edge("Caller", "A", Relation::Calls),
            edge("Caller", "E", Relation::Calls),
            edge("Caller", "E", Relation::Creates),
            edge("Caller", "Hub", Relation::Calls),
        ];
        // E is reached by two relations, Hub by one, A by one, B and D by none.
        order_hub_column(&mut laid, &edges);
        let y = |id: &str| laid.nodes.iter().find(|node| node.id == id).expect(id).y;
        assert_eq!(y("E"), 1_500.0, "the most called takes the middle slot");
        assert_eq!(y("Caller"), 500.0, "other columns are untouched");
        let mut ys: Vec<f64> = ["A", "B", "Hub", "D", "E"].iter().map(|id| y(id)).collect();
        ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
        assert_eq!(ys, vec![500.0, 1_000.0, 1_500.0, 2_000.0, 2_500.0], "the same slots, reassigned");
    }

    #[test]
    fn centre_out_fills_the_middle_then_alternates() {
        let order: Vec<usize> = (0..5).map(|rank| centre_out(rank, 5)).collect();
        assert_eq!(order, vec![2, 3, 1, 4, 0]);
        let order: Vec<usize> = (0..4).map(|rank| centre_out(rank, 4)).collect();
        assert_eq!(order, vec![1, 2, 0, 3]);
    }

    /// One colour for the relations a reader walks, three strokes to tell them apart, and the
    /// two colours that mean something: red for an arrow that runs backwards, green for one
    /// that DEPLOYED the contract at its head. Neither carries a word any more.
    #[test]
    fn one_colour_three_strokes_and_a_colour_where_it_means_something() {
        for relation in [Relation::Calls, Relation::WiresAtConstruction, Relation::Unresolved] {
            assert_eq!(style_of(relation, false).stroke_color, EDGE_COLOUR);
        }
        assert_eq!(style_of(Relation::Creates, false).stroke_color, super::CREATES_COLOUR);
        assert_eq!(style_of(Relation::Creates, false).caption, None, "the colour replaced the word");
        assert_eq!(style_of(Relation::Calls, false).stroke, ConnectorStroke::Solid);
        assert_eq!(style_of(Relation::Unresolved, false).stroke, ConnectorStroke::Dashed);
        assert_eq!(style_of(Relation::Unresolved, false).caption.as_deref(), Some("?"));
        assert_eq!(style_of(Relation::WiresAtConstruction, false).stroke, ConnectorStroke::Dotted);
        assert_eq!(style_of(Relation::Calls, true).stroke_color, CYCLE_COLOUR);
    }

    /// A cycle — the layout had to reverse it — is drawn red, by us and not by Miro, and the
    /// short way round: out of the caller's left, one row down, across, up and in. It used to
    /// be dropped without a word, then drawn through the boxes, then sent on a lap of the whole
    /// frame to reach a contract two rows above.
    #[test]
    fn a_backwards_arrow_is_drawn_red_box_to_box() {
        let laid = layout(
            vec![node("Left", 0, 500.0, 1_000.0), node("Right", 1, 2_500.0, 1_000.0)],
            vec![Vec::new(), Vec::new()],
        );
        let edges = [
            // Left → Right is the flow; Right → Left runs back against it and is the cycle.
            edge("Left", "Right", Relation::Calls),
            edge("Right", "Left", Relation::Calls),
        ];
        let routed = route_arrows(&edges, &laid, false);
        let back = routed.iter().find(|arrow| arrow.edge == Some(1)).expect("the cycle is drawn");
        assert_eq!(back.style.stroke_color, CYCLE_COLOUR);
        let legs = segments(back);
        // Down out of the caller, left under every box, up into the callee: three legs, the
        // head on the last. Routed by us and not by Miro, which drew it through the middle of
        // the frame and across every other arrow.
        assert_eq!(legs.len(), 5);
        let row_bottom = 1_000.0 + NODE_HEIGHT / 2.0;
        assert_eq!(legs[0].0, (2_000.0, 1_000.0), "out of Right's LEFT side, towards the callee");
        assert!(legs[0].1 .0 < 2_000.0, "into the lane beside it: {legs:?}");
        assert!(legs[1].1 .1 > row_bottom, "down just past its own row, not past the frame");
        assert_eq!(legs[2].0 .1, legs[2].1 .1, "along the corridor");
        assert!(legs[3].1 .0 < 0.0, "up outside the callee's column");
        assert_eq!(legs[4].1, (0.0, 1_000.0), "and into Left's left side");
        assert!(back.plan.legs[..4].iter().all(|leg| !leg.4), "no head before the end");
        assert!(back.plan.legs[4].4, "the last leg carries the head");
    }

    /// The legend is drawn by the same code as the map: its samples are arrows, so they are
    /// counted and previewed with the rest, and the layout reserves exactly its rows.
    #[test]
    fn the_legend_is_rows_of_real_samples() {
        let rows = legend_rows();
        assert_eq!(rows.len(), LEGEND_ROWS);
        let legs = rows.iter().filter(|row| matches!(row.sample, Sample::Leg(_))).count();
        let laid = layout(vec![node("A", 0, 500.0, 1_000.0), node("B", 1, 2_500.0, 1_000.0)], vec![Vec::new()]);
        let routed = route_arrows(&[edge("B", "A", Relation::Calls)], &laid, true);
        assert_eq!(routed.iter().filter(|arrow| arrow.edge.is_none()).count(), legs);
        assert!(rows.iter().any(|row| matches!(row.sample, Sample::Leg(ref style) if style.stroke_color == CYCLE_COLOUR)));
    }

    /// The strip stacks under the legend's rows, heading first — present on the picture, and
    /// apart from the diagrams.
    #[test]
    fn the_strip_stacks_under_the_legend() {
        let strip = strip_of(&["Alone".to_string(), "Proxy".to_string()], 4_000.0);
        assert_eq!(strip.len(), 3);
        assert_eq!(strip[0].id, STRIP_HEADING);
        assert_eq!(strip[0].y, 4_000.0);
        assert!(strip[1].y > strip[0].y && strip[2].y > strip[1].y);
        assert!(strip_of(&[], 4_000.0).is_empty());
    }
}

#[cfg(test)]
mod framing_test {
    use super::{original_of, partition_frames, unfold, BTreeMap, Edge, Relation};
    use crate::batbelt::evm::metadata::bat_metadata::{ContractMetadata, EvmBatMetadata};

    /// The least a contract can be and still be one, for a fixture about colours.
    pub(super) fn contract_named(name: &str) -> ContractMetadata {
        ContractMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            using_libraries: Vec::new(),
            file_path: format!("src/{name}.sol"),
            contract_type: crate::batbelt::evm::types::EvmContractType::Contract,
            base_contracts: Vec::new(),
            functions: Vec::new(),
            state_variables: Vec::new(),
            structs: Vec::new(),
            events: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            vendored: false,
        }
    }

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

    /// The second branch to reach an entity draws the BOX and not what hangs off it.
    ///
    /// `AscendCtoRegistry` creates `AscendCtoReceiver` and both call `launchpad`, so one frame
    /// drew the launchpad's entire system twice. Three ways out of that, and this is the third:
    /// drawing it twice says one thing twice; pointing the second arrow at the first box puts
    /// the shared box wherever the other branch left it, and an arrow that does not move right
    /// is drawn red, which the legend reads as a cycle. Cutting the subtree costs one box and
    /// invents no arrow.
    #[test]
    fn the_second_branch_draws_the_box_and_not_the_subtree() {
        use super::{rejoin, same_box};
        let mut edges = vec![
            edge("Registry", "Receiver"),
            edge("Registry", "launchpad%Launchpad"),
            edge("Receiver", "launchpad%Launchpad"),
        ];
        for at in 0..10 {
            edges.push(edge("Launchpad", &format!("Pool{at}")));
        }
        let drawn = rejoin(unfold("Registry", &edges), "Registry");

        // Both branches still reach it, each with its own box: no arrow was moved.
        let boxes: Vec<&str> = drawn
            .iter()
            .map(|edge| edge.to.as_str())
            .filter(|id| same_box(id) == "launchpad%Launchpad")
            .collect();
        assert_eq!(boxes.len(), 2, "two boxes, two arrows: {boxes:?}");
        assert_ne!(boxes[0], boxes[1], "and they are not one box");

        // The pools are drawn ONCE, under whichever of the two keeps them.
        assert_eq!(drawn.iter().filter(|edge| edge.to.starts_with("Pool")).count(), 10);

        // And the one that lost them says so with a leaf, rather than reading as a contract
        // that calls nothing at all. A leaf and not a second line in the box, so every box
        // standing for a contract looks like every other one.
        let notes: Vec<&str> = drawn
            .iter()
            .filter(|edge| super::destination_of(&edge.to) == Some("drawn in this frame"))
            .map(|edge| edge.from.as_str())
            .collect();
        assert_eq!(notes.len(), 1, "one note, under the cut copy: {notes:?}");
        assert_eq!(same_box(notes[0]), "launchpad%Launchpad");
    }

    /// A copy that reaches somewhere the other does not keeps its own subtree: a relation drawn
    /// once is a relation lost, and saving a row is never worth that.
    #[test]
    fn a_copy_that_says_more_keeps_its_own_branch() {
        use super::{rejoin, same_box};
        let mut edges = vec![edge("Registry", "Receiver"), edge("Registry", "desk%Desk")];
        for at in 0..10 {
            edges.push(edge("Desk", &format!("Pool{at}")));
        }
        edges.push(edge("Receiver", "desk%Desk"));
        edges.push(edge("Pool0", "Vault"));
        let drawn = rejoin(unfold("Registry", &edges), "Registry");
        assert!(
            drawn.iter().any(|edge| same_box(&edge.to) == "Vault"),
            "the branch survives: {drawn:?}"
        );
    }

    /// One frame per top caller, each holding everything that caller reaches. A contract two
    /// of them use is in both — repeated on purpose, the way a screenshot is repeated in two
    /// deployment frames, because a copy is cheap and a crossing arrow is not.
    #[test]
    fn a_frame_per_top_caller_repeats_what_they_share() {
        let edges = vec![edge("Launchpad", "Treasury"), edge("Router", "Treasury")];
        let frames = partition_frames(&edges, None);
        assert_eq!(frames.len(), 2);
        assert!(frames.iter().any(|plan| plan.root == "Launchpad"));
        assert!(frames.iter().any(|plan| plan.root == "Router"));
        assert!(
            frames.iter().all(|plan| plan.edges.len() == 1 && plan.edges[0].to == "Treasury"),
            "Treasury is drawn in both frames"
        );
    }

    /// A frame holds the whole chain under its top, not only what it calls directly.
    #[test]
    fn a_frame_holds_everything_its_top_reaches() {
        let edges = vec![edge("Launchpad", "Desk"), edge("Desk", "Treasury")];
        let frames = partition_frames(&edges, None);
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].root, "Launchpad");
        assert_eq!(frames[0].edges.len(), 2);
    }

    /// A cycle nothing points into has no top caller, and is still every bit as much a part of
    /// the system — it gets a frame rather than being dropped.
    #[test]
    fn a_cycle_with_nothing_above_it_still_gets_a_frame() {
        let edges = vec![edge("A", "B"), edge("B", "A")];
        let frames = partition_frames(&edges, None);
        assert_eq!(frames.len(), 1, "one frame, not none: {frames:?}");
        assert_eq!(frames[0].edges.len(), 2, "both relations drawn");
    }

    /// The tree the frame draws has no crossings — which is the certificate, printed per frame,
    /// and not something anyone has to judge from a picture.
    #[test]
    fn the_tree_a_frame_draws_has_no_crossings() {
        let edges = vec![
            edge("Top", "Middle"),
            edge("Top", "Shared"),
            edge("Middle", "Shared"),
            edge("Top", "Other"),
            edge("Other", "Shared"),
        ];
        assert_eq!(super::layout_map(&unfold("Top", &edges)).crossings, 0);
    }

    /// A frame is self-contained: everything its contract reaches is IN it, and a contract two
    /// branches both reach is drawn twice rather than lifted into a frame of its own. Fewer
    /// frames, each answering one question, beats fewer boxes.
    #[test]
    fn a_frame_holds_its_whole_tree_and_repeats_what_is_shared() {
        let edges = vec![
            edge("Registry", "Receiver"),
            edge("Receiver", "Desk"),
            edge("Registry", "Desk"),
            edge("Desk", "Treasury"),
        ];
        let frames = partition_frames(&edges, None);
        assert_eq!(frames.len(), 1, "one top caller, one frame: {frames:?}");
        let mine = &frames[0].edges;
        // Desk is reached two ways, so it is drawn twice — and `Treasury` under each of them.
        let desks: Vec<&str> = mine
            .iter()
            .map(|edge| edge.to.as_str())
            .filter(|to| original_of(to) == "Desk")
            .collect();
        assert_eq!(desks.len(), 2, "Desk is drawn once per branch that reaches it: {mine:?}");
        assert_ne!(desks[0], desks[1], "and the two are different boxes");
        assert_eq!(
            mine.iter().filter(|edge| original_of(&edge.to) == "Treasury").count(),
            2,
            "its own chain comes with each copy"
        );
    }

    /// Nothing is shared inside a frame, which is what makes it a tree: every box has exactly
    /// one arrow into it.
    #[test]
    fn a_frame_is_a_tree() {
        let edges = vec![
            edge("Top", "Middle"),
            edge("Top", "Shared"),
            edge("Middle", "Shared"),
            edge("Shared", "Leaf"),
        ];
        let mine = unfold("Top", &edges);
        let mut into: BTreeMap<&str, usize> = BTreeMap::new();
        for edge in &mine {
            *into.entry(edge.to.as_str()).or_default() += 1;
        }
        assert!(into.values().all(|count| *count == 1), "one arrow into each box: {into:?}");
    }

    /// A cycle has no top caller, so one of its members has to be the frame's root — and it is
    /// the one that CALLS THE MOST, not whichever the relations happen to list first.
    #[test]
    fn the_root_of_a_cycle_is_the_member_that_calls_the_most() {
        let edges = vec![
            // `Quiet` comes first alphabetically and calls one; `Busy` calls three. The frame
            // belongs to `Busy`, whose story is the longer one.
            edge("Quiet", "Busy"),
            edge("Busy", "Quiet"),
            edge("Busy", "LeafOne"),
            edge("Busy", "LeafTwo"),
        ];
        let frames = partition_frames(&edges, None);
        assert_eq!(frames.len(), 1, "one cycle, one frame: {frames:?}");
        assert_eq!(frames[0].root, "Busy");
        assert_eq!(frames[0].edges.len(), 4, "and it draws every relation of the cycle");
    }

    /// A cycle is NOT unfolded for ever: the arrow goes back to the copy this path came
    /// through, which is the one red arrow on the frame.
    #[test]
    fn a_cycle_points_back_instead_of_unfolding() {
        let edges = vec![edge("A", "B"), edge("B", "C"), edge("C", "A")];
        let mine = unfold("A", &edges);
        assert_eq!(mine.len(), 3, "three relations, drawn once each: {mine:?}");
        let back = mine.iter().find(|edge| edge.to == "A").expect("the arrow home");
        assert_eq!(back.from, "C");
    }

    /// What leaves the repository is drawn — and every caller gets its OWN copy of it. One
    /// shared `IERC20` pulled an arrow from each of its seven callers across the whole frame;
    /// an outside box has no chain under it, so a copy costs one box and saves a crossing.
    /// An interface of somebody else's protocol, for a fixture about copies and colours.
    fn outside_metadata(names: &[&str]) -> crate::batbelt::evm::metadata::bat_metadata::EvmBatMetadata {
        use crate::batbelt::evm::metadata::bat_metadata::{ContractMetadata, EvmBatMetadata};
        EvmBatMetadata {
            contracts: names
                .iter()
                .map(|name| ContractMetadata {
                    metadata_id: name.to_string(),
                    name: name.to_string(),
                    using_libraries: Vec::new(),
                    file_path: format!("lib/{name}.sol"),
                    contract_type: crate::batbelt::evm::types::EvmContractType::Interface,
                    base_contracts: Vec::new(),
                    functions: Vec::new(),
                    state_variables: Vec::new(),
                    structs: Vec::new(),
                    events: Vec::new(),
                    modifiers: Vec::new(),
                    line: 1,
                    vendored: true,
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn every_caller_gets_its_own_copy_of_what_is_outside() {
        let all = vec![
            Edge { from: "Vault".into(), to: "IERC20".into(), relation: Relation::Boundary },
            Edge { from: "Router".into(), to: "IERC20".into(), relation: Relation::Boundary },
            edge("Vault", "Oracle"),
        ];
        let metadata = outside_metadata(&["IERC20"]);
        let drawn = super::drawn_edges(&metadata, &all, false);
        let outside: Vec<&str> = drawn
            .iter()
            .filter(|edge| edge.relation == Relation::Boundary)
            .map(|edge| edge.to.as_str())
            .collect();
        assert_eq!(outside, vec!["IERC20@Vault", "IERC20@Router"], "never one shared box");
        for id in outside {
            assert_eq!(original_of(id), "IERC20", "and both read as IERC20");
            assert!(super::is_outside(id));
        }
        assert!(
            super::drawn_edges(&metadata, &all, true).iter().all(|edge| edge.to == "Oracle"),
            "--no-boundaries leaves them out altogether"
        );
    }

    /// Within a frame, every copy of one interface carries ONE colour and no two interfaces
    /// carry the same: the copies are what keep the arrows short, the colour is what says the
    /// four boxes reading `IERC20` are one thing.
    #[test]
    fn one_colour_per_interface_and_never_two_the_same() {
        let all = vec![
            Edge { from: "Vault".into(), to: "IERC20".into(), relation: Relation::Boundary },
            Edge { from: "Router".into(), to: "IERC20".into(), relation: Relation::Boundary },
            Edge { from: "Vault".into(), to: "IVault".into(), relation: Relation::Boundary },
            edge("Vault", "Oracle"),
        ];
        let metadata = outside_metadata(&["IERC20", "IVault"]);
        let drawn = super::drawn_edges(&metadata, &all, false);
        let fills = super::PreparedFrame::outside_fills(&drawn);
        assert_eq!(fills.len(), 2, "one entry per interface, not per copy: {fills:?}");
        assert_ne!(fills["IERC20"], fills["IVault"], "two interfaces never share a colour");
        // Both copies of IERC20 resolve to the same fill, whichever caller they belong to.
        assert_eq!(fills[original_of("IERC20@Vault")], fills[original_of("IERC20@Router")]);
    }

    /// A frame is laid out as a TREE: a parent sits at the middle of its children and one column
    /// to their left, so a box is always beside the boxes it points at. Packed from the top
    /// instead, a contract's callees sat level with somebody else's and following one arrow
    /// meant scrolling a frame whose answer was two boxes apart.
    #[test]
    fn a_parent_sits_beside_its_own_children() {
        let edges = vec![
            edge("Root", "First"),
            edge("Root", "Second"),
            edge("Second", "Deep"),
            edge("Second", "Deeper"),
        ];
        let layout = super::layout_tree("Root", &edges);
        let at = |id: &str| layout.node(id).cloned().expect(id);
        assert_eq!(at("Root").layer, 0);
        assert_eq!(at("Second").layer, 1);
        assert_eq!(at("Deep").layer, 2, "a column per depth");
        assert!(at("Root").x < at("Second").x && at("Second").x < at("Deep").x, "left to right");
        // Each parent at the middle of its own children, which is what puts it beside them.
        let middle = |a: f64, b: f64| (a + b) / 2.0;
        assert!((at("Second").y - middle(at("Deep").y, at("Deeper").y)).abs() < 1.0);
        assert!((at("Root").y - middle(at("First").y, at("Second").y)).abs() < 1.0);
        assert_eq!(layout.crossings, 0, "a tidy tree cannot cross");
    }

    /// The frame of a CYCLE still draws its boxes: its root is the one the caller names, not
    /// "whatever has no parent" — in a cycle the root is itself somebody's callee, so that rule
    /// found no root and the frame reached the board titled and empty.
    #[test]
    fn the_frame_of_a_cycle_is_not_empty() {
        let edges = vec![
            edge("Converter", "Treasury"),
            edge("Treasury", "Converter"),
            edge("Converter", "Oracle"),
        ];
        let mine = unfold("Converter", &edges);
        let layout = super::layout_tree("Converter", &mine);
        assert_eq!(layout.nodes.len(), 3, "every box is placed: {:?}", layout.nodes);
        assert_eq!(layout.node("Converter").expect("the root").layer, 0);
        assert!(layout.frame_width > 0.0 && layout.frame_height > 0.0);
    }

    /// A contract drawn twice in one frame carries its own border colour on both copies, so the
    /// two boxes read as one address; a contract drawn once keeps the plain border, because a
    /// colour that means nothing is a colour to decode.
    #[test]
    fn a_contract_drawn_twice_gets_a_border_of_its_own() {
        let edges = vec![
            edge("Registry", "Receiver"),
            edge("Registry", "Desk"),
            edge("Receiver", "Desk"),
        ];
        let mine = unfold("Registry", &edges);
        // The colour is for a CONTRACT of this repository, so the fixture declares them.
        let metadata = EvmBatMetadata {
            contracts: ["Registry", "Receiver", "Desk"]
                .iter()
                .map(|name| contract_named(name))
                .collect(),
            ..Default::default()
        };
        let borders = super::PreparedFrame::repeat_borders(&metadata, &mine);
        assert_eq!(borders.len(), 1, "only Desk is drawn twice: {borders:?}");
        let desk = borders["Desk"];
        assert_ne!(desk, super::BOX_BORDER);
        // Both copies carry it, and `Receiver`, drawn once, does not.
        let frame = super::PreparedFrame {
            many: super::BTreeSet::new(),
            title: String::new(),
            root: String::new(),
            edges: mine.clone(),
            layout: super::layout_map(&mine),
            arrows: Vec::new(),
            fills: BTreeMap::new(),
            borders,
            strip: Vec::new(),
            width: 0.0,
            height: 0.0,
            crossings: 0,
            over_boxes: 0,
            left: 0.0,
            top: 0.0,
        };
        assert_eq!(frame.border_of("Desk"), (desk, super::REPEAT_BORDER_WIDTH));
        assert_eq!(frame.border_of("Desk#2"), (desk, super::REPEAT_BORDER_WIDTH));
        assert_eq!(frame.border_of("Receiver"), (super::BOX_BORDER, super::BORDER_WIDTH));
        assert!(
            super::REPEAT_BORDER_WIDTH > super::BORDER_WIDTH,
            "a colour nobody can see at the frame's zoom is not a signal"
        );
    }

    /// A copy is a second box for the same contract, and reads as that contract.
    #[test]
    fn a_copy_carries_its_originals_name() {
        assert_eq!(original_of("Treasury#2"), "Treasury");
        assert_eq!(original_of("Treasury"), "Treasury");
        assert_eq!(super::box_text("Treasury#3"), "Treasury");
    }
}

#[cfg(test)]
mod failure_message_test {
    use crate::batbelt::miro::MiroError;
    use error_stack::Report;

    /// A failed item says WHY: the HTTP status and Miro's own words, which the client already
    /// attaches. Printing the context alone printed "Miro error" and nothing a reader can act on.
    #[test]
    fn a_failure_carries_the_api_s_own_words() {
        let report = Report::new(MiroError)
            .attach_printable("create_connector: HTTP 400 Bad Request: {\"message\":\"too close\"}".to_string());
        let line = super::why(&report);
        assert!(line.contains("400"), "{line}");
        assert!(line.contains("too close"), "{line}");
    }

    /// Nothing attached, nothing invented: the context is still better than an empty line.
    #[test]
    fn a_bare_failure_still_says_something() {
        assert_eq!(super::why(&Report::new(MiroError)), MiroError.to_string());
    }
}

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

    /// No two markers of one arrow land on the same point.
    ///
    /// Miro refuses a connector whose two ends are the same item — `"The startitem id and
    /// enditem id cannot be the same"` — and two markers at identical coordinates come back
    /// from the bulk endpoint as one item, so an arrow that plans a zero-length leg is an arrow
    /// that cannot be drawn. It cost four relations on a real board.
    #[test]
    fn no_leg_of_an_arrow_is_zero_length() {
        let edges = vec![Edge {
            from: "AscendFeeController".into(),
            to: "ICLPoolManager@AscendFeeController".into(),
            relation: Relation::Boundary,
        }];
        let layout = layout_tree("AscendFeeController", &edges);
        for arrow in route_arrows(&edges, &layout, false) {
            for (index, point) in arrow.plan.points.iter().enumerate() {
                for other in arrow.plan.points.iter().skip(index + 1) {
                    assert!(
                        (point.0 - other.0).abs() > 0.5 || (point.1 - other.1).abs() > 0.5,
                        "two markers on {point:?}: {:?}",
                        arrow.plan.points
                    );
                }
            }
        }
    }
}

#[cfg(test)]
mod card_test {
    use super::{CARD_GAP, CARD_WIDTH, MAX_CARDS};
    use crate::batbelt::miro::client::MiroClient;

    /// The cards of one cluster are centred on its shape and evenly spread, so three of them
    /// read as one row belonging to one column rather than as three loose chips.
    fn placed(count: usize, centre: f64) -> Vec<f64> {
        let drawn = count.min(MAX_CARDS);
        let span = drawn as f64 * CARD_WIDTH + (drawn as f64 - 1.0) * CARD_GAP;
        (0..drawn)
            .map(|index| centre - span / 2.0 + CARD_WIDTH / 2.0 + index as f64 * (CARD_WIDTH + CARD_GAP))
            .collect()
    }

    #[test]
    fn cards_are_centred_on_the_cluster_and_evenly_spread() {
        let centre = 10_000.0;
        let one = placed(1, centre);
        assert_eq!(one, vec![centre], "a single card sits on the centre");
        let three = placed(3, centre);
        assert_eq!(three.len(), 3);
        let middle = (three[0] + three[2]) / 2.0;
        assert!((middle - centre).abs() < 1.0, "the row is centred: {three:?}");
        assert!(
            ((three[1] - three[0]) - (three[2] - three[1])).abs() < 1.0,
            "evenly spread: {three:?}"
        );
        assert!((three[1] - three[0]) >= CARD_WIDTH, "and never overlapping");
    }

    /// Past the cap the row stops growing: a cluster is not a place to list twelve frames.
    #[test]
    fn a_cluster_never_carries_more_than_the_cap() {
        assert_eq!(placed(12, 0.0).len(), MAX_CARDS);
    }

    /// The card carries the frame's URL as an anchor INSIDE its text, because Miro's REST API
    /// rejects `linkedTo` — and the words name the frame, so a deleted map leaves a card that
    /// still says something true.
    #[test]
    fn a_card_carries_the_link_in_its_words() {
        let item = MiroClient::link_card_item(
            "map · YieldRouter",
            "https://miro.com/app/board/x=/?moveToWidget=123",
            0.0,
            0.0,
            100.0,
            50.0,
            90,
            "#ffffff",
            "#1a73e8",
        );
        let content = item["data"]["content"].as_str().expect("the words");
        assert!(content.contains("moveToWidget=123"), "{content}");
        assert!(content.contains("YieldRouter"), "{content}");
        assert!(item["parent"].is_null(), "a card sits on the board, not inside a frame");
    }
}

#[cfg(test)]
mod cards_for_test {
    use super::frames_showing;
    use crate::batbelt::evm::metadata::bat_metadata::MapFrameRef;

    fn frame(root: &str, contracts: &[&str]) -> MapFrameRef {
        MapFrameRef {
            root: root.to_string(),
            frame_id: format!("id-{root}"),
            contracts: contracts.iter().map(|name| name.to_string()).collect(),
            cards: Vec::new(),
        }
    }

    /// A cluster is carded for every frame that DRAWS its contract, not only for the frame
    /// named after it: `Treasury` is a leaf of three other systems and has no frame of its own.
    #[test]
    fn a_cluster_is_carded_for_every_frame_that_draws_it() {
        let frames = [
            frame("YieldRouter", &["YieldRouter", "AscendLaunchpad", "Treasury"]),
            frame("AscendCtoRegistry", &["AscendCtoRegistry", "Treasury"]),
            frame("ReferralPot", &["ReferralPot"]),
        ];
        let roots: Vec<&str> = frames_showing(&frames, "Treasury")
            .iter()
            .map(|frame| frame.root.as_str())
            .collect();
        assert_eq!(roots, vec!["YieldRouter", "AscendCtoRegistry"]);
        assert!(frames_showing(&frames, "BurnSink").is_empty(), "nothing drawn, nothing to point at");
    }
}

#[cfg(test)]
mod stale_card_test {
    use super::is_map_card;
    use crate::batbelt::miro::client::MiroClient;

    /// A card is recognised on the board by its OWN signature, so a lost registry cannot leave
    /// one behind: the prefix it is written with and the link it carries, both.
    #[test]
    fn a_card_is_recognised_by_what_it_says() {
        let card = MiroClient::link_card_item(
            "map · YieldRouter",
            "https://miro.com/app/board/x=/?moveToWidget=123",
            0.0,
            0.0,
            10.0,
            10.0,
            90,
            "#ffffff",
            "#1a73e8",
        );
        assert!(is_map_card(card["data"]["content"].as_str().expect("the words")));
    }

    /// Nothing else is touched. This is the only place the tool deletes an item it holds no id
    /// for, so the test is the guard: a note of the auditor's that merely mentions the map, or
    /// a link of theirs to a frame, is NOT a card.
    #[test]
    fn nothing_the_auditor_wrote_is_mistaken_for_one() {
        assert!(!is_map_card("<p>map · YieldRouter</p>"), "a label with no link");
        assert!(
            !is_map_card("<p><a href=\"https://miro.com/app/board/x=/?moveToWidget=9\">ir al mapa</a></p>"),
            "a link of their own, without the prefix"
        );
        assert!(!is_map_card("<p>revisar el map de nuevo</p>"));
    }
}

#[cfg(test)]
mod method_leaf_test {
    use super::{box_text, method_of, original_of, METHOD_MARK, OUTSIDE_MARK};

    /// A method leaf says the METHOD; which interface it belongs to is the box it hangs from,
    /// and its colour is still the interface's, so the three levels read as one chain:
    /// `YieldRouter → IERC20 → safeTransfer`.
    #[test]
    fn a_method_leaf_reads_as_its_method_and_keeps_its_interfaces_identity() {
        let leaf = format!("IERC20{OUTSIDE_MARK}YieldRouter{METHOD_MARK}safeTransfer");
        assert_eq!(box_text(&leaf), "safeTransfer()", "written as Solidity writes a call");
        assert_eq!(original_of(&leaf), "IERC20", "the colour is the interface's");
        assert!(super::is_outside(&leaf), "and it is still outside the repository");
        assert_eq!(method_of(&leaf), Some("safeTransfer"));
    }

    /// A COPY of a method leaf still says the method: `collect#3` is our bookkeeping, not
    /// something the reader asked about.
    #[test]
    fn a_copied_method_leaf_still_says_the_method() {
        let leaf = format!("IListing{OUTSIDE_MARK}Desk{METHOD_MARK}collect#3");
        assert_eq!(box_text(&leaf), "collect()");
        assert_eq!(original_of(&leaf), "IListing");
    }

    /// An ordinary box is not a method leaf.
    #[test]
    fn a_contract_box_has_no_method() {
        assert_eq!(method_of("Treasury"), None);
        assert_eq!(box_text("Treasury#2"), "Treasury");
        assert_eq!(box_text(&format!("IERC20{OUTSIDE_MARK}YieldRouter")), "IERC20");
    }
}

#[cfg(test)]
mod mark_test {
    use super::{PreparedFrame, BOX_BORDER, BOX_FILL, MARK_FILL, OUTSIDE_MARK};
    use std::collections::{BTreeMap, BTreeSet};

    fn frame(fills: BTreeMap<String, &'static str>) -> PreparedFrame {
        PreparedFrame {
                many: super::BTreeSet::new(),
                title: String::new(),
            root: String::new(),
            edges: Vec::new(),
            layout: super::layout_tree("x", &[]),
            arrows: Vec::new(),
            fills,
            borders: BTreeMap::new(),
            strip: Vec::new(),
            width: 0.0,
            height: 0.0,
            crossings: 0,
            over_boxes: 0,
            left: 0.0,
            top: 0.0,
        }
    }

    /// Three channels, one meaning each. A marked contract takes the FILL, because a background
    /// is what carries at the zoom where a whole frame fits; an interface gives the fill up and
    /// takes a dotted border with its name in its own colour; everything else stays plain.
    #[test]
    fn a_marked_contract_is_filled_and_an_interface_is_dotted() {
        let fills: BTreeMap<String, &'static str> = [("IERC20".to_string(), "#d9ecff")].into();
        let frame = frame(fills);
        let marked: BTreeSet<String> = ["YieldRouter".to_string()].into();

        assert_eq!(frame.paint_of("YieldRouter", &marked), (MARK_FILL, BOX_BORDER, "normal"));
        assert_eq!(frame.paint_of("Treasury", &marked), (BOX_FILL, BOX_BORDER, "normal"));
        assert_eq!(
            frame.paint_of(&format!("IERC20{OUTSIDE_MARK}YieldRouter"), &marked),
            (BOX_FILL, "#d9ecff", "dotted"),
            "the fill is free for the marks; the interface keeps its colour on the border"
        );
    }

    /// A copy of a marked contract is marked too: the reader asked for the contract, not for one
    /// of its boxes.
    #[test]
    fn every_copy_of_a_marked_contract_is_filled() {
        let frame = frame(BTreeMap::new());
        let marked: BTreeSet<String> = ["Treasury".to_string()].into();
        assert_eq!(frame.paint_of("Treasury#3", &marked).0, MARK_FILL);
    }
}

#[cfg(test)]
mod repaint_test {
    use super::shape_name;

    /// A box's words are its contract's name, so the repaint knows what each one stands for
    /// without an id per box in the registry.
    #[test]
    fn a_box_says_which_contract_it_is() {
        assert_eq!(shape_name("<p><b>YieldRouter</b></p>").as_deref(), Some("YieldRouter"));
        assert_eq!(shape_name("<p><b>IERC20</b></p>").as_deref(), Some("IERC20"));
    }

    /// Everything that is not a contract box is left alone: the legend's rows, the strip's
    /// heading and a method leaf all carry words no contract has.
    #[test]
    fn nothing_else_is_repainted() {
        assert_eq!(shape_name("<p><b>not connected in scope</b></p>"), None);
        assert_eq!(shape_name("<p><b>filled: a contract you marked to see</b></p>"), None);
        assert_eq!(shape_name("<p></p>"), None);
        // A party box stands for its contract, so `mark --apply` paints it like the contract's
        // own box; an account is never filled, exactly as a redrawn map leaves it.
        assert_eq!(
            shape_name("<p><b>to: StakerDistributor</b></p>").as_deref(),
            Some("StakerDistributor")
        );
        assert_eq!(shape_name("<p><b>to: the claimant (address)</b></p>"), None);
    }

    /// A box named after the VARIABLE holding it stands for the contract in its brackets.
    ///
    /// The registry stores real contract names, so comparing the whole text against it never
    /// matched once boxes started reading `opexTreasury (Treasury)`: `mark --apply` repainted
    /// nothing and reported `0 of 0 contract box(es)`, on every map, with no way to tell that
    /// from "nothing is marked".
    #[test]
    fn a_box_named_after_its_variable_is_still_its_contract() {
        assert_eq!(
            shape_name("<p><b>opexTreasury (Treasury)</b></p>").as_deref(),
            Some("Treasury")
        );
        assert_eq!(
            shape_name("<p><b>launchpad (AscendLaunchpad)</b></p>").as_deref(),
            Some("AscendLaunchpad")
        );
        // A party naming a deployment is that contract too: role off the front, contract out
        // of the brackets.
        assert_eq!(
            shape_name("<p><b>to: cohortTreasury (Treasury)</b></p>").as_deref(),
            Some("Treasury")
        );
        // And an account in brackets is still not a contract.
        assert_eq!(shape_name("<p><b>to: the pool creator (address)</b></p>"), None);
        // A legend row with brackets in it is not a contract either.
        assert_eq!(
            shape_name("<p><b>yellow: creates it — new X(...)</b></p>"),
            None
        );
    }
}

#[cfg(test)]
mod reads_only_test {
    use super::reads_only;
    use crate::batbelt::evm::metadata::bat_metadata::{ContractMetadata, EvmBatMetadata, FunctionMetadata};
    use crate::batbelt::evm::types::{EvmContractType, EvmMutability, EvmVisibility};

    fn function(name: &str, mutability: EvmMutability) -> FunctionMetadata {
        FunctionMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            contract_name: String::new(),
            visibility: EvmVisibility::External,
            mutability,
            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::new(),
            unknown_external_calls: Vec::new(),
            resolved_calls: Vec::new(),
            callbacks: Vec::new(),
            creations: Vec::new(),
        }
    }

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

    /// The language's own word decides, not a vocabulary of names: `view`/`pure` is a read,
    /// anything else can move value and keeps its leaf. Seventeen `balanceOf` boxes were
    /// crowding out the one `safeTransfer` that matters.
    #[test]
    fn a_view_is_a_read_and_the_rest_is_not() {
        let metadata = EvmBatMetadata {
            contracts: vec![contract(
                "IERC20",
                &[],
                vec![
                    function("balanceOf", EvmMutability::View),
                    function("transfer", EvmMutability::NonPayable),
                ],
            )],
            ..Default::default()
        };
        assert!(reads_only(&metadata, "IERC20", "balanceOf"));
        assert!(!reads_only(&metadata, "IERC20", "transfer"));
    }

    /// An interface that declares only part of its surface is answered by whoever implements
    /// it: same rule, wider search.
    #[test]
    fn an_implementers_declaration_counts() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                contract("IListing", &[], Vec::new()),
                contract("Listing", &["IListing"], vec![function("poolCreator", EvmMutability::View)]),
            ],
            ..Default::default()
        };
        assert!(reads_only(&metadata, "IListing", "poolCreator"));
    }

    /// Nothing declares it: the leaf is DRAWN. An audit can discard a box it does not need; it
    /// cannot discard a transfer it was never shown. Guessing by name among unrelated contracts
    /// is what `bat-cli resolve` exists to replace.
    #[test]
    fn what_cannot_be_decided_is_drawn() {
        let metadata = EvmBatMetadata {
            contracts: vec![contract(
                "Unrelated",
                &[],
                vec![function("poolCreator", EvmMutability::View)],
            )],
            ..Default::default()
        };
        assert!(!reads_only(&metadata, "IListing", "poolCreator"));
    }

    /// One writer among several declarations of a name keeps the leaf.
    #[test]
    fn one_writer_is_enough_to_keep_it() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                contract("IVault", &[], vec![function("pay", EvmMutability::View)]),
                contract("Vault", &["IVault"], vec![function("pay", EvmMutability::NonPayable)]),
            ],
            ..Default::default()
        };
        assert!(!reads_only(&metadata, "IVault", "pay"));
    }
}

#[cfg(test)]
mod inherited_mutability_test {
    use super::reads_only;
    use crate::batbelt::evm::metadata::bat_metadata::{ContractMetadata, EvmBatMetadata, FunctionMetadata};
    use crate::batbelt::evm::types::{EvmContractType, EvmMutability, EvmVisibility};

    fn function(name: &str, mutability: EvmMutability) -> FunctionMetadata {
        FunctionMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            contract_name: String::new(),
            visibility: EvmVisibility::External,
            mutability,
            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::new(),
            unknown_external_calls: Vec::new(),
            resolved_calls: Vec::new(),
            callbacks: Vec::new(),
            creations: Vec::new(),
        }
    }

    fn interface(name: &str, bases: &[&str], functions: Vec<FunctionMetadata>) -> ContractMetadata {
        ContractMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            using_libraries: Vec::new(),
            file_path: format!("lib/{name}.sol"),
            contract_type: EvmContractType::Interface,
            base_contracts: bases.iter().map(|b| b.to_string()).collect(),
            functions,
            state_variables: Vec::new(),
            structs: Vec::new(),
            events: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            vendored: true,
        }
    }

    /// A method INHERITED by the type is answered by the base that declares it, however deep.
    /// `ICLPoolManager` declares eleven methods and `vault` is not one of them: it comes from the
    /// interface it extends, and a getter drawn as if it moved value is the noise this filter
    /// exists to remove.
    #[test]
    fn a_getter_inherited_from_a_base_interface_is_still_a_read() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                interface("ICLPoolManager", &["IPoolManager"], vec![function("swap", EvmMutability::NonPayable)]),
                interface("IPoolManager", &["IProtocolFees"], Vec::new()),
                interface("IProtocolFees", &[], vec![function("vault", EvmMutability::View)]),
            ],
            ..Default::default()
        };
        assert!(reads_only(&metadata, "ICLPoolManager", "vault"), "two levels up");
        assert!(!reads_only(&metadata, "ICLPoolManager", "swap"));
    }
}

#[cfg(test)]
mod address_box_test {
    use super::{
        box_text, is_wiring_point, node_height, ADDRESS_MARK, DESTINATION_MARK, METHOD_MARK,
        NODE_HEIGHT, OUTSIDE_MARK,
    };

    /// A destination is an entity, and an entity nobody has named is an ADDRESS. Drawn with the
    /// interface leaves' half-height dotted box it read as one more interface, and `yieldSink`
    /// sent the reader looking for a contract by that name.
    #[test]
    fn an_unnamed_destination_says_it_is_an_address() {
        let leaf = format!("IERC20{OUTSIDE_MARK}Vault{METHOD_MARK}transfer");
        let point = format!("{leaf}{DESTINATION_MARK}yieldSink{ADDRESS_MARK}");
        let named = format!("{leaf}{DESTINATION_MARK}BurnSink");

        assert_eq!(box_text(&point), "yieldSink (address)");
        assert_eq!(box_text(&named), "BurnSink");
        assert!(is_wiring_point(&point));
        assert!(!is_wiring_point(&named));
        // And both are contract-sized: a party is read from across the frame.
        assert_eq!(node_height(&point), NODE_HEIGHT);
        assert_eq!(node_height(&named), NODE_HEIGHT);
    }
}

#[cfg(test)]
mod node_width_test {
    use super::{node_width, METHOD_MARK, OUTSIDE_MARK};

    /// A box is as wide as the words it carries. A method leaf's id starts with its interface's
    /// name, and sizing by the id made `safeTransfer()` as narrow as `IERC20`.
    #[test]
    fn a_box_is_sized_by_what_it_says() {
        let short = format!("IERC20{OUTSIDE_MARK}Vault{METHOD_MARK}pay");
        let long = format!("IERC20{OUTSIDE_MARK}Vault{METHOD_MARK}safeTransferFrom");
        assert!(node_width(&long) > node_width(&short), "a longer method, a wider box");

        // And a copy is as wide as the original: `Treasury#2` carries `Treasury`.
        assert_eq!(node_width("Treasury#2"), node_width("Treasury"));
    }
}

#[cfg(test)]
mod parties_test {
    use super::{entity_of, is_address_like};
    use crate::batbelt::evm::metadata::bat_metadata::{ContractMetadata, EvmBatMetadata};
    use crate::batbelt::evm::types::{EvmContractType, EvmVisibility, StorageVariable};

    fn variable(name: &str, type_name: &str) -> StorageVariable {
        StorageVariable {
            name: name.to_string(),
            type_name: type_name.to_string(),
            visibility: EvmVisibility::Public,
            is_constant: false,
            is_immutable: true,
            line: 1,
        }
    }

    fn stub(name: &str) -> crate::batbelt::evm::metadata::bat_metadata::FunctionMetadata {
        use crate::batbelt::evm::types::EvmMutability;
        crate::batbelt::evm::metadata::bat_metadata::FunctionMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            contract_name: String::new(),
            visibility: EvmVisibility::External,
            mutability: EvmMutability::NonPayable,
            params: Vec::new(),
            returns: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            end_line: 2,
            is_constructor: false,
            is_stub: true,
            storage_writes: Vec::new(),
            storage_write_sites: Vec::new(),
            unresolved_calls: Vec::new(),
            unknown_external_calls: Vec::new(),
            resolved_calls: Vec::new(),
            callbacks: Vec::new(),
            creations: Vec::new(),
        }
    }

    fn contract(name: &str, variables: Vec<StorageVariable>) -> ContractMetadata {
        ContractMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            using_libraries: Vec::new(),
            file_path: format!("src/{name}.sol"),
            contract_type: EvmContractType::Contract,
            base_contracts: Vec::new(),
            functions: Vec::new(),
            state_variables: variables,
            structs: Vec::new(),
            events: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            vendored: false,
        }
    }

    /// Three outcomes, and the middle one is the point: an argument that names a contract draws
    /// that contract, a plain `address` held in STATE draws its own name — it is a fixed party,
    /// decided at deployment and never changed, even though the code never says which contract
    /// it is — and anything else draws nothing.
    #[test]
    fn an_argument_is_a_contract_a_wiring_point_or_nothing() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                contract(
                    "YieldRouter",
                    vec![
                        variable("burnSink", "address"),
                        variable("vault", "AscendYieldVault"),
                    ],
                ),
                contract("AscendYieldVault", Vec::new()),
            ],
            ..Default::default()
        };
        let router = &metadata.contracts[0];

        // The VARIABLE that holds it, then the contract: a caller with two vaults has two
        // addresses, and the type alone would draw one box for both.
        assert_eq!(
            entity_of(&metadata, router, "pay", "vault").as_deref(),
            Some("vault%AscendYieldVault")
        );
        assert_eq!(
            entity_of(&metadata, router, "pay", "burnSink").as_deref(),
            Some("burnSink~"),
            "a fixed party the code cannot name — marked as the address it is"
        );
        // `this` keeps the word: `to: this (YieldRouter)` answers "which one" on the box.
        assert_eq!(
            entity_of(&metadata, router, "pay", "this").as_deref(),
            Some("this%YieldRouter")
        );
        // Whoever called this time is not a party of the system.
        assert_eq!(entity_of(&metadata, router, "pay", "msg.sender"), None);
        assert_eq!(entity_of(&metadata, router, "pay", "recipient"), None, "a parameter is not one");
    }

    /// The one fact the code can never hold: which contract a state `address` was wired to at
    /// deployment. Once somebody records it, the box is that contract and stops being an
    /// address — and it is keyed by the HOLDER, so another contract's `burnSink` is untouched.
    #[test]
    fn a_recorded_wiring_turns_an_address_into_the_entity_it_holds() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                contract("YieldRouter", vec![variable("burnSink", "address")]),
                contract("ReferralPot", vec![variable("burnSink", "address")]),
                contract("BurnSink", Vec::new()),
            ],
            wiring: std::collections::HashMap::from([(
                "YieldRouter.burnSink".to_string(),
                "BurnSink".to_string(),
            )]),
            ..Default::default()
        };
        // The variable stays in front of the answer: two slots of one type are two addresses.
        assert_eq!(
            entity_of(&metadata, &metadata.contracts[0], "pay", "burnSink").as_deref(),
            Some("burnSink%BurnSink")
        );
        assert_eq!(
            entity_of(&metadata, &metadata.contracts[1], "pay", "burnSink").as_deref(),
            Some("burnSink~"),
            "another contract's variable of the same name is still unnamed"
        );
    }

    /// A call site's own answer. `to` is whatever the caller passed, which no analysis can
    /// settle — but a reader who traced it can, and the key carries the FUNCTION, so the same
    /// name in another function is a separate question.
    #[test]
    fn a_recorded_call_site_names_the_party_the_caller_passes() {
        let metadata = EvmBatMetadata {
            contracts: vec![contract("StakerDistributor", Vec::new()), contract("Treasury", Vec::new())],
            wiring: std::collections::HashMap::from([(
                "StakerDistributor._pay.to".to_string(),
                "Treasury".to_string(),
            )]),
            ..Default::default()
        };
        let distributor = &metadata.contracts[0];
        assert_eq!(entity_of(&metadata, distributor, "_pay", "to").as_deref(), Some("Treasury"));
        assert_eq!(
            entity_of(&metadata, distributor, "refund", "to"),
            None,
            "another function's `to` is another question"
        );
    }

    /// Which parameter a party fills. `transferFrom(from, to, amount)` hands addresses to two
    /// different roles, and two boxes carrying only names do not say which one pays.
    #[test]
    fn a_party_says_which_parameter_it_fills() {
        use super::{parties_of, ADDRESS_MARK};
        use crate::batbelt::evm::types::{EvmMutability, EvmParam};
        let mut token = contract("IERC20", Vec::new());
        token.contract_type = EvmContractType::Interface;
        token.functions = vec![crate::batbelt::evm::metadata::bat_metadata::FunctionMetadata {
            metadata_id: "f".to_string(),
            name: "transferFrom".to_string(),
            contract_name: "IERC20".to_string(),
            visibility: EvmVisibility::External,
            mutability: EvmMutability::NonPayable,
            params: vec![
                EvmParam { name: "from".to_string(), type_name: "address".to_string(), storage_location: None },
                EvmParam { name: "to".to_string(), type_name: "address".to_string(), storage_location: None },
                EvmParam { name: "amount".to_string(), type_name: "uint256".to_string(), storage_location: None },
            ],
            returns: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            end_line: 2,
            is_constructor: false,
            is_stub: true,
            storage_writes: Vec::new(),
            storage_write_sites: Vec::new(),
            unresolved_calls: Vec::new(),
            unknown_external_calls: Vec::new(),
            resolved_calls: Vec::new(),
            callbacks: Vec::new(),
            creations: Vec::new(),
        }];
        let mut caller = contract("Vault", vec![variable("treasury", "Treasury")]);
        caller.functions = vec![token.functions[0].clone()];
        let metadata = EvmBatMetadata {
            contracts: vec![caller.clone(), token, contract("Treasury", Vec::new())],
            wiring: std::collections::HashMap::from([
                ("Vault.pull.payer".to_string(), "a staker".to_string()),
            ]),
            ..Default::default()
        };
        let mut pull = metadata.contracts[0].functions[0].clone();
        pull.name = "pull".to_string();
        let (parties, unnamed) = parties_of(
            &metadata,
            &metadata.contracts[0],
            &pull,
            "IERC20",
            "transferFrom",
            &["payer".to_string(), "treasury".to_string()],
        );
        assert!(unnamed.is_empty(), "both arguments answered: {unnamed:?}");
        assert_eq!(parties[0], format!("from: a staker{ADDRESS_MARK}"));
        assert_eq!(parties[1], "to: treasury%Treasury");
    }

    /// A struct is where an address hides from a signature: `exactInput(ExactInputParams(path,
    /// address(this), …))` declares no address and hands one over. Three call sites in ascend,
    /// and not one of them was drawn or even reported.
    #[test]
    fn an_address_inside_a_struct_is_still_a_party() {
        use super::addressed_arguments;
        use crate::batbelt::evm::types::{EvmParam, EvmStruct};
        let mut router = contract("IStakingSwapRouter", Vec::new());
        router.structs = vec![EvmStruct {
            name: "ExactInputParams".to_string(),
            fields: vec![
                EvmParam { name: "path".to_string(), type_name: "bytes".to_string(), storage_location: None },
                EvmParam { name: "recipient".to_string(), type_name: "address".to_string(), storage_location: None },
                EvmParam { name: "amount".to_string(), type_name: "uint256".to_string(), storage_location: None },
            ],
        }];
        let metadata = EvmBatMetadata { contracts: vec![router], ..Default::default() };
        let params = [EvmParam {
            name: "params".to_string(),
            type_name: "IStakingSwapRouter.ExactInputParams".to_string(),
            storage_location: None,
        }];
        let found = addressed_arguments(
            &metadata,
            &params,
            0,
            &["ExactInputParams(paths[], this, amount)".to_string()],
        );
        assert_eq!(found, vec![("params.recipient".to_string(), "this".to_string())]);
    }

    /// The control that comes back. `lock(bytes)` says nothing; the body it lands on says
    /// `ILockCallback(msg.sender).lockAcquired(data)`, so the caller is called back — and only
    /// a caller that declares the callback can receive one.
    #[test]
    fn a_callee_that_calls_msg_sender_calls_its_caller_back() {
        use super::calls_back;
        let mut vault = contract("IVault", Vec::new());
        vault.contract_type = EvmContractType::Interface;
        let mut lock = stub("lock");
        lock.callbacks = vec!["lockAcquired".to_string()];
        vault.functions = vec![lock];
        let mut router = contract("YieldRouter", Vec::new());
        router.functions = vec![stub("lockAcquired")];
        let deaf = contract("ReferralPot", Vec::new());
        let metadata = EvmBatMetadata {
            contracts: vec![vault, router.clone(), deaf.clone()],
            ..Default::default()
        };
        assert_eq!(calls_back(&metadata, &router, "IVault", "lock"), vec!["lockAcquired".to_string()]);
        assert!(
            calls_back(&metadata, &deaf, "IVault", "lock").is_empty(),
            "a caller with no `lockAcquired` never receives one"
        );
    }

    /// Five deployments of one contract are five boxes, told apart by the variable that holds
    /// each one. `AscendLaunchpad` pays five `Treasury`s in `_routeProtocolFees`, and with the
    /// type alone on the box the reader cannot tell which one got what.
    #[test]
    fn two_variables_of_one_type_are_two_boxes() {
        use super::{box_text, entity_named};
        let launchpad = contract(
            "AscendLaunchpad",
            vec![variable("opexTreasury", "Treasury"), variable("kntqTreasury", "Treasury")],
        );
        let metadata = EvmBatMetadata {
            contracts: vec![launchpad, contract("Treasury", Vec::new())],
            ..Default::default()
        };
        let opex = entity_of(&metadata, &metadata.contracts[0], "_route", "opexTreasury").unwrap();
        let kntq = entity_of(&metadata, &metadata.contracts[0], "_route", "kntqTreasury").unwrap();
        assert_ne!(opex, kntq);
        assert_eq!(
            box_text(&format!("IERC20@AscendLaunchpad::safeTransfer=>to: {opex}")),
            "to: opexTreasury (Treasury)"
        );
        // And both still stand for `Treasury`, so `bat-cli mark Treasury` paints the pair.
        assert_eq!(entity_named(&format!("to: {kntq}")), "Treasury");
    }

    /// A library's parameters are filled by whoever calls it, and each host fills them
    /// differently: `VaultPay.buyExactIn(…, to)` takes `l.receiver` from the router and
    /// `d.devBuyRecipient` from the launchpad. One set of destinations hung on every host made
    /// the router's `take()` show the launchpad's recipients and the launchpad show the
    /// router's.
    #[test]
    fn a_librarys_destinations_are_its_call_sites_own() {
        use super::call_sites;
        use crate::batbelt::evm::metadata::bat_metadata::ExternalUnknownCall;
        use crate::batbelt::evm::types::EvmParam;
        let mut library = contract("VaultPay", Vec::new());
        library.contract_type = EvmContractType::Library;
        let mut buy = stub("buyExactIn");
        buy.params = vec![
            EvmParam { name: "vault".to_string(), type_name: "IVault".to_string(), storage_location: None },
            EvmParam { name: "to".to_string(), type_name: "address".to_string(), storage_location: None },
        ];
        library.functions = vec![buy.clone()];

        let mut host = contract("YieldRouter", Vec::new());
        let mut locked = stub("lockAcquired");
        locked.unknown_external_calls = vec![ExternalUnknownCall {
            receiver: "poolVault".to_string(),
            method: "buyExactIn".to_string(),
            inferred_type: "IVault".to_string(),
            arguments: vec!["l.receiver".to_string()],
        }];
        host.functions = vec![locked];

        // The library's internal call hands `to` on; the host's call site decides what that is.
        let sites = call_sites(&host, &library, &buy, &["to".to_string()]);
        assert_eq!(sites.len(), 1);
        assert_eq!(sites[0].0.name, "YieldRouter", "resolved where the argument is written");
        assert_eq!(sites[0].1.name, "lockAcquired", "and the reader is sent to that line");
        assert_eq!(sites[0].2, vec!["l.receiver".to_string()]);

        // Reached through another function of the library itself: nothing is substituted and
        // the names stay the LIBRARY's, because `VaultPay.pay`'s own `vault` is not
        // `YieldRouter.vault`.
        let orphan = contract("ReferralPot", Vec::new());
        let sites = call_sites(&orphan, &library, &buy, &["to".to_string()]);
        assert_eq!(sites[0].0.name, "VaultPay");
        assert_eq!(sites[0].2, vec!["to".to_string()]);
    }

    /// The strip is for a contract no arrow touches. A box named after the variable that holds
    /// it, or a party at the end of a call, is that contract drawn — and `BurnSink` sat in the
    /// strip while `YieldRouter` wired it and paid it.
    #[test]
    fn a_contract_reached_by_its_variable_is_not_unconnected() {
        use super::{unconnected, Edge, Relation};
        let metadata = EvmBatMetadata {
            contracts: vec![contract("YieldRouter", Vec::new()), contract("BurnSink", Vec::new())],
            ..Default::default()
        };
        let wired = vec![Edge {
            from: "YieldRouter".to_string(),
            to: "burnSink%BurnSink".to_string(),
            relation: Relation::WiresAtConstruction,
        }];
        assert!(!unconnected(&metadata, &wired).contains(&"BurnSink".to_string()), "the wiring reaches it");

        let paid = vec![Edge {
            from: "IVault@YieldRouter::take".to_string(),
            to: "IVault@YieldRouter::take=>to: BurnSink".to_string(),
            relation: Relation::Boundary,
        }];
        assert!(
            !unconnected(&metadata, &paid).contains(&"BurnSink".to_string()),
            "so does the party of a call"
        );
    }

    /// `this` is the box whose subtree the leaf hangs in, which the WALK knows and a name
    /// cannot: a frame with seven `Treasury`s has seven `this`, one per subtree, and the party
    /// has to land on the one it belongs to.
    #[test]
    fn this_lands_on_the_box_it_hangs_under() {
        use super::{unfold, Edge, Relation};
        let edges = vec![
            Edge {
                from: "AscendLaunchpad".to_string(),
                to: "opexTreasury%Treasury".to_string(),
                relation: Relation::Creates,
            },
            Edge {
                from: "Treasury".to_string(),
                to: "ERC20@Treasury".to_string(),
                relation: Relation::Boundary,
            },
            Edge {
                from: "ERC20@Treasury".to_string(),
                to: "ERC20@Treasury::safeTransfer".to_string(),
                relation: Relation::Boundary,
            },
            Edge {
                from: "ERC20@Treasury::safeTransfer".to_string(),
                to: "ERC20@Treasury::safeTransfer=>to: this%Treasury".to_string(),
                relation: Relation::Boundary,
            },
        ];
        let drawn = unfold("AscendLaunchpad", &edges);
        let party = drawn
            .iter()
            .find(|edge| edge.to.contains("=>to: "))
            .expect("the party is drawn");
        assert!(
            party.to.ends_with("=>to: opexTreasury%Treasury"),
            "it names the treasury it hangs under: {}",
            party.to
        );
    }

    /// One `Treasury` paying another: the `this` inside the SECOND is the second, because the
    /// code that ran is its own. The nearest box of that contract going up is the answer.
    #[test]
    fn this_is_the_nearest_one_up_not_the_first() {
        use super::{unfold, Edge, Relation};
        let edges = vec![
            Edge {
                from: "AscendLaunchpad".to_string(),
                to: "opexTreasury%Treasury".to_string(),
                relation: Relation::Creates,
            },
            // The first treasury calls the second, which is drawn as its own box.
            Edge {
                from: "Treasury".to_string(),
                to: "kntqTreasury%Treasury".to_string(),
                relation: Relation::Calls,
            },
            Edge {
                from: "Treasury".to_string(),
                to: "ERC20@Treasury".to_string(),
                relation: Relation::Boundary,
            },
            Edge {
                from: "ERC20@Treasury".to_string(),
                to: "ERC20@Treasury::safeTransfer".to_string(),
                relation: Relation::Boundary,
            },
            Edge {
                from: "ERC20@Treasury::safeTransfer".to_string(),
                to: "ERC20@Treasury::safeTransfer=>to: this%Treasury".to_string(),
                relation: Relation::Boundary,
            },
        ];
        let drawn = unfold("AscendLaunchpad", &edges);
        let under_the_second: Vec<&str> = drawn
            .iter()
            .filter(|edge| edge.to.contains("=>to: "))
            .map(|edge| edge.to.as_str())
            .collect();
        assert!(
            under_the_second.iter().any(|id| id.ends_with("=>to: kntqTreasury%Treasury")),
            "the leaf inside the second names the second: {under_the_second:?}"
        );
        assert!(
            under_the_second.iter().any(|id| id.ends_with("=>to: opexTreasury%Treasury")),
            "and the one inside the first names the first: {under_the_second:?}"
        );
    }

    /// A state address is marked once, by `entity_of`. Marked twice, the box read
    /// `POOL~ (address)` — the map's own bookkeeping, printed for the reader.
    #[test]
    fn a_wiring_point_carries_one_address_mark() {
        use super::{parties_of, ADDRESS_MARK};
        use crate::batbelt::evm::types::{EvmMutability, EvmParam};
        let mut token = contract("IERC20", Vec::new());
        token.contract_type = EvmContractType::Interface;
        let mut transfer = stub("safeTransfer");
        transfer.params = vec![EvmParam {
            name: "to".to_string(),
            type_name: "address".to_string(),
            storage_location: None,
        }];
        transfer.mutability = EvmMutability::NonPayable;
        token.functions = vec![transfer];
        let caller = contract("Account", vec![variable("POOL", "address")]);
        let metadata = EvmBatMetadata { contracts: vec![caller.clone(), token], ..Default::default() };
        let (parties, _) = parties_of(
            &metadata,
            &metadata.contracts[0],
            &stub("repay"),
            "IERC20",
            "safeTransfer",
            &["POOL".to_string()],
        );
        assert_eq!(parties, vec![format!("to: POOL{ADDRESS_MARK}")]);
    }

    /// An answer that names no contract of this repository is an ACCOUNT — a creator, a
    /// multisig, whoever called. It is still an answer, and it is still drawn; what it must not
    /// do is look like code somebody can open.
    #[test]
    fn an_answer_that_is_not_a_contract_is_drawn_as_an_account() {
        let metadata = EvmBatMetadata {
            contracts: vec![contract("Desk", Vec::new())],
            wiring: std::collections::HashMap::from([
                ("Desk.enroll.creator".to_string(), "the launch creator".to_string()),
            ]),
            ..Default::default()
        };
        assert_eq!(
            entity_of(&metadata, &metadata.contracts[0], "enroll", "creator").as_deref(),
            Some("the launch creator")
        );
    }

    /// The zero address is a destination like any other: value sent there is burnt, and the
    /// argument says so in full. Asking the reader to resolve `address(0)` is asking them to
    /// name what is already named.
    #[test]
    fn the_zero_address_is_its_own_name() {
        let metadata = EvmBatMetadata {
            contracts: vec![contract("ListingDesk", Vec::new())],
            ..Default::default()
        };
        assert_eq!(
            entity_of(&metadata, &metadata.contracts[0], "_stop", "address(0)").as_deref(),
            Some("address(0)")
        );
    }

    /// A binding for ONE caller. `lib/` vendors three `IVault`s; a global resolution answers
    /// for every one of them, so the specific entry has to win where it exists and leave the
    /// rest asking.
    #[test]
    fn a_scoped_resolution_beats_the_global_one() {
        let metadata = EvmBatMetadata {
            resolutions: std::collections::HashMap::from([
                ("IVault".to_string(), "AscendYieldVault".to_string()),
                ("YieldRouter:IVault".to_string(), "CLVault".to_string()),
            ]),
            ..Default::default()
        };
        assert_eq!(
            metadata.resolution_for(Some("YieldRouter"), "IVault").map(String::as_str),
            Some("CLVault")
        );
        assert_eq!(
            metadata.resolution_for(Some("ReferralPot"), "IVault").map(String::as_str),
            Some("AscendYieldVault"),
            "another caller still reads the global binding"
        );
        assert_eq!(metadata.resolution_for(None, "IVault").map(String::as_str), Some("AscendYieldVault"));
    }

    /// One key, several contracts: a function reached from two places with two destinations is
    /// two parties, and recording one of them would hide the other.
    #[test]
    fn a_recorded_answer_may_name_several_contracts() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                contract("Router", vec![variable("sink", "address")]),
                contract("BurnSink", Vec::new()),
                contract("Treasury", Vec::new()),
            ],
            wiring: std::collections::HashMap::from([(
                "Router.sink".to_string(),
                "BurnSink, Treasury".to_string(),
            )]),
            ..Default::default()
        };
        assert_eq!(
            entity_of(&metadata, &metadata.contracts[0], "pay", "sink").as_deref(),
            Some("BurnSink,Treasury")
        );
    }

    /// Which parameters are parties: the ones whose type is an address, plainly or because it
    /// names a contract.
    #[test]
    fn a_party_is_an_address_or_a_contract() {
        let metadata = EvmBatMetadata {
            contracts: vec![contract("Treasury", Vec::new())],
            ..Default::default()
        };
        assert!(is_address_like(&metadata, "address"));
        assert!(is_address_like(&metadata, "address payable"));
        assert!(is_address_like(&metadata, "Treasury"));
        assert!(!is_address_like(&metadata, "uint256"));
        assert!(!is_address_like(&metadata, "bytes"));
    }
}

#[cfg(test)]
mod wrapper_test {
    use super::unwrap_library_call;
    use crate::batbelt::evm::metadata::bat_metadata::{
        ContractMetadata, EvmBatMetadata, ExternalUnknownCall, FunctionMetadata,
    };
    use crate::batbelt::evm::types::{EvmContractType, EvmMutability, EvmParam, EvmVisibility};

    fn param(name: &str, type_name: &str) -> EvmParam {
        EvmParam {
            name: name.to_string(),
            type_name: type_name.to_string(),
            storage_location: None,
        }
    }

    fn wrapper(name: &str, params: Vec<EvmParam>, inner: Vec<ExternalUnknownCall>) -> FunctionMetadata {
        FunctionMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            contract_name: "SafeERC20".to_string(),
            visibility: EvmVisibility::Internal,
            mutability: EvmMutability::NonPayable,
            modifiers: Vec::new(),
            params,
            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::new(),
            unknown_external_calls: inner,
            resolved_calls: Vec::new(),
            callbacks: Vec::new(),
            creations: Vec::new(),
        }
    }

    fn inner(receiver: &str, method: &str, arguments: &[&str]) -> ExternalUnknownCall {
        ExternalUnknownCall {
            receiver: receiver.to_string(),
            method: method.to_string(),
            inferred_type: "IERC20".to_string(),
            arguments: arguments.iter().map(|a| a.to_string()).collect(),
        }
    }

    fn two(library: ContractMetadata, caller: ContractMetadata) -> EvmBatMetadata {
        EvmBatMetadata {
            contracts: vec![library, caller],
            ..Default::default()
        }
    }

    fn contract(name: &str, using: &[&str], functions: Vec<FunctionMetadata>) -> ContractMetadata {
        ContractMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            using_libraries: using.iter().map(|u| u.to_string()).collect(),
            file_path: format!("src/{name}.sol"),
            contract_type: EvmContractType::Contract,
            base_contracts: Vec::new(),
            functions,
            state_variables: Vec::new(),
            structs: Vec::new(),
            events: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            vendored: false,
        }
    }

    /// A wrapper is drawn as the call it actually makes, with the call site's arguments put in
    /// the wrapper's parameters: `token.safeTransfer(burnSink, amount)` is a `transfer` to
    /// `burnSink`. `IERC20` has no `safeTransfer` to show — it comes from `using SafeERC20`.
    #[test]
    fn a_wrapper_is_drawn_as_the_call_it_makes() {
        let library = contract(
            "SafeERC20",
            &[],
            vec![wrapper(
                "safeTransfer",
                vec![param("token", "IERC20"), param("to", "address"), param("value", "uint256")],
                vec![inner("token", "transfer", &["to", "value"])],
            )],
        );
        let caller = contract("YieldRouter", &["SafeERC20"], Vec::new());
        let metadata = two(library, caller);
        let found = unwrap_library_call(
            &metadata,
            &metadata.contracts[1],
            "safeTransfer",
            &["burnSink".to_string(), "amount".to_string()],
        );
        assert_eq!(
            found,
            Some(("transfer".to_string(), vec!["burnSink".to_string(), "amount".to_string()]))
        );
    }

    /// Calling the same method twice is still one relation — `forceApprove` approves zero and
    /// then the value — but a wrapper that calls two DIFFERENT methods is not flattened into one
    /// box.
    #[test]
    fn one_method_twice_is_fine_and_two_methods_are_not() {
        let twice = contract(
            "SafeERC20",
            &[],
            vec![wrapper(
                "forceApprove",
                vec![param("token", "IERC20"), param("spender", "address"), param("value", "uint256")],
                vec![
                    inner("token", "approve", &["spender", "value"]),
                    inner("token", "approve", &["spender", "0"]),
                ],
            )],
        );
        let caller = contract("YieldRouter", &["SafeERC20"], Vec::new());
        let metadata = two(twice, caller);
        assert_eq!(
            unwrap_library_call(
                &metadata,
                &metadata.contracts[1],
                "forceApprove",
                &["venue".to_string(), "amount".to_string()]
            )
            .map(|(method, _)| method),
            Some("approve".to_string())
        );

        let mixed = contract(
            "Odd",
            &[],
            vec![wrapper(
                "doBoth",
                vec![param("token", "IERC20"), param("to", "address")],
                vec![inner("token", "approve", &["to"]), inner("token", "transfer", &["to"])],
            )],
        );
        let caller = contract("YieldRouter", &["Odd"], Vec::new());
        let metadata = two(mixed, caller);
        assert_eq!(
            unwrap_library_call(&metadata, &metadata.contracts[1], "doBoth", &["x".to_string()]),
            None,
            "two different methods are not one box"
        );
    }

    /// A library leaf is hidden only when the library's body says what crosses INSTEAD.
    /// `VaultPay.pay(IVault vault, …)` calls `vault.settle()`, which is its own box, so
    /// `IVault → pay()` is a method the vault does not have. `SafeTransferLib.safeTransfer(ERC20
    /// token, …)` writes its call in assembly and never names `token` again — hiding that leaf
    /// hid every transfer and left `ERC20` reaching nothing.
    #[test]
    fn an_assembly_library_keeps_its_leaf() {
        use super::attached_elsewhere;
        let mut pay = contract(
            "VaultPay",
            &[],
            vec![wrapper(
                "pay",
                vec![param("vault", "IVault"), param("amount", "uint256")],
                vec![inner("vault", "settle", &["amount"])],
            )],
        );
        pay.contract_type = EvmContractType::Library;
        let mut safe = contract(
            "SafeTransferLib",
            &[],
            vec![wrapper(
                "safeTransfer",
                vec![param("token", "ERC20"), param("to", "address"), param("amount", "uint256")],
                vec![inner("assembly", "call", &[])],
            )],
        );
        safe.contract_type = EvmContractType::Library;
        let metadata = EvmBatMetadata {
            contracts: vec![
                pay,
                safe,
                contract("IVault", &[], Vec::new()),
                contract("ERC20", &[], Vec::new()),
            ],
            ..Default::default()
        };
        assert!(
            attached_elsewhere(&metadata, "IVault", "pay"),
            "the vault's own settle() is drawn in its place"
        );
        assert!(
            !attached_elsewhere(&metadata, "ERC20", "safeTransfer"),
            "nothing replaces it, so the transfer stays on the map"
        );
    }

    /// A method of the type itself is not a wrapper and is left alone.
    #[test]
    fn a_plain_call_is_not_unwrapped() {
        let caller = contract("YieldRouter", &["SafeERC20"], Vec::new());
        let metadata = two(contract("SafeERC20", &[], Vec::new()), caller);
        assert_eq!(
            unwrap_library_call(&metadata, &metadata.contracts[1], "transfer", &[]),
            None
        );
    }
}

#[cfg(test)]
mod palette_test {
    use super::{BOX_BORDER, REPEAT_BORDERS};

    /// Perceived brightness, 0 (black) to 255 (white).
    fn luma(colour: &str) -> f64 {
        let channel = |at: usize| {
            u8::from_str_radix(&colour[at..at + 2], 16).expect("six hex digits") as f64
        };
        0.299 * channel(1) + 0.587 * channel(3) + 0.114 * channel(5)
    }

    /// Every repeat colour is a COLOUR at a glance, not a dark line.
    ///
    /// The job of that border is to be matched against another one across a frame, at the zoom
    /// where the whole frame fits. The first palette was chosen by hue and half of it landed
    /// around luma 45 — `#1a237e`, `#3e2723`, `#4a148c` — where the plain border `#1a1a1a` is
    /// 26: a reader comparing two of them was comparing two blacks. The floor is what stops a
    /// hue picked on a screen at full zoom from going back in.
    ///
    /// And a ceiling, because the other end is just as useless: a border at luma 230 on white
    /// is not a border.
    #[test]
    fn no_repeat_colour_reads_as_black_or_as_white() {
        assert!(luma(BOX_BORDER) < 60.0, "the plain border is the dark one");
        for colour in REPEAT_BORDERS {
            let seen = luma(colour);
            assert!(
                (100.0..=210.0).contains(&seen),
                "{colour} is at luma {seen:.0}, outside 100..=210"
            );
        }
    }

    /// Sixteen colours and no two the same, or a repeated contract shares a colour with another
    /// repeated contract and the frame says they are one address.
    #[test]
    fn the_palette_has_no_duplicates() {
        let mut seen: Vec<&str> = REPEAT_BORDERS.to_vec();
        seen.sort_unstable();
        let before = seen.len();
        seen.dedup();
        assert_eq!(seen.len(), before, "a colour appears twice");
    }
}

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

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

    /// A variable in front of a contract's name earns its place only when the frame holds more
    /// than one of that contract.
    ///
    /// Six `Treasury`s are six addresses and the variable is the only thing telling them apart.
    /// ONE launchpad is one address, and naming it on the one branch that reaches it through a
    /// variable made the frame's own root and that box read as two different contracts — with
    /// nothing on the picture saying otherwise, and the reader left to trace back to wherever
    /// the name was given.
    #[test]
    fn a_variable_is_printed_only_when_there_is_more_than_one() {
        let edges = vec![
            edge("AscendLaunchpad", "listingDesk%ListingDesk"),
            // The same launchpad, reached through the desk's variable.
            edge("listingDesk%ListingDesk", "launchpad%AscendLaunchpad"),
            // Two treasuries: two addresses of one contract.
            edge("AscendLaunchpad", "cohortTreasury%Treasury"),
            edge("AscendLaunchpad", "opexTreasury%Treasury"),
        ];
        let many = drawn_more_than_once(&edges);
        assert!(many.contains("Treasury"), "two deployments: {many:?}");
        assert!(
            !many.contains("AscendLaunchpad"),
            "the root and the variable holding it are one address: {many:?}"
        );
        assert!(!many.contains("ListingDesk"), "one desk: {many:?}");
    }
}

#[cfg(test)]
mod over_boxes_test {
    use super::{arrows_over_boxes, layout_tree, route_arrows, Edge, Relation};

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

    /// An arrow that skips a column goes AROUND the column it skips.
    ///
    /// `rejoin` puts a box two branches share below both of them, so the shorter branch's
    /// arrow spans two columns. It used to be drawn as one straight line from caller to
    /// callee, straight through whatever stood in between — `AscendCtoRegistry`'s arrow ran
    /// across `AscendCtoReceiver`'s name on a frame certified as having no crossings, because
    /// an arrow crossing a BOX was not a thing anything counted.
    #[test]
    fn an_arrow_that_skips_a_column_goes_round_what_is_in_it() {
        // Registry -> Receiver -> launchpad, and Registry -> launchpad: the second one spans
        // two columns and the receiver sits in the one it crosses.
        let edges = vec![
            edge("Registry", "Receiver"),
            edge("Receiver", "launchpad%Launchpad"),
            edge("Registry", "launchpad%Launchpad"),
        ];
        let layout = layout_tree("Registry", &edges);
        let arrows = route_arrows(&edges, &layout, false);
        assert_eq!(
            arrows_over_boxes(&arrows, &edges, &layout),
            0,
            "no arrow runs across a box it does not touch"
        );
        // And it got there by turning, not by luck: the skipping arrow has a corridor.
        let skipping = edges
            .iter()
            .position(|edge| edge.from == "Registry" && edge.to == "launchpad%Launchpad")
            .expect("the edge is there");
        assert_eq!(
            layout.routes[skipping].len(),
            1,
            "one corridor for the one column it skips"
        );
    }

    /// The certificate has to be able to FAIL, or it certifies nothing. An arrow laid straight
    /// over a box is counted.
    #[test]
    fn a_line_through_a_box_is_counted() {
        use super::RoutedArrow;
        use crate::batbelt::evm::miro::auto_deploy::{LaneSide, PlannedLaneArrow};
        use crate::batbelt::miro::client::RelativeAnchor;

        let edges = vec![edge("Registry", "Receiver"), edge("Receiver", "launchpad%Launchpad")];
        let layout = layout_tree("Registry", &edges);
        let receiver = layout.node("Receiver").expect("placed").clone();
        let straight = RoutedArrow {
            edge: Some(0),
            plan: PlannedLaneArrow {
                points: vec![
                    (receiver.x - receiver.width, receiver.y),
                    (receiver.x + receiver.width, receiver.y),
                ],
                legs: vec![(
                    LaneSide::Marker(0),
                    RelativeAnchor::new(1.0, 0.5),
                    LaneSide::Marker(1),
                    RelativeAnchor::new(0.0, 0.5),
                    true,
                )],
            },
            style: super::style_of(Relation::Calls, false),
        };
        assert_eq!(
            arrows_over_boxes(&[straight], &[edge("Registry", "launchpad%Launchpad")], &layout),
            1,
            "a line laid across the receiver is one crossing"
        );
    }
}

#[cfg(test)]
mod preview_words_test {
    use super::write_words;

    /// The preview has to carry the words, or a name that overflows its box and a name lost in
    /// one look exactly alike — which is how three box sizes reached the board unseen.
    #[test]
    fn the_words_reach_the_canvas() {
        let mut canvas = image::RgbaImage::from_pixel(400, 80, image::Rgba([250, 250, 250, 255]));
        write_words(
            &mut canvas,
            "YieldRouter",
            (10, 10),
            (390, 70),
            0.2,
            image::Rgba([26, 26, 26, 255]),
        );
        let inked = canvas.pixels().filter(|pixel| pixel.0[0] < 200).count();
        assert!(inked > 20, "the words were drawn: {inked} dark pixel(s)");
    }
}

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

    /// A party naming a contract is that contract's box too: `to: StakerDistributor` under a
    /// method leaf and `distributor (StakerDistributor)` beside it are one address, so they
    /// carry one colour.
    #[test]
    fn a_party_shares_the_repeated_contracts_colour() {
        let edges = vec![
            Edge {
                from: "YieldRouter".to_string(),
                to: "distributor%StakerDistributor".to_string(),
                relation: Relation::Calls,
            },
            Edge {
                from: "IERC20@StakerDistributor::transferFrom".to_string(),
                to: "IERC20@StakerDistributor::transferFrom=>to: this%StakerDistributor".to_string(),
                relation: Relation::Boundary,
            },
        ];
        // The colour groups by ADDRESS: the variable that holds it, not the type.
        assert_eq!(super::addressed_as(&edges[0].to), "distributor%StakerDistributor");
        assert_eq!(super::addressed_as(&edges[1].to), "this%StakerDistributor");
        let metadata = crate::batbelt::evm::metadata::bat_metadata::EvmBatMetadata {
            contracts: vec![super::framing_test::contract_named("StakerDistributor")],
            ..Default::default()
        };
        let borders = PreparedFrame::repeat_borders(&metadata, &edges);
        println!("borders: {borders:?}");
        // One variable of that contract in the frame, so `this` is that address and the two
        // boxes carry one colour.
        assert!(borders.contains_key("distributor%StakerDistributor"), "{borders:?}");
        assert_eq!(
            borders["distributor%StakerDistributor"], borders["this%StakerDistributor"],
            "the party and the box it names read as one address"
        );
    }
}