foundry_config/lib.rs
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
//! # foundry-config
//!
//! Foundry configuration.
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#[macro_use]
extern crate tracing;
use crate::cache::StorageCachingConfig;
use alloy_primitives::{address, Address, B256, U256};
use eyre::{ContextCompat, WrapErr};
use figment::{
providers::{Env, Format, Serialized, Toml},
value::{Dict, Map, Value},
Error, Figment, Metadata, Profile, Provider,
};
use filter::GlobMatcher;
use foundry_compilers::{
artifacts::{
output_selection::{ContractOutputSelection, OutputSelection},
remappings::{RelativeRemapping, Remapping},
serde_helpers, BytecodeHash, DebuggingSettings, EofVersion, EvmVersion, Libraries,
ModelCheckerSettings, ModelCheckerTarget, Optimizer, OptimizerDetails, RevertStrings,
Settings, SettingsMetadata, Severity,
},
cache::SOLIDITY_FILES_CACHE_FILENAME,
compilers::{
multi::{MultiCompiler, MultiCompilerSettings},
solc::{Solc, SolcCompiler},
vyper::{Vyper, VyperSettings},
Compiler,
},
error::SolcError,
multi::{MultiCompilerParsedSource, MultiCompilerRestrictions},
solc::{CliSettings, SolcSettings},
ConfigurableArtifacts, Graph, Project, ProjectPathsConfig, RestrictionsWithVersion,
VyperLanguage,
};
use inflector::Inflector;
use regex::Regex;
use revm_primitives::{map::AddressHashMap, FixedBytes, SpecId};
use semver::Version;
use serde::{Deserialize, Serialize, Serializer};
use std::{
borrow::Cow,
collections::BTreeMap,
fs,
path::{Path, PathBuf},
str::FromStr,
sync::mpsc::{self, RecvTimeoutError},
time::Duration,
};
mod macros;
pub mod utils;
pub use utils::*;
mod endpoints;
pub use endpoints::{ResolvedRpcEndpoints, RpcEndpoint, RpcEndpoints};
mod etherscan;
use etherscan::{
EtherscanConfigError, EtherscanConfigs, EtherscanEnvProvider, ResolvedEtherscanConfig,
};
mod resolve;
pub use resolve::UnresolvedEnvVarError;
pub mod cache;
use cache::{Cache, ChainCache};
pub mod fmt;
pub use fmt::FormatterConfig;
pub mod fs_permissions;
pub use fs_permissions::FsPermissions;
use fs_permissions::PathPermission;
pub mod error;
use error::ExtractConfigError;
pub use error::SolidityErrorCode;
pub mod doc;
pub use doc::DocConfig;
pub mod filter;
pub use filter::SkipBuildFilters;
mod warning;
pub use warning::*;
pub mod fix;
// reexport so cli types can implement `figment::Provider` to easily merge compiler arguments
pub use alloy_chains::{Chain, NamedChain};
pub use figment;
pub mod providers;
use providers::{remappings::RemappingsProvider, FallbackProfileProvider, WarningsProvider};
mod fuzz;
pub use fuzz::{FuzzConfig, FuzzDictionaryConfig};
mod invariant;
pub use invariant::InvariantConfig;
mod inline;
pub use inline::{validate_profiles, InlineConfig, InlineConfigError, InlineConfigParser, NatSpec};
pub mod soldeer;
use soldeer::{SoldeerConfig, SoldeerDependencyConfig};
mod vyper;
use vyper::VyperConfig;
mod bind_json;
use bind_json::BindJsonConfig;
mod compilation;
use compilation::{CompilationRestrictions, SettingsOverrides};
/// Foundry configuration
///
/// # Defaults
///
/// All configuration values have a default, documented in the [fields](#fields)
/// section below. [`Config::default()`] returns the default values for
/// the default profile while [`Config::with_root()`] returns the values based on the given
/// directory. [`Config::load()`] starts with the default profile and merges various providers into
/// the config, same for [`Config::load_with_root()`], but there the default values are determined
/// by [`Config::with_root()`]
///
/// # Provider Details
///
/// `Config` is a Figment [`Provider`] with the following characteristics:
///
/// * **Profile**
///
/// The profile is set to the value of the `profile` field.
///
/// * **Metadata**
///
/// This provider is named `Foundry Config`. It does not specify a
/// [`Source`](figment::Source) and uses default interpolation.
///
/// * **Data**
///
/// The data emitted by this provider are the keys and values corresponding
/// to the fields and values of the structure. The dictionary is emitted to
/// the "default" meta-profile.
///
/// Note that these behaviors differ from those of [`Config::figment()`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Config {
/// The selected profile. **(default: _default_ `default`)**
///
/// **Note:** This field is never serialized nor deserialized. When a
/// `Config` is merged into a `Figment` as a `Provider`, this profile is
/// selected on the `Figment`. When a `Config` is extracted, this field is
/// set to the extracting Figment's selected `Profile`.
#[serde(skip)]
pub profile: Profile,
/// path of the source contracts dir, like `src` or `contracts`
pub src: PathBuf,
/// path of the test dir
pub test: PathBuf,
/// path of the script dir
pub script: PathBuf,
/// path to where artifacts shut be written to
pub out: PathBuf,
/// all library folders to include, `lib`, `node_modules`
pub libs: Vec<PathBuf>,
/// `Remappings` to use for this repo
pub remappings: Vec<RelativeRemapping>,
/// Whether to autodetect remappings by scanning the `libs` folders recursively
pub auto_detect_remappings: bool,
/// library addresses to link
pub libraries: Vec<String>,
/// whether to enable cache
pub cache: bool,
/// where the cache is stored if enabled
pub cache_path: PathBuf,
/// where the gas snapshots are stored
pub snapshots: PathBuf,
/// where the broadcast logs are stored
pub broadcast: PathBuf,
/// additional solc allow paths for `--allow-paths`
pub allow_paths: Vec<PathBuf>,
/// additional solc include paths for `--include-path`
pub include_paths: Vec<PathBuf>,
/// glob patterns to skip
pub skip: Vec<GlobMatcher>,
/// whether to force a `project.clean()`
pub force: bool,
/// evm version to use
#[serde(with = "from_str_lowercase")]
pub evm_version: EvmVersion,
/// list of contracts to report gas of
pub gas_reports: Vec<String>,
/// list of contracts to ignore for gas reports
pub gas_reports_ignore: Vec<String>,
/// Whether to include gas reports for tests.
pub gas_reports_include_tests: bool,
/// The Solc instance to use if any.
///
/// This takes precedence over `auto_detect_solc`, if a version is set then this overrides
/// auto-detection.
///
/// **Note** for backwards compatibility reasons this also accepts solc_version from the toml
/// file, see `BackwardsCompatTomlProvider`.
pub solc: Option<SolcReq>,
/// whether to autodetect the solc compiler version to use
pub auto_detect_solc: bool,
/// Offline mode, if set, network access (downloading solc) is disallowed.
///
/// Relationship with `auto_detect_solc`:
/// - if `auto_detect_solc = true` and `offline = true`, the required solc version(s) will
/// be auto detected but if the solc version is not installed, it will _not_ try to
/// install it
pub offline: bool,
/// Whether to activate optimizer
pub optimizer: bool,
/// The number of runs specifies roughly how often each opcode of the deployed code will be
/// executed across the life-time of the contract. This means it is a trade-off parameter
/// between code size (deploy cost) and code execution cost (cost after deployment).
/// An `optimizer_runs` parameter of `1` will produce short but expensive code. In contrast, a
/// larger `optimizer_runs` parameter will produce longer but more gas efficient code. The
/// maximum value of the parameter is `2**32-1`.
///
/// A common misconception is that this parameter specifies the number of iterations of the
/// optimizer. This is not true: The optimizer will always run as many times as it can
/// still improve the code.
pub optimizer_runs: usize,
/// Switch optimizer components on or off in detail.
/// The "enabled" switch above provides two defaults which can be
/// tweaked here. If "details" is given, "enabled" can be omitted.
pub optimizer_details: Option<OptimizerDetails>,
/// Model checker settings.
pub model_checker: Option<ModelCheckerSettings>,
/// verbosity to use
pub verbosity: u8,
/// url of the rpc server that should be used for any rpc calls
pub eth_rpc_url: Option<String>,
/// JWT secret that should be used for any rpc calls
pub eth_rpc_jwt: Option<String>,
/// Timeout that should be used for any rpc calls
pub eth_rpc_timeout: Option<u64>,
/// etherscan API key, or alias for an `EtherscanConfig` in `etherscan` table
pub etherscan_api_key: Option<String>,
/// Multiple etherscan api configs and their aliases
#[serde(default, skip_serializing_if = "EtherscanConfigs::is_empty")]
pub etherscan: EtherscanConfigs,
/// list of solidity error codes to always silence in the compiler output
pub ignored_error_codes: Vec<SolidityErrorCode>,
/// list of file paths to ignore
#[serde(rename = "ignored_warnings_from")]
pub ignored_file_paths: Vec<PathBuf>,
/// When true, compiler warnings are treated as errors
pub deny_warnings: bool,
/// Only run test functions matching the specified regex pattern.
#[serde(rename = "match_test")]
pub test_pattern: Option<RegexWrapper>,
/// Only run test functions that do not match the specified regex pattern.
#[serde(rename = "no_match_test")]
pub test_pattern_inverse: Option<RegexWrapper>,
/// Only run tests in contracts matching the specified regex pattern.
#[serde(rename = "match_contract")]
pub contract_pattern: Option<RegexWrapper>,
/// Only run tests in contracts that do not match the specified regex pattern.
#[serde(rename = "no_match_contract")]
pub contract_pattern_inverse: Option<RegexWrapper>,
/// Only run tests in source files matching the specified glob pattern.
#[serde(rename = "match_path", with = "from_opt_glob")]
pub path_pattern: Option<globset::Glob>,
/// Only run tests in source files that do not match the specified glob pattern.
#[serde(rename = "no_match_path", with = "from_opt_glob")]
pub path_pattern_inverse: Option<globset::Glob>,
/// Only show coverage for files that do not match the specified regex pattern.
#[serde(rename = "no_match_coverage")]
pub coverage_pattern_inverse: Option<RegexWrapper>,
/// Path where last test run failures are recorded.
pub test_failures_file: PathBuf,
/// Max concurrent threads to use.
pub threads: Option<usize>,
/// Whether to show test execution progress.
pub show_progress: bool,
/// Configuration for fuzz testing
pub fuzz: FuzzConfig,
/// Configuration for invariant testing
pub invariant: InvariantConfig,
/// Whether to allow ffi cheatcodes in test
pub ffi: bool,
/// Use the create 2 factory in all cases including tests and non-broadcasting scripts.
pub always_use_create_2_factory: bool,
/// Sets a timeout in seconds for vm.prompt cheatcodes
pub prompt_timeout: u64,
/// The address which will be executing all tests
pub sender: Address,
/// The tx.origin value during EVM execution
pub tx_origin: Address,
/// the initial balance of each deployed test contract
pub initial_balance: U256,
/// the block.number value during EVM execution
pub block_number: u64,
/// pins the block number for the state fork
pub fork_block_number: Option<u64>,
/// The chain name or EIP-155 chain ID.
#[serde(rename = "chain_id", alias = "chain")]
pub chain: Option<Chain>,
/// Block gas limit.
pub gas_limit: GasLimit,
/// EIP-170: Contract code size limit in bytes. Useful to increase this because of tests.
pub code_size_limit: Option<usize>,
/// `tx.gasprice` value during EVM execution.
///
/// This is an Option, so we can determine in fork mode whether to use the config's gas price
/// (if set by user) or the remote client's gas price.
pub gas_price: Option<u64>,
/// The base fee in a block.
pub block_base_fee_per_gas: u64,
/// The `block.coinbase` value during EVM execution.
pub block_coinbase: Address,
/// The `block.timestamp` value during EVM execution.
pub block_timestamp: u64,
/// The `block.difficulty` value during EVM execution.
pub block_difficulty: u64,
/// Before merge the `block.max_hash`, after merge it is `block.prevrandao`.
pub block_prevrandao: B256,
/// The `block.gaslimit` value during EVM execution.
pub block_gas_limit: Option<GasLimit>,
/// The memory limit per EVM execution in bytes.
/// If this limit is exceeded, a `MemoryLimitOOG` result is thrown.
///
/// The default is 128MiB.
pub memory_limit: u64,
/// Additional output selection for all contracts, such as "ir", "devdoc", "storageLayout",
/// etc.
///
/// See the [Solc Compiler Api](https://docs.soliditylang.org/en/latest/using-the-compiler.html#compiler-api) for more information.
///
/// The following values are always set because they're required by `forge`:
/// ```json
/// {
/// "*": [
/// "abi",
/// "evm.bytecode",
/// "evm.deployedBytecode",
/// "evm.methodIdentifiers"
/// ]
/// }
/// ```
#[serde(default)]
pub extra_output: Vec<ContractOutputSelection>,
/// If set, a separate JSON file will be emitted for every contract depending on the
/// selection, eg. `extra_output_files = ["metadata"]` will create a `metadata.json` for
/// each contract in the project.
///
/// See [Contract Metadata](https://docs.soliditylang.org/en/latest/metadata.html) for more information.
///
/// The difference between `extra_output = ["metadata"]` and
/// `extra_output_files = ["metadata"]` is that the former will include the
/// contract's metadata in the contract's json artifact, whereas the latter will emit the
/// output selection as separate files.
#[serde(default)]
pub extra_output_files: Vec<ContractOutputSelection>,
/// Whether to print the names of the compiled contracts.
pub names: bool,
/// Whether to print the sizes of the compiled contracts.
pub sizes: bool,
/// If set to true, changes compilation pipeline to go through the Yul intermediate
/// representation.
pub via_ir: bool,
/// Whether to include the AST as JSON in the compiler output.
pub ast: bool,
/// RPC storage caching settings determines what chains and endpoints to cache
pub rpc_storage_caching: StorageCachingConfig,
/// Disables storage caching entirely. This overrides any settings made in
/// `rpc_storage_caching`
pub no_storage_caching: bool,
/// Disables rate limiting entirely. This overrides any settings made in
/// `compute_units_per_second`
pub no_rpc_rate_limit: bool,
/// Multiple rpc endpoints and their aliases
#[serde(default, skip_serializing_if = "RpcEndpoints::is_empty")]
pub rpc_endpoints: RpcEndpoints,
/// Whether to store the referenced sources in the metadata as literal data.
pub use_literal_content: bool,
/// Whether to include the metadata hash.
///
/// The metadata hash is machine dependent. By default, this is set to [BytecodeHash::None] to allow for deterministic code, See: <https://docs.soliditylang.org/en/latest/metadata.html>
#[serde(with = "from_str_lowercase")]
pub bytecode_hash: BytecodeHash,
/// Whether to append the metadata hash to the bytecode.
///
/// If this is `false` and the `bytecode_hash` option above is not `None` solc will issue a
/// warning.
pub cbor_metadata: bool,
/// How to treat revert (and require) reason strings.
#[serde(with = "serde_helpers::display_from_str_opt")]
pub revert_strings: Option<RevertStrings>,
/// Whether to compile in sparse mode
///
/// If this option is enabled, only the required contracts/files will be selected to be
/// included in solc's output selection, see also [`OutputSelection`].
pub sparse_mode: bool,
/// Generates additional build info json files for every new build, containing the
/// `CompilerInput` and `CompilerOutput`.
pub build_info: bool,
/// The path to the `build-info` directory that contains the build info json files.
pub build_info_path: Option<PathBuf>,
/// Configuration for `forge fmt`
pub fmt: FormatterConfig,
/// Configuration for `forge doc`
pub doc: DocConfig,
/// Configuration for `forge bind-json`
pub bind_json: BindJsonConfig,
/// Configures the permissions of cheat codes that touch the file system.
///
/// This includes what operations can be executed (read, write)
pub fs_permissions: FsPermissions,
/// Whether to enable call isolation.
///
/// Useful for more correct gas accounting and EVM behavior in general.
pub isolate: bool,
/// Whether to disable the block gas limit.
pub disable_block_gas_limit: bool,
/// Address labels
pub labels: AddressHashMap<String>,
/// Whether to enable safety checks for `vm.getCode` and `vm.getDeployedCode` invocations.
/// If disabled, it is possible to access artifacts which were not recompiled or cached.
pub unchecked_cheatcode_artifacts: bool,
/// CREATE2 salt to use for the library deployment in scripts.
pub create2_library_salt: B256,
/// Configuration for Vyper compiler
pub vyper: VyperConfig,
/// Soldeer dependencies
pub dependencies: Option<SoldeerDependencyConfig>,
/// Soldeer custom configs
pub soldeer: Option<SoldeerConfig>,
/// The root path where the config detection started from, [`Config::with_root`].
// We're skipping serialization here, so it won't be included in the [`Config::to_string()`]
// representation, but will be deserialized from the `Figment` so that forge commands can
// override it.
#[serde(default, skip_serializing)]
pub root: RootPath,
/// Whether failed assertions should revert.
///
/// Note that this only applies to native (cheatcode) assertions, invoked on Vm contract.
pub assertions_revert: bool,
/// Whether `failed()` should be invoked to check if the test have failed.
pub legacy_assertions: bool,
/// Optional additional CLI arguments to pass to `solc` binary.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra_args: Vec<String>,
/// Optional EOF version.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub eof_version: Option<EofVersion>,
/// Whether to enable Alphanet features.
pub alphanet: bool,
/// Timeout for transactions in seconds.
pub transaction_timeout: u64,
/// Use EOF-enabled solc for compilation.
pub eof: bool,
/// Warnings gathered when loading the Config. See [`WarningsProvider`] for more information
#[serde(rename = "__warnings", default, skip_serializing)]
pub warnings: Vec<Warning>,
/// Additional settings profiles to use when compiling.
#[serde(default)]
pub additional_compiler_profiles: Vec<SettingsOverrides>,
/// Restrictions on compilation of certain files.
#[serde(default)]
pub compilation_restrictions: Vec<CompilationRestrictions>,
/// PRIVATE: This structure may grow, As such, constructing this structure should
/// _always_ be done using a public constructor or update syntax:
///
/// ```ignore
/// use foundry_config::Config;
///
/// let config = Config { src: "other".into(), ..Default::default() };
/// ```
#[doc(hidden)]
#[serde(skip)]
pub _non_exhaustive: (),
}
/// Mapping of fallback standalone sections. See [`FallbackProfileProvider`]
pub const STANDALONE_FALLBACK_SECTIONS: &[(&str, &str)] = &[("invariant", "fuzz")];
/// Deprecated keys and their replacements.
///
/// See [Warning::DeprecatedKey]
pub const DEPRECATIONS: &[(&str, &str)] = &[("cancun", "evm_version = Cancun")];
impl Config {
/// The default profile: "default"
pub const DEFAULT_PROFILE: Profile = Profile::const_new("default");
/// The hardhat profile: "hardhat"
pub const HARDHAT_PROFILE: Profile = Profile::const_new("hardhat");
/// TOML section for profiles
pub const PROFILE_SECTION: &'static str = "profile";
/// Standalone sections in the config which get integrated into the selected profile
pub const STANDALONE_SECTIONS: &'static [&'static str] = &[
"rpc_endpoints",
"etherscan",
"fmt",
"doc",
"fuzz",
"invariant",
"labels",
"dependencies",
"soldeer",
"vyper",
"bind_json",
];
/// File name of config toml file
pub const FILE_NAME: &'static str = "foundry.toml";
/// The name of the directory foundry reserves for itself under the user's home directory: `~`
pub const FOUNDRY_DIR_NAME: &'static str = ".foundry";
/// Default address for tx.origin
///
/// `0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38`
pub const DEFAULT_SENDER: Address = address!("1804c8AB1F12E6bbf3894d4083f33e07309d1f38");
/// Default salt for create2 library deployments
pub const DEFAULT_CREATE2_LIBRARY_SALT: FixedBytes<32> = FixedBytes::<32>::ZERO;
/// Docker image with eof-enabled solc binary
pub const EOF_SOLC_IMAGE: &'static str = "ghcr.io/paradigmxyz/forge-eof@sha256:46f868ce5264e1190881a3a335d41d7f42d6f26ed20b0c823609c715e38d603f";
/// Returns the current `Config`
///
/// See [`figment`](Self::figment) for more details.
#[track_caller]
pub fn load() -> Self {
Self::from_provider(Self::figment())
}
/// Returns the current `Config` with the given `providers` preset
///
/// See [`figment`](Self::figment) for more details.
#[track_caller]
pub fn load_with_providers(providers: FigmentProviders) -> Self {
Self::default().to_figment(providers).extract().unwrap()
}
/// Returns the current `Config`
///
/// See [`figment_with_root`](Self::figment_with_root) for more details.
#[track_caller]
pub fn load_with_root(root: impl AsRef<Path>) -> Self {
Self::from_provider(Self::figment_with_root(root.as_ref()))
}
/// Extract a `Config` from `provider`, panicking if extraction fails.
///
/// # Panics
///
/// If extraction fails, prints an error message indicating the failure and
/// panics. For a version that doesn't panic, use [`Config::try_from()`].
///
/// # Example
///
/// ```no_run
/// use figment::providers::{Env, Format, Toml};
/// use foundry_config::Config;
///
/// // Use foundry's default `Figment`, but allow values from `other.toml`
/// // to supersede its values.
/// let figment = Config::figment().merge(Toml::file("other.toml").nested());
///
/// let config = Config::from_provider(figment);
/// ```
#[track_caller]
pub fn from_provider<T: Provider>(provider: T) -> Self {
trace!("load config with provider: {:?}", provider.metadata());
Self::try_from(provider).unwrap_or_else(|err| panic!("{}", err))
}
/// Attempts to extract a `Config` from `provider`, returning the result.
///
/// # Example
///
/// ```rust
/// use figment::providers::{Env, Format, Toml};
/// use foundry_config::Config;
///
/// // Use foundry's default `Figment`, but allow values from `other.toml`
/// // to supersede its values.
/// let figment = Config::figment().merge(Toml::file("other.toml").nested());
///
/// let config = Config::try_from(figment);
/// ```
pub fn try_from<T: Provider>(provider: T) -> Result<Self, ExtractConfigError> {
let figment = Figment::from(provider);
let mut config = figment.extract::<Self>().map_err(ExtractConfigError::new)?;
config.profile = figment.profile().clone();
Ok(config)
}
/// Returns the populated [Figment] using the requested [FigmentProviders] preset.
///
/// This will merge various providers, such as env,toml,remappings into the figment.
pub fn to_figment(self, providers: FigmentProviders) -> Figment {
let mut c = self;
let profile = Self::selected_profile();
let mut figment = Figment::default().merge(DappHardhatDirProvider(&c.root.0));
// merge global foundry.toml file
if let Some(global_toml) = Self::foundry_dir_toml().filter(|p| p.exists()) {
figment = Self::merge_toml_provider(
figment,
TomlFileProvider::new(None, global_toml).cached(),
profile.clone(),
);
}
// merge local foundry.toml file
figment = Self::merge_toml_provider(
figment,
TomlFileProvider::new(Some("FOUNDRY_CONFIG"), c.root.0.join(Self::FILE_NAME)).cached(),
profile.clone(),
);
// merge environment variables
figment = figment
.merge(
Env::prefixed("DAPP_")
.ignore(&["REMAPPINGS", "LIBRARIES", "FFI", "FS_PERMISSIONS"])
.global(),
)
.merge(
Env::prefixed("DAPP_TEST_")
.ignore(&["CACHE", "FUZZ_RUNS", "DEPTH", "FFI", "FS_PERMISSIONS"])
.global(),
)
.merge(DappEnvCompatProvider)
.merge(EtherscanEnvProvider::default())
.merge(
Env::prefixed("FOUNDRY_")
.ignore(&["PROFILE", "REMAPPINGS", "LIBRARIES", "FFI", "FS_PERMISSIONS"])
.map(|key| {
let key = key.as_str();
if Self::STANDALONE_SECTIONS.iter().any(|section| {
key.starts_with(&format!("{}_", section.to_ascii_uppercase()))
}) {
key.replacen('_', ".", 1).into()
} else {
key.into()
}
})
.global(),
)
.select(profile.clone());
// only resolve remappings if all providers are requested
if providers.is_all() {
// we try to merge remappings after we've merged all other providers, this prevents
// redundant fs lookups to determine the default remappings that are eventually updated
// by other providers, like the toml file
let remappings = RemappingsProvider {
auto_detect_remappings: figment
.extract_inner::<bool>("auto_detect_remappings")
.unwrap_or(true),
lib_paths: figment
.extract_inner::<Vec<PathBuf>>("libs")
.map(Cow::Owned)
.unwrap_or_else(|_| Cow::Borrowed(&c.libs)),
root: &c.root.0,
remappings: figment.extract_inner::<Vec<Remapping>>("remappings"),
};
figment = figment.merge(remappings);
}
// normalize defaults
figment = c.normalize_defaults(figment);
Figment::from(c).merge(figment).select(profile)
}
/// The config supports relative paths and tracks the root path separately see
/// `Config::with_root`
///
/// This joins all relative paths with the current root and attempts to make them canonic
#[must_use]
pub fn canonic(self) -> Self {
let root = self.root.0.clone();
self.canonic_at(root)
}
/// Joins all relative paths with the given root so that paths that are defined as:
///
/// ```toml
/// [profile.default]
/// src = "src"
/// out = "./out"
/// libs = ["lib", "/var/lib"]
/// ```
///
/// Will be made canonic with the given root:
///
/// ```toml
/// [profile.default]
/// src = "<root>/src"
/// out = "<root>/out"
/// libs = ["<root>/lib", "/var/lib"]
/// ```
#[must_use]
pub fn canonic_at(mut self, root: impl Into<PathBuf>) -> Self {
let root = canonic(root);
fn p(root: &Path, rem: &Path) -> PathBuf {
canonic(root.join(rem))
}
self.src = p(&root, &self.src);
self.test = p(&root, &self.test);
self.script = p(&root, &self.script);
self.out = p(&root, &self.out);
self.broadcast = p(&root, &self.broadcast);
self.cache_path = p(&root, &self.cache_path);
self.snapshots = p(&root, &self.snapshots);
if let Some(build_info_path) = self.build_info_path {
self.build_info_path = Some(p(&root, &build_info_path));
}
self.libs = self.libs.into_iter().map(|lib| p(&root, &lib)).collect();
self.remappings =
self.remappings.into_iter().map(|r| RelativeRemapping::new(r.into(), &root)).collect();
self.allow_paths = self.allow_paths.into_iter().map(|allow| p(&root, &allow)).collect();
self.include_paths = self.include_paths.into_iter().map(|allow| p(&root, &allow)).collect();
self.fs_permissions.join_all(&root);
if let Some(ref mut model_checker) = self.model_checker {
model_checker.contracts = std::mem::take(&mut model_checker.contracts)
.into_iter()
.map(|(path, contracts)| {
(format!("{}", p(&root, path.as_ref()).display()), contracts)
})
.collect();
}
self
}
/// Normalizes the evm version if a [SolcReq] is set
pub fn normalized_evm_version(mut self) -> Self {
self.normalize_evm_version();
self
}
/// Normalizes the evm version if a [SolcReq] is set to a valid version.
pub fn normalize_evm_version(&mut self) {
self.evm_version = self.get_normalized_evm_version();
}
/// Returns the normalized [EvmVersion] if a [SolcReq] is set to a valid version or if the solc
/// path is a valid solc binary.
///
/// Otherwise it returns the configured [EvmVersion].
pub fn get_normalized_evm_version(&self) -> EvmVersion {
if let Some(version) = self.solc.as_ref().and_then(|solc| solc.try_version().ok()) {
if let Some(evm_version) = self.evm_version.normalize_version_solc(&version) {
return evm_version;
}
}
self.evm_version
}
/// Returns a sanitized version of the Config where are paths are set correctly and potential
/// duplicates are resolved
///
/// See [`Self::canonic`]
#[must_use]
pub fn sanitized(self) -> Self {
let mut config = self.canonic();
config.sanitize_remappings();
config.libs.sort_unstable();
config.libs.dedup();
config.sanitize_eof_settings();
config
}
/// Cleans up any duplicate `Remapping` and sorts them
///
/// On windows this will convert any `\` in the remapping path into a `/`
pub fn sanitize_remappings(&mut self) {
#[cfg(target_os = "windows")]
{
// force `/` in remappings on windows
use path_slash::PathBufExt;
self.remappings.iter_mut().for_each(|r| {
r.path.path = r.path.path.to_slash_lossy().into_owned().into();
});
}
}
/// Adjusts settings if EOF compilation is enabled.
///
/// This includes enabling via_ir, eof_version and ensuring that evm_version is not lower than
/// Prague.
pub fn sanitize_eof_settings(&mut self) {
if self.eof {
self.via_ir = true;
if self.eof_version.is_none() {
self.eof_version = Some(EofVersion::V1);
}
if self.evm_version < EvmVersion::Prague {
self.evm_version = EvmVersion::Prague;
}
}
}
/// Returns the directory in which dependencies should be installed
///
/// Returns the first dir from `libs` that is not `node_modules` or `lib` if `libs` is empty
pub fn install_lib_dir(&self) -> &Path {
self.libs
.iter()
.find(|p| !p.ends_with("node_modules"))
.map(|p| p.as_path())
.unwrap_or_else(|| Path::new("lib"))
}
/// Serves as the entrypoint for obtaining the project.
///
/// Returns the `Project` configured with all `solc` and path related values.
///
/// *Note*: this also _cleans_ [`Project::cleanup`] the workspace if `force` is set to true.
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// let config = Config::load_with_root(".").sanitized();
/// let project = config.project();
/// ```
pub fn project(&self) -> Result<Project<MultiCompiler>, SolcError> {
self.create_project(self.cache, false)
}
/// Same as [`Self::project()`] but sets configures the project to not emit artifacts and ignore
/// cache.
pub fn ephemeral_no_artifacts_project(&self) -> Result<Project<MultiCompiler>, SolcError> {
self.create_project(false, true)
}
/// Builds mapping with additional settings profiles.
fn additional_settings(
&self,
base: &MultiCompilerSettings,
) -> BTreeMap<String, MultiCompilerSettings> {
let mut map = BTreeMap::new();
for profile in &self.additional_compiler_profiles {
let mut settings = base.clone();
profile.apply(&mut settings);
map.insert(profile.name.clone(), settings);
}
map
}
/// Resolves globs and builds a mapping from individual source files to their restrictions
fn restrictions(
&self,
paths: &ProjectPathsConfig,
) -> Result<BTreeMap<PathBuf, RestrictionsWithVersion<MultiCompilerRestrictions>>, SolcError>
{
let mut map = BTreeMap::new();
if self.compilation_restrictions.is_empty() {
return Ok(BTreeMap::new());
}
let graph = Graph::<MultiCompilerParsedSource>::resolve(paths)?;
let (sources, _) = graph.into_sources();
for res in &self.compilation_restrictions {
for source in sources.keys().filter(|path| {
if res.paths.is_match(path) {
true
} else if let Ok(path) = path.strip_prefix(&paths.root) {
res.paths.is_match(path)
} else {
false
}
}) {
let res: RestrictionsWithVersion<_> =
res.clone().try_into().map_err(SolcError::msg)?;
if !map.contains_key(source) {
map.insert(source.clone(), res);
} else {
map.get_mut(source.as_path()).unwrap().merge(res);
}
}
}
Ok(map)
}
/// Creates a [Project] with the given `cached` and `no_artifacts` flags
pub fn create_project(&self, cached: bool, no_artifacts: bool) -> Result<Project, SolcError> {
let settings = self.compiler_settings()?;
let paths = self.project_paths();
let mut builder = Project::builder()
.artifacts(self.configured_artifacts_handler())
.additional_settings(self.additional_settings(&settings))
.restrictions(self.restrictions(&paths)?)
.settings(settings)
.paths(paths)
.ignore_error_codes(self.ignored_error_codes.iter().copied().map(Into::into))
.ignore_paths(self.ignored_file_paths.clone())
.set_compiler_severity_filter(if self.deny_warnings {
Severity::Warning
} else {
Severity::Error
})
.set_offline(self.offline)
.set_cached(cached)
.set_build_info(!no_artifacts && self.build_info)
.set_no_artifacts(no_artifacts);
if !self.skip.is_empty() {
let filter = SkipBuildFilters::new(self.skip.clone(), self.root.0.clone());
builder = builder.sparse_output(filter);
}
let project = builder.build(self.compiler()?)?;
if self.force {
self.cleanup(&project)?;
}
Ok(project)
}
/// Cleans the project.
pub fn cleanup<C: Compiler>(&self, project: &Project<C>) -> Result<(), SolcError> {
project.cleanup()?;
// Remove last test run failures file.
let _ = fs::remove_file(&self.test_failures_file);
// Remove fuzz and invariant cache directories.
let remove_test_dir = |test_dir: &Option<PathBuf>| {
if let Some(test_dir) = test_dir {
let path = project.root().join(test_dir);
if path.exists() {
let _ = fs::remove_dir_all(&path);
}
}
};
remove_test_dir(&self.fuzz.failure_persist_dir);
remove_test_dir(&self.invariant.failure_persist_dir);
// Remove snapshot directory.
let snapshot_dir = project.root().join(&self.snapshots);
if snapshot_dir.exists() {
let _ = fs::remove_dir_all(&snapshot_dir);
}
Ok(())
}
/// Ensures that the configured version is installed if explicitly set
///
/// If `solc` is [`SolcReq::Version`] then this will download and install the solc version if
/// it's missing, unless the `offline` flag is enabled, in which case an error is thrown.
///
/// If `solc` is [`SolcReq::Local`] then this will ensure that the path exists.
#[allow(clippy::disallowed_macros)]
fn ensure_solc(&self) -> Result<Option<Solc>, SolcError> {
if self.eof {
let (tx, rx) = mpsc::channel();
let root = self.root.0.clone();
std::thread::spawn(move || {
tx.send(
Solc::new_with_args(
"docker",
[
"run",
"--rm",
"-i",
"-v",
&format!("{}:/app/root", root.display()),
Self::EOF_SOLC_IMAGE,
],
)
.map(Some),
)
});
// If it takes more than 1 second, this likely means we are pulling the image.
return match rx.recv_timeout(Duration::from_secs(1)) {
Ok(res) => res,
Err(RecvTimeoutError::Timeout) => {
// `sh_warn!` is a circular dependency, preventing us from using it here.
eprintln!(
"{}",
yansi::Paint::yellow(
"Pulling Docker image for eof-solc, this might take some time..."
)
);
rx.recv().expect("sender dropped")
}
Err(RecvTimeoutError::Disconnected) => panic!("sender dropped"),
}
}
if let Some(ref solc) = self.solc {
let solc = match solc {
SolcReq::Version(version) => {
if let Some(solc) = Solc::find_svm_installed_version(version)? {
solc
} else {
if self.offline {
return Err(SolcError::msg(format!(
"can't install missing solc {version} in offline mode"
)));
}
Solc::blocking_install(version)?
}
}
SolcReq::Local(solc) => {
if !solc.is_file() {
return Err(SolcError::msg(format!(
"`solc` {} does not exist",
solc.display()
)));
}
Solc::new(solc)?
}
};
return Ok(Some(solc));
}
Ok(None)
}
/// Returns the [SpecId] derived from the configured [EvmVersion]
#[inline]
pub fn evm_spec_id(&self) -> SpecId {
evm_spec_id(&self.evm_version, self.alphanet)
}
/// Returns whether the compiler version should be auto-detected
///
/// Returns `false` if `solc_version` is explicitly set, otherwise returns the value of
/// `auto_detect_solc`
pub fn is_auto_detect(&self) -> bool {
if self.solc.is_some() {
return false;
}
self.auto_detect_solc
}
/// Whether caching should be enabled for the given chain id
pub fn enable_caching(&self, endpoint: &str, chain_id: impl Into<u64>) -> bool {
!self.no_storage_caching &&
self.rpc_storage_caching.enable_for_chain_id(chain_id.into()) &&
self.rpc_storage_caching.enable_for_endpoint(endpoint)
}
/// Returns the `ProjectPathsConfig` sub set of the config.
///
/// **NOTE**: this uses the paths as they are and does __not__ modify them, see
/// `[Self::sanitized]`
///
/// # Example
///
/// ```
/// use foundry_compilers::solc::Solc;
/// use foundry_config::Config;
/// let config = Config::load_with_root(".").sanitized();
/// let paths = config.project_paths::<Solc>();
/// ```
pub fn project_paths<L>(&self) -> ProjectPathsConfig<L> {
let mut builder = ProjectPathsConfig::builder()
.cache(self.cache_path.join(SOLIDITY_FILES_CACHE_FILENAME))
.sources(&self.src)
.tests(&self.test)
.scripts(&self.script)
.artifacts(&self.out)
.libs(self.libs.iter())
.remappings(self.get_all_remappings())
.allowed_path(&self.root.0)
.allowed_paths(&self.libs)
.allowed_paths(&self.allow_paths)
.include_paths(&self.include_paths);
if let Some(build_info_path) = &self.build_info_path {
builder = builder.build_infos(build_info_path);
}
builder.build_with_root(&self.root.0)
}
/// Returns configuration for a compiler to use when setting up a [Project].
pub fn solc_compiler(&self) -> Result<SolcCompiler, SolcError> {
if let Some(solc) = self.ensure_solc()? {
Ok(SolcCompiler::Specific(solc))
} else {
Ok(SolcCompiler::AutoDetect)
}
}
/// Returns configured [Vyper] compiler.
pub fn vyper_compiler(&self) -> Result<Option<Vyper>, SolcError> {
// Only instantiate Vyper if there are any Vyper files in the project.
if self.project_paths::<VyperLanguage>().input_files_iter().next().is_none() {
return Ok(None);
}
let vyper = if let Some(path) = &self.vyper.path {
Some(Vyper::new(path)?)
} else {
Vyper::new("vyper").ok()
};
Ok(vyper)
}
/// Returns configuration for a compiler to use when setting up a [Project].
pub fn compiler(&self) -> Result<MultiCompiler, SolcError> {
Ok(MultiCompiler { solc: Some(self.solc_compiler()?), vyper: self.vyper_compiler()? })
}
/// Returns configured [MultiCompilerSettings].
pub fn compiler_settings(&self) -> Result<MultiCompilerSettings, SolcError> {
Ok(MultiCompilerSettings { solc: self.solc_settings()?, vyper: self.vyper_settings()? })
}
/// Returns all configured remappings.
pub fn get_all_remappings(&self) -> impl Iterator<Item = Remapping> + '_ {
self.remappings.iter().map(|m| m.clone().into())
}
/// Returns the configured rpc jwt secret
///
/// Returns:
/// - The jwt secret, if configured
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_jwt = config.get_rpc_jwt_secret().unwrap().unwrap();
/// # }
/// ```
pub fn get_rpc_jwt_secret(&self) -> Result<Option<Cow<'_, str>>, UnresolvedEnvVarError> {
Ok(self.eth_rpc_jwt.as_ref().map(|jwt| Cow::Borrowed(jwt.as_str())))
}
/// Returns the configured rpc url
///
/// Returns:
/// - the matching, resolved url of `rpc_endpoints` if `eth_rpc_url` is an alias
/// - the `eth_rpc_url` as-is if it isn't an alias
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url().unwrap().unwrap();
/// # }
/// ```
pub fn get_rpc_url(&self) -> Option<Result<Cow<'_, str>, UnresolvedEnvVarError>> {
let maybe_alias = self.eth_rpc_url.as_ref().or(self.etherscan_api_key.as_ref())?;
if let Some(alias) = self.get_rpc_url_with_alias(maybe_alias) {
Some(alias)
} else {
Some(Ok(Cow::Borrowed(self.eth_rpc_url.as_deref()?)))
}
}
/// Resolves the given alias to a matching rpc url
///
/// # Returns
///
/// In order of resolution:
///
/// - the matching, resolved url of `rpc_endpoints` if `maybe_alias` is an alias
/// - a mesc resolved url if `maybe_alias` is a known alias in mesc
/// - `None` otherwise
///
/// # Note on mesc
///
/// The endpoint is queried for in mesc under the `foundry` profile, allowing users to customize
/// endpoints for Foundry specifically.
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url_with_alias("mainnet").unwrap().unwrap();
/// # }
/// ```
pub fn get_rpc_url_with_alias(
&self,
maybe_alias: &str,
) -> Option<Result<Cow<'_, str>, UnresolvedEnvVarError>> {
let mut endpoints = self.rpc_endpoints.clone().resolved();
if let Some(endpoint) = endpoints.remove(maybe_alias) {
return Some(endpoint.map(Cow::Owned))
}
if let Ok(Some(endpoint)) = mesc::get_endpoint_by_query(maybe_alias, Some("foundry")) {
return Some(Ok(Cow::Owned(endpoint.url)))
}
None
}
/// Returns the configured rpc, or the fallback url
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url_or("http://localhost:8545").unwrap();
/// # }
/// ```
pub fn get_rpc_url_or<'a>(
&'a self,
fallback: impl Into<Cow<'a, str>>,
) -> Result<Cow<'a, str>, UnresolvedEnvVarError> {
if let Some(url) = self.get_rpc_url() {
url
} else {
Ok(fallback.into())
}
}
/// Returns the configured rpc or `"http://localhost:8545"` if no `eth_rpc_url` is set
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url_or_localhost_http().unwrap();
/// # }
/// ```
pub fn get_rpc_url_or_localhost_http(&self) -> Result<Cow<'_, str>, UnresolvedEnvVarError> {
self.get_rpc_url_or("http://localhost:8545")
}
/// Returns the `EtherscanConfig` to use, if any
///
/// Returns
/// - the matching `ResolvedEtherscanConfig` of the `etherscan` table if `etherscan_api_key` is
/// an alias
/// - the matching `ResolvedEtherscanConfig` of the `etherscan` table if a `chain` is
/// configured. an alias
/// - the Mainnet `ResolvedEtherscanConfig` if `etherscan_api_key` is set, `None` otherwise
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let etherscan_config = config.get_etherscan_config().unwrap().unwrap();
/// let client = etherscan_config.into_client().unwrap();
/// # }
/// ```
pub fn get_etherscan_config(
&self,
) -> Option<Result<ResolvedEtherscanConfig, EtherscanConfigError>> {
self.get_etherscan_config_with_chain(None).transpose()
}
/// Same as [`Self::get_etherscan_config()`] but optionally updates the config with the given
/// `chain`, and `etherscan_api_key`
///
/// If not matching alias was found, then this will try to find the first entry in the table
/// with a matching chain id. If an etherscan_api_key is already set it will take precedence
/// over the chain's entry in the table.
pub fn get_etherscan_config_with_chain(
&self,
chain: Option<Chain>,
) -> Result<Option<ResolvedEtherscanConfig>, EtherscanConfigError> {
if let Some(maybe_alias) = self.etherscan_api_key.as_ref().or(self.eth_rpc_url.as_ref()) {
if self.etherscan.contains_key(maybe_alias) {
return self.etherscan.clone().resolved().remove(maybe_alias).transpose();
}
}
// try to find by comparing chain IDs after resolving
if let Some(res) = chain
.or(self.chain)
.and_then(|chain| self.etherscan.clone().resolved().find_chain(chain))
{
match (res, self.etherscan_api_key.as_ref()) {
(Ok(mut config), Some(key)) => {
// we update the key, because if an etherscan_api_key is set, it should take
// precedence over the entry, since this is usually set via env var or CLI args.
config.key.clone_from(key);
return Ok(Some(config));
}
(Ok(config), None) => return Ok(Some(config)),
(Err(err), None) => return Err(err),
(Err(_), Some(_)) => {
// use the etherscan key as fallback
}
}
}
// etherscan fallback via API key
if let Some(key) = self.etherscan_api_key.as_ref() {
let chain = chain.or(self.chain).unwrap_or_default();
return Ok(ResolvedEtherscanConfig::create(key, chain));
}
Ok(None)
}
/// Helper function to just get the API key
///
/// Optionally updates the config with the given `chain`.
///
/// See also [Self::get_etherscan_config_with_chain]
pub fn get_etherscan_api_key(&self, chain: Option<Chain>) -> Option<String> {
self.get_etherscan_config_with_chain(chain).ok().flatten().map(|c| c.key)
}
/// Returns the remapping for the project's _src_ directory
///
/// **Note:** this will add an additional `<src>/=<src path>` remapping here so imports that
/// look like `import {Foo} from "src/Foo.sol";` are properly resolved.
///
/// This is due the fact that `solc`'s VFS resolves [direct imports](https://docs.soliditylang.org/en/develop/path-resolution.html#direct-imports) that start with the source directory's name.
pub fn get_source_dir_remapping(&self) -> Option<Remapping> {
get_dir_remapping(&self.src)
}
/// Returns the remapping for the project's _test_ directory, but only if it exists
pub fn get_test_dir_remapping(&self) -> Option<Remapping> {
if self.root.0.join(&self.test).exists() {
get_dir_remapping(&self.test)
} else {
None
}
}
/// Returns the remapping for the project's _script_ directory, but only if it exists
pub fn get_script_dir_remapping(&self) -> Option<Remapping> {
if self.root.0.join(&self.script).exists() {
get_dir_remapping(&self.script)
} else {
None
}
}
/// Returns the `Optimizer` based on the configured settings
///
/// Note: optimizer details can be set independently of `enabled`
/// See also: <https://github.com/foundry-rs/foundry/issues/7689>
/// and <https://github.com/ethereum/solidity/blob/bbb7f58be026fdc51b0b4694a6f25c22a1425586/docs/using-the-compiler.rst?plain=1#L293-L294>
pub fn optimizer(&self) -> Optimizer {
Optimizer {
enabled: Some(self.optimizer),
runs: Some(self.optimizer_runs),
// we always set the details because `enabled` is effectively a specific details profile
// that can still be modified
details: self.optimizer_details.clone(),
}
}
/// returns the [`foundry_compilers::ConfigurableArtifacts`] for this config, that includes the
/// `extra_output` fields
pub fn configured_artifacts_handler(&self) -> ConfigurableArtifacts {
let mut extra_output = self.extra_output.clone();
// Sourcify verification requires solc metadata output. Since, it doesn't
// affect the UX & performance of the compiler, output the metadata files
// by default.
// For more info see: <https://github.com/foundry-rs/foundry/issues/2795>
// Metadata is not emitted as separate file because this breaks typechain support: <https://github.com/foundry-rs/foundry/issues/2969>
if !extra_output.contains(&ContractOutputSelection::Metadata) {
extra_output.push(ContractOutputSelection::Metadata);
}
ConfigurableArtifacts::new(extra_output, self.extra_output_files.iter().cloned())
}
/// Parses all libraries in the form of
/// `<file>:<lib>:<addr>`
pub fn parsed_libraries(&self) -> Result<Libraries, SolcError> {
Libraries::parse(&self.libraries)
}
/// Returns all libraries with applied remappings. Same as `self.solc_settings()?.libraries`.
pub fn libraries_with_remappings(&self) -> Result<Libraries, SolcError> {
let paths: ProjectPathsConfig = self.project_paths();
Ok(self.parsed_libraries()?.apply(|libs| paths.apply_lib_remappings(libs)))
}
/// Returns the configured `solc` `Settings` that includes:
/// - all libraries
/// - the optimizer (including details, if configured)
/// - evm version
pub fn solc_settings(&self) -> Result<SolcSettings, SolcError> {
// By default if no targets are specifically selected the model checker uses all targets.
// This might be too much here, so only enable assertion checks.
// If users wish to enable all options they need to do so explicitly.
let mut model_checker = self.model_checker.clone();
if let Some(model_checker_settings) = &mut model_checker {
if model_checker_settings.targets.is_none() {
model_checker_settings.targets = Some(vec![ModelCheckerTarget::Assert]);
}
}
let mut settings = Settings {
libraries: self.libraries_with_remappings()?,
optimizer: self.optimizer(),
evm_version: Some(self.evm_version),
metadata: Some(SettingsMetadata {
use_literal_content: Some(self.use_literal_content),
bytecode_hash: Some(self.bytecode_hash),
cbor_metadata: Some(self.cbor_metadata),
}),
debug: self.revert_strings.map(|revert_strings| DebuggingSettings {
revert_strings: Some(revert_strings),
// Not used.
debug_info: Vec::new(),
}),
model_checker,
via_ir: Some(self.via_ir),
// Not used.
stop_after: None,
// Set in project paths.
remappings: Vec::new(),
// Set with `with_extra_output` below.
output_selection: Default::default(),
eof_version: self.eof_version,
}
.with_extra_output(self.configured_artifacts_handler().output_selection());
// We're keeping AST in `--build-info` for backwards compatibility with HardHat.
if self.ast || self.build_info {
settings = settings.with_ast();
}
let cli_settings =
CliSettings { extra_args: self.extra_args.clone(), ..Default::default() };
Ok(SolcSettings { settings, cli_settings })
}
/// Returns the configured [VyperSettings] that includes:
/// - evm version
pub fn vyper_settings(&self) -> Result<VyperSettings, SolcError> {
Ok(VyperSettings {
evm_version: Some(self.evm_version),
optimize: self.vyper.optimize,
bytecode_metadata: None,
// TODO: We don't yet have a way to deserialize other outputs correctly, so request only
// those for now. It should be enough to run tests and deploy contracts.
output_selection: OutputSelection::common_output_selection([
"abi".to_string(),
"evm.bytecode".to_string(),
"evm.deployedBytecode".to_string(),
]),
search_paths: None,
experimental_codegen: self.vyper.experimental_codegen,
})
}
/// Returns the default figment
///
/// The default figment reads from the following sources, in ascending
/// priority order:
///
/// 1. [`Config::default()`] (see [defaults](#defaults))
/// 2. `foundry.toml` _or_ filename in `FOUNDRY_CONFIG` environment variable
/// 3. `FOUNDRY_` prefixed environment variables
///
/// The profile selected is the value set in the `FOUNDRY_PROFILE`
/// environment variable. If it is not set, it defaults to `default`.
///
/// # Example
///
/// ```rust
/// use foundry_config::Config;
/// use serde::Deserialize;
///
/// let my_config = Config::figment().extract::<Config>();
/// ```
pub fn figment() -> Figment {
Self::default().into()
}
/// Returns the default figment enhanced with additional context extracted from the provided
/// root, like remappings and directories.
///
/// # Example
///
/// ```rust
/// use foundry_config::Config;
/// use serde::Deserialize;
///
/// let my_config = Config::figment_with_root(".").extract::<Config>();
/// ```
pub fn figment_with_root(root: impl AsRef<Path>) -> Figment {
Self::with_root(root.as_ref()).into()
}
/// Creates a new Config that adds additional context extracted from the provided root.
///
/// # Example
///
/// ```rust
/// use foundry_config::Config;
/// let my_config = Config::with_root(".");
/// ```
pub fn with_root(root: impl AsRef<Path>) -> Self {
Self::_with_root(root.as_ref())
}
fn _with_root(root: &Path) -> Self {
// autodetect paths
let paths = ProjectPathsConfig::builder().build_with_root::<()>(root);
let artifacts: PathBuf = paths.artifacts.file_name().unwrap().into();
Self {
root: paths.root.into(),
src: paths.sources.file_name().unwrap().into(),
out: artifacts.clone(),
libs: paths.libraries.into_iter().map(|lib| lib.file_name().unwrap().into()).collect(),
remappings: paths
.remappings
.into_iter()
.map(|r| RelativeRemapping::new(r, root))
.collect(),
fs_permissions: FsPermissions::new([PathPermission::read(artifacts)]),
..Self::default()
}
}
/// Returns the default config but with hardhat paths
pub fn hardhat() -> Self {
Self {
src: "contracts".into(),
out: "artifacts".into(),
libs: vec!["node_modules".into()],
..Self::default()
}
}
/// Returns the default config that uses dapptools style paths
pub fn dapptools() -> Self {
Self {
chain: Some(Chain::from_id(99)),
block_timestamp: 0,
block_number: 0,
..Self::default()
}
}
/// Extracts a basic subset of the config, used for initialisations.
///
/// # Example
///
/// ```rust
/// use foundry_config::Config;
/// let my_config = Config::with_root(".").into_basic();
/// ```
pub fn into_basic(self) -> BasicConfig {
BasicConfig {
profile: self.profile,
src: self.src,
out: self.out,
libs: self.libs,
remappings: self.remappings,
}
}
/// Updates the `foundry.toml` file for the given `root` based on the provided closure.
///
/// **Note:** the closure will only be invoked if the `foundry.toml` file exists, See
/// [Self::get_config_path()] and if the closure returns `true`.
pub fn update_at<F>(root: &Path, f: F) -> eyre::Result<()>
where
F: FnOnce(&Self, &mut toml_edit::DocumentMut) -> bool,
{
let config = Self::load_with_root(root).sanitized();
config.update(|doc| f(&config, doc))
}
/// Updates the `foundry.toml` file this `Config` ias based on with the provided closure.
///
/// **Note:** the closure will only be invoked if the `foundry.toml` file exists, See
/// [Self::get_config_path()] and if the closure returns `true`
pub fn update<F>(&self, f: F) -> eyre::Result<()>
where
F: FnOnce(&mut toml_edit::DocumentMut) -> bool,
{
let file_path = self.get_config_path();
if !file_path.exists() {
return Ok(());
}
let contents = fs::read_to_string(&file_path)?;
let mut doc = contents.parse::<toml_edit::DocumentMut>()?;
if f(&mut doc) {
fs::write(file_path, doc.to_string())?;
}
Ok(())
}
/// Sets the `libs` entry inside a `foundry.toml` file but only if it exists
///
/// # Errors
///
/// An error if the `foundry.toml` could not be parsed.
pub fn update_libs(&self) -> eyre::Result<()> {
self.update(|doc| {
let profile = self.profile.as_str().as_str();
let root = &self.root.0;
let libs: toml_edit::Value = self
.libs
.iter()
.map(|path| {
let path =
if let Ok(relative) = path.strip_prefix(root) { relative } else { path };
toml_edit::Value::from(&*path.to_string_lossy())
})
.collect();
let libs = toml_edit::value(libs);
doc[Self::PROFILE_SECTION][profile]["libs"] = libs;
true
})
}
/// Serialize the config type as a String of TOML.
///
/// This serializes to a table with the name of the profile
///
/// ```toml
/// [profile.default]
/// src = "src"
/// out = "out"
/// libs = ["lib"]
/// # ...
/// ```
pub fn to_string_pretty(&self) -> Result<String, toml::ser::Error> {
// serializing to value first to prevent `ValueAfterTable` errors
let mut value = toml::Value::try_from(self)?;
// Config map always gets serialized as a table
let value_table = value.as_table_mut().unwrap();
// remove standalone sections from inner table
let standalone_sections = Self::STANDALONE_SECTIONS
.iter()
.filter_map(|section| {
let section = section.to_string();
value_table.remove(§ion).map(|value| (section, value))
})
.collect::<Vec<_>>();
// wrap inner table in [profile.<profile>]
let mut wrapping_table = [(
Self::PROFILE_SECTION.into(),
toml::Value::Table([(self.profile.to_string(), value)].into_iter().collect()),
)]
.into_iter()
.collect::<toml::map::Map<_, _>>();
// insert standalone sections
for (section, value) in standalone_sections {
wrapping_table.insert(section, value);
}
// stringify
toml::to_string_pretty(&toml::Value::Table(wrapping_table))
}
/// Returns the path to the `foundry.toml` of this `Config`.
pub fn get_config_path(&self) -> PathBuf {
self.root.0.join(Self::FILE_NAME)
}
/// Returns the selected profile.
///
/// If the `FOUNDRY_PROFILE` env variable is not set, this returns the `DEFAULT_PROFILE`.
pub fn selected_profile() -> Profile {
Profile::from_env_or("FOUNDRY_PROFILE", Self::DEFAULT_PROFILE)
}
/// Returns the path to foundry's global TOML file: `~/.foundry/foundry.toml`.
pub fn foundry_dir_toml() -> Option<PathBuf> {
Self::foundry_dir().map(|p| p.join(Self::FILE_NAME))
}
/// Returns the path to foundry's config dir: `~/.foundry/`.
pub fn foundry_dir() -> Option<PathBuf> {
dirs_next::home_dir().map(|p| p.join(Self::FOUNDRY_DIR_NAME))
}
/// Returns the path to foundry's cache dir: `~/.foundry/cache`.
pub fn foundry_cache_dir() -> Option<PathBuf> {
Self::foundry_dir().map(|p| p.join("cache"))
}
/// Returns the path to foundry rpc cache dir: `~/.foundry/cache/rpc`.
pub fn foundry_rpc_cache_dir() -> Option<PathBuf> {
Some(Self::foundry_cache_dir()?.join("rpc"))
}
/// Returns the path to foundry chain's cache dir: `~/.foundry/cache/rpc/<chain>`
pub fn foundry_chain_cache_dir(chain_id: impl Into<Chain>) -> Option<PathBuf> {
Some(Self::foundry_rpc_cache_dir()?.join(chain_id.into().to_string()))
}
/// Returns the path to foundry's etherscan cache dir: `~/.foundry/cache/etherscan`.
pub fn foundry_etherscan_cache_dir() -> Option<PathBuf> {
Some(Self::foundry_cache_dir()?.join("etherscan"))
}
/// Returns the path to foundry's keystores dir: `~/.foundry/keystores`.
pub fn foundry_keystores_dir() -> Option<PathBuf> {
Some(Self::foundry_dir()?.join("keystores"))
}
/// Returns the path to foundry's etherscan cache dir for `chain_id`:
/// `~/.foundry/cache/etherscan/<chain>`
pub fn foundry_etherscan_chain_cache_dir(chain_id: impl Into<Chain>) -> Option<PathBuf> {
Some(Self::foundry_etherscan_cache_dir()?.join(chain_id.into().to_string()))
}
/// Returns the path to the cache dir of the `block` on the `chain`:
/// `~/.foundry/cache/rpc/<chain>/<block>`
pub fn foundry_block_cache_dir(chain_id: impl Into<Chain>, block: u64) -> Option<PathBuf> {
Some(Self::foundry_chain_cache_dir(chain_id)?.join(format!("{block}")))
}
/// Returns the path to the cache file of the `block` on the `chain`:
/// `~/.foundry/cache/rpc/<chain>/<block>/storage.json`
pub fn foundry_block_cache_file(chain_id: impl Into<Chain>, block: u64) -> Option<PathBuf> {
Some(Self::foundry_block_cache_dir(chain_id, block)?.join("storage.json"))
}
/// Returns the path to `foundry`'s data directory inside the user's data directory.
///
/// | Platform | Value | Example |
/// | ------- | --------------------------------------------- | ------------------------------------------------ |
/// | Linux | `$XDG_CONFIG_HOME` or `$HOME`/.config/foundry | /home/alice/.config/foundry |
/// | macOS | `$HOME`/Library/Application Support/foundry | /Users/Alice/Library/Application Support/foundry |
/// | Windows | `{FOLDERID_RoamingAppData}/foundry` | C:\Users\Alice\AppData\Roaming/foundry |
pub fn data_dir() -> eyre::Result<PathBuf> {
let path = dirs_next::data_dir().wrap_err("Failed to find data directory")?.join("foundry");
std::fs::create_dir_all(&path).wrap_err("Failed to create module directory")?;
Ok(path)
}
/// Returns the path to the `foundry.toml` file, the file is searched for in
/// the current working directory and all parent directories until the root,
/// and the first hit is used.
///
/// If this search comes up empty, then it checks if a global `foundry.toml` exists at
/// `~/.foundry/foundry.toml`, see [`Self::foundry_dir_toml`].
pub fn find_config_file() -> Option<PathBuf> {
fn find(path: &Path) -> Option<PathBuf> {
if path.is_absolute() {
return match path.is_file() {
true => Some(path.to_path_buf()),
false => None,
};
}
let cwd = std::env::current_dir().ok()?;
let mut cwd = cwd.as_path();
loop {
let file_path = cwd.join(path);
if file_path.is_file() {
return Some(file_path);
}
cwd = cwd.parent()?;
}
}
find(Env::var_or("FOUNDRY_CONFIG", Self::FILE_NAME).as_ref())
.or_else(|| Self::foundry_dir_toml().filter(|p| p.exists()))
}
/// Clears the foundry cache.
pub fn clean_foundry_cache() -> eyre::Result<()> {
if let Some(cache_dir) = Self::foundry_cache_dir() {
let path = cache_dir.as_path();
let _ = fs::remove_dir_all(path);
} else {
eyre::bail!("failed to get foundry_cache_dir");
}
Ok(())
}
/// Clears the foundry cache for `chain`.
pub fn clean_foundry_chain_cache(chain: Chain) -> eyre::Result<()> {
if let Some(cache_dir) = Self::foundry_chain_cache_dir(chain) {
let path = cache_dir.as_path();
let _ = fs::remove_dir_all(path);
} else {
eyre::bail!("failed to get foundry_chain_cache_dir");
}
Ok(())
}
/// Clears the foundry cache for `chain` and `block`.
pub fn clean_foundry_block_cache(chain: Chain, block: u64) -> eyre::Result<()> {
if let Some(cache_dir) = Self::foundry_block_cache_dir(chain, block) {
let path = cache_dir.as_path();
let _ = fs::remove_dir_all(path);
} else {
eyre::bail!("failed to get foundry_block_cache_dir");
}
Ok(())
}
/// Clears the foundry etherscan cache.
pub fn clean_foundry_etherscan_cache() -> eyre::Result<()> {
if let Some(cache_dir) = Self::foundry_etherscan_cache_dir() {
let path = cache_dir.as_path();
let _ = fs::remove_dir_all(path);
} else {
eyre::bail!("failed to get foundry_etherscan_cache_dir");
}
Ok(())
}
/// Clears the foundry etherscan cache for `chain`.
pub fn clean_foundry_etherscan_chain_cache(chain: Chain) -> eyre::Result<()> {
if let Some(cache_dir) = Self::foundry_etherscan_chain_cache_dir(chain) {
let path = cache_dir.as_path();
let _ = fs::remove_dir_all(path);
} else {
eyre::bail!("failed to get foundry_etherscan_cache_dir for chain: {}", chain);
}
Ok(())
}
/// List the data in the foundry cache.
pub fn list_foundry_cache() -> eyre::Result<Cache> {
if let Some(cache_dir) = Self::foundry_rpc_cache_dir() {
let mut cache = Cache { chains: vec![] };
if !cache_dir.exists() {
return Ok(cache);
}
if let Ok(entries) = cache_dir.as_path().read_dir() {
for entry in entries.flatten().filter(|x| x.path().is_dir()) {
match Chain::from_str(&entry.file_name().to_string_lossy()) {
Ok(chain) => cache.chains.push(Self::list_foundry_chain_cache(chain)?),
Err(_) => continue,
}
}
Ok(cache)
} else {
eyre::bail!("failed to access foundry_cache_dir");
}
} else {
eyre::bail!("failed to get foundry_cache_dir");
}
}
/// List the cached data for `chain`.
pub fn list_foundry_chain_cache(chain: Chain) -> eyre::Result<ChainCache> {
let block_explorer_data_size = match Self::foundry_etherscan_chain_cache_dir(chain) {
Some(cache_dir) => Self::get_cached_block_explorer_data(&cache_dir)?,
None => {
warn!("failed to access foundry_etherscan_chain_cache_dir");
0
}
};
if let Some(cache_dir) = Self::foundry_chain_cache_dir(chain) {
let blocks = Self::get_cached_blocks(&cache_dir)?;
Ok(ChainCache {
name: chain.to_string(),
blocks,
block_explorer: block_explorer_data_size,
})
} else {
eyre::bail!("failed to get foundry_chain_cache_dir");
}
}
/// The path provided to this function should point to a cached chain folder.
fn get_cached_blocks(chain_path: &Path) -> eyre::Result<Vec<(String, u64)>> {
let mut blocks = vec![];
if !chain_path.exists() {
return Ok(blocks);
}
for block in chain_path.read_dir()?.flatten() {
let file_type = block.file_type()?;
let file_name = block.file_name();
let filepath = if file_type.is_dir() {
block.path().join("storage.json")
} else if file_type.is_file() &&
file_name.to_string_lossy().chars().all(char::is_numeric)
{
block.path()
} else {
continue;
};
blocks.push((file_name.to_string_lossy().into_owned(), fs::metadata(filepath)?.len()));
}
Ok(blocks)
}
/// The path provided to this function should point to the etherscan cache for a chain.
fn get_cached_block_explorer_data(chain_path: &Path) -> eyre::Result<u64> {
if !chain_path.exists() {
return Ok(0);
}
fn dir_size_recursive(mut dir: fs::ReadDir) -> eyre::Result<u64> {
dir.try_fold(0, |acc, file| {
let file = file?;
let size = match file.metadata()? {
data if data.is_dir() => dir_size_recursive(fs::read_dir(file.path())?)?,
data => data.len(),
};
Ok(acc + size)
})
}
dir_size_recursive(fs::read_dir(chain_path)?)
}
fn merge_toml_provider(
mut figment: Figment,
toml_provider: impl Provider,
profile: Profile,
) -> Figment {
figment = figment.select(profile.clone());
// add warnings
figment = {
let warnings = WarningsProvider::for_figment(&toml_provider, &figment);
figment.merge(warnings)
};
// use [profile.<profile>] as [<profile>]
let mut profiles = vec![Self::DEFAULT_PROFILE];
if profile != Self::DEFAULT_PROFILE {
profiles.push(profile.clone());
}
let provider = toml_provider.strict_select(profiles);
// apply any key fixes
let provider = BackwardsCompatTomlProvider(ForcedSnakeCaseData(provider));
// merge the default profile as a base
if profile != Self::DEFAULT_PROFILE {
figment = figment.merge(provider.rename(Self::DEFAULT_PROFILE, profile.clone()));
}
// merge special keys into config
for standalone_key in Self::STANDALONE_SECTIONS {
if let Some((_, fallback)) =
STANDALONE_FALLBACK_SECTIONS.iter().find(|(key, _)| standalone_key == key)
{
figment = figment.merge(
provider
.fallback(standalone_key, fallback)
.wrap(profile.clone(), standalone_key),
);
} else {
figment = figment.merge(provider.wrap(profile.clone(), standalone_key));
}
}
// merge the profile
figment = figment.merge(provider);
figment
}
/// Check if any defaults need to be normalized.
///
/// This normalizes the default `evm_version` if a `solc` was provided in the config.
///
/// See also <https://github.com/foundry-rs/foundry/issues/7014>
fn normalize_defaults(&mut self, figment: Figment) -> Figment {
if let Ok(solc) = figment.extract_inner::<SolcReq>("solc") {
// check if evm_version is set
// TODO: add a warning if evm_version is provided but incompatible
if figment.find_value("evm_version").is_err() {
if let Some(version) = solc
.try_version()
.ok()
.and_then(|version| self.evm_version.normalize_version_solc(&version))
{
// normalize evm_version based on the provided solc version
self.evm_version = version;
}
}
}
figment
}
}
impl From<Config> for Figment {
fn from(c: Config) -> Self {
c.to_figment(FigmentProviders::All)
}
}
/// Determines what providers should be used when loading the [Figment] for a [Config]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FigmentProviders {
/// Include all providers
#[default]
All,
/// Only include necessary providers that are useful for cast commands
///
/// This will exclude more expensive providers such as remappings
Cast,
/// Only include necessary providers that are useful for anvil
///
/// This will exclude more expensive providers such as remappings
Anvil,
}
impl FigmentProviders {
/// Returns true if all providers should be included
pub const fn is_all(&self) -> bool {
matches!(self, Self::All)
}
/// Returns true if this is the cast preset
pub const fn is_cast(&self) -> bool {
matches!(self, Self::Cast)
}
}
/// Wrapper type for `regex::Regex` that implements `PartialEq`
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RegexWrapper {
#[serde(with = "serde_regex")]
inner: regex::Regex,
}
impl std::ops::Deref for RegexWrapper {
type Target = regex::Regex;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl std::cmp::PartialEq for RegexWrapper {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl From<RegexWrapper> for regex::Regex {
fn from(wrapper: RegexWrapper) -> Self {
wrapper.inner
}
}
impl From<regex::Regex> for RegexWrapper {
fn from(re: Regex) -> Self {
Self { inner: re }
}
}
/// Ser/de `globset::Glob` explicitly to handle `Option<Glob>` properly
pub(crate) mod from_opt_glob {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>(value: &Option<globset::Glob>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match value {
Some(glob) => serializer.serialize_str(glob.glob()),
None => serializer.serialize_none(),
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<globset::Glob>, D::Error>
where
D: Deserializer<'de>,
{
let s: Option<String> = Option::deserialize(deserializer)?;
if let Some(s) = s {
return Ok(Some(globset::Glob::new(&s).map_err(serde::de::Error::custom)?));
}
Ok(None)
}
}
/// A helper wrapper around the root path used during Config detection
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RootPath(pub PathBuf);
impl Default for RootPath {
fn default() -> Self {
".".into()
}
}
impl<P: Into<PathBuf>> From<P> for RootPath {
fn from(p: P) -> Self {
Self(p.into())
}
}
impl AsRef<Path> for RootPath {
fn as_ref(&self) -> &Path {
&self.0
}
}
/// Parses a config profile
///
/// All `Profile` date is ignored by serde, however the `Config::to_string_pretty` includes it and
/// returns a toml table like
///
/// ```toml
/// #[profile.default]
/// src = "..."
/// ```
/// This ignores the `#[profile.default]` part in the toml
pub fn parse_with_profile<T: serde::de::DeserializeOwned>(
s: &str,
) -> Result<Option<(Profile, T)>, Error> {
let figment = Config::merge_toml_provider(
Figment::new(),
Toml::string(s).nested(),
Config::DEFAULT_PROFILE,
);
if figment.profiles().any(|p| p == Config::DEFAULT_PROFILE) {
Ok(Some((Config::DEFAULT_PROFILE, figment.select(Config::DEFAULT_PROFILE).extract()?)))
} else {
Ok(None)
}
}
impl Provider for Config {
fn metadata(&self) -> Metadata {
Metadata::named("Foundry Config")
}
#[track_caller]
fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
let mut data = Serialized::defaults(self).data()?;
if let Some(entry) = data.get_mut(&self.profile) {
entry.insert("root".to_string(), Value::serialize(self.root.clone())?);
}
Ok(data)
}
fn profile(&self) -> Option<Profile> {
Some(self.profile.clone())
}
}
impl Default for Config {
fn default() -> Self {
Self {
profile: Self::DEFAULT_PROFILE,
fs_permissions: FsPermissions::new([PathPermission::read("out")]),
#[cfg(not(feature = "isolate-by-default"))]
isolate: false,
#[cfg(feature = "isolate-by-default")]
isolate: true,
root: Default::default(),
src: "src".into(),
test: "test".into(),
script: "script".into(),
out: "out".into(),
libs: vec!["lib".into()],
cache: true,
cache_path: "cache".into(),
broadcast: "broadcast".into(),
snapshots: "snapshots".into(),
allow_paths: vec![],
include_paths: vec![],
force: false,
evm_version: EvmVersion::Cancun,
gas_reports: vec!["*".to_string()],
gas_reports_ignore: vec![],
gas_reports_include_tests: false,
solc: None,
vyper: Default::default(),
auto_detect_solc: true,
offline: false,
optimizer: true,
optimizer_runs: 200,
optimizer_details: None,
model_checker: None,
extra_output: Default::default(),
extra_output_files: Default::default(),
names: false,
sizes: false,
test_pattern: None,
test_pattern_inverse: None,
contract_pattern: None,
contract_pattern_inverse: None,
path_pattern: None,
path_pattern_inverse: None,
coverage_pattern_inverse: None,
test_failures_file: "cache/test-failures".into(),
threads: None,
show_progress: false,
fuzz: FuzzConfig::new("cache/fuzz".into()),
invariant: InvariantConfig::new("cache/invariant".into()),
always_use_create_2_factory: false,
ffi: false,
prompt_timeout: 120,
sender: Self::DEFAULT_SENDER,
tx_origin: Self::DEFAULT_SENDER,
initial_balance: U256::from((1u128 << 96) - 1),
block_number: 1,
fork_block_number: None,
chain: None,
gas_limit: (1u64 << 30).into(), // ~1B
code_size_limit: None,
gas_price: None,
block_base_fee_per_gas: 0,
block_coinbase: Address::ZERO,
block_timestamp: 1,
block_difficulty: 0,
block_prevrandao: Default::default(),
block_gas_limit: None,
disable_block_gas_limit: false,
memory_limit: 1 << 27, // 2**27 = 128MiB = 134_217_728 bytes
eth_rpc_url: None,
eth_rpc_jwt: None,
eth_rpc_timeout: None,
etherscan_api_key: None,
verbosity: 0,
remappings: vec![],
auto_detect_remappings: true,
libraries: vec![],
ignored_error_codes: vec![
SolidityErrorCode::SpdxLicenseNotProvided,
SolidityErrorCode::ContractExceeds24576Bytes,
SolidityErrorCode::ContractInitCodeSizeExceeds49152Bytes,
SolidityErrorCode::TransientStorageUsed,
],
ignored_file_paths: vec![],
deny_warnings: false,
via_ir: false,
ast: false,
rpc_storage_caching: Default::default(),
rpc_endpoints: Default::default(),
etherscan: Default::default(),
no_storage_caching: false,
no_rpc_rate_limit: false,
use_literal_content: false,
bytecode_hash: BytecodeHash::Ipfs,
cbor_metadata: true,
revert_strings: None,
sparse_mode: false,
build_info: false,
build_info_path: None,
fmt: Default::default(),
doc: Default::default(),
bind_json: Default::default(),
labels: Default::default(),
unchecked_cheatcode_artifacts: false,
create2_library_salt: Self::DEFAULT_CREATE2_LIBRARY_SALT,
skip: vec![],
dependencies: Default::default(),
soldeer: Default::default(),
assertions_revert: true,
legacy_assertions: false,
warnings: vec![],
extra_args: vec![],
eof_version: None,
alphanet: false,
transaction_timeout: 120,
additional_compiler_profiles: Default::default(),
compilation_restrictions: Default::default(),
eof: false,
_non_exhaustive: (),
}
}
}
/// Wrapper for the config's `gas_limit` value necessary because toml-rs can't handle larger number because integers are stored signed: <https://github.com/alexcrichton/toml-rs/issues/256>
///
/// Due to this limitation this type will be serialized/deserialized as String if it's larger than
/// `i64`
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
pub struct GasLimit(#[serde(deserialize_with = "crate::deserialize_u64_or_max")] pub u64);
impl From<u64> for GasLimit {
fn from(gas: u64) -> Self {
Self(gas)
}
}
impl From<GasLimit> for u64 {
fn from(gas: GasLimit) -> Self {
gas.0
}
}
impl Serialize for GasLimit {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if self.0 == u64::MAX {
serializer.serialize_str("max")
} else if self.0 > i64::MAX as u64 {
serializer.serialize_str(&self.0.to_string())
} else {
serializer.serialize_u64(self.0)
}
}
}
/// Variants for selecting the [`Solc`] instance
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SolcReq {
/// Requires a specific solc version, that's either already installed (via `svm`) or will be
/// auto installed (via `svm`)
Version(Version),
/// Path to an existing local solc installation
Local(PathBuf),
}
impl SolcReq {
/// Tries to get the solc version from the `SolcReq`
///
/// If the `SolcReq` is a `Version` it will return the version, if it's a path to a binary it
/// will try to get the version from the binary.
fn try_version(&self) -> Result<Version, SolcError> {
match self {
Self::Version(version) => Ok(version.clone()),
Self::Local(path) => Solc::new(path).map(|solc| solc.version),
}
}
}
impl<T: AsRef<str>> From<T> for SolcReq {
fn from(s: T) -> Self {
let s = s.as_ref();
if let Ok(v) = Version::from_str(s) {
Self::Version(v)
} else {
Self::Local(s.into())
}
}
}
/// A convenience provider to retrieve a toml file.
/// This will return an error if the env var is set but the file does not exist
struct TomlFileProvider {
pub env_var: Option<&'static str>,
pub default: PathBuf,
pub cache: Option<Result<Map<Profile, Dict>, Error>>,
}
impl TomlFileProvider {
fn new(env_var: Option<&'static str>, default: impl Into<PathBuf>) -> Self {
Self { env_var, default: default.into(), cache: None }
}
fn env_val(&self) -> Option<String> {
self.env_var.and_then(Env::var)
}
fn file(&self) -> PathBuf {
self.env_val().map(PathBuf::from).unwrap_or_else(|| self.default.clone())
}
fn is_missing(&self) -> bool {
if let Some(file) = self.env_val() {
let path = Path::new(&file);
if !path.exists() {
return true;
}
}
false
}
pub fn cached(mut self) -> Self {
self.cache = Some(self.read());
self
}
fn read(&self) -> Result<Map<Profile, Dict>, Error> {
use serde::de::Error as _;
if let Some(file) = self.env_val() {
let path = Path::new(&file);
if !path.exists() {
return Err(Error::custom(format!(
"Config file `{}` set in env var `{}` does not exist",
file,
self.env_var.unwrap()
)));
}
Toml::file(file)
} else {
Toml::file(&self.default)
}
.nested()
.data()
}
}
impl Provider for TomlFileProvider {
fn metadata(&self) -> Metadata {
if self.is_missing() {
Metadata::named("TOML file provider")
} else {
Toml::file(self.file()).nested().metadata()
}
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
if let Some(cache) = self.cache.as_ref() {
cache.clone()
} else {
self.read()
}
}
}
/// A Provider that ensures all keys are snake case if they're not standalone sections, See
/// `Config::STANDALONE_SECTIONS`
struct ForcedSnakeCaseData<P>(P);
impl<P: Provider> Provider for ForcedSnakeCaseData<P> {
fn metadata(&self) -> Metadata {
self.0.metadata()
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
let mut map = Map::new();
for (profile, dict) in self.0.data()? {
if Config::STANDALONE_SECTIONS.contains(&profile.as_ref()) {
// don't force snake case for keys in standalone sections
map.insert(profile, dict);
continue;
}
map.insert(profile, dict.into_iter().map(|(k, v)| (k.to_snake_case(), v)).collect());
}
Ok(map)
}
}
/// A Provider that handles breaking changes in toml files
struct BackwardsCompatTomlProvider<P>(P);
impl<P: Provider> Provider for BackwardsCompatTomlProvider<P> {
fn metadata(&self) -> Metadata {
self.0.metadata()
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
let mut map = Map::new();
let solc_env = std::env::var("FOUNDRY_SOLC_VERSION")
.or_else(|_| std::env::var("DAPP_SOLC_VERSION"))
.map(Value::from)
.ok();
for (profile, mut dict) in self.0.data()? {
if let Some(v) = solc_env.clone() {
// ENV var takes precedence over config file
dict.insert("solc".to_string(), v);
} else if let Some(v) = dict.remove("solc_version") {
// only insert older variant if not already included
if !dict.contains_key("solc") {
dict.insert("solc".to_string(), v);
}
}
if let Some(v) = dict.remove("odyssey") {
dict.insert("alphanet".to_string(), v);
}
map.insert(profile, dict);
}
Ok(map)
}
}
/// A provider that sets the `src` and `output` path depending on their existence.
struct DappHardhatDirProvider<'a>(&'a Path);
impl Provider for DappHardhatDirProvider<'_> {
fn metadata(&self) -> Metadata {
Metadata::named("Dapp Hardhat dir compat")
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
let mut dict = Dict::new();
dict.insert(
"src".to_string(),
ProjectPathsConfig::find_source_dir(self.0)
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.into(),
);
dict.insert(
"out".to_string(),
ProjectPathsConfig::find_artifacts_dir(self.0)
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
.into(),
);
// detect libs folders:
// if `lib` _and_ `node_modules` exists: include both
// if only `node_modules` exists: include `node_modules`
// include `lib` otherwise
let mut libs = vec![];
let node_modules = self.0.join("node_modules");
let lib = self.0.join("lib");
if node_modules.exists() {
if lib.exists() {
libs.push(lib.file_name().unwrap().to_string_lossy().to_string());
}
libs.push(node_modules.file_name().unwrap().to_string_lossy().to_string());
} else {
libs.push(lib.file_name().unwrap().to_string_lossy().to_string());
}
dict.insert("libs".to_string(), libs.into());
Ok(Map::from([(Config::selected_profile(), dict)]))
}
}
/// A provider that checks for DAPP_ env vars that are named differently than FOUNDRY_
struct DappEnvCompatProvider;
impl Provider for DappEnvCompatProvider {
fn metadata(&self) -> Metadata {
Metadata::named("Dapp env compat")
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
use serde::de::Error as _;
use std::env;
let mut dict = Dict::new();
if let Ok(val) = env::var("DAPP_TEST_NUMBER") {
dict.insert(
"block_number".to_string(),
val.parse::<u64>().map_err(figment::Error::custom)?.into(),
);
}
if let Ok(val) = env::var("DAPP_TEST_ADDRESS") {
dict.insert("sender".to_string(), val.into());
}
if let Ok(val) = env::var("DAPP_FORK_BLOCK") {
dict.insert(
"fork_block_number".to_string(),
val.parse::<u64>().map_err(figment::Error::custom)?.into(),
);
} else if let Ok(val) = env::var("DAPP_TEST_NUMBER") {
dict.insert(
"fork_block_number".to_string(),
val.parse::<u64>().map_err(figment::Error::custom)?.into(),
);
}
if let Ok(val) = env::var("DAPP_TEST_TIMESTAMP") {
dict.insert(
"block_timestamp".to_string(),
val.parse::<u64>().map_err(figment::Error::custom)?.into(),
);
}
if let Ok(val) = env::var("DAPP_BUILD_OPTIMIZE_RUNS") {
dict.insert(
"optimizer_runs".to_string(),
val.parse::<u64>().map_err(figment::Error::custom)?.into(),
);
}
if let Ok(val) = env::var("DAPP_BUILD_OPTIMIZE") {
// Activate Solidity optimizer (0 or 1)
let val = val.parse::<u8>().map_err(figment::Error::custom)?;
if val > 1 {
return Err(
format!("Invalid $DAPP_BUILD_OPTIMIZE value `{val}`, expected 0 or 1").into()
);
}
dict.insert("optimizer".to_string(), (val == 1).into());
}
// libraries in env vars either as `[..]` or single string separated by comma
if let Ok(val) = env::var("DAPP_LIBRARIES").or_else(|_| env::var("FOUNDRY_LIBRARIES")) {
dict.insert("libraries".to_string(), utils::to_array_value(&val)?);
}
let mut fuzz_dict = Dict::new();
if let Ok(val) = env::var("DAPP_TEST_FUZZ_RUNS") {
fuzz_dict.insert(
"runs".to_string(),
val.parse::<u32>().map_err(figment::Error::custom)?.into(),
);
}
dict.insert("fuzz".to_string(), fuzz_dict.into());
let mut invariant_dict = Dict::new();
if let Ok(val) = env::var("DAPP_TEST_DEPTH") {
invariant_dict.insert(
"depth".to_string(),
val.parse::<u32>().map_err(figment::Error::custom)?.into(),
);
}
dict.insert("invariant".to_string(), invariant_dict.into());
Ok(Map::from([(Config::selected_profile(), dict)]))
}
}
/// Renames a profile from `from` to `to`.
///
/// For example given:
///
/// ```toml
/// [from]
/// key = "value"
/// ```
///
/// RenameProfileProvider will output
///
/// ```toml
/// [to]
/// key = "value"
/// ```
struct RenameProfileProvider<P> {
provider: P,
from: Profile,
to: Profile,
}
impl<P> RenameProfileProvider<P> {
pub fn new(provider: P, from: impl Into<Profile>, to: impl Into<Profile>) -> Self {
Self { provider, from: from.into(), to: to.into() }
}
}
impl<P: Provider> Provider for RenameProfileProvider<P> {
fn metadata(&self) -> Metadata {
self.provider.metadata()
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
let mut data = self.provider.data()?;
if let Some(data) = data.remove(&self.from) {
return Ok(Map::from([(self.to.clone(), data)]));
}
Ok(Default::default())
}
fn profile(&self) -> Option<Profile> {
Some(self.to.clone())
}
}
/// Unwraps a profile reducing the key depth
///
/// For example given:
///
/// ```toml
/// [wrapping_key.profile]
/// key = "value"
/// ```
///
/// UnwrapProfileProvider will output:
///
/// ```toml
/// [profile]
/// key = "value"
/// ```
struct UnwrapProfileProvider<P> {
provider: P,
wrapping_key: Profile,
profile: Profile,
}
impl<P> UnwrapProfileProvider<P> {
pub fn new(provider: P, wrapping_key: impl Into<Profile>, profile: impl Into<Profile>) -> Self {
Self { provider, wrapping_key: wrapping_key.into(), profile: profile.into() }
}
}
impl<P: Provider> Provider for UnwrapProfileProvider<P> {
fn metadata(&self) -> Metadata {
self.provider.metadata()
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
self.provider.data().and_then(|mut data| {
if let Some(profiles) = data.remove(&self.wrapping_key) {
for (profile_str, profile_val) in profiles {
let profile = Profile::new(&profile_str);
if profile != self.profile {
continue;
}
match profile_val {
Value::Dict(_, dict) => return Ok(profile.collect(dict)),
bad_val => {
let mut err = Error::from(figment::error::Kind::InvalidType(
bad_val.to_actual(),
"dict".into(),
));
err.metadata = Some(self.provider.metadata());
err.profile = Some(self.profile.clone());
return Err(err);
}
}
}
}
Ok(Default::default())
})
}
fn profile(&self) -> Option<Profile> {
Some(self.profile.clone())
}
}
/// Wraps a profile in another profile
///
/// For example given:
///
/// ```toml
/// [profile]
/// key = "value"
/// ```
///
/// WrapProfileProvider will output:
///
/// ```toml
/// [wrapping_key.profile]
/// key = "value"
/// ```
struct WrapProfileProvider<P> {
provider: P,
wrapping_key: Profile,
profile: Profile,
}
impl<P> WrapProfileProvider<P> {
pub fn new(provider: P, wrapping_key: impl Into<Profile>, profile: impl Into<Profile>) -> Self {
Self { provider, wrapping_key: wrapping_key.into(), profile: profile.into() }
}
}
impl<P: Provider> Provider for WrapProfileProvider<P> {
fn metadata(&self) -> Metadata {
self.provider.metadata()
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
if let Some(inner) = self.provider.data()?.remove(&self.profile) {
let value = Value::from(inner);
let dict = [(self.profile.to_string().to_snake_case(), value)].into_iter().collect();
Ok(self.wrapping_key.collect(dict))
} else {
Ok(Default::default())
}
}
fn profile(&self) -> Option<Profile> {
Some(self.profile.clone())
}
}
/// Extracts the profile from the `profile` key and using the original key as backup, merging
/// values where necessary
///
/// For example given:
///
/// ```toml
/// [profile.cool]
/// key = "value"
///
/// [cool]
/// key2 = "value2"
/// ```
///
/// OptionalStrictProfileProvider will output:
///
/// ```toml
/// [cool]
/// key = "value"
/// key2 = "value2"
/// ```
///
/// And emit a deprecation warning
struct OptionalStrictProfileProvider<P> {
provider: P,
profiles: Vec<Profile>,
}
impl<P> OptionalStrictProfileProvider<P> {
pub const PROFILE_PROFILE: Profile = Profile::const_new("profile");
pub fn new(provider: P, profiles: impl IntoIterator<Item = impl Into<Profile>>) -> Self {
Self { provider, profiles: profiles.into_iter().map(|profile| profile.into()).collect() }
}
}
impl<P: Provider> Provider for OptionalStrictProfileProvider<P> {
fn metadata(&self) -> Metadata {
self.provider.metadata()
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
let mut figment = Figment::from(&self.provider);
for profile in &self.profiles {
figment = figment.merge(UnwrapProfileProvider::new(
&self.provider,
Self::PROFILE_PROFILE,
profile.clone(),
));
}
figment.data().map_err(|err| {
// figment does tag metadata and tries to map metadata to an error, since we use a new
// figment in this provider this new figment does not know about the metadata of the
// provider and can't map the metadata to the error. Therefore we return the root error
// if this error originated in the provider's data.
if let Err(root_err) = self.provider.data() {
return root_err;
}
err
})
}
fn profile(&self) -> Option<Profile> {
self.profiles.last().cloned()
}
}
trait ProviderExt: Provider {
fn rename(
&self,
from: impl Into<Profile>,
to: impl Into<Profile>,
) -> RenameProfileProvider<&Self> {
RenameProfileProvider::new(self, from, to)
}
fn wrap(
&self,
wrapping_key: impl Into<Profile>,
profile: impl Into<Profile>,
) -> WrapProfileProvider<&Self> {
WrapProfileProvider::new(self, wrapping_key, profile)
}
fn strict_select(
&self,
profiles: impl IntoIterator<Item = impl Into<Profile>>,
) -> OptionalStrictProfileProvider<&Self> {
OptionalStrictProfileProvider::new(self, profiles)
}
fn fallback(
&self,
profile: impl Into<Profile>,
fallback: impl Into<Profile>,
) -> FallbackProfileProvider<&Self> {
FallbackProfileProvider::new(self, profile, fallback)
}
}
impl<P: Provider> ProviderExt for P {}
/// A subset of the foundry `Config`
/// used to initialize a `foundry.toml` file
///
/// # Example
///
/// ```rust
/// use foundry_config::{BasicConfig, Config};
/// use serde::Deserialize;
///
/// let my_config = Config::figment().extract::<BasicConfig>();
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BasicConfig {
/// the profile tag: `[profile.default]`
#[serde(skip)]
pub profile: Profile,
/// path of the source contracts dir, like `src` or `contracts`
pub src: PathBuf,
/// path to where artifacts shut be written to
pub out: PathBuf,
/// all library folders to include, `lib`, `node_modules`
pub libs: Vec<PathBuf>,
/// `Remappings` to use for this repo
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub remappings: Vec<RelativeRemapping>,
}
impl BasicConfig {
/// Serialize the config as a String of TOML.
///
/// This serializes to a table with the name of the profile
pub fn to_string_pretty(&self) -> Result<String, toml::ser::Error> {
let s = toml::to_string_pretty(self)?;
Ok(format!(
"\
[profile.{}]
{s}
# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options\n",
self.profile
))
}
}
pub(crate) mod from_str_lowercase {
use serde::{Deserialize, Deserializer, Serializer};
use std::str::FromStr;
pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
T: std::fmt::Display,
S: Serializer,
{
serializer.collect_str(&value.to_string().to_lowercase())
}
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: FromStr,
T::Err: std::fmt::Display,
{
String::deserialize(deserializer)?.to_lowercase().parse().map_err(serde::de::Error::custom)
}
}
fn canonic(path: impl Into<PathBuf>) -> PathBuf {
let path = path.into();
foundry_compilers::utils::canonicalize(&path).unwrap_or(path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
cache::{CachedChains, CachedEndpoints},
endpoints::{RpcEndpointConfig, RpcEndpointType},
etherscan::ResolvedEtherscanConfigs,
};
use endpoints::RpcAuth;
use figment::error::Kind::InvalidType;
use foundry_compilers::artifacts::{
vyper::VyperOptimizationMode, ModelCheckerEngine, YulDetails,
};
use similar_asserts::assert_eq;
use soldeer::RemappingsLocation;
use std::{collections::BTreeMap, fs::File, io::Write};
use tempfile::tempdir;
use NamedChain::Moonbeam;
// Helper function to clear `__warnings` in config, since it will be populated during loading
// from file, causing testing problem when comparing to those created from `default()`, etc.
fn clear_warning(config: &mut Config) {
config.warnings = vec![];
}
#[test]
fn default_sender() {
assert_eq!(
Config::DEFAULT_SENDER,
Address::from_str("0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38").unwrap()
);
}
#[test]
fn test_caching() {
let mut config = Config::default();
let chain_id = NamedChain::Mainnet;
let url = "https://eth-mainnet.alchemyapi";
assert!(config.enable_caching(url, chain_id));
config.no_storage_caching = true;
assert!(!config.enable_caching(url, chain_id));
config.no_storage_caching = false;
assert!(!config.enable_caching(url, NamedChain::Dev));
}
#[test]
fn test_install_dir() {
figment::Jail::expect_with(|jail| {
let config = Config::load();
assert_eq!(config.install_lib_dir(), PathBuf::from("lib"));
jail.create_file(
"foundry.toml",
r"
[profile.default]
libs = ['node_modules', 'lib']
",
)?;
let config = Config::load();
assert_eq!(config.install_lib_dir(), PathBuf::from("lib"));
jail.create_file(
"foundry.toml",
r"
[profile.default]
libs = ['custom', 'node_modules', 'lib']
",
)?;
let config = Config::load();
assert_eq!(config.install_lib_dir(), PathBuf::from("custom"));
Ok(())
});
}
#[test]
fn test_figment_is_default() {
figment::Jail::expect_with(|_| {
let mut default: Config = Config::figment().extract().unwrap();
default.profile = Config::default().profile;
assert_eq!(default, Config::default());
Ok(())
});
}
#[test]
fn test_default_round_trip() {
figment::Jail::expect_with(|_| {
let original = Config::figment();
let roundtrip = Figment::from(Config::from_provider(&original));
for figment in &[original, roundtrip] {
let config = Config::from_provider(figment);
assert_eq!(config, Config::default());
}
Ok(())
});
}
#[test]
fn ffi_env_disallowed() {
figment::Jail::expect_with(|jail| {
jail.set_env("FOUNDRY_FFI", "true");
jail.set_env("FFI", "true");
jail.set_env("DAPP_FFI", "true");
let config = Config::load();
assert!(!config.ffi);
Ok(())
});
}
#[test]
fn test_profile_env() {
figment::Jail::expect_with(|jail| {
jail.set_env("FOUNDRY_PROFILE", "default");
let figment = Config::figment();
assert_eq!(figment.profile(), "default");
jail.set_env("FOUNDRY_PROFILE", "hardhat");
let figment: Figment = Config::hardhat().into();
assert_eq!(figment.profile(), "hardhat");
jail.create_file(
"foundry.toml",
r"
[profile.default]
libs = ['lib']
[profile.local]
libs = ['modules']
",
)?;
jail.set_env("FOUNDRY_PROFILE", "local");
let config = Config::load();
assert_eq!(config.libs, vec![PathBuf::from("modules")]);
Ok(())
});
}
#[test]
fn test_default_test_path() {
figment::Jail::expect_with(|_| {
let config = Config::default();
let paths_config = config.project_paths::<Solc>();
assert_eq!(paths_config.tests, PathBuf::from(r"test"));
Ok(())
});
}
#[test]
fn test_default_libs() {
figment::Jail::expect_with(|jail| {
let config = Config::load();
assert_eq!(config.libs, vec![PathBuf::from("lib")]);
fs::create_dir_all(jail.directory().join("node_modules")).unwrap();
let config = Config::load();
assert_eq!(config.libs, vec![PathBuf::from("node_modules")]);
fs::create_dir_all(jail.directory().join("lib")).unwrap();
let config = Config::load();
assert_eq!(config.libs, vec![PathBuf::from("lib"), PathBuf::from("node_modules")]);
Ok(())
});
}
#[test]
fn test_inheritance_from_default_test_path() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
test = "defaulttest"
src = "defaultsrc"
libs = ['lib', 'node_modules']
[profile.custom]
src = "customsrc"
"#,
)?;
let config = Config::load();
assert_eq!(config.src, PathBuf::from("defaultsrc"));
assert_eq!(config.libs, vec![PathBuf::from("lib"), PathBuf::from("node_modules")]);
jail.set_env("FOUNDRY_PROFILE", "custom");
let config = Config::load();
assert_eq!(config.src, PathBuf::from("customsrc"));
assert_eq!(config.test, PathBuf::from("defaulttest"));
assert_eq!(config.libs, vec![PathBuf::from("lib"), PathBuf::from("node_modules")]);
Ok(())
});
}
#[test]
fn test_custom_test_path() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
test = "mytest"
"#,
)?;
let config = Config::load();
let paths_config = config.project_paths::<Solc>();
assert_eq!(paths_config.tests, PathBuf::from(r"mytest"));
Ok(())
});
}
#[test]
fn test_remappings() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
src = "some-source"
out = "some-out"
cache = true
"#,
)?;
let config = Config::load();
assert!(config.remappings.is_empty());
jail.create_file(
"remappings.txt",
r"
file-ds-test/=lib/ds-test/
file-other/=lib/other/
",
)?;
let config = Config::load();
assert_eq!(
config.remappings,
vec![
Remapping::from_str("file-ds-test/=lib/ds-test/").unwrap().into(),
Remapping::from_str("file-other/=lib/other/").unwrap().into(),
],
);
jail.set_env("DAPP_REMAPPINGS", "ds-test=lib/ds-test/\nother/=lib/other/");
let config = Config::load();
assert_eq!(
config.remappings,
vec![
// From environment (should have precedence over remapping.txt)
Remapping::from_str("ds-test=lib/ds-test/").unwrap().into(),
Remapping::from_str("other/=lib/other/").unwrap().into(),
// From remapping.txt (should have less precedence than remapping.txt)
Remapping::from_str("file-ds-test/=lib/ds-test/").unwrap().into(),
Remapping::from_str("file-other/=lib/other/").unwrap().into(),
],
);
Ok(())
});
}
#[test]
fn test_remappings_override() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
src = "some-source"
out = "some-out"
cache = true
"#,
)?;
let config = Config::load();
assert!(config.remappings.is_empty());
jail.create_file(
"remappings.txt",
r"
ds-test/=lib/ds-test/
other/=lib/other/
",
)?;
let config = Config::load();
assert_eq!(
config.remappings,
vec![
Remapping::from_str("ds-test/=lib/ds-test/").unwrap().into(),
Remapping::from_str("other/=lib/other/").unwrap().into(),
],
);
jail.set_env("DAPP_REMAPPINGS", "ds-test/=lib/ds-test/src/\nenv-lib/=lib/env-lib/");
let config = Config::load();
// Remappings should now be:
// - ds-test from environment (lib/ds-test/src/)
// - other from remappings.txt (lib/other/)
// - env-lib from environment (lib/env-lib/)
assert_eq!(
config.remappings,
vec![
Remapping::from_str("ds-test/=lib/ds-test/src/").unwrap().into(),
Remapping::from_str("env-lib/=lib/env-lib/").unwrap().into(),
Remapping::from_str("other/=lib/other/").unwrap().into(),
],
);
// contains additional remapping to the source dir
assert_eq!(
config.get_all_remappings().collect::<Vec<_>>(),
vec![
Remapping::from_str("ds-test/=lib/ds-test/src/").unwrap(),
Remapping::from_str("env-lib/=lib/env-lib/").unwrap(),
Remapping::from_str("other/=lib/other/").unwrap(),
],
);
Ok(())
});
}
#[test]
fn test_can_update_libs() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
libs = ["node_modules"]
"#,
)?;
let mut config = Config::load();
config.libs.push("libs".into());
config.update_libs().unwrap();
let config = Config::load();
assert_eq!(config.libs, vec![PathBuf::from("node_modules"), PathBuf::from("libs"),]);
Ok(())
});
}
#[test]
fn test_large_gas_limit() {
figment::Jail::expect_with(|jail| {
let gas = u64::MAX;
jail.create_file(
"foundry.toml",
&format!(
r#"
[profile.default]
gas_limit = "{gas}"
"#
),
)?;
let config = Config::load();
assert_eq!(config, Config { gas_limit: gas.into(), ..Config::default() });
Ok(())
});
}
#[test]
#[should_panic]
fn test_toml_file_parse_failure() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
eth_rpc_url = "https://example.com/
"#,
)?;
let _config = Config::load();
Ok(())
});
}
#[test]
#[should_panic]
fn test_toml_file_non_existing_config_var_failure() {
figment::Jail::expect_with(|jail| {
jail.set_env("FOUNDRY_CONFIG", "this config does not exist");
let _config = Config::load();
Ok(())
});
}
#[test]
fn test_resolve_etherscan_with_chain() {
figment::Jail::expect_with(|jail| {
let env_key = "__BSC_ETHERSCAN_API_KEY";
let env_value = "env value";
jail.create_file(
"foundry.toml",
r#"
[profile.default]
[etherscan]
bsc = { key = "${__BSC_ETHERSCAN_API_KEY}", url = "https://api.bscscan.com/api" }
"#,
)?;
let config = Config::load();
assert!(config
.get_etherscan_config_with_chain(Some(NamedChain::BinanceSmartChain.into()))
.is_err());
std::env::set_var(env_key, env_value);
assert_eq!(
config
.get_etherscan_config_with_chain(Some(NamedChain::BinanceSmartChain.into()))
.unwrap()
.unwrap()
.key,
env_value
);
let mut with_key = config;
with_key.etherscan_api_key = Some("via etherscan_api_key".to_string());
assert_eq!(
with_key
.get_etherscan_config_with_chain(Some(NamedChain::BinanceSmartChain.into()))
.unwrap()
.unwrap()
.key,
"via etherscan_api_key"
);
std::env::remove_var(env_key);
Ok(())
});
}
#[test]
fn test_resolve_etherscan() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
[etherscan]
mainnet = { key = "FX42Z3BBJJEWXWGYV2X1CIPRSCN" }
moonbeam = { key = "${_CONFIG_ETHERSCAN_MOONBEAM}" }
"#,
)?;
let config = Config::load();
assert!(config.etherscan.clone().resolved().has_unresolved());
jail.set_env("_CONFIG_ETHERSCAN_MOONBEAM", "123456789");
let configs = config.etherscan.resolved();
assert!(!configs.has_unresolved());
let mb_urls = Moonbeam.etherscan_urls().unwrap();
let mainnet_urls = NamedChain::Mainnet.etherscan_urls().unwrap();
assert_eq!(
configs,
ResolvedEtherscanConfigs::new([
(
"mainnet",
ResolvedEtherscanConfig {
api_url: mainnet_urls.0.to_string(),
chain: Some(NamedChain::Mainnet.into()),
browser_url: Some(mainnet_urls.1.to_string()),
key: "FX42Z3BBJJEWXWGYV2X1CIPRSCN".to_string(),
}
),
(
"moonbeam",
ResolvedEtherscanConfig {
api_url: mb_urls.0.to_string(),
chain: Some(Moonbeam.into()),
browser_url: Some(mb_urls.1.to_string()),
key: "123456789".to_string(),
}
),
])
);
Ok(())
});
}
#[test]
fn test_resolve_etherscan_chain_id() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
chain_id = "sepolia"
[etherscan]
sepolia = { key = "FX42Z3BBJJEWXWGYV2X1CIPRSCN" }
"#,
)?;
let config = Config::load();
let etherscan = config.get_etherscan_config().unwrap().unwrap();
assert_eq!(etherscan.chain, Some(NamedChain::Sepolia.into()));
assert_eq!(etherscan.key, "FX42Z3BBJJEWXWGYV2X1CIPRSCN");
Ok(())
});
}
#[test]
fn test_resolve_rpc_url() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
[rpc_endpoints]
optimism = "https://example.com/"
mainnet = "${_CONFIG_MAINNET}"
"#,
)?;
jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
let mut config = Config::load();
assert_eq!("http://localhost:8545", config.get_rpc_url_or_localhost_http().unwrap());
config.eth_rpc_url = Some("mainnet".to_string());
assert_eq!(
"https://eth-mainnet.alchemyapi.io/v2/123455",
config.get_rpc_url_or_localhost_http().unwrap()
);
config.eth_rpc_url = Some("optimism".to_string());
assert_eq!("https://example.com/", config.get_rpc_url_or_localhost_http().unwrap());
Ok(())
})
}
#[test]
fn test_resolve_rpc_url_if_etherscan_set() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
etherscan_api_key = "dummy"
[rpc_endpoints]
optimism = "https://example.com/"
"#,
)?;
let config = Config::load();
assert_eq!("http://localhost:8545", config.get_rpc_url_or_localhost_http().unwrap());
Ok(())
})
}
#[test]
fn test_resolve_rpc_url_alias() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
[rpc_endpoints]
polygonMumbai = "https://polygon-mumbai.g.alchemy.com/v2/${_RESOLVE_RPC_ALIAS}"
"#,
)?;
let mut config = Config::load();
config.eth_rpc_url = Some("polygonMumbai".to_string());
assert!(config.get_rpc_url().unwrap().is_err());
jail.set_env("_RESOLVE_RPC_ALIAS", "123455");
let mut config = Config::load();
config.eth_rpc_url = Some("polygonMumbai".to_string());
assert_eq!(
"https://polygon-mumbai.g.alchemy.com/v2/123455",
config.get_rpc_url().unwrap().unwrap()
);
Ok(())
})
}
#[test]
fn test_resolve_rpc_aliases() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
[etherscan]
arbitrum_alias = { key = "${TEST_RESOLVE_RPC_ALIAS_ARBISCAN}" }
[rpc_endpoints]
arbitrum_alias = "https://arb-mainnet.g.alchemy.com/v2/${TEST_RESOLVE_RPC_ALIAS_ARB_ONE}"
"#,
)?;
jail.set_env("TEST_RESOLVE_RPC_ALIAS_ARB_ONE", "123455");
jail.set_env("TEST_RESOLVE_RPC_ALIAS_ARBISCAN", "123455");
let config = Config::load();
let config = config.get_etherscan_config_with_chain(Some(NamedChain::Arbitrum.into()));
assert!(config.is_err());
assert_eq!(config.unwrap_err().to_string(), "At least one of `url` or `chain` must be present for Etherscan config with unknown alias `arbitrum_alias`");
Ok(())
});
}
#[test]
fn test_resolve_rpc_config() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[rpc_endpoints]
optimism = "https://example.com/"
mainnet = { endpoint = "${_CONFIG_MAINNET}", retries = 3, retry_backoff = 1000, compute_units_per_second = 1000 }
"#,
)?;
jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
let config = Config::load();
assert_eq!(
RpcEndpoints::new([
(
"optimism",
RpcEndpointType::String(RpcEndpoint::Url(
"https://example.com/".to_string()
))
),
(
"mainnet",
RpcEndpointType::Config(RpcEndpointConfig {
endpoint: RpcEndpoint::Env("${_CONFIG_MAINNET}".to_string()),
retries: Some(3),
retry_backoff: Some(1000),
compute_units_per_second: Some(1000),
auth: None,
})
),
]),
config.rpc_endpoints
);
let resolved = config.rpc_endpoints.resolved();
assert_eq!(
RpcEndpoints::new([
("optimism", RpcEndpoint::Url("https://example.com/".to_string())),
(
"mainnet",
RpcEndpoint::Url("https://eth-mainnet.alchemyapi.io/v2/123455".to_string())
),
])
.resolved(),
resolved
);
Ok(())
})
}
#[test]
fn test_resolve_auth() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
eth_rpc_url = "optimism"
[rpc_endpoints]
optimism = "https://example.com/"
mainnet = { endpoint = "${_CONFIG_MAINNET}", retries = 3, retry_backoff = 1000, compute_units_per_second = 1000, auth = "Bearer ${_CONFIG_AUTH}" }
"#,
)?;
let config = Config::load();
jail.set_env("_CONFIG_AUTH", "123456");
jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
assert_eq!(
RpcEndpoints::new([
(
"optimism",
RpcEndpointType::String(RpcEndpoint::Url(
"https://example.com/".to_string()
))
),
(
"mainnet",
RpcEndpointType::Config(RpcEndpointConfig {
endpoint: RpcEndpoint::Env("${_CONFIG_MAINNET}".to_string()),
retries: Some(3),
retry_backoff: Some(1000),
compute_units_per_second: Some(1000),
auth: Some(RpcAuth::Env("Bearer ${_CONFIG_AUTH}".to_string())),
})
),
]),
config.rpc_endpoints
);
let resolved = config.rpc_endpoints.resolved();
assert_eq!(
RpcEndpoints::new([
(
"optimism",
RpcEndpointType::String(RpcEndpoint::Url(
"https://example.com/".to_string()
))
),
(
"mainnet",
RpcEndpointType::Config(RpcEndpointConfig {
endpoint: RpcEndpoint::Url(
"https://eth-mainnet.alchemyapi.io/v2/123455".to_string()
),
retries: Some(3),
retry_backoff: Some(1000),
compute_units_per_second: Some(1000),
auth: Some(RpcAuth::Raw("Bearer 123456".to_string())),
})
),
])
.resolved(),
resolved
);
Ok(())
});
}
#[test]
fn test_resolve_endpoints() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
eth_rpc_url = "optimism"
[rpc_endpoints]
optimism = "https://example.com/"
mainnet = "${_CONFIG_MAINNET}"
mainnet_2 = "https://eth-mainnet.alchemyapi.io/v2/${_CONFIG_API_KEY1}"
mainnet_3 = "https://eth-mainnet.alchemyapi.io/v2/${_CONFIG_API_KEY1}/${_CONFIG_API_KEY2}"
"#,
)?;
let config = Config::load();
assert_eq!(config.get_rpc_url().unwrap().unwrap(), "https://example.com/");
assert!(config.rpc_endpoints.clone().resolved().has_unresolved());
jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
jail.set_env("_CONFIG_API_KEY1", "123456");
jail.set_env("_CONFIG_API_KEY2", "98765");
let endpoints = config.rpc_endpoints.resolved();
assert!(!endpoints.has_unresolved());
assert_eq!(
endpoints,
RpcEndpoints::new([
("optimism", RpcEndpoint::Url("https://example.com/".to_string())),
(
"mainnet",
RpcEndpoint::Url("https://eth-mainnet.alchemyapi.io/v2/123455".to_string())
),
(
"mainnet_2",
RpcEndpoint::Url("https://eth-mainnet.alchemyapi.io/v2/123456".to_string())
),
(
"mainnet_3",
RpcEndpoint::Url(
"https://eth-mainnet.alchemyapi.io/v2/123456/98765".to_string()
)
),
])
.resolved()
);
Ok(())
});
}
#[test]
fn test_extract_etherscan_config() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
etherscan_api_key = "optimism"
[etherscan]
optimism = { key = "https://etherscan-optimism.com/" }
mumbai = { key = "https://etherscan-mumbai.com/" }
"#,
)?;
let mut config = Config::load();
let optimism = config.get_etherscan_api_key(Some(NamedChain::Optimism.into()));
assert_eq!(optimism, Some("https://etherscan-optimism.com/".to_string()));
config.etherscan_api_key = Some("mumbai".to_string());
let mumbai = config.get_etherscan_api_key(Some(NamedChain::PolygonMumbai.into()));
assert_eq!(mumbai, Some("https://etherscan-mumbai.com/".to_string()));
Ok(())
});
}
#[test]
fn test_extract_etherscan_config_by_chain() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
[etherscan]
mumbai = { key = "https://etherscan-mumbai.com/", chain = 80001 }
"#,
)?;
let config = Config::load();
let mumbai = config
.get_etherscan_config_with_chain(Some(NamedChain::PolygonMumbai.into()))
.unwrap()
.unwrap();
assert_eq!(mumbai.key, "https://etherscan-mumbai.com/".to_string());
Ok(())
});
}
#[test]
fn test_extract_etherscan_config_by_chain_with_url() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
[etherscan]
mumbai = { key = "https://etherscan-mumbai.com/", chain = 80001 , url = "https://verifier-url.com/"}
"#,
)?;
let config = Config::load();
let mumbai = config
.get_etherscan_config_with_chain(Some(NamedChain::PolygonMumbai.into()))
.unwrap()
.unwrap();
assert_eq!(mumbai.key, "https://etherscan-mumbai.com/".to_string());
assert_eq!(mumbai.api_url, "https://verifier-url.com/".to_string());
Ok(())
});
}
#[test]
fn test_extract_etherscan_config_by_chain_and_alias() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
eth_rpc_url = "mumbai"
[etherscan]
mumbai = { key = "https://etherscan-mumbai.com/" }
[rpc_endpoints]
mumbai = "https://polygon-mumbai.g.alchemy.com/v2/mumbai"
"#,
)?;
let config = Config::load();
let mumbai = config.get_etherscan_config_with_chain(None).unwrap().unwrap();
assert_eq!(mumbai.key, "https://etherscan-mumbai.com/".to_string());
let mumbai_rpc = config.get_rpc_url().unwrap().unwrap();
assert_eq!(mumbai_rpc, "https://polygon-mumbai.g.alchemy.com/v2/mumbai");
Ok(())
});
}
#[test]
fn test_toml_file() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
src = "some-source"
out = "some-out"
cache = true
eth_rpc_url = "https://example.com/"
verbosity = 3
remappings = ["ds-test=lib/ds-test/"]
via_ir = true
rpc_storage_caching = { chains = [1, "optimism", 999999], endpoints = "all"}
use_literal_content = false
bytecode_hash = "ipfs"
cbor_metadata = true
revert_strings = "strip"
allow_paths = ["allow", "paths"]
build_info_path = "build-info"
always_use_create_2_factory = true
[rpc_endpoints]
optimism = "https://example.com/"
mainnet = "${RPC_MAINNET}"
mainnet_2 = "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}"
mainnet_3 = "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}/${ANOTHER_KEY}"
"#,
)?;
let config = Config::load();
assert_eq!(
config,
Config {
src: "some-source".into(),
out: "some-out".into(),
cache: true,
eth_rpc_url: Some("https://example.com/".to_string()),
remappings: vec![Remapping::from_str("ds-test=lib/ds-test/").unwrap().into()],
verbosity: 3,
via_ir: true,
rpc_storage_caching: StorageCachingConfig {
chains: CachedChains::Chains(vec![
Chain::mainnet(),
Chain::optimism_mainnet(),
Chain::from_id(999999)
]),
endpoints: CachedEndpoints::All,
},
use_literal_content: false,
bytecode_hash: BytecodeHash::Ipfs,
cbor_metadata: true,
revert_strings: Some(RevertStrings::Strip),
allow_paths: vec![PathBuf::from("allow"), PathBuf::from("paths")],
rpc_endpoints: RpcEndpoints::new([
("optimism", RpcEndpoint::Url("https://example.com/".to_string())),
("mainnet", RpcEndpoint::Env("${RPC_MAINNET}".to_string())),
(
"mainnet_2",
RpcEndpoint::Env(
"https://eth-mainnet.alchemyapi.io/v2/${API_KEY}".to_string()
)
),
(
"mainnet_3",
RpcEndpoint::Env(
"https://eth-mainnet.alchemyapi.io/v2/${API_KEY}/${ANOTHER_KEY}"
.to_string()
)
),
]),
build_info_path: Some("build-info".into()),
always_use_create_2_factory: true,
..Config::default()
}
);
Ok(())
});
}
#[test]
fn test_load_remappings() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[profile.default]
remappings = ['nested/=lib/nested/']
",
)?;
let config = Config::load_with_root(jail.directory());
assert_eq!(
config.remappings,
vec![Remapping::from_str("nested/=lib/nested/").unwrap().into()]
);
Ok(())
});
}
#[test]
fn test_load_full_toml() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
auto_detect_solc = true
block_base_fee_per_gas = 0
block_coinbase = '0x0000000000000000000000000000000000000000'
block_difficulty = 0
block_prevrandao = '0x0000000000000000000000000000000000000000000000000000000000000000'
block_number = 1
block_timestamp = 1
use_literal_content = false
bytecode_hash = 'ipfs'
cbor_metadata = true
cache = true
cache_path = 'cache'
evm_version = 'london'
extra_output = []
extra_output_files = []
always_use_create_2_factory = false
ffi = false
force = false
gas_limit = 9223372036854775807
gas_price = 0
gas_reports = ['*']
ignored_error_codes = [1878]
ignored_warnings_from = ["something"]
deny_warnings = false
initial_balance = '0xffffffffffffffffffffffff'
libraries = []
libs = ['lib']
memory_limit = 134217728
names = false
no_storage_caching = false
no_rpc_rate_limit = false
offline = false
optimizer = true
optimizer_runs = 200
out = 'out'
remappings = ['nested/=lib/nested/']
sender = '0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38'
sizes = false
sparse_mode = false
src = 'src'
test = 'test'
tx_origin = '0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38'
verbosity = 0
via_ir = false
[profile.default.rpc_storage_caching]
chains = 'all'
endpoints = 'all'
[rpc_endpoints]
optimism = "https://example.com/"
mainnet = "${RPC_MAINNET}"
mainnet_2 = "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}"
[fuzz]
runs = 256
seed = '0x3e8'
max_test_rejects = 65536
[invariant]
runs = 256
depth = 500
fail_on_revert = false
call_override = false
shrink_run_limit = 5000
"#,
)?;
let config = Config::load_with_root(jail.directory());
assert_eq!(config.ignored_file_paths, vec![PathBuf::from("something")]);
assert_eq!(config.fuzz.seed, Some(U256::from(1000)));
assert_eq!(
config.remappings,
vec![Remapping::from_str("nested/=lib/nested/").unwrap().into()]
);
assert_eq!(
config.rpc_endpoints,
RpcEndpoints::new([
("optimism", RpcEndpoint::Url("https://example.com/".to_string())),
("mainnet", RpcEndpoint::Env("${RPC_MAINNET}".to_string())),
(
"mainnet_2",
RpcEndpoint::Env(
"https://eth-mainnet.alchemyapi.io/v2/${API_KEY}".to_string()
)
),
]),
);
Ok(())
});
}
#[test]
fn test_solc_req() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
solc_version = "0.8.12"
"#,
)?;
let config = Config::load();
assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 12))));
jail.create_file(
"foundry.toml",
r#"
[profile.default]
solc = "0.8.12"
"#,
)?;
let config = Config::load();
assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 12))));
jail.create_file(
"foundry.toml",
r#"
[profile.default]
solc = "path/to/local/solc"
"#,
)?;
let config = Config::load();
assert_eq!(config.solc, Some(SolcReq::Local("path/to/local/solc".into())));
jail.set_env("FOUNDRY_SOLC_VERSION", "0.6.6");
let config = Config::load();
assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 6, 6))));
Ok(())
});
}
// ensures the newer `solc` takes precedence over `solc_version`
#[test]
fn test_backwards_solc_version() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[default]
solc = "0.8.12"
solc_version = "0.8.20"
"#,
)?;
let config = Config::load();
assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 12))));
Ok(())
});
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[default]
solc_version = "0.8.20"
"#,
)?;
let config = Config::load();
assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 20))));
Ok(())
});
}
#[test]
fn test_toml_casing_file() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
src = "some-source"
out = "some-out"
cache = true
eth-rpc-url = "https://example.com/"
evm-version = "berlin"
auto-detect-solc = false
"#,
)?;
let config = Config::load();
assert_eq!(
config,
Config {
src: "some-source".into(),
out: "some-out".into(),
cache: true,
eth_rpc_url: Some("https://example.com/".to_string()),
auto_detect_solc: false,
evm_version: EvmVersion::Berlin,
..Config::default()
}
);
Ok(())
});
}
#[test]
fn test_output_selection() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
extra_output = ["metadata", "ir-optimized"]
extra_output_files = ["metadata"]
"#,
)?;
let config = Config::load();
assert_eq!(
config.extra_output,
vec![ContractOutputSelection::Metadata, ContractOutputSelection::IrOptimized]
);
assert_eq!(config.extra_output_files, vec![ContractOutputSelection::Metadata]);
Ok(())
});
}
#[test]
fn test_precedence() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
src = "mysrc"
out = "myout"
verbosity = 3
"#,
)?;
let config = Config::load();
assert_eq!(
config,
Config {
src: "mysrc".into(),
out: "myout".into(),
verbosity: 3,
..Config::default()
}
);
jail.set_env("FOUNDRY_SRC", r"other-src");
let config = Config::load();
assert_eq!(
config,
Config {
src: "other-src".into(),
out: "myout".into(),
verbosity: 3,
..Config::default()
}
);
jail.set_env("FOUNDRY_PROFILE", "foo");
let val: Result<String, _> = Config::figment().extract_inner("profile");
assert!(val.is_err());
Ok(())
});
}
#[test]
fn test_extract_basic() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
src = "mysrc"
out = "myout"
verbosity = 3
evm_version = 'berlin'
[profile.other]
src = "other-src"
"#,
)?;
let loaded = Config::load();
assert_eq!(loaded.evm_version, EvmVersion::Berlin);
let base = loaded.into_basic();
let default = Config::default();
assert_eq!(
base,
BasicConfig {
profile: Config::DEFAULT_PROFILE,
src: "mysrc".into(),
out: "myout".into(),
libs: default.libs.clone(),
remappings: default.remappings.clone(),
}
);
jail.set_env("FOUNDRY_PROFILE", r"other");
let base = Config::figment().extract::<BasicConfig>().unwrap();
assert_eq!(
base,
BasicConfig {
profile: Config::DEFAULT_PROFILE,
src: "other-src".into(),
out: "myout".into(),
libs: default.libs.clone(),
remappings: default.remappings,
}
);
Ok(())
});
}
#[test]
#[should_panic]
fn test_parse_invalid_fuzz_weight() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[fuzz]
dictionary_weight = 101
",
)?;
let _config = Config::load();
Ok(())
});
}
#[test]
fn test_fallback_provider() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[fuzz]
runs = 1
include_storage = false
dictionary_weight = 99
[invariant]
runs = 420
[profile.ci.fuzz]
dictionary_weight = 5
[profile.ci.invariant]
runs = 400
",
)?;
let invariant_default = InvariantConfig::default();
let config = Config::load();
assert_ne!(config.invariant.runs, config.fuzz.runs);
assert_eq!(config.invariant.runs, 420);
assert_ne!(
config.fuzz.dictionary.include_storage,
invariant_default.dictionary.include_storage
);
assert_eq!(
config.invariant.dictionary.include_storage,
config.fuzz.dictionary.include_storage
);
assert_ne!(
config.fuzz.dictionary.dictionary_weight,
invariant_default.dictionary.dictionary_weight
);
assert_eq!(
config.invariant.dictionary.dictionary_weight,
config.fuzz.dictionary.dictionary_weight
);
jail.set_env("FOUNDRY_PROFILE", "ci");
let ci_config = Config::load();
assert_eq!(ci_config.fuzz.runs, 1);
assert_eq!(ci_config.invariant.runs, 400);
assert_eq!(ci_config.fuzz.dictionary.dictionary_weight, 5);
assert_eq!(
ci_config.invariant.dictionary.dictionary_weight,
config.fuzz.dictionary.dictionary_weight
);
Ok(())
})
}
#[test]
fn test_standalone_profile_sections() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[fuzz]
runs = 100
[invariant]
runs = 120
[profile.ci.fuzz]
runs = 420
[profile.ci.invariant]
runs = 500
",
)?;
let config = Config::load();
assert_eq!(config.fuzz.runs, 100);
assert_eq!(config.invariant.runs, 120);
jail.set_env("FOUNDRY_PROFILE", "ci");
let config = Config::load();
assert_eq!(config.fuzz.runs, 420);
assert_eq!(config.invariant.runs, 500);
Ok(())
});
}
#[test]
fn can_handle_deviating_dapp_aliases() {
figment::Jail::expect_with(|jail| {
let addr = Address::ZERO;
jail.set_env("DAPP_TEST_NUMBER", 1337);
jail.set_env("DAPP_TEST_ADDRESS", format!("{addr:?}"));
jail.set_env("DAPP_TEST_FUZZ_RUNS", 420);
jail.set_env("DAPP_TEST_DEPTH", 20);
jail.set_env("DAPP_FORK_BLOCK", 100);
jail.set_env("DAPP_BUILD_OPTIMIZE_RUNS", 999);
jail.set_env("DAPP_BUILD_OPTIMIZE", 0);
let config = Config::load();
assert_eq!(config.block_number, 1337);
assert_eq!(config.sender, addr);
assert_eq!(config.fuzz.runs, 420);
assert_eq!(config.invariant.depth, 20);
assert_eq!(config.fork_block_number, Some(100));
assert_eq!(config.optimizer_runs, 999);
assert!(!config.optimizer);
Ok(())
});
}
#[test]
fn can_parse_libraries() {
figment::Jail::expect_with(|jail| {
jail.set_env(
"DAPP_LIBRARIES",
"[src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6]",
);
let config = Config::load();
assert_eq!(
config.libraries,
vec!["src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
.to_string()]
);
jail.set_env(
"DAPP_LIBRARIES",
"src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6",
);
let config = Config::load();
assert_eq!(
config.libraries,
vec!["src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
.to_string(),]
);
jail.set_env(
"DAPP_LIBRARIES",
"src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6,src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6",
);
let config = Config::load();
assert_eq!(
config.libraries,
vec![
"src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
.to_string(),
"src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
.to_string()
]
);
Ok(())
});
}
#[test]
fn test_parse_many_libraries() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[profile.default]
libraries= [
'./src/SizeAuctionDiscount.sol:Chainlink:0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5',
'./src/SizeAuction.sol:ChainlinkTWAP:0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5',
'./src/SizeAuction.sol:Math:0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c',
'./src/test/ChainlinkTWAP.t.sol:ChainlinkTWAP:0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5',
'./src/SizeAuctionDiscount.sol:Math:0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c',
]
",
)?;
let config = Config::load();
let libs = config.parsed_libraries().unwrap().libs;
similar_asserts::assert_eq!(
libs,
BTreeMap::from([
(
PathBuf::from("./src/SizeAuctionDiscount.sol"),
BTreeMap::from([
(
"Chainlink".to_string(),
"0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5".to_string()
),
(
"Math".to_string(),
"0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c".to_string()
)
])
),
(
PathBuf::from("./src/SizeAuction.sol"),
BTreeMap::from([
(
"ChainlinkTWAP".to_string(),
"0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5".to_string()
),
(
"Math".to_string(),
"0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c".to_string()
)
])
),
(
PathBuf::from("./src/test/ChainlinkTWAP.t.sol"),
BTreeMap::from([(
"ChainlinkTWAP".to_string(),
"0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5".to_string()
)])
),
])
);
Ok(())
});
}
#[test]
fn config_roundtrip() {
figment::Jail::expect_with(|jail| {
let default = Config::default();
let basic = default.clone().into_basic();
jail.create_file("foundry.toml", &basic.to_string_pretty().unwrap())?;
let mut other = Config::load();
clear_warning(&mut other);
assert_eq!(default, other);
let other = other.into_basic();
assert_eq!(basic, other);
jail.create_file("foundry.toml", &default.to_string_pretty().unwrap())?;
let mut other = Config::load();
clear_warning(&mut other);
assert_eq!(default, other);
Ok(())
});
}
#[test]
fn test_fs_permissions() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[profile.default]
fs_permissions = [{ access = "read-write", path = "./"}]
"#,
)?;
let loaded = Config::load();
assert_eq!(
loaded.fs_permissions,
FsPermissions::new(vec![PathPermission::read_write("./")])
);
jail.create_file(
"foundry.toml",
r#"
[profile.default]
fs_permissions = [{ access = "none", path = "./"}]
"#,
)?;
let loaded = Config::load();
assert_eq!(loaded.fs_permissions, FsPermissions::new(vec![PathPermission::none("./")]));
Ok(())
});
}
#[test]
fn test_optimizer_settings_basic() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[profile.default]
optimizer = true
[profile.default.optimizer_details]
yul = false
[profile.default.optimizer_details.yulDetails]
stackAllocation = true
",
)?;
let mut loaded = Config::load();
clear_warning(&mut loaded);
assert_eq!(
loaded.optimizer_details,
Some(OptimizerDetails {
yul: Some(false),
yul_details: Some(YulDetails {
stack_allocation: Some(true),
..Default::default()
}),
..Default::default()
})
);
let s = loaded.to_string_pretty().unwrap();
jail.create_file("foundry.toml", &s)?;
let mut reloaded = Config::load();
clear_warning(&mut reloaded);
assert_eq!(loaded, reloaded);
Ok(())
});
}
#[test]
fn test_model_checker_settings_basic() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[profile.default]
[profile.default.model_checker]
contracts = { 'a.sol' = [ 'A1', 'A2' ], 'b.sol' = [ 'B1', 'B2' ] }
engine = 'chc'
targets = [ 'assert', 'outOfBounds' ]
timeout = 10000
",
)?;
let mut loaded = Config::load();
clear_warning(&mut loaded);
assert_eq!(
loaded.model_checker,
Some(ModelCheckerSettings {
contracts: BTreeMap::from([
("a.sol".to_string(), vec!["A1".to_string(), "A2".to_string()]),
("b.sol".to_string(), vec!["B1".to_string(), "B2".to_string()]),
]),
engine: Some(ModelCheckerEngine::CHC),
targets: Some(vec![
ModelCheckerTarget::Assert,
ModelCheckerTarget::OutOfBounds
]),
timeout: Some(10000),
invariants: None,
show_unproved: None,
div_mod_with_slacks: None,
solvers: None,
show_unsupported: None,
show_proved_safe: None,
})
);
let s = loaded.to_string_pretty().unwrap();
jail.create_file("foundry.toml", &s)?;
let mut reloaded = Config::load();
clear_warning(&mut reloaded);
assert_eq!(loaded, reloaded);
Ok(())
});
}
#[test]
fn test_model_checker_settings_relative_paths() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[profile.default]
[profile.default.model_checker]
contracts = { 'a.sol' = [ 'A1', 'A2' ], 'b.sol' = [ 'B1', 'B2' ] }
engine = 'chc'
targets = [ 'assert', 'outOfBounds' ]
timeout = 10000
",
)?;
let loaded = Config::load().sanitized();
// NOTE(onbjerg): We have to canonicalize the path here using dunce because figment will
// canonicalize the jail path using the standard library. The standard library *always*
// transforms Windows paths to some weird extended format, which none of our code base
// does.
let dir = foundry_compilers::utils::canonicalize(jail.directory())
.expect("Could not canonicalize jail path");
assert_eq!(
loaded.model_checker,
Some(ModelCheckerSettings {
contracts: BTreeMap::from([
(
format!("{}", dir.join("a.sol").display()),
vec!["A1".to_string(), "A2".to_string()]
),
(
format!("{}", dir.join("b.sol").display()),
vec!["B1".to_string(), "B2".to_string()]
),
]),
engine: Some(ModelCheckerEngine::CHC),
targets: Some(vec![
ModelCheckerTarget::Assert,
ModelCheckerTarget::OutOfBounds
]),
timeout: Some(10000),
invariants: None,
show_unproved: None,
div_mod_with_slacks: None,
solvers: None,
show_unsupported: None,
show_proved_safe: None,
})
);
Ok(())
});
}
#[test]
fn test_fmt_config() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[fmt]
line_length = 100
tab_width = 2
bracket_spacing = true
",
)?;
let loaded = Config::load().sanitized();
assert_eq!(
loaded.fmt,
FormatterConfig {
line_length: 100,
tab_width: 2,
bracket_spacing: true,
..Default::default()
}
);
Ok(())
});
}
#[test]
fn test_invariant_config() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[invariant]
runs = 512
depth = 10
",
)?;
let loaded = Config::load().sanitized();
assert_eq!(
loaded.invariant,
InvariantConfig {
runs: 512,
depth: 10,
failure_persist_dir: Some(PathBuf::from("cache/invariant")),
..Default::default()
}
);
Ok(())
});
}
#[test]
fn test_standalone_sections_env() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[fuzz]
runs = 100
[invariant]
depth = 1
",
)?;
jail.set_env("FOUNDRY_FMT_LINE_LENGTH", "95");
jail.set_env("FOUNDRY_FUZZ_DICTIONARY_WEIGHT", "99");
jail.set_env("FOUNDRY_INVARIANT_DEPTH", "5");
let config = Config::load();
assert_eq!(config.fmt.line_length, 95);
assert_eq!(config.fuzz.dictionary.dictionary_weight, 99);
assert_eq!(config.invariant.depth, 5);
Ok(())
});
}
#[test]
fn test_parse_with_profile() {
let foundry_str = r"
[profile.default]
src = 'src'
out = 'out'
libs = ['lib']
# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options
";
assert_eq!(
parse_with_profile::<BasicConfig>(foundry_str).unwrap().unwrap(),
(
Config::DEFAULT_PROFILE,
BasicConfig {
profile: Config::DEFAULT_PROFILE,
src: "src".into(),
out: "out".into(),
libs: vec!["lib".into()],
remappings: vec![]
}
)
);
}
#[test]
fn test_implicit_profile_loads() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[default]
src = 'my-src'
out = 'my-out'
",
)?;
let loaded = Config::load().sanitized();
assert_eq!(loaded.src.file_name().unwrap(), "my-src");
assert_eq!(loaded.out.file_name().unwrap(), "my-out");
assert_eq!(
loaded.warnings,
vec![Warning::UnknownSection {
unknown_section: Profile::new("default"),
source: Some("foundry.toml".into())
}]
);
Ok(())
});
}
#[test]
fn test_etherscan_api_key() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[default]
",
)?;
jail.set_env("ETHERSCAN_API_KEY", "");
let loaded = Config::load().sanitized();
assert!(loaded.etherscan_api_key.is_none());
jail.set_env("ETHERSCAN_API_KEY", "DUMMY");
let loaded = Config::load().sanitized();
assert_eq!(loaded.etherscan_api_key, Some("DUMMY".into()));
Ok(())
});
}
#[test]
fn test_etherscan_api_key_figment() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[default]
etherscan_api_key = 'DUMMY'
",
)?;
jail.set_env("ETHERSCAN_API_KEY", "ETHER");
let figment = Config::figment_with_root(jail.directory())
.merge(("etherscan_api_key", "USER_KEY"));
let loaded = Config::from_provider(figment);
assert_eq!(loaded.etherscan_api_key, Some("USER_KEY".into()));
Ok(())
});
}
#[test]
fn test_normalize_defaults() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[default]
solc = '0.8.13'
",
)?;
let loaded = Config::load().sanitized();
assert_eq!(loaded.evm_version, EvmVersion::London);
Ok(())
});
}
// a test to print the config, mainly used to update the example config in the README
#[allow(clippy::disallowed_macros)]
#[test]
#[ignore]
fn print_config() {
let config = Config {
optimizer_details: Some(OptimizerDetails {
peephole: None,
inliner: None,
jumpdest_remover: None,
order_literals: None,
deduplicate: None,
cse: None,
constant_optimizer: Some(true),
yul: Some(true),
yul_details: Some(YulDetails {
stack_allocation: None,
optimizer_steps: Some("dhfoDgvulfnTUtnIf".to_string()),
}),
simple_counter_for_loop_unchecked_increment: None,
}),
..Default::default()
};
println!("{}", config.to_string_pretty().unwrap());
}
#[test]
#[allow(unknown_lints, non_local_definitions)]
fn can_use_impl_figment_macro() {
#[derive(Default, Serialize)]
struct MyArgs {
#[serde(skip_serializing_if = "Option::is_none")]
root: Option<PathBuf>,
}
impl_figment_convert!(MyArgs);
impl Provider for MyArgs {
fn metadata(&self) -> Metadata {
Metadata::default()
}
fn data(&self) -> Result<Map<Profile, Dict>, Error> {
let value = Value::serialize(self)?;
let error = InvalidType(value.to_actual(), "map".into());
let dict = value.into_dict().ok_or(error)?;
Ok(Map::from([(Config::selected_profile(), dict)]))
}
}
let _figment: Figment = From::from(&MyArgs::default());
let _config: Config = From::from(&MyArgs::default());
#[derive(Default)]
struct Outer {
start: MyArgs,
other: MyArgs,
another: MyArgs,
}
impl_figment_convert!(Outer, start, other, another);
let _figment: Figment = From::from(&Outer::default());
let _config: Config = From::from(&Outer::default());
}
#[test]
fn list_cached_blocks() -> eyre::Result<()> {
fn fake_block_cache(chain_path: &Path, block_number: &str, size_bytes: usize) {
let block_path = chain_path.join(block_number);
fs::create_dir(block_path.as_path()).unwrap();
let file_path = block_path.join("storage.json");
let mut file = File::create(file_path).unwrap();
writeln!(file, "{}", vec![' '; size_bytes - 1].iter().collect::<String>()).unwrap();
}
fn fake_block_cache_block_path_as_file(
chain_path: &Path,
block_number: &str,
size_bytes: usize,
) {
let block_path = chain_path.join(block_number);
let mut file = File::create(block_path).unwrap();
writeln!(file, "{}", vec![' '; size_bytes - 1].iter().collect::<String>()).unwrap();
}
let chain_dir = tempdir()?;
fake_block_cache(chain_dir.path(), "1", 100);
fake_block_cache(chain_dir.path(), "2", 500);
fake_block_cache_block_path_as_file(chain_dir.path(), "3", 900);
// Pollution file that should not show up in the cached block
let mut pol_file = File::create(chain_dir.path().join("pol.txt")).unwrap();
writeln!(pol_file, "{}", [' '; 10].iter().collect::<String>()).unwrap();
let result = Config::get_cached_blocks(chain_dir.path())?;
assert_eq!(result.len(), 3);
let block1 = &result.iter().find(|x| x.0 == "1").unwrap();
let block2 = &result.iter().find(|x| x.0 == "2").unwrap();
let block3 = &result.iter().find(|x| x.0 == "3").unwrap();
assert_eq!(block1.0, "1");
assert_eq!(block1.1, 100);
assert_eq!(block2.0, "2");
assert_eq!(block2.1, 500);
assert_eq!(block3.0, "3");
assert_eq!(block3.1, 900);
chain_dir.close()?;
Ok(())
}
#[test]
fn list_etherscan_cache() -> eyre::Result<()> {
fn fake_etherscan_cache(chain_path: &Path, address: &str, size_bytes: usize) {
let metadata_path = chain_path.join("sources");
let abi_path = chain_path.join("abi");
let _ = fs::create_dir(metadata_path.as_path());
let _ = fs::create_dir(abi_path.as_path());
let metadata_file_path = metadata_path.join(address);
let mut metadata_file = File::create(metadata_file_path).unwrap();
writeln!(metadata_file, "{}", vec![' '; size_bytes / 2 - 1].iter().collect::<String>())
.unwrap();
let abi_file_path = abi_path.join(address);
let mut abi_file = File::create(abi_file_path).unwrap();
writeln!(abi_file, "{}", vec![' '; size_bytes / 2 - 1].iter().collect::<String>())
.unwrap();
}
let chain_dir = tempdir()?;
fake_etherscan_cache(chain_dir.path(), "1", 100);
fake_etherscan_cache(chain_dir.path(), "2", 500);
let result = Config::get_cached_block_explorer_data(chain_dir.path())?;
assert_eq!(result, 600);
chain_dir.close()?;
Ok(())
}
#[test]
fn test_parse_error_codes() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[default]
ignored_error_codes = ["license", "unreachable", 1337]
"#,
)?;
let config = Config::load();
assert_eq!(
config.ignored_error_codes,
vec![
SolidityErrorCode::SpdxLicenseNotProvided,
SolidityErrorCode::Unreachable,
SolidityErrorCode::Other(1337)
]
);
Ok(())
});
}
#[test]
fn test_parse_file_paths() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[default]
ignored_warnings_from = ["something"]
"#,
)?;
let config = Config::load();
assert_eq!(config.ignored_file_paths, vec![Path::new("something").to_path_buf()]);
Ok(())
});
}
#[test]
fn test_parse_optimizer_settings() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r"
[default]
[profile.default.optimizer_details]
",
)?;
let config = Config::load();
assert_eq!(config.optimizer_details, Some(OptimizerDetails::default()));
Ok(())
});
}
#[test]
fn test_parse_labels() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[labels]
0x1F98431c8aD98523631AE4a59f267346ea31F984 = "Uniswap V3: Factory"
0xC36442b4a4522E871399CD717aBDD847Ab11FE88 = "Uniswap V3: Positions NFT"
"#,
)?;
let config = Config::load();
assert_eq!(
config.labels,
AddressHashMap::from_iter(vec![
(
Address::from_str("0x1F98431c8aD98523631AE4a59f267346ea31F984").unwrap(),
"Uniswap V3: Factory".to_string()
),
(
Address::from_str("0xC36442b4a4522E871399CD717aBDD847Ab11FE88").unwrap(),
"Uniswap V3: Positions NFT".to_string()
),
])
);
Ok(())
});
}
#[test]
fn test_parse_vyper() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[vyper]
optimize = "codesize"
path = "/path/to/vyper"
experimental_codegen = true
"#,
)?;
let config = Config::load();
assert_eq!(
config.vyper,
VyperConfig {
optimize: Some(VyperOptimizationMode::Codesize),
path: Some("/path/to/vyper".into()),
experimental_codegen: Some(true),
}
);
Ok(())
});
}
#[test]
fn test_parse_soldeer() {
figment::Jail::expect_with(|jail| {
jail.create_file(
"foundry.toml",
r#"
[soldeer]
remappings_generate = true
remappings_regenerate = false
remappings_version = true
remappings_prefix = "@"
remappings_location = "txt"
recursive_deps = true
"#,
)?;
let config = Config::load();
assert_eq!(
config.soldeer,
Some(SoldeerConfig {
remappings_generate: true,
remappings_regenerate: false,
remappings_version: true,
remappings_prefix: "@".to_string(),
remappings_location: RemappingsLocation::Txt,
recursive_deps: true,
})
);
Ok(())
});
}
}