All files / evm-wallet-experiment/src/vats coordinator-vat.ts

88.21% Statements 696/789
80.06% Branches 514/642
93.4% Functions 85/91
88.15% Lines 685/777

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                1x                   58x 58x 58x                     23x         23x                                 7x         3x       4x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         253x                                                                                         253x                     3036x       253x 253x 253x 253x 253x 253x 253x   253x 253x     253x   253x     253x                       92x 43x   49x 11x   38x         38x                     26x 10x           10x     16x 2x   14x           14x       14x 14x                                       8x     8x 8x 8x 5x 5x 5x   8x 8x                 8x 8x                     8x 8x                                 10x 1x   9x               9x 10x 10x 10x 14x 14x 14x           1x       1x 1x   13x       8x 8x 1x     1x     7x 8x   5x   1x                       6x 4x                             3x 2x     2x   3x                   23x 21x 21x 20x     3x           3x     253x                         13x     13x 13x       13x   12x 12x 12x     1x 1x 1x                         764x 34x   730x                             2x                                   26x 2x 1x       1x         24x 20x 20x 20x       4x 2x 2x 2x       2x 1x         1x                               7x 2x 1x           1x         5x 2x 2x 2x       3x 1x 1x 1x       2x 1x             1x                           28x 25x 25x 24x         4x 1x           3x                                       18x     18x       18x         18x 18x 8x 8x 8x         18x                 18x       18x         18x                   18x             18x 18x         3x   3x                       18x                                         18x   2x 2x 1x     2x             2x                         16x           16x                           18x                 18x     18x         18x                                                 18x 4x 3x 3x                 1x     1x           1x           14x   18x 14x           14x 4x               10x                     10x 10x 10x   10x 10x     10x                                     4x 2x 2x 2x             1x     1x                       2x 4x       2x 2x           2x 1x     1x           1x                           7x   7x 7x         7x 7x 7x 2x       2x   5x 1x       4x       4x   1x                                   18x 1x         17x 17x   2x       15x                 15x         15x   12x         12x 12x         3x               3x   3x   3x                     3x       3x 3x                         2x 1x     1x   1x           1x       1x   1x           1x     1x               3x 3x           3x                     3x         3x           3x 3x 47x       47x 2x   45x         45x 1x       44x       46x         46x 46x     253x           232x 232x 232x 232x     232x       232x 215x   232x 229x   232x 217x                             111x       111x       111x 111x       1x     1x       2x     2x       11x         11x 2x         9x 1x         8x   8x 8x               9x 4x   5x 5x                     44x 2x         42x 3x         39x             44x   44x         39x                               29x   29x 18x       11x       11x       29x     6x 6x   1x         5x 5x   5x         5x 5x     10x               10x 10x       3x                   78x 12x 12x         11x 11x 11x   1x 1x 1x             66x 1x     65x       78x         78x 78x 78x 2x 1x 1x     65x       5x       19x             19x 18x 18x         18x 18x           18x 3x           3x                         15x         15x 1x     1x                   15x   15x 13x 12x 13x 13x 13x   15x                           15x 14x           12x 1x     11x 1x     10x         10x         12x         3x         12x 18x           9x         9x 9x 18x             9x 12x         12x 6x 6x     6x       6x     9x 3x                   6x 11x         11x 1x                     5x 5x       5x 5x 1x   4x 1x         3x       1x 1x 2x   1x       8x       7x       3x 1x   2x                               6x 1x       5x 3x 3x               2x 1x               1x               4x         4x 3x           1x               46x                       46x 42x 42x 42x 42x 42x         46x 3x 3x 3x 3x     3x 3x         46x 1x     45x         45x       45x   45x   45x       2x 1x   1x                     4x         4x 4x 3x 2x       1x                               10x 1x     9x 9x 2x   7x             7x 7x 7x 10x 7x   10x     10x                   7x   6x 2x     2x 1x             4x     4x 4x                   4x 1x             4x   4x       8x     8x                             17x             17x   2x 15x 12x     12x 3x   2x 2x 2x         2x 1x         1x             1x   1x       15x 15x 1x           14x                               2x 1x   1x 1x       1x         1x           3x 1x     2x                               2x                     2x 2x 2x 2x               2x 2x 2x 2x                       2x                                     3x 3x 3x 1x     2x     3x 3x                                     13x 1x     12x 1x       11x 13x       11x   11x     11x               11x     66x       11x   11x   11x 1x             10x   10x 13x 13x 3x     10x     13x 13x 10x 10x       10x 1x         9x                   6x   6x 6x 6x         6x             6x     6x 6x 6x 4x       4x 4x 4x           4x       4x     6x                 6x 1x             1x           1x       1x                       5x 2x               5x 5x   4x               1x   1x 1x                           8x 1x     7x                   7x 8x 8x   8x 13x       13x 6x   7x   1x                                       8x                             3x     3x     3x     3x 3x 3x                 3x 3x       1x         2x 1x   1x 1x 1x       10x 4x       6x 6x             5x 1x           4x           4x       6x         4x       2x 2x       2x       2x 1x   1x                   7x   2x     2x         2x     2x           2x 1x 1x 1x           1x     2x     2x 1x 1x 1x           1x 1x 1x 1x                 1x                               7x 1x               6x     7x 1x         5x 2x 1x   1x               3x 2x 1x   1x           1x                   7x   7x       7x     7x 2x             7x 7x 1x 1x       1x 1x 1x         6x 1x 5x 4x         7x                                 7x           7x   7x 7x 2x 2x       2x     2x 1x   1x     5x     5x       7x 7x         7x                                   253x    
import { E } from '@endo/eventual-send';
import { makeDefaultExo } from '@metamask/kernel-utils/exo';
import { Logger } from '@metamask/logger';
import type { Baggage } from '@metamask/ocap-kernel';
 
import {
  decodeAllowanceResult,
  decodeBalanceOfResult,
  decodeDecimalsResult,
  decodeNameResult,
  decodeSymbolResult,
  encodeAllowance,
  encodeBalanceOf,
  encodeDecimals,
  encodeName,
  encodeSymbol,
  encodeTransfer,
} from '../lib/erc20.ts';
import {
  buildBatchExecuteCallData,
  buildSdkBatchRedeemCallData,
  buildSdkDisableCallData,
  buildSdkRedeemCallData,
  computeSmartAccountAddress,
  isEip7702Delegated,
  prepareUserOpTypedData,
  resolveEnvironment,
} from '../lib/sdk.ts';
import { ENTRY_POINT_V07 } from '../lib/userop.ts';
import type {
  Action,
  Address,
  Caveat,
  ChainConfig,
  CreateDelegationOptions,
  Delegation,
  DelegationMatchResult,
  Eip712TypedData,
  Execution,
  Hex,
  SmartAccountConfig,
  SwapQuote,
  SwapResult,
  TransactionRequest,
  UserOperation,
  WalletCapabilities,
} from '../types.ts';
 
const harden = globalThis.harden ?? (<T>(value: T): T => value);
 
/**
 * Apply a percentage buffer to a hex gas value.
 *
 * @param gasHex - The gas value as a hex string.
 * @param bufferPercent - The buffer percentage to add (e.g. 10 for 10%).
 * @returns The buffered gas value as a hex string.
 */
function applyGasBuffer(gasHex: Hex, bufferPercent: number): Hex {
  const gas = BigInt(gasHex);
  const buffered = gas + (gas * BigInt(bufferPercent)) / 100n;
  return `0x${buffered.toString(16)}`;
}
 
/**
 * Validate that an `eth_estimateGas` response is a valid hex string.
 *
 * @param result - The raw RPC response.
 * @returns The validated hex string.
 * @throws If the result is not a hex string.
 */
function validateGasEstimate(result: unknown): Hex {
  Iif (typeof result !== 'string' || !result.startsWith('0x')) {
    throw new Error(
      `eth_estimateGas returned unexpected value: ${String(result)}`,
    );
  }
  return result as Hex;
}
 
/**
 * Validate that a token `eth_call` response is a usable hex string.
 *
 * @param result - The raw RPC response.
 * @param method - The ERC-20 method name (for error context).
 * @param token - The token address (for error context).
 * @returns The validated hex string.
 * @throws If the result is not a non-empty hex string.
 */
function validateTokenCallResult(
  result: unknown,
  method: string,
  token: Address,
): Hex {
  if (
    typeof result !== 'string' ||
    !result.startsWith('0x') ||
    result === '0x'
  ) {
    throw new Error(
      `${method}() call to token ${token} returned unexpected value: ${String(result)}`,
    );
  }
  return result as Hex;
}
 
/**
 * Convert a wei amount in hex to a human-readable ETH string.
 *
 * @param weiHex - The wei amount as a hex string.
 * @returns A formatted string like "1.5 ETH".
 */
function weiToEth(weiHex: string): string {
  const wei = BigInt(weiHex);
  const whole = wei / 10n ** 18n;
  const frac = wei % 10n ** 18n;
  if (frac === 0n) {
    return `${String(whole)} ETH`;
  }
  const fracStr = frac.toString().padStart(18, '0').replace(/0+$/u, '');
  return `${String(whole)}.${fracStr} ETH`;
}
 
/**
 * Convert a caveat to a human-readable description.
 *
 * @param caveat - The caveat to describe.
 * @returns A human-readable string describing the caveat's constraint.
 */
function describeCaveat(caveat: Caveat): string {
  switch (caveat.type) {
    case 'nativeTokenTransferAmount':
      return `total spend limit: ${weiToEth(caveat.terms)}`;
    case 'valueLte':
      return `max per tx: ${weiToEth(caveat.terms)}`;
    case 'allowedTargets':
      return 'restricted target addresses';
    case 'allowedMethods':
      return 'restricted methods';
    case 'limitedCalls':
      return 'limited number of calls';
    case 'timestamp':
      return 'time-limited';
    case 'erc20TransferAmount': {
      // ABI-encoded (address, uint256): 12 bytes padding + 20 bytes address + 32 bytes uint256
      // In hex string: '0x' + 24 pad chars + 40 address chars + 64 amount chars = 130 chars
      if (caveat.terms.length >= 130) {
        try {
          const token = `0x${caveat.terms.slice(26, 66)}`;
          const amount = BigInt(`0x${caveat.terms.slice(66)}`);
          return `ERC-20 transfer limit: ${amount.toString()} units on ${token}`;
        } catch {
          // Fall through to generic description
        }
      }
      return 'ERC-20 transfer limit';
    }
    default:
      return `${String(caveat.type)} enforced`;
  }
}
 
/**
 * Vat powers for the coordinator vat.
 */
type VatPowers = {
  logger?: Logger;
};
 
/**
 * Vat references available in the wallet subcluster.
 */
type WalletVats = {
  keyring?: unknown;
  provider?: unknown;
  delegation?: unknown;
};
 
/**
 * Services available to the wallet subcluster.
 */
type WalletServices = {
  ocapURLIssuerService?: unknown;
  ocapURLRedemptionService?: unknown;
};
 
// Typed facets for E() calls (avoid `any` by using explicit method signatures)
type KeyringFacet = {
  initialize: (
    options: { type: string; mnemonic?: string },
    password?: string,
    salt?: string,
  ) => Promise<void>;
  unlock: (password: string) => Promise<void>;
  isLocked: () => Promise<boolean>;
  hasKeys: () => Promise<boolean>;
  getAccounts: () => Promise<Address[]>;
  deriveAccount: (index: number) => Promise<Address>;
  signTransaction: (tx: TransactionRequest) => Promise<Hex>;
  signTypedData: (data: Eip712TypedData, from?: Address) => Promise<Hex>;
  signMessage: (message: string, from?: Address) => Promise<Hex>;
  signHash: (hash: Hex, from?: Address) => Promise<Hex>;
  signAuthorization: (options: {
    contractAddress: Address;
    chainId: number;
    nonce?: number;
    from?: Address;
  }) => Promise<unknown>;
};
 
type ProviderFacet = {
  configure: (config: ChainConfig) => Promise<void>;
  request: (method: string, params?: unknown[]) => Promise<unknown>;
  broadcastTransaction: (signedTx: Hex) => Promise<Hex>;
  getChainId: () => Promise<number>;
  getNonce: (address: Address) => Promise<number>;
  getEntryPointNonce: (options: {
    entryPoint: Address;
    sender: Address;
    key?: Hex;
  }) => Promise<Hex>;
  submitUserOp: (options: {
    bundlerUrl: string;
    entryPoint: Hex;
    userOp: UserOperation;
  }) => Promise<Hex>;
  estimateUserOpGas: (options: {
    bundlerUrl: string;
    entryPoint: Hex;
    userOp: UserOperation;
  }) => Promise<{
    callGasLimit: Hex;
    verificationGasLimit: Hex;
    preVerificationGas: Hex;
  }>;
  getUserOpReceipt: (options: {
    bundlerUrl: string;
    userOpHash: Hex;
  }) => Promise<unknown>;
  getGasFees: () => Promise<{
    maxFeePerGas: Hex;
    maxPriorityFeePerGas: Hex;
  }>;
  configureBundler: (config: {
    bundlerUrl: string;
    chainId: number;
  }) => Promise<void>;
  httpGetJson: (url: string) => Promise<unknown>;
  getUserOperationGasPrice: () => Promise<{
    fast: { maxFeePerGas: Hex; maxPriorityFeePerGas: Hex };
  }>;
  sponsorUserOp: (options: {
    bundlerUrl: string;
    entryPoint: Hex;
    userOp: UserOperation;
    context?: Record<string, unknown>;
  }) => Promise<{
    paymaster: Address;
    paymasterData: Hex;
    paymasterVerificationGasLimit: Hex;
    paymasterPostOpGasLimit: Hex;
    callGasLimit: Hex;
    verificationGasLimit: Hex;
    preVerificationGas: Hex;
  }>;
};
 
type DelegationFacet = {
  createDelegation: (
    options: CreateDelegationOptions & { delegator: Address },
  ) => Promise<Delegation>;
  prepareDelegationForSigning: (id: string) => Promise<Eip712TypedData>;
  storeSigned: (id: string, signature: Hex) => Promise<void>;
  receiveDelegation: (delegation: Delegation) => Promise<void>;
  findDelegationForAction: (
    action: Action,
    chainId?: number,
    currentTime?: number,
  ) => Promise<Delegation | undefined>;
  explainActionMatch: (
    action: Action,
    chainId?: number,
    currentTime?: number,
  ) => Promise<{ delegationId: string; result: DelegationMatchResult }[]>;
  getDelegation: (id: string) => Promise<Delegation>;
  listDelegations: () => Promise<Delegation[]>;
  revokeDelegation: (id: string) => Promise<void>;
};
 
type PeerWalletFacet = {
  getAccounts: () => Promise<Address[]>;
  getCapabilities: () => Promise<WalletCapabilities>;
  handleSigningRequest: (request: {
    type: string;
    tx?: TransactionRequest;
    data?: Eip712TypedData;
    message?: string;
    account?: Address;
  }) => Promise<Hex>;
  registerAwayWallet: (awayRef: unknown) => Promise<void>;
  registerDelegateAddress: (address: string) => Promise<void>;
  handleRedemptionRequest: (request: {
    type: 'single' | 'batch';
    delegations: Delegation[];
    execution?: Execution;
    executions?: Execution[];
    maxFeePerGas?: Hex;
    maxPriorityFeePerGas?: Hex;
  }) => Promise<Hex>;
};
 
type ExternalSignerFacet = {
  getAccounts: () => Promise<Address[]>;
  signTypedData: (data: Eip712TypedData, from: Address) => Promise<Hex>;
  signMessage: (message: string, from: Address) => Promise<Hex>;
  signTransaction: (tx: TransactionRequest) => Promise<Hex>;
};
 
type AwayWalletFacet = {
  receiveDelegation: (delegation: Delegation) => Promise<void>;
  revokeDelegationLocally: (id: string) => Promise<void>;
};
 
type OcapURLIssuerFacet = {
  issue: (target: unknown) => Promise<string>;
};
 
type OcapURLRedemptionFacet = {
  redeem: (url: string) => Promise<unknown>;
};
 
/**
 * Build the root object for the coordinator vat (bootstrap vat).
 *
 * The coordinator orchestrates signing strategy resolution, delegation
 * management, and peer wallet communication. It is the public API of
 * the wallet subcluster.
 *
 * @param vatPowers - Special powers granted to this vat.
 * @param _parameters - Initialization parameters.
 * @param baggage - Root of vat's persistent state.
 * @returns The root object for the coordinator vat.
 */
export function buildRootObject(
  vatPowers: VatPowers,
  _parameters: unknown,
  baggage: Baggage,
): object {
  const logger = (vatPowers.logger ?? new Logger()).subLogger({
    tags: ['coordinator-vat'],
  });
 
  // References to other vats (set during bootstrap)
  let keyringVat: KeyringFacet | undefined;
  let providerVat: ProviderFacet | undefined;
  let delegationVat: DelegationFacet | undefined;
  let issuerService: OcapURLIssuerFacet | undefined;
  let redemptionService: OcapURLRedemptionFacet | undefined;
 
  // Peer wallet reference (set via connectToPeer)
  let peerWallet: PeerWalletFacet | undefined;
 
  // External signer reference (e.g. MetaMask).
  // Note: external signers are transient — they must be reconnected after
  // kernel restart via connectExternalSigner(). The baggage entry tracks
  // the reference but it may be stale after resuscitation.
  let externalSigner: ExternalSignerFacet | undefined;
 
  // Bundler configuration for ERC-4337 UserOps
  let bundlerConfig:
    | {
        bundlerUrl: string;
        entryPoint: Hex;
        chainId: number;
        usePaymaster?: boolean;
        sponsorshipPolicyId?: string;
      }
    | undefined;
 
  // Smart account configuration (persisted in baggage)
  let smartAccountConfig: SmartAccountConfig | undefined;
 
  // Away wallet reference (set via registerAwayWallet from the away device).
  // Note: like externalSigner, this is a transient CapTP reference — it will
  // be stale after kernel restart. The baggage entry is restored but the
  // remote endpoint may be gone. pushDelegationToAway() will fail at call
  // time if the reference is dead.
  let awayWallet: AwayWalletFacet | undefined;
 
  // Delegate address sent by the away device for delegation creation
  let pendingDelegateAddress: Address | undefined;
 
  // Cached peer (home) accounts for offline autonomy
  let cachedPeerAccounts: Address[] = [];
  // Cached peer signing mode for offline autonomy
  let cachedPeerSigningMode: string | undefined;
 
  /**
   * Typed helper for restoring values from baggage (resuscitation).
   *
   * @param key - The baggage key to look up.
   * @returns The stored value cast to T, or undefined if not present.
   */
  function restoreFromBaggage<T>(key: string): T | undefined {
    return baggage.has(key) ? (baggage.get(key) as T) : undefined;
  }
 
  // Restore vat references from baggage if available (resuscitation)
  keyringVat = restoreFromBaggage<KeyringFacet>('keyringVat');
  providerVat = restoreFromBaggage<ProviderFacet>('providerVat');
  delegationVat = restoreFromBaggage<DelegationFacet>('delegationVat');
  peerWallet = restoreFromBaggage<PeerWalletFacet>('peerWallet');
  externalSigner = restoreFromBaggage<ExternalSignerFacet>('externalSigner');
  bundlerConfig = restoreFromBaggage<typeof bundlerConfig>('bundlerConfig');
  smartAccountConfig =
    restoreFromBaggage<SmartAccountConfig>('smartAccountConfig');
  awayWallet = restoreFromBaggage<AwayWalletFacet>('awayWallet');
  pendingDelegateAddress = restoreFromBaggage<Address>(
    'pendingDelegateAddress',
  );
  cachedPeerAccounts =
    restoreFromBaggage<Address[]>('cachedPeerAccounts') ?? [];
  cachedPeerSigningMode = restoreFromBaggage<string>('cachedPeerSigningMode');
 
  /** Chain ID from the last `configureProvider` call (avoids RPC on every send). */
  let cachedProviderChainId: number | undefined = restoreFromBaggage<number>(
    'cachedProviderChainId',
  );
 
  /**
   * Resolve the wallet chain ID for delegation matching, SDK addresses, and txs.
   *
   * Order: bundler config → cached provider config → `eth_chainId` RPC.
   *
   * @returns The resolved chain ID.
   */
  async function resolveChainId(): Promise<number> {
    if (bundlerConfig?.chainId !== undefined) {
      return bundlerConfig.chainId;
    }
    if (cachedProviderChainId !== undefined) {
      return cachedProviderChainId;
    }
    Iif (!providerVat) {
      throw new Error(
        'Provider not configured — call configureProvider() first',
      );
    }
    return E(providerVat).getChainId();
  }
 
  /**
   * Whether smart-account operations for this sender should use Infura-style
   * raw transactions (stateless 7702) instead of ERC-4337 UserOps.
   *
   * @param sender - Smart account address (same as EOA for stateless 7702).
   * @returns True when direct EIP-1559 submission should be used.
   */
  async function useDirect7702Tx(sender: Address): Promise<boolean> {
    if (smartAccountConfig?.implementation === 'stateless7702') {
      Iif (
        smartAccountConfig.address !== undefined &&
        smartAccountConfig.address.toLowerCase() !== sender.toLowerCase()
      ) {
        // Config points at a different account — fall through to lazy check.
      } else {
        return true;
      }
    }
    if (smartAccountConfig?.implementation === 'hybrid') {
      return false;
    }
    Iif (!providerVat) {
      throw new Error(
        'Cannot determine account type: provider not configured and ' +
          'smartAccountConfig is absent. Call configureProvider() first.',
      );
    }
    const code = (await E(providerVat).request('eth_getCode', [
      sender,
      'latest',
    ])) as string;
    const chainId = await resolveChainId();
    return isEip7702Delegated(code, chainId);
  }
 
  /**
   * Sign and broadcast a self-call tx with SDK-encoded DeleGator calldata
   * (7702 EOA). Returns the transaction hash immediately after broadcast.
   *
   * @param options - Direct submission options.
   * @param options.sender - Upgraded EOA / smart account address.
   * @param options.callData - SDK-wrapped `execute` calldata.
   * @param options.maxFeePerGas - Optional max fee per gas override.
   * @param options.maxPriorityFeePerGas - Optional priority fee override.
   * @returns The transaction hash from `eth_sendRawTransaction`.
   */
  async function buildAndSubmitDirect7702Tx(options: {
    sender: Address;
    callData: Hex;
    maxFeePerGas?: Hex;
    maxPriorityFeePerGas?: Hex;
  }): Promise<Hex> {
    Iif (!providerVat) {
      throw new Error('Provider vat not available');
    }
    const chainId = await resolveChainId();
    let { maxFeePerGas, maxPriorityFeePerGas } = options;
    if (!maxFeePerGas || !maxPriorityFeePerGas) {
      const fees = await E(providerVat).getGasFees();
      maxFeePerGas = maxFeePerGas ?? fees.maxFeePerGas;
      maxPriorityFeePerGas = maxPriorityFeePerGas ?? fees.maxPriorityFeePerGas;
    }
    const nonce = await E(providerVat).getNonce(options.sender);
    const estimatedGas = validateGasEstimate(
      await E(providerVat).request('eth_estimateGas', [
        {
          from: options.sender,
          to: options.sender,
          data: options.callData,
        },
      ]),
    );
    const gasLimit = applyGasBuffer(estimatedGas, 10);
    const filledTx: TransactionRequest = {
      from: options.sender,
      to: options.sender,
      chainId,
      nonce,
      maxFeePerGas,
      maxPriorityFeePerGas,
      gasLimit,
      data: options.callData,
      value: '0x0' as Hex,
    };
    const signedTx = await resolveTransactionSigning(filledTx);
    return E(providerVat).broadcastTransaction(signedTx);
  }
 
  /**
   * Poll until an EIP-1559 transaction is mined or timeout.
   *
   * @param options - Polling options.
   * @param options.txHash - Transaction hash to wait for.
   * @param options.pollIntervalMs - Delay between RPC polls in milliseconds.
   * @param options.timeoutMs - Maximum time to wait in milliseconds.
   * @returns Whether the mined transaction succeeded (`status` 0x1).
   */
  async function pollTransactionReceipt(options: {
    txHash: Hex;
    pollIntervalMs?: number;
    timeoutMs?: number;
  }): Promise<{ success: boolean }> {
    if (!providerVat) {
      throw new Error('Provider not configured');
    }
    Iif (
      typeof globalThis.Date?.now !== 'function' ||
      typeof globalThis.setTimeout !== 'function'
    ) {
      throw new Error(
        'Transaction receipt polling requires Date.now and setTimeout',
      );
    }
    const interval = options.pollIntervalMs ?? 2000;
    const timeout = options.timeoutMs ?? 120_000;
    const start = Date.now();
    while (Date.now() - start < timeout) {
      let receipt: { status?: string | number } | null = null;
      try {
        receipt = (await E(providerVat).request('eth_getTransactionReceipt', [
          options.txHash,
        ])) as { status?: string | number } | null;
      } catch (error) {
        // Transient RPC errors (network hiccups, rate limits) should not
        // abort polling — the tx was already broadcast and may still mine.
        logger.warn(
          `RPC error polling receipt for ${options.txHash}, will retry`,
          error,
        );
        await new Promise((resolve) => setTimeout(resolve, interval));
        continue;
      }
      if (receipt) {
        // Normalize: some providers return status as a number (1) rather
        // than the standard hex string ('0x1'). EIP-1559 receipts must have
        // a status field; a missing one likely indicates a malformed response.
        const { status } = receipt;
        if (status === undefined || status === null) {
          logger.warn(
            `Receipt for ${options.txHash} has no status field — assuming success`,
          );
          return harden({ success: true });
        }
        const normalizedStatus =
          typeof status === 'number' ? `0x${status.toString(16)}` : status;
        return harden({ success: normalizedStatus === '0x1' });
      }
      await new Promise((resolve) => setTimeout(resolve, interval));
    }
    throw new Error(
      `Transaction ${options.txHash} not mined after ${String(timeout)}ms`,
    );
  }
 
  /**
   * Check if an address belongs to the cached peer (home) accounts.
   *
   * @param address - The Ethereum address to check.
   * @returns True if the address is a cached peer account.
   */
  function isPeerAccount(address: Address): boolean {
    return cachedPeerAccounts.some(
      (a) => a.toLowerCase() === address.toLowerCase(),
    );
  }
 
  /**
   * Build a human-readable error message from delegation match results.
   *
   * @param matchResults - The match results from explainActionMatch.
   * @param context - A message prefix describing the context.
   * @returns A formatted error message string.
   */
  function buildDelegationMismatchError(
    matchResults: { delegationId: string; result: DelegationMatchResult }[],
    context: string,
  ): string {
    const reasons = matchResults
      .filter((entry) => !entry.result.matches)
      .map(
        (entry) =>
          `delegation ${entry.delegationId.slice(0, 10)}…: ${entry.result.reason ?? 'unknown'} (caveat: ${entry.result.failedCaveat ?? 'n/a'})`,
      );
    return `${context}. ${reasons.length} delegation(s) checked: ${reasons.join('; ')}`;
  }
 
  /**
   * Resolve the EOA owner address from the keyring or external signer.
   *
   * @returns The first available EOA address.
   * @throws If no accounts are available.
   */
  async function resolveOwnerAddress(): Promise<Address> {
    if (keyringVat) {
      const accounts = await E(keyringVat).getAccounts();
      if (accounts.length > 0) {
        return accounts[0] as Address;
      }
    }
    Iif (externalSigner) {
      const accounts = await E(externalSigner).getAccounts();
      if (accounts.length > 0) {
        return accounts[0] as Address;
      }
    }
    throw new Error('No accounts available');
  }
 
  const PEER_TIMEOUT_MS = 5000;
 
  /**
   * Race a promise against a timeout.
   *
   * @param promise - The promise to race.
   * @param ms - Timeout in milliseconds.
   * @returns The resolved value of the promise.
   */
  async function raceWithTimeout<T>(
    promise: Promise<T>,
    ms: number,
  ): Promise<T> {
    Iif (typeof globalThis.setTimeout !== 'function') {
      return promise;
    }
    return new Promise<T>((resolve, reject) => {
      const timer = globalThis.setTimeout(() => {
        reject(new Error(`Peer call timed out after ${String(ms)}ms`));
      }, ms);
      // eslint-disable-next-line promise/catch-or-return
      promise.then(
        (value) => {
          globalThis.clearTimeout(timer);
          resolve(value);
          return undefined;
        },
        (error: unknown) => {
          globalThis.clearTimeout(timer);
          reject(error instanceof Error ? error : new Error(String(error)));
          return undefined;
        },
      );
    });
  }
 
  /**
   * Persist a baggage key-value pair, handling both init and update.
   *
   * @param key - The baggage key.
   * @param value - The value to persist.
   */
  function persistBaggage(key: string, value: unknown): void {
    if (baggage.has(key)) {
      baggage.set(key, value);
    } else {
      baggage.init(key, value);
    }
  }
 
  /**
   * Build a peer signing request for typed data.
   *
   * @param data - The typed data to sign.
   * @param account - Optional account to sign with.
   * @returns The peer signing request payload.
   */
  function makeTypedDataSigningRequest(
    data: Eip712TypedData,
    account?: Address,
  ): { type: 'typedData'; data: Eip712TypedData; account?: Address } {
    return account
      ? { type: 'typedData', data, account }
      : { type: 'typedData', data };
  }
 
  /**
   * Resolve the signing strategy for typed data.
   * Priority: keyring → external signer → peer wallet → error
   *
   * @param data - The EIP-712 typed data to sign.
   * @param from - Optional sender address.
   * @returns The signature as a hex string.
   */
  async function resolveTypedDataSigning(
    data: Eip712TypedData,
    from?: Address,
  ): Promise<Hex> {
    // If the requested address belongs to the home device, route to peer
    if (from && isPeerAccount(from)) {
      if (peerWallet) {
        return E(peerWallet).handleSigningRequest(
          makeTypedDataSigningRequest(data, from),
        );
      }
      throw new Error(
        `Cannot sign typed data as ${from}: home device is offline and this address requires home signing authority`,
      );
    }
 
    if (keyringVat) {
      const hasKeys = await E(keyringVat).hasKeys();
      Eif (hasKeys) {
        return E(keyringVat).signTypedData(data, from);
      }
    }
 
    if (externalSigner) {
      const accounts = await E(externalSigner).getAccounts();
      Eif (accounts.length > 0) {
        return E(externalSigner).signTypedData(data, from ?? accounts[0]);
      }
    }
 
    if (peerWallet) {
      return E(peerWallet).handleSigningRequest(
        makeTypedDataSigningRequest(data, from),
      );
    }
 
    throw new Error('No authority to sign typed data');
  }
 
  /**
   * Resolve the signing strategy for a personal message.
   * Priority: keyring → external signer → peer wallet → error
   *
   * @param message - The message to sign.
   * @param from - Optional sender address.
   * @returns The signature as a hex string.
   */
  async function resolveMessageSigning(
    message: string,
    from?: Address,
  ): Promise<Hex> {
    // If the requested address belongs to the home device, route to peer
    if (from && isPeerAccount(from)) {
      if (peerWallet) {
        return E(peerWallet).handleSigningRequest({
          type: 'message',
          message,
          account: from,
        });
      }
      throw new Error(
        `Cannot sign message as ${from}: home device is offline and this address requires home signing authority`,
      );
    }
 
    if (keyringVat) {
      const hasKeys = await E(keyringVat).hasKeys();
      Eif (hasKeys) {
        return E(keyringVat).signMessage(message, from);
      }
    }
 
    if (externalSigner) {
      const accounts = await E(externalSigner).getAccounts();
      Eif (accounts.length > 0) {
        return E(externalSigner).signMessage(message, from ?? accounts[0]);
      }
    }
 
    if (peerWallet) {
      return E(peerWallet).handleSigningRequest({
        type: 'message',
        message,
        ...(from ? { account: from } : {}),
      });
    }
 
    throw new Error('No authority to sign message');
  }
 
  /**
   * Resolve the signing strategy for a transaction.
   * Priority: local key → external signer → reject
   *
   * @param tx - The transaction request to sign.
   * @returns The signed transaction as a hex string.
   */
  async function resolveTransactionSigning(
    tx: TransactionRequest,
  ): Promise<Hex> {
    // Strategy 1: Check if local keyring owns this account
    if (keyringVat) {
      const accounts = await E(keyringVat).getAccounts();
      if (accounts.includes(tx.from.toLowerCase() as Address)) {
        return E(keyringVat).signTransaction(tx);
      }
    }
 
    // Strategy 2: Check if external signer can handle it
    if (externalSigner) {
      return E(externalSigner).signTransaction({
        ...tx,
        from: tx.from.toLowerCase() as Address,
      });
    }
 
    throw new Error('No authority to sign this transaction');
  }
 
  /**
   * Build, sign, and submit a UserOp. Shared pipeline for both delegation
   * redemption and on-chain delegation revocation.
   *
   * @param options - Pipeline options.
   * @param options.sender - The smart account address that sends the UserOp.
   * @param options.callData - The encoded callData for the UserOp.
   * @param options.maxFeePerGas - Optional max fee per gas override.
   * @param options.maxPriorityFeePerGas - Optional max priority fee per gas override.
   * @returns The UserOp hash from the bundler.
   */
  async function buildAndSubmitUserOp(options: {
    sender: Address;
    callData: Hex;
    maxFeePerGas?: Hex;
    maxPriorityFeePerGas?: Hex;
  }): Promise<Hex> {
    Iif (!providerVat) {
      throw new Error('Provider vat not available');
    }
    Iif (!bundlerConfig) {
      throw new Error('Bundler not configured');
    }
 
    const { sender, callData } = options;
 
    // Get gas prices from the bundler (pimlico_getUserOperationGasPrice)
    // which returns prices the bundler will accept, avoiding rejection
    // due to stale node-reported fees.
    let { maxFeePerGas, maxPriorityFeePerGas } = options;
    if (!maxFeePerGas || !maxPriorityFeePerGas) {
      const gasPrice = await E(providerVat).getUserOperationGasPrice();
      maxFeePerGas = maxFeePerGas ?? gasPrice.fast.maxFeePerGas;
      maxPriorityFeePerGas =
        maxPriorityFeePerGas ?? gasPrice.fast.maxPriorityFeePerGas;
    }
 
    // Get nonce from EntryPoint contract (ERC-4337 nonce)
    const nonceHex = await E(providerVat).getEntryPointNonce({
      entryPoint: bundlerConfig.entryPoint,
      sender,
    });
 
    // Detect signing mode: check smartAccountConfig first, then fall back
    // to on-chain code inspection. This ensures the correct signing mode
    // even if smartAccountConfig is lost from baggage.
    let isStateless7702 =
      smartAccountConfig?.implementation === 'stateless7702';
 
    // Always fetch on-chain code — needed for both factory detection and
    // signing mode fallback.
    const onChainCode = (await E(providerVat).request('eth_getCode', [
      sender,
      'latest',
    ])) as string | undefined;
 
    Iif (typeof onChainCode !== 'string') {
      throw new Error(
        `eth_getCode for ${sender} returned ${String(onChainCode)}; check provider configuration`,
      );
    }
 
    // Fall back to on-chain code detection for 7702 accounts that weren't
    // configured via smartAccountConfig (e.g., restored from stale baggage).
    // Any EIP-7702 designator prefix (0xef0100) indicates a Stateless7702
    // DeleGator, which uses a different EIP-712 domain name for signing.
    Iif (!isStateless7702 && onChainCode.toLowerCase().startsWith('0xef0100')) {
      isStateless7702 = true;
    }
 
    // Check on-chain whether the smart account is deployed (eth_getCode).
    // This avoids relying on a cached flag that could be stale if the
    // deployment UserOp failed on-chain.
    let includeFactory = false;
    if (
      !isStateless7702 &&
      smartAccountConfig?.factory &&
      smartAccountConfig.factoryData
    ) {
      includeFactory = onChainCode === '0x' || onChainCode === '0x0';
 
      Iif (!includeFactory && smartAccountConfig.deployed === false) {
        smartAccountConfig = harden({
          ...smartAccountConfig,
          deployed: true,
        });
        persistBaggage('smartAccountConfig', smartAccountConfig);
      }
    }
 
    // Build unsigned UserOp with a dummy 65-byte signature so that the
    // smart account's validateUserOp can parse the ECDSA signature during
    // bundler/paymaster simulation. An empty signature (0x) causes revert.
    const unsignedUserOp: UserOperation = {
      sender,
      nonce: nonceHex,
      callData,
      callGasLimit: '0x50000' as Hex,
      verificationGasLimit: '0x60000' as Hex,
      preVerificationGas: '0x10000' as Hex,
      maxFeePerGas,
      maxPriorityFeePerGas,
      signature:
        '0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c' as Hex,
      ...(includeFactory && smartAccountConfig
        ? {
            factory: smartAccountConfig.factory as Hex,
            factoryData: smartAccountConfig.factoryData as Hex,
          }
        : {}),
    };
 
    let userOpWithGas: UserOperation;
 
    if (bundlerConfig.usePaymaster) {
      // Use paymaster sponsorship instead of gas estimation
      const sponsorContext: Record<string, unknown> = {};
      if (bundlerConfig.sponsorshipPolicyId) {
        sponsorContext.sponsorshipPolicyId = bundlerConfig.sponsorshipPolicyId;
      }
 
      const sponsorResult = await E(providerVat).sponsorUserOp({
        bundlerUrl: bundlerConfig.bundlerUrl,
        entryPoint: bundlerConfig.entryPoint,
        userOp: unsignedUserOp,
        context: sponsorContext,
      });
 
      userOpWithGas = {
        ...unsignedUserOp,
        paymaster: sponsorResult.paymaster,
        paymasterData: sponsorResult.paymasterData,
        paymasterVerificationGasLimit:
          sponsorResult.paymasterVerificationGasLimit,
        paymasterPostOpGasLimit: sponsorResult.paymasterPostOpGasLimit,
        callGasLimit: sponsorResult.callGasLimit,
        verificationGasLimit: sponsorResult.verificationGasLimit,
        preVerificationGas: sponsorResult.preVerificationGas,
      };
    } else {
      // Estimate gas via bundler
      const gasEstimate = await E(providerVat).estimateUserOpGas({
        bundlerUrl: bundlerConfig.bundlerUrl,
        entryPoint: bundlerConfig.entryPoint,
        userOp: unsignedUserOp,
      });
 
      userOpWithGas = {
        ...unsignedUserOp,
        callGasLimit: applyGasBuffer(gasEstimate.callGasLimit, 10),
        verificationGasLimit: applyGasBuffer(
          gasEstimate.verificationGasLimit,
          10,
        ),
        preVerificationGas: gasEstimate.preVerificationGas,
      };
    }
 
    // Sign the UserOp via EIP-712 typed data. Both Hybrid and Stateless7702
    // DeleGators validate signatures using EIP-712 — the only difference is
    // the domain name.
    const userOpTypedData = prepareUserOpTypedData({
      userOp: userOpWithGas,
      entryPoint: bundlerConfig.entryPoint,
      chainId: bundlerConfig.chainId,
      smartAccountAddress: sender,
      ...(isStateless7702
        ? { smartAccountName: 'EIP7702StatelessDeleGator' }
        : {}),
    });
    const signature: Hex = await resolveTypedDataSigning(userOpTypedData);
 
    // Attach signature and submit
    const signedUserOp: UserOperation = {
      ...userOpWithGas,
      signature,
    };
 
    return E(providerVat).submitUserOp({
      bundlerUrl: bundlerConfig.bundlerUrl,
      entryPoint: bundlerConfig.entryPoint,
      userOp: signedUserOp,
    });
  }
 
  /**
   * Build, sign, and submit a UserOp that redeems one or more delegations.
   *
   * @param options - UserOp pipeline options.
   * @param options.delegations - The delegation chain (leaf to root).
   * @param options.execution - The execution to perform.
   * @param options.maxFeePerGas - Max fee per gas.
   * @param options.maxPriorityFeePerGas - Max priority fee per gas.
   * @returns The UserOp hash from the bundler.
   */
  async function submitDelegationUserOp(options: {
    delegations: Delegation[];
    execution: Execution;
    maxFeePerGas?: Hex | undefined;
    maxPriorityFeePerGas?: Hex | undefined;
  }): Promise<Hex> {
    // Check the relay path first — it forwards raw delegations/execution to
    // the home wallet and does not need local chain ID or SDK calldata.
    if (!bundlerConfig && !smartAccountConfig) {
      if (peerWallet) {
        try {
          return await E(peerWallet).handleRedemptionRequest({
            type: 'single',
            delegations: options.delegations,
            execution: options.execution,
            maxFeePerGas: options.maxFeePerGas,
            maxPriorityFeePerGas: options.maxPriorityFeePerGas,
          });
        } catch (relayError) {
          const detail =
            relayError instanceof Error
              ? relayError.message
              : String(relayError);
          throw new Error(
            `Failed to relay delegation redemption to home wallet: ${detail}`,
            { cause: relayError },
          );
        }
      }
      throw new Error(
        'Bundler not configured and no peer wallet available for relay',
      );
    }
 
    const sender =
      smartAccountConfig?.address ?? options.delegations[0].delegate;
 
    const chainId = await resolveChainId();
    const sdkCallData = buildSdkRedeemCallData({
      delegations: options.delegations,
      execution: options.execution,
      chainId,
    });
 
    if (await useDirect7702Tx(sender)) {
      return buildAndSubmitDirect7702Tx({
        sender,
        callData: sdkCallData,
        maxFeePerGas: options.maxFeePerGas,
        maxPriorityFeePerGas: options.maxPriorityFeePerGas,
      });
    }
 
    Iif (!bundlerConfig) {
      throw new Error(
        'Bundler not configured (required for hybrid smart account redemption)',
      );
    }
 
    const userOpOptions: {
      sender: Address;
      callData: Hex;
      maxFeePerGas?: Hex;
      maxPriorityFeePerGas?: Hex;
    } = { sender, callData: sdkCallData };
    Eif (options.maxFeePerGas) {
      userOpOptions.maxFeePerGas = options.maxFeePerGas;
    }
    Eif (options.maxPriorityFeePerGas) {
      userOpOptions.maxPriorityFeePerGas = options.maxPriorityFeePerGas;
    }
 
    return buildAndSubmitUserOp(userOpOptions);
  }
 
  /**
   * Submit a batch of executions via delegation redemption in a single UserOp.
   * Uses `ExecutionMode.BatchDefault` so all executions share the same
   * delegation chain.
   *
   * @param options - Batch delegation options.
   * @param options.delegations - The delegation chain (leaf to root).
   * @param options.executions - The executions to batch.
   * @returns The UserOp hash from the bundler.
   */
  async function submitBatchDelegationUserOp(options: {
    delegations: Delegation[];
    executions: Execution[];
  }): Promise<Hex> {
    // Check the relay path first — it forwards raw delegations/executions to
    // the home wallet and does not need local chain ID or SDK calldata.
    if (!bundlerConfig && !smartAccountConfig) {
      Eif (peerWallet) {
        try {
          return await E(peerWallet).handleRedemptionRequest({
            type: 'batch',
            delegations: options.delegations,
            executions: options.executions,
          });
        } catch (relayError) {
          const detail =
            relayError instanceof Error
              ? relayError.message
              : String(relayError);
          throw new Error(
            `Failed to relay batch delegation redemption to home wallet: ${detail}`,
            { cause: relayError },
          );
        }
      }
      throw new Error(
        'Bundler not configured and no peer wallet available for relay',
      );
    }
 
    const sender =
      smartAccountConfig?.address ?? options.delegations[0]?.delegate;
    Iif (!sender) {
      throw new Error('No sender address available for batch delegation');
    }
 
    const chainId = await resolveChainId();
    const sdkCallData = buildSdkBatchRedeemCallData({
      delegations: options.delegations,
      executions: options.executions,
      chainId,
    });
 
    if (await useDirect7702Tx(sender)) {
      return buildAndSubmitDirect7702Tx({ sender, callData: sdkCallData });
    }
 
    Iif (!bundlerConfig) {
      throw new Error(
        'Bundler not configured (required for hybrid smart account batch redemption)',
      );
    }
 
    return buildAndSubmitUserOp({ sender, callData: sdkCallData });
  }
 
  /**
   * Submit a transaction that calls `DelegationManager.disableDelegation` to
   * revoke a delegation on-chain — either via a direct EIP-1559 tx (7702) or
   * an ERC-4337 UserOp (hybrid).
   *
   * @param delegation - The delegation to disable.
   * @returns The hash and whether the direct 7702 path was used.
   */
  async function submitDisableUserOp(
    delegation: Delegation,
  ): Promise<{ hash: Hex; isDirect: boolean }> {
    const sender = smartAccountConfig?.address ?? delegation.delegator;
 
    const chainId = await resolveChainId();
    const disableCallData = buildSdkDisableCallData({
      delegation,
      chainId,
    });
 
    try {
      const isDirect = await useDirect7702Tx(sender);
      if (isDirect) {
        const hash = await buildAndSubmitDirect7702Tx({
          sender,
          callData: disableCallData,
        });
        return { hash, isDirect: true };
      }
      if (!bundlerConfig) {
        throw new Error(
          'Bundler not configured (required for hybrid on-chain revocation)',
        );
      }
      const hash = await buildAndSubmitUserOp({
        sender,
        callData: disableCallData,
      });
      return { hash, isDirect: false };
    } catch (error) {
      throw new Error(
        `Failed to submit on-chain revocation for delegator ${delegation.delegator}`,
        { cause: error },
      );
    }
  }
 
  /**
   * Create a Stateless7702 smart account by signing and broadcasting
   * an EIP-7702 authorization transaction. The user's EOA address
   * becomes the smart account — no factory deployment or funding needed.
   *
   * @param chainId - The chain ID.
   * @returns The smart account configuration.
   */
  async function createStateless7702SmartAccount(
    chainId: number,
  ): Promise<SmartAccountConfig> {
    if (!providerVat) {
      throw new Error('Provider vat required for EIP-7702 authorization');
    }
 
    // Resolve EOA address: keyring first, then external signer.
    let eoaAddress: Address;
    try {
      eoaAddress = await resolveOwnerAddress();
    } catch {
      throw new Error('No accounts available for EIP-7702 smart account');
    }
 
    // Check if already set up (persisted from a prior call)
    Iif (
      smartAccountConfig?.implementation === 'stateless7702' &&
      smartAccountConfig.address === eoaAddress
    ) {
      return smartAccountConfig;
    }
 
    // Best-effort on-chain check — works on providers that support
    // EIP-7702 designator codes via eth_getCode (not all do, e.g. Infura).
    const code = (await E(providerVat).request('eth_getCode', [
      eoaAddress,
      'latest',
    ])) as string;
 
    if (isEip7702Delegated(code, chainId)) {
      // eslint-disable-next-line require-atomic-updates
      smartAccountConfig = harden({
        implementation: 'stateless7702' as const,
        address: eoaAddress,
        deployed: true,
      });
      persistBaggage('smartAccountConfig', smartAccountConfig);
      return smartAccountConfig;
    }
 
    // EIP-7702 promotion requires signAuthorization which is only
    // available on the local keyring (not supported by external signers).
    Iif (!keyringVat || !(await E(keyringVat).hasKeys())) {
      throw new Error(
        'EIP-7702 promotion requires a local keyring with initialized keys. ' +
          'Use implementation: "hybrid", or promote the account through MetaMask first.',
      );
    }
 
    // Sign EIP-7702 authorization
    const env = resolveEnvironment(chainId);
    const implAddress = (
      env.implementations as Record<string, string | undefined>
    ).EIP7702StatelessDeleGatorImpl;
    Iif (!implAddress) {
      throw new Error(
        `EIP7702StatelessDeleGatorImpl not found in environment for chain ${String(chainId)}`,
      );
    }
 
    // Fetch the EOA nonce, gas fees, and sign the authorization in parallel.
    // EIP-7702 self-execution: the tx sender is the same EOA as the
    // authorization authority. The sender's nonce is incremented by the tx
    // validity check BEFORE authorizations are processed, so the
    // authorization nonce must be txNonce + 1.
    const EIP7702_FALLBACK_GAS = '0x19000' as Hex; // 102400
    // Minimum plausible gas for an EIP-7702 auth tx (~40k). Estimates
    // below this likely indicate the RPC ignored the authorizationList
    // and returned a plain-transfer estimate (21000).
    const EIP7702_MIN_GAS = 0xa000n; // 40960
    const [nonce, fees, estimatedAuthGas] = await Promise.all([
      E(providerVat).getNonce(eoaAddress),
      E(providerVat).getGasFees(),
      (
        E(providerVat).request('eth_estimateGas', [
          {
            from: eoaAddress,
            to: eoaAddress,
            authorizationList: [{ address: implAddress, chainId }],
          },
        ]) as Promise<Hex>
      ).then(
        (result) => {
          if (typeof result !== 'string' || !result.startsWith('0x')) {
            logger.warn(
              `eth_estimateGas returned non-hex for EIP-7702 auth: ${String(result)}, using fallback`,
            );
            return EIP7702_FALLBACK_GAS;
          }
          Iif (BigInt(result) < EIP7702_MIN_GAS) {
            logger.warn(
              `eth_estimateGas returned suspiciously low value ${result} for EIP-7702 auth, using fallback`,
            );
            return EIP7702_FALLBACK_GAS;
          }
          return result;
        },
        (error: unknown) => {
          const message =
            error instanceof Error ? error.message : String(error);
          // Only fall back when the RPC doesn't support authorizationList param
          Eif (
            message.includes('-32602') ||
            message.includes('-32601') ||
            message.includes('not supported') ||
            message.includes('unknown field')
          ) {
            logger.warn(
              'eth_estimateGas does not support authorizationList, using fallback gas',
            );
            return EIP7702_FALLBACK_GAS;
          }
          throw new Error(
            `eth_estimateGas failed for EIP-7702 authorization: ${message}`,
          );
        },
      ),
    ]);
    const authGasLimit = applyGasBuffer(estimatedAuthGas, 20);
    const signedAuth = await E(keyringVat).signAuthorization({
      contractAddress: implAddress as Address,
      chainId,
      nonce: nonce + 1,
    });
 
    const signedTx = await E(keyringVat).signTransaction({
      from: eoaAddress,
      to: eoaAddress,
      chainId,
      nonce,
      maxFeePerGas: fees.maxFeePerGas,
      maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
      gasLimit: authGasLimit,
      authorizationList: [signedAuth],
    });
 
    const txHash = await E(providerVat).broadcastTransaction(signedTx);
 
    // Wait for the authorization tx to be mined. Some RPC providers (e.g.
    // Infura) don't expose EIP-7702 designator code via eth_getCode, so we
    // poll eth_getTransactionReceipt instead (status 0x1 = success).
    Iif (typeof globalThis.setTimeout !== 'function') {
      throw new Error(
        'EIP-7702 confirmation polling requires setTimeout ' +
          '(not available in SES compartments without timer endowments)',
      );
    }
    const maxAttempts = 45;
    for (let i = 0; i < maxAttempts; i++) {
      const receipt = (await E(providerVat).request(
        'eth_getTransactionReceipt',
        [txHash],
      )) as { status?: string } | null;
      if (receipt?.status === '0x1') {
        break;
      }
      Iif (receipt?.status === '0x0') {
        throw new Error(
          `EIP-7702 authorization tx ${txHash as string} reverted on-chain`,
        );
      }
      if (i === maxAttempts - 1) {
        throw new Error(
          `EIP-7702 authorization tx ${txHash} not confirmed after 90s`,
        );
      }
      await new Promise((resolve) => setTimeout(resolve, 2000));
    }
 
    // eslint-disable-next-line require-atomic-updates
    smartAccountConfig = harden({
      implementation: 'stateless7702' as const,
      address: eoaAddress,
      deployed: true,
    });
    persistBaggage('smartAccountConfig', smartAccountConfig);
    return smartAccountConfig;
  }
 
  const coordinator = makeDefaultExo('walletCoordinator', {
    // ------------------------------------------------------------------
    // Lifecycle
    // ------------------------------------------------------------------
 
    async bootstrap(vats: WalletVats, services: WalletServices): Promise<void> {
      keyringVat = vats.keyring as KeyringFacet | undefined;
      providerVat = vats.provider as ProviderFacet | undefined;
      delegationVat = vats.delegation as DelegationFacet | undefined;
      issuerService = services.ocapURLIssuerService as
        | OcapURLIssuerFacet
        | undefined;
      redemptionService = services.ocapURLRedemptionService as
        | OcapURLRedemptionFacet
        | undefined;
 
      if (keyringVat) {
        persistBaggage('keyringVat', keyringVat);
      }
      if (providerVat) {
        persistBaggage('providerVat', providerVat);
      }
      if (delegationVat) {
        persistBaggage('delegationVat', delegationVat);
      }
    },
 
    // ------------------------------------------------------------------
    // Wallet initialization
    // ------------------------------------------------------------------
 
    async initializeKeyring(options: {
      type: 'srp' | 'throwaway';
      mnemonic?: string;
      entropy?: Hex;
      password?: string;
      salt?: string;
    }): Promise<void> {
      Iif (!keyringVat) {
        throw new Error('Keyring vat not available');
      }
      const initOptions =
        options.type === 'srp'
          ? { type: 'srp' as const, mnemonic: options.mnemonic ?? '' }
          : { type: 'throwaway' as const, entropy: options.entropy };
 
      const password = options.type === 'srp' ? options.password : undefined;
      await E(keyringVat).initialize(initOptions, password, options.salt);
    },
 
    async unlockKeyring(password: string): Promise<void> {
      Iif (!keyringVat) {
        throw new Error('Keyring vat not available');
      }
      await E(keyringVat).unlock(password);
    },
 
    async isKeyringLocked(): Promise<boolean> {
      Iif (!keyringVat) {
        throw new Error('Keyring vat not available');
      }
      return E(keyringVat).isLocked();
    },
 
    async configureProvider(chainConfig: ChainConfig): Promise<void> {
      Iif (!providerVat) {
        throw new Error('Provider vat not available');
      }
 
      // Validate RPC URL (regex — URL constructor unavailable under SES)
      if (!/^https?:\/\/.+/u.test(chainConfig.rpcUrl)) {
        throw new Error(
          `Invalid RPC URL: "${chainConfig.rpcUrl}". Must be a valid HTTP(S) URL.`,
        );
      }
 
      if (!Number.isInteger(chainConfig.chainId) || chainConfig.chainId <= 0) {
        throw new Error(
          `Invalid chain ID: ${String(chainConfig.chainId)}. Must be a positive integer.`,
        );
      }
 
      await E(providerVat).configure(chainConfig);
 
      cachedProviderChainId = chainConfig.chainId;
      persistBaggage('cachedProviderChainId', cachedProviderChainId);
    },
 
    // ------------------------------------------------------------------
    // External signer & bundler configuration
    // ------------------------------------------------------------------
 
    async connectExternalSigner(signer: ExternalSignerFacet): Promise<void> {
      if (!signer || typeof signer !== 'object') {
        throw new Error('Invalid external signer: must be a non-null object');
      }
      externalSigner = signer;
      persistBaggage('externalSigner', externalSigner);
    },
 
    async configureBundler(config: {
      bundlerUrl: string;
      entryPoint?: Hex;
      chainId: number;
      usePaymaster?: boolean;
      sponsorshipPolicyId?: string;
    }): Promise<void> {
      // Validate bundler URL (regex — URL constructor unavailable under SES)
      if (!/^https?:\/\/.+/u.test(config.bundlerUrl)) {
        throw new Error(
          `Invalid bundler URL: "${config.bundlerUrl}". Must be a valid HTTP(S) URL.`,
        );
      }
 
      if (!Number.isInteger(config.chainId) || config.chainId <= 0) {
        throw new Error(
          `Invalid chain ID: ${String(config.chainId)}. Must be a positive integer.`,
        );
      }
 
      bundlerConfig = harden({
        bundlerUrl: config.bundlerUrl,
        entryPoint: config.entryPoint ?? ENTRY_POINT_V07,
        chainId: config.chainId,
        usePaymaster: config.usePaymaster,
        sponsorshipPolicyId: config.sponsorshipPolicyId,
      });
      persistBaggage('bundlerConfig', bundlerConfig);
 
      Iif (!providerVat) {
        throw new Error(
          'Provider vat not available. Call configureProvider() before configureBundler().',
        );
      }
      await E(providerVat).configureBundler({
        bundlerUrl: config.bundlerUrl,
        chainId: config.chainId,
      });
    },
 
    // ------------------------------------------------------------------
    // Smart account configuration
    // ------------------------------------------------------------------
 
    async createSmartAccount(config: {
      deploySalt?: Hex;
      chainId: number;
      address?: Address;
      implementation?: 'hybrid' | 'stateless7702';
    }): Promise<SmartAccountConfig> {
      const implementation = config.implementation ?? 'hybrid';
 
      if (implementation === 'stateless7702') {
        return createStateless7702SmartAccount(config.chainId);
      }
 
      // Hybrid path (existing logic)
      let { address } = config;
      let factory: Address | undefined;
      let factoryData: Hex | undefined;
      const deploySalt =
        config.deploySalt ??
        ('0x0000000000000000000000000000000000000000000000000000000000000001' as Hex);
 
      // Derive counterfactual address if not explicitly provided
      if (!address) {
        // Find the owner EOA from keyring or external signer
        let owner: Address;
        try {
          owner = await resolveOwnerAddress();
        } catch {
          throw new Error(
            'No owner account available to derive smart account address',
          );
        }
 
        const env = resolveEnvironment(config.chainId);
        factory = env.SimpleFactory;
 
        const derived = await computeSmartAccountAddress({
          owner,
          deploySalt,
          chainId: config.chainId,
        });
        address = derived.address;
        factoryData = derived.factoryData;
      }
 
      smartAccountConfig = harden({
        implementation: 'hybrid' as const,
        deploySalt,
        address,
        factory,
        factoryData,
        deployed: false,
      });
      persistBaggage('smartAccountConfig', smartAccountConfig);
      return smartAccountConfig;
    },
 
    async getSmartAccountAddress(): Promise<Address | undefined> {
      return smartAccountConfig?.address;
    },
 
    // ------------------------------------------------------------------
    // Public wallet API
    // ------------------------------------------------------------------
 
    async getAccounts(): Promise<Address[]> {
      // When a peer wallet is connected, try to fetch live accounts.
      // Fall back to cached peer accounts if the peer is unreachable.
      if (peerWallet) {
        try {
          const liveAccounts: Address[] = await raceWithTimeout(
            E(peerWallet).getAccounts(),
            PEER_TIMEOUT_MS,
          );
          // Refresh the cache on success
          cachedPeerAccounts = liveAccounts;
          persistBaggage('cachedPeerAccounts', cachedPeerAccounts);
          return liveAccounts;
        } catch (error) {
          logger.debug('peer getAccounts timed out, using cache', error);
          Eif (cachedPeerAccounts.length > 0) {
            return cachedPeerAccounts;
          }
          // No cache — fall through to local accounts
        }
      }
 
      // Return cached peer accounts if available (peer may have disconnected)
      if (cachedPeerAccounts.length > 0) {
        return cachedPeerAccounts;
      }
 
      const localAccounts: Address[] = keyringVat
        ? await E(keyringVat).getAccounts()
        : [];
 
      const extAccounts: Address[] = externalSigner
        ? await E(externalSigner).getAccounts()
        : [];
 
      // Deduplicate by lowercasing
      const seen = new Set(localAccounts.map((a) => a.toLowerCase()));
      const merged = [...localAccounts];
      for (const account of extAccounts) {
        if (!seen.has(account.toLowerCase())) {
          seen.add(account.toLowerCase());
          merged.push(account);
        }
      }
      return merged;
    },
 
    async signTransaction(tx: TransactionRequest): Promise<Hex> {
      return resolveTransactionSigning(tx);
    },
 
    async sendTransaction(tx: TransactionRequest): Promise<Hex> {
      Iif (!providerVat) {
        throw new Error('Provider not configured');
      }
 
      // Enforce delegations whenever the delegation vat exists (bundler optional
      // for 7702). Delegations are a security boundary — if we cannot resolve the
      // chain ID we must fail rather than silently bypassing caveat enforcement.
      if (delegationVat) {
        const walletChainId = await resolveChainId();
        const action: Action = {
          to: tx.to,
          value: tx.value,
          data: tx.data,
        };
        const now = Date.now();
        const delegation = await E(delegationVat).findDelegationForAction(
          action,
          walletChainId,
          now,
        );
 
        if (delegation) {
          Iif (delegation.status !== 'signed') {
            throw new Error(
              `Found delegation ${delegation.id} but its status is '${delegation.status}' (expected 'signed'). ` +
                `Direct signing is not used when a delegation exists, to avoid bypassing caveats.`,
            );
          }
          return submitDelegationUserOp({
            delegations: [delegation],
            execution: {
              target: tx.to,
              value: tx.value ?? ('0x0' as Hex),
              callData: tx.data ?? ('0x' as Hex),
            },
            maxFeePerGas: tx.maxFeePerGas,
            maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
          });
        }
 
        // No delegation matched — explain why before falling through
        const explanations = await E(delegationVat).explainActionMatch(
          action,
          walletChainId,
          now,
        );
        if (explanations.length > 0) {
          const valueDesc = tx.value
            ? `${BigInt(tx.value)} wei (${Number(BigInt(tx.value)) / 1e18} ETH)`
            : 'no value';
          throw new Error(
            buildDelegationMismatchError(
              explanations,
              `No delegation covers this transaction (to: ${tx.to}, value: ${valueDesc})`,
            ),
          );
        }
      }
 
      // Estimate missing gas fields for direct (non-delegation) sends
      const filledTx = { ...tx };
 
      filledTx.nonce ??= await E(providerVat).getNonce(filledTx.from);
      filledTx.chainId ??= await E(providerVat).getChainId();
      if (!filledTx.maxFeePerGas || !filledTx.maxPriorityFeePerGas) {
        const fees = await E(providerVat).getGasFees();
        filledTx.maxFeePerGas ??= fees.maxFeePerGas;
        filledTx.maxPriorityFeePerGas ??= fees.maxPriorityFeePerGas;
      }
      filledTx.gasLimit ??= applyGasBuffer(
        validateGasEstimate(
          await E(providerVat).request('eth_estimateGas', [
            {
              from: filledTx.from,
              to: filledTx.to,
              value: filledTx.value,
              data: filledTx.data,
            },
          ]),
        ),
        10,
      );
 
      const signedTx = await resolveTransactionSigning(filledTx);
      return E(providerVat).broadcastTransaction(signedTx);
    },
 
    async sendBatchTransaction(
      txs: TransactionRequest[],
    ): Promise<Hex | Hex[]> {
      if (txs.length === 0) {
        throw new Error('No transactions to send');
      }
 
      if (txs.length === 1) {
        return coordinator.sendTransaction(txs[0]);
      }
 
      Iif (!providerVat) {
        throw new Error('Provider not configured');
      }
 
      const batchSender =
        smartAccountConfig?.address ?? (await coordinator.getAccounts())[0];
 
      // Cache the predicate result — useDirect7702Tx is impure (eth_getCode)
      // and must not be called twice for the same sender (see revokeDelegation).
      const isDirect7702Batch =
        batchSender !== undefined &&
        smartAccountConfig?.implementation === 'stateless7702' &&
        (await useDirect7702Tx(batchSender));
 
      const useSmartAccountBatchPath =
        bundlerConfig !== undefined ||
        isDirect7702Batch ||
        (peerWallet !== undefined && delegationVat !== undefined);
 
      // Smart account path: single UserOp or direct 7702 self-call
      if (useSmartAccountBatchPath) {
        const executions: Execution[] = txs.map((tx) => ({
          target: tx.to,
          value: tx.value ?? ('0x0' as Hex),
          callData: tx.data ?? ('0x' as Hex),
        }));
 
        const walletChainId = await resolveChainId();
 
        // Delegation path: batch via redeemDelegations with BatchDefault mode.
        // Validate that the delegation covers ALL actions in the batch,
        // not just the first one, to avoid on-chain reverts.
        Eif (delegationVat) {
          const now = Date.now();
          const actions: Action[] = txs.map((tx) => ({
            to: tx.to,
            value: tx.value,
            data: tx.data,
          }));
 
          let delegation: Delegation | undefined;
          for (const action of actions) {
            const found = await E(delegationVat).findDelegationForAction(
              action,
              walletChainId,
              now,
            );
            if (!found || found.status !== 'signed') {
              delegation = undefined;
              break;
            }
            // All actions must be covered by the same delegation.
            Iif (delegation && delegation.id !== found.id) {
              delegation = undefined;
              break;
            }
            delegation = found;
          }
 
          if (delegation) {
            return submitBatchDelegationUserOp({
              delegations: [delegation],
              executions,
            });
          }
 
          // No single delegation covers all batch actions — check whether
          // delegations exist that partially match. If so, block the batch
          // (same enforcement as sendTransaction) to prevent bypassing caveats
          // via the direct execute path.
          for (const action of actions) {
            const explanations = await E(delegationVat).explainActionMatch(
              action,
              walletChainId,
              now,
            );
            if (explanations.length > 0) {
              throw new Error(
                buildDelegationMismatchError(
                  explanations,
                  `No single delegation covers all ${String(actions.length)} batch actions`,
                ),
              );
            }
          }
        }
 
        // Direct smart account batch (no delegation)
        const sender = batchSender;
        Iif (!sender) {
          throw new Error('No accounts available for batch');
        }
 
        const callData = buildBatchExecuteCallData({ executions });
        if (isDirect7702Batch) {
          return buildAndSubmitDirect7702Tx({ sender, callData });
        }
        if (!bundlerConfig) {
          throw new Error(
            'Non-delegation batch execution requires a bundler or direct 7702; ' +
              'peer relay is only available for delegation redemptions',
          );
        }
        return buildAndSubmitUserOp({ sender, callData });
      }
 
      // EOA fallback: execute sequentially
      const hashes: Hex[] = [];
      for (const tx of txs) {
        hashes.push(await coordinator.sendTransaction(tx));
      }
      return hashes;
    },
 
    async signTypedData(data: Eip712TypedData, from?: Address): Promise<Hex> {
      return resolveTypedDataSigning(data, from);
    },
 
    async signMessage(message: string, account?: Address): Promise<Hex> {
      return resolveMessageSigning(message, account);
    },
 
    async request(method: string, params?: unknown[]): Promise<unknown> {
      if (!providerVat) {
        throw new Error('Provider not configured');
      }
      return E(providerVat).request(method, params);
    },
 
    /**
     * Look up a transaction by hash. Tries the bundler first (in case the
     * hash is a UserOp hash from delegation redemption), then falls back
     * to a regular `eth_getTransactionReceipt` RPC call.
     *
     * @param hash - A UserOp hash or regular tx hash.
     * @returns An object with `txHash` and `receipt`, or null if not found.
     */
    async getTransactionReceipt(hash: Hex): Promise<{
      txHash: Hex;
      userOpHash?: Hex;
      success: boolean;
    } | null> {
      if (!providerVat) {
        throw new Error('Provider not configured');
      }
 
      // Try bundler first (UserOp hash)
      if (bundlerConfig) {
        try {
          const userOpReceipt = (await E(providerVat).getUserOpReceipt({
            bundlerUrl: bundlerConfig.bundlerUrl,
            userOpHash: hash,
          })) as {
            success: boolean;
            receipt?: { transactionHash?: string };
          } | null;
 
          if (userOpReceipt?.receipt?.transactionHash) {
            return harden({
              txHash: userOpReceipt.receipt.transactionHash as Hex,
              userOpHash: hash,
              success: userOpReceipt.success,
            });
          }
        } catch (error) {
          // Not a UserOp hash — fall through to regular RPC
          logger.debug(
            'UserOp receipt lookup failed, trying regular RPC',
            error,
          );
        }
      }
 
      // Try regular tx receipt
      const receipt = (await E(providerVat).request(
        'eth_getTransactionReceipt',
        [hash],
      )) as { status?: string; transactionHash?: string } | null;
 
      if (receipt?.transactionHash) {
        return harden({
          txHash: receipt.transactionHash as Hex,
          success: receipt.status === '0x1',
        });
      }
 
      return null;
    },
 
    // ------------------------------------------------------------------
    // Delegation management
    // ------------------------------------------------------------------
 
    async createDelegation(opts: CreateDelegationOptions): Promise<Delegation> {
      Iif (!delegationVat) {
        throw new Error('Delegation vat not available');
      }
 
      // Determine delegator and signing function.
      // When a smart account is configured, use its address as delegator
      // but sign with the underlying EOA key (the smart account's owner).
      let delegator: Address | undefined;
      let signTypedDataFn:
        | ((data: Eip712TypedData) => Promise<Hex>)
        | undefined;
 
      if (keyringVat) {
        const accounts = await E(keyringVat).getAccounts();
        Eif (accounts.length > 0) {
          delegator = smartAccountConfig?.address ?? accounts[0];
          const kv = keyringVat;
          signTypedDataFn = async (data: Eip712TypedData) =>
            E(kv).signTypedData(data);
        }
      }
 
      if (!delegator && externalSigner) {
        const accounts = await E(externalSigner).getAccounts();
        Eif (accounts.length > 0) {
          delegator = smartAccountConfig?.address ?? accounts[0];
          const ext = externalSigner;
          // Smart-account delegations are signed by the owner EOA, not the
          // smart-account address used as delegator in typed data.
          const from = accounts[0];
          signTypedDataFn = async (data: Eip712TypedData) =>
            E(ext).signTypedData(data, from);
        }
      }
 
      if (!delegator || !signTypedDataFn) {
        throw new Error('No accounts available to create delegation');
      }
 
      const delegation = await E(delegationVat).createDelegation({
        ...opts,
        delegator,
      });
 
      const typedData = await E(delegationVat).prepareDelegationForSigning(
        delegation.id,
      );
 
      const signature = await signTypedDataFn(typedData);
 
      await E(delegationVat).storeSigned(delegation.id, signature);
 
      return E(delegationVat).getDelegation(delegation.id);
    },
 
    async receiveDelegation(delegation: Delegation): Promise<void> {
      if (!delegationVat) {
        throw new Error('Delegation vat not available');
      }
      await E(delegationVat).receiveDelegation(delegation);
    },
 
    /**
     * Mark a delegation as revoked in the local store without submitting
     * an on-chain transaction. Used by the home device to propagate
     * revocations to the away device over CapTP.
     *
     * @param id - The delegation identifier.
     */
    async revokeDelegationLocally(id: string): Promise<void> {
      Iif (!delegationVat) {
        throw new Error('Delegation vat not available');
      }
      // Silently ignore if the delegation doesn't exist locally
      // (the away device may not have received it yet).
      try {
        const delegation = await E(delegationVat).getDelegation(id);
        if (delegation.status !== 'revoked') {
          await E(delegationVat).revokeDelegation(id);
        }
      } catch (error) {
        // Delegation not found locally — nothing to revoke.
        logger.debug('revokeDelegationLocally: delegation not found', error);
      }
    },
 
    /**
     * Revoke a delegation on-chain by calling `DelegationManager.disableDelegation`
     * via a UserOp (hybrid) or a direct EIP-1559 transaction (stateless 7702).
     * Blocks until the transaction is confirmed on-chain, then updates the local
     * delegation status.
     *
     * Hybrid accounts require a configured bundler (paymaster optional).
     *
     * @param id - The delegation identifier.
     * @returns The UserOp hash or transaction hash of the on-chain revocation.
     */
    async revokeDelegation(id: string): Promise<Hex> {
      if (!delegationVat) {
        throw new Error('Delegation vat not available');
      }
 
      const delegation = await E(delegationVat).getDelegation(id);
      if (delegation.status === 'revoked') {
        throw new Error(`Delegation ${id} is already revoked`);
      }
      Iif (delegation.status !== 'signed') {
        throw new Error(
          `Delegation ${id} has status '${delegation.status}', expected 'signed'`,
        );
      }
 
      // Verify this wallet controls the delegator address
      const accounts = await coordinator.getAccounts();
      const delegatorLower = delegation.delegator.toLowerCase();
      const smartAccountLower = smartAccountConfig?.address?.toLowerCase();
      const matchesAccount = accounts.some(
        (a: string) => a.toLowerCase() === delegatorLower,
      );
      const isOwned = matchesAccount
        ? true
        : smartAccountLower === delegatorLower;
      Iif (!isOwned) {
        throw new Error(
          `Cannot revoke delegation ${id}: delegator ${delegation.delegator} is not controlled by this wallet`,
        );
      }
 
      // Submit on-chain disable — returns the hash and which path was used
      // so we poll the right receipt endpoint without calling useDirect7702Tx
      // a second time (the predicate is impure due to eth_getCode).
      const { hash: submissionHash, isDirect } =
        await submitDisableUserOp(delegation);
 
      if (isDirect) {
        const receipt = await pollTransactionReceipt({
          txHash: submissionHash,
        });
        if (!receipt.success) {
          throw new Error(
            `On-chain revocation reverted for delegation ${id} (tx: ${submissionHash})`,
          );
        }
      } else {
        // waitForUserOpReceipt either returns a non-null receipt or throws
        // on timeout — validate the shape to catch unexpected bundler responses.
        const rawReceipt = await coordinator.waitForUserOpReceipt({
          userOpHash: submissionHash,
        });
        const receipt = rawReceipt as { success?: boolean } | undefined;
        Iif (
          !receipt ||
          typeof receipt !== 'object' ||
          !('success' in receipt)
        ) {
          throw new Error(
            `Unexpected UserOp receipt format for delegation ${id} ` +
              `(userOpHash: ${submissionHash})`,
          );
        }
        if (!receipt.success) {
          throw new Error(
            `On-chain revocation reverted for delegation ${id} (userOpHash: ${submissionHash})`,
          );
        }
      }
 
      // Update local status after on-chain confirmation
      await E(delegationVat).revokeDelegation(id);
 
      return submissionHash;
    },
 
    async listDelegations(): Promise<Delegation[]> {
      Iif (!delegationVat) {
        throw new Error('Delegation vat not available');
      }
      return E(delegationVat).listDelegations();
    },
 
    // ------------------------------------------------------------------
    // Delegation redemption (ERC-4337)
    // ------------------------------------------------------------------
 
    async redeemDelegation(options: {
      execution: Execution;
      delegations?: Delegation[];
      delegationId?: string;
      action?: Action;
      maxFeePerGas?: Hex;
      maxPriorityFeePerGas?: Hex;
    }): Promise<Hex> {
      Iif (!delegationVat) {
        throw new Error('Delegation vat not available');
      }
 
      // Resolve the delegation chain
      let delegations: Delegation[];
 
      if (options.delegations && options.delegations.length > 0) {
        // Explicit delegation chain provided
        delegations = options.delegations;
      } else if (options.delegationId) {
        const delegation = await E(delegationVat).getDelegation(
          options.delegationId,
        );
        delegations = [delegation];
      } else if (options.action) {
        // Only resolve chain ID when needed for delegation matching
        const walletChainId = await resolveChainId();
        const now = Date.now();
        const delegation = await E(delegationVat).findDelegationForAction(
          options.action,
          walletChainId,
          now,
        );
        if (!delegation) {
          const explanations = await E(delegationVat).explainActionMatch(
            options.action,
            walletChainId,
            now,
          );
          throw new Error(
            buildDelegationMismatchError(
              explanations,
              'No matching delegation found',
            ),
          );
        }
        delegations = [delegation];
      } else {
        throw new Error('Must provide delegations, delegationId, or action');
      }
 
      // Validate all delegations in the chain are signed
      for (const delegation of delegations) {
        if (delegation.status !== 'signed') {
          throw new Error(
            `Delegation ${delegation.id} has status '${delegation.status}', expected 'signed'`,
          );
        }
      }
 
      return submitDelegationUserOp({
        delegations,
        execution: options.execution,
        maxFeePerGas: options.maxFeePerGas,
        maxPriorityFeePerGas: options.maxPriorityFeePerGas,
      });
    },
 
    // ------------------------------------------------------------------
    // ERC-20 token utilities
    // ------------------------------------------------------------------
 
    async getTokenBalance(options: {
      token: Address;
      owner: Address;
    }): Promise<string> {
      if (!providerVat) {
        throw new Error('Provider not configured');
      }
      const callData = encodeBalanceOf(options.owner);
      const result = await E(providerVat).request('eth_call', [
        { to: options.token, data: callData },
        'latest',
      ]);
      const validated = validateTokenCallResult(
        result,
        'balanceOf',
        options.token,
      );
      return decodeBalanceOfResult(validated).toString();
    },
 
    async getTokenMetadata(options: {
      token: Address;
    }): Promise<{ name: string; symbol: string; decimals: number }> {
      if (!providerVat) {
        throw new Error('Provider not configured');
      }
      const [nameSettled, symbolSettled, decimalsSettled] =
        await Promise.allSettled([
          E(providerVat).request('eth_call', [
            { to: options.token, data: encodeName() },
            'latest',
          ]),
          E(providerVat).request('eth_call', [
            { to: options.token, data: encodeSymbol() },
            'latest',
          ]),
          E(providerVat).request('eth_call', [
            { to: options.token, data: encodeDecimals() },
            'latest',
          ]),
        ]);
 
      // decimals is mandatory — wrong decimals causes financial errors
      Iif (decimalsSettled.status === 'rejected') {
        throw new Error(
          `decimals() call failed for token ${options.token}: ${
            decimalsSettled.reason instanceof Error
              ? decimalsSettled.reason.message
              : String(decimalsSettled.reason)
          }`,
        );
      }
 
      // name and symbol are optional in ERC-20; fall back gracefully
      let name = 'Unknown';
      Eif (nameSettled.status === 'fulfilled') {
        try {
          name = decodeNameResult(
            validateTokenCallResult(nameSettled.value, 'name', options.token),
          );
        } catch {
          // name() not implemented or returned invalid data
        }
      }
 
      let symbol = 'Unknown';
      Eif (symbolSettled.status === 'fulfilled') {
        try {
          symbol = decodeSymbolResult(
            validateTokenCallResult(
              symbolSettled.value,
              'symbol',
              options.token,
            ),
          );
        } catch {
          // symbol() not implemented or returned invalid data
        }
      }
 
      return harden({
        name,
        symbol,
        decimals: decodeDecimalsResult(
          validateTokenCallResult(
            decimalsSettled.value,
            'decimals',
            options.token,
          ),
        ),
      });
    },
 
    async sendErc20Transfer(options: {
      token: Address;
      to: Address;
      amount: bigint | Hex;
      from?: Address;
    }): Promise<Hex> {
      const accounts = await coordinator.getAccounts();
      const from = options.from ?? accounts[0];
      if (!from) {
        throw new Error('No accounts available');
      }
      const rawAmount =
        typeof options.amount === 'bigint'
          ? options.amount
          : BigInt(options.amount);
      const callData = encodeTransfer(options.to, rawAmount);
      return coordinator.sendTransaction({
        from,
        to: options.token,
        data: callData,
        value: '0x0' as Hex,
      });
    },
 
    // ------------------------------------------------------------------
    // Token swaps (MetaSwap API)
    // ------------------------------------------------------------------
 
    async getSwapQuote(options: {
      srcToken: Address;
      destToken: Address;
      srcAmount: Hex;
      slippage: number;
      walletAddress?: Address;
    }): Promise<SwapQuote> {
      if (!providerVat) {
        throw new Error('Provider not configured');
      }
 
      if (options.slippage < 0.1 || options.slippage > 50) {
        throw new Error('Slippage must be between 0.1 and 50');
      }
 
      const walletAddress =
        options.walletAddress ?? (await coordinator.getAccounts())[0];
      Iif (!walletAddress) {
        throw new Error('No accounts available');
      }
 
      const chainId = await resolveChainId();
 
      const rawAmount = BigInt(options.srcAmount).toString();
 
      // Build query string manually — URLSearchParams is unavailable in SES vats.
      const queryEntries: [string, string][] = [
        ['sourceToken', options.srcToken.toLowerCase()],
        ['destinationToken', options.destToken.toLowerCase()],
        ['sourceAmount', rawAmount],
        ['slippage', String(options.slippage)],
        ['walletAddress', walletAddress],
        ['timeout', '10000'],
      ];
      const query = queryEntries
        .map(
          ([key, val]) =>
            `${encodeURIComponent(key)}=${encodeURIComponent(val)}`,
        )
        .join('&');
 
      const url = `https://swap.api.cx.metamask.io/networks/${String(chainId)}/trades?${query}`;
 
      const response = await E(providerVat).httpGetJson(url);
 
      if (!Array.isArray(response) || response.length === 0) {
        throw new Error(
          'No swap quotes available for this token pair and amount',
        );
      }
 
      // Select the best quote by highest destinationAmount
      let best: SwapQuote | undefined;
      let bestAmount = -1n;
 
      for (const entry of response) {
        const quote = entry as Record<string, unknown>;
        if (quote.error) {
          continue;
        }
        const rawDest =
          typeof quote.destinationAmount === 'string'
            ? quote.destinationAmount
            : '0';
        const destAmount = BigInt(rawDest);
        if (destAmount > bestAmount) {
          bestAmount = destAmount;
          best = quote as unknown as SwapQuote;
        }
      }
 
      if (!best) {
        throw new Error(
          'All swap aggregators returned errors. Try a different amount or token pair.',
        );
      }
 
      return harden(best);
    },
 
    async swapTokens(options: {
      srcToken: Address;
      destToken: Address;
      srcAmount: Hex;
      slippage: number;
    }): Promise<SwapResult> {
      const ZERO_ADDRESS =
        '0x0000000000000000000000000000000000000000' as Address;
 
      const accounts = await coordinator.getAccounts();
      const from = accounts[0];
      Iif (!from) {
        throw new Error('No accounts available');
      }
 
      // Fetch a fresh quote at execution time, reusing the resolved account
      const quote = await coordinator.getSwapQuote({
        ...options,
        walletAddress: from,
      });
 
      // Determine if approval is needed
      const needsApproval =
        quote.approvalNeeded !== null &&
        options.srcToken.toLowerCase() !== ZERO_ADDRESS;
 
      const approvalInfo = needsApproval ? quote.approvalNeeded : null;
      let approvalNeeded = false;
      if (approvalInfo) {
        Iif (!providerVat) {
          throw new Error('Provider not configured');
        }
 
        const spender = approvalInfo.to as Address;
        const allowanceCallData = encodeAllowance(from, spender);
        const allowanceResult = await E(providerVat).request('eth_call', [
          { to: options.srcToken, data: allowanceCallData },
          'latest',
        ]);
 
        const currentAllowance =
          typeof allowanceResult === 'string' && allowanceResult !== '0x'
            ? decodeAllowanceResult(allowanceResult as Hex)
            : 0n;
 
        approvalNeeded = currentAllowance < BigInt(options.srcAmount);
      }
 
      const swapTx: TransactionRequest = {
        from,
        to: quote.trade.to as Address,
        data: quote.trade.data as Hex,
        value: (quote.trade.value ?? '0x0') as Hex,
      };
 
      // Batch path: combine approve + swap in a single UserOp when
      // the bundler is configured (smart account).
      if (approvalNeeded && approvalInfo && bundlerConfig) {
        const approvalTx: TransactionRequest = {
          from,
          to: options.srcToken,
          data: approvalInfo.data as Hex,
          value: (approvalInfo.value ?? '0x0') as Hex,
        };
 
        const batchResult = await coordinator.sendBatchTransaction([
          approvalTx,
          swapTx,
        ]);
 
        // sendBatchTransaction returns a single Hex for batched UserOps
        const batchHash = Array.isArray(batchResult)
          ? (batchResult[0] as Hex)
          : batchResult;
 
        return harden({
          approvalTxHash: undefined,
          swapTxHash: batchHash,
          sourceAmount: quote.sourceAmount,
          destinationAmount: quote.destinationAmount,
          aggregator: quote.aggregator,
          batched: true,
        });
      }
 
      // Sequential path: approve then swap (EOA or no approval needed)
      let approvalTxHash: Hex | undefined;
      if (approvalNeeded && approvalInfo) {
        approvalTxHash = await coordinator.sendTransaction({
          from,
          to: options.srcToken,
          data: approvalInfo.data as Hex,
          value: (approvalInfo.value ?? '0x0') as Hex,
        });
      }
 
      try {
        const swapTxHash = await coordinator.sendTransaction(swapTx);
 
        return harden({
          approvalTxHash,
          swapTxHash,
          sourceAmount: quote.sourceAmount,
          destinationAmount: quote.destinationAmount,
          aggregator: quote.aggregator,
        });
      } catch (error: unknown) {
        Eif (approvalTxHash) {
          const message =
            error instanceof Error ? error.message : String(error);
          throw new Error(
            `Swap transaction failed after approval was sent (approval tx: ${approvalTxHash}). ` +
              `The token allowance was set but the swap did not complete: ${message}`,
          );
        }
        throw error;
      }
    },
 
    async waitForUserOpReceipt(options: {
      userOpHash: Hex;
      pollIntervalMs?: number;
      timeoutMs?: number;
    }): Promise<unknown> {
      if (!providerVat || !bundlerConfig) {
        throw new Error('Provider and bundler must be configured');
      }
 
      Iif (
        typeof globalThis.Date?.now !== 'function' ||
        typeof globalThis.setTimeout !== 'function'
      ) {
        throw new Error(
          'waitForUserOpReceipt requires Date.now and setTimeout ' +
            '(not available in SES compartments without timer endowments)',
        );
      }
 
      const interval = options.pollIntervalMs ?? 2000;
      const timeout = options.timeoutMs ?? 60000;
      const start = Date.now();
 
      while (Date.now() - start < timeout) {
        const receipt = await E(providerVat).getUserOpReceipt({
          bundlerUrl: bundlerConfig.bundlerUrl,
          userOpHash: options.userOpHash,
        });
        if (receipt !== null) {
          return receipt;
        }
        await new Promise((resolve) => setTimeout(resolve, interval));
      }
      throw new Error(
        `UserOp ${options.userOpHash} not found after ${timeout}ms`,
      );
    },
 
    /**
     * Poll until a regular EIP-1559 transaction is mined (e.g. stateless 7702
     * direct sends). Prefer `waitForUserOpReceipt` for ERC-4337 UserOp hashes.
     *
     * @param options - Polling options.
     * @param options.txHash - Transaction hash to wait for.
     * @param options.pollIntervalMs - Delay between RPC polls in milliseconds.
     * @param options.timeoutMs - Maximum time to wait in milliseconds.
     * @returns Whether the mined transaction succeeded (`status` 0x1).
     */
    async waitForTransactionReceipt(options: {
      txHash: Hex;
      pollIntervalMs?: number;
      timeoutMs?: number;
    }): Promise<{ success: boolean }> {
      return pollTransactionReceipt(options);
    },
 
    // ------------------------------------------------------------------
    // Peer wallet connectivity
    // ------------------------------------------------------------------
 
    async issueOcapUrl(): Promise<string> {
      if (!issuerService) {
        throw new Error('OCAP URL issuer service not available');
      }
      return E(issuerService).issue(coordinator);
    },
 
    async connectToPeer(ocapUrl: string): Promise<void> {
      Iif (!redemptionService) {
        throw new Error('OCAP URL redemption service not available');
      }
      peerWallet = (await E(redemptionService).redeem(
        ocapUrl,
      )) as PeerWalletFacet;
      persistBaggage('peerWallet', peerWallet);
 
      // Cache the peer accounts for offline autonomy
      try {
        cachedPeerAccounts = await E(peerWallet).getAccounts();
        persistBaggage('cachedPeerAccounts', cachedPeerAccounts);
      } catch (error) {
        // Peer may not be ready yet; accounts can be cached later
        // via refreshPeerAccounts()
        logger.warn('peer account fetch failed during connect', error);
      }
 
      // Register this coordinator as the away wallet on the home device
      // so the home can push delegations directly over CapTP.
      try {
        await E(peerWallet).registerAwayWallet(coordinator);
      } catch (error) {
        // Home device may not support registerAwayWallet yet (older version).
        // Delegation transfer falls back to copy-paste.
        logger.warn('registerAwayWallet failed', error);
      }
    },
 
    async refreshPeerAccounts(): Promise<Address[]> {
      if (!peerWallet) {
        throw new Error('No peer wallet connected');
      }
      cachedPeerAccounts = await E(peerWallet).getAccounts();
      persistBaggage('cachedPeerAccounts', cachedPeerAccounts);
      return cachedPeerAccounts;
    },
 
    async registerAwayWallet(awayRef: unknown): Promise<void> {
      if (!awayRef || typeof awayRef !== 'object') {
        throw new Error(
          'Invalid away wallet reference: must be a non-null object',
        );
      }
      awayWallet = awayRef as AwayWalletFacet;
      persistBaggage('awayWallet', awayWallet);
    },
 
    async pushDelegationToAway(
      delegation: Delegation,
      revokeIds?: string[],
    ): Promise<void> {
      if (!awayWallet) {
        throw new Error(
          'No away wallet registered. The away device must connect first.',
        );
      }
 
      // Revoke old delegations on the away device first so it stops using them
      Iif (revokeIds && revokeIds.length > 0) {
        for (const id of revokeIds) {
          await E(awayWallet).revokeDelegationLocally(id);
        }
      }
 
      await E(awayWallet).receiveDelegation(delegation);
    },
 
    async registerDelegateAddress(address: string): Promise<void> {
      if (
        !address ||
        typeof address !== 'string' ||
        !/^0x[\da-f]{40}$/iu.test(address)
      ) {
        throw new Error(
          'Invalid delegate address: must be a 0x-prefixed 40-hex-char string',
        );
      }
      pendingDelegateAddress = address as Address;
      persistBaggage('pendingDelegateAddress', pendingDelegateAddress);
    },
 
    async getDelegateAddress(): Promise<Address | undefined> {
      return pendingDelegateAddress;
    },
 
    async sendDelegateAddressToPeer(address: string): Promise<void> {
      if (!peerWallet) {
        throw new Error('No peer wallet connected');
      }
      await E(peerWallet).registerDelegateAddress(address);
    },
 
    async handleSigningRequest(request: {
      type: string;
      tx?: TransactionRequest;
      data?: Eip712TypedData;
      message?: string;
      account?: Address;
    }): Promise<Hex> {
      switch (request.type) {
        case 'transaction':
          Iif (!request.tx) {
            throw new Error('Missing transaction in signing request');
          }
          throw new Error(
            'Peer transaction signing is disabled; use delegation redemption',
          );
 
        case 'typedData':
          Iif (!request.data) {
            throw new Error('Missing typed data in signing request');
          }
          Iif (keyringVat) {
            const hasKeys = await E(keyringVat).hasKeys();
            if (hasKeys) {
              return E(keyringVat).signTypedData(request.data, request.account);
            }
          }
          if (externalSigner) {
            const accounts = await E(externalSigner).getAccounts();
            Eif (accounts.length > 0) {
              return E(externalSigner).signTypedData(
                request.data,
                request.account ?? accounts[0],
              );
            }
          }
          throw new Error('No signer available to handle signing request');
 
        case 'message':
          Iif (!request.message) {
            throw new Error('Missing message in signing request');
          }
          if (keyringVat) {
            const hasKeys = await E(keyringVat).hasKeys();
            Eif (hasKeys) {
              return E(keyringVat).signMessage(
                request.message,
                request.account,
              );
            }
          }
          Eif (externalSigner) {
            const accounts = await E(externalSigner).getAccounts();
            Eif (accounts.length > 0) {
              return E(externalSigner).signMessage(
                request.message,
                request.account ?? accounts[0],
              );
            }
          }
          throw new Error('No signer available to handle signing request');
 
        default:
          throw new Error(`Unknown signing request type: ${request.type}`);
      }
    },
 
    // ------------------------------------------------------------------
    // Peer delegation redemption relay
    // ------------------------------------------------------------------
 
    async handleRedemptionRequest(request: {
      type: 'single' | 'batch';
      delegations: Delegation[];
      execution?: Execution;
      executions?: Execution[];
      maxFeePerGas?: Hex;
      maxPriorityFeePerGas?: Hex;
    }): Promise<Hex> {
      if (!request.delegations || request.delegations.length === 0) {
        throw new Error('Missing or empty delegations in redemption request');
      }
 
      // Guard against infinite relay loops: if this wallet cannot fulfill
      // the request locally, it must not relay it back to its own peer.
      // Uses the same config-based check as the relay entry condition in
      // submitDelegationUserOp/submitBatchDelegationUserOp — keep in sync.
      const canFulfillLocally =
        bundlerConfig !== undefined ||
        (smartAccountConfig?.implementation === 'stateless7702' &&
          providerVat !== undefined);
      if (!canFulfillLocally) {
        throw new Error(
          'Cannot fulfill relayed redemption: no bundler or direct 7702 configured',
        );
      }
 
      if (request.type === 'single') {
        if (!request.execution) {
          throw new Error('Missing execution in single redemption request');
        }
        return submitDelegationUserOp({
          delegations: request.delegations,
          execution: request.execution,
          maxFeePerGas: request.maxFeePerGas,
          maxPriorityFeePerGas: request.maxPriorityFeePerGas,
        });
      }
 
      if (request.type === 'batch') {
        if (!request.executions || request.executions.length === 0) {
          throw new Error('Missing executions in batch redemption request');
        }
        return submitBatchDelegationUserOp({
          delegations: request.delegations,
          executions: request.executions,
        });
      }
 
      throw new Error(
        `Unknown redemption request type: ${String(request.type)}`,
      );
    },
 
    // ------------------------------------------------------------------
    // Introspection
    // ------------------------------------------------------------------
 
    async getCapabilities(): Promise<WalletCapabilities> {
      const hasLocalKeys = keyringVat ? await E(keyringVat).hasKeys() : false;
 
      const localAccounts: Address[] = keyringVat
        ? await E(keyringVat).getAccounts()
        : [];
 
      const allDelegations: Delegation[] = delegationVat
        ? await E(delegationVat).listDelegations()
        : [];
      const activeDelegations = allDelegations.filter(
        (del) => del.status === 'signed',
      );
 
      // Resolve the signing mode so consumers (including AI agents) know
      // how signing works and whether user approval is needed.
      // Peer wallet takes priority — when present, it is the actual signing
      // authority (the local throwaway key is an implementation detail).
      let signingMode: string = 'none';
      if (peerWallet) {
        try {
          const peerCaps = await raceWithTimeout(
            E(peerWallet).getCapabilities(),
            PEER_TIMEOUT_MS,
          );
          signingMode = `peer:${peerCaps.signingMode ?? 'unknown'}`;
          cachedPeerSigningMode = signingMode;
          persistBaggage('cachedPeerSigningMode', cachedPeerSigningMode);
        } catch (error) {
          logger.warn('peer getCapabilities failed, using cache', error);
          signingMode = cachedPeerSigningMode ?? 'peer:unknown';
        }
      } else if (externalSigner) {
        signingMode = 'external:metamask';
      } else if (hasLocalKeys) {
        signingMode = 'local';
      }
 
      // Build human-readable delegation summaries so AI agents understand
      // what they can do autonomously without further user approval.
      const delegationInfos = activeDelegations.map((del) => ({
        id: del.id,
        delegator: del.delegator,
        delegate: del.delegate,
        caveats: del.caveats.map((cav) => ({
          type: cav.type,
          humanReadable: describeCaveat(cav),
        })),
      }));
 
      // Determine the agent's autonomy level based on delegations.
      // When delegations exist, the agent can send ETH within the
      // delegation's limits without requiring further user approval.
      // Stateless 7702 can redeem via direct RPC without a bundler.
      // Peer relay can redeem but requires the home wallet to be online.
      let autonomy: string;
      const canRedeemLocally =
        bundlerConfig !== undefined ||
        (smartAccountConfig?.implementation === 'stateless7702' &&
          providerVat !== undefined);
      // Relay requires no smartAccountConfig — mirrors the entry condition
      // in submitDelegationUserOp/submitBatchDelegationUserOp.
      const canRedeemViaRelay =
        !canRedeemLocally && !smartAccountConfig && peerWallet !== undefined;
      const canRedeemDelegationsOnChain =
        activeDelegations.length > 0 && (canRedeemLocally || canRedeemViaRelay);
      if (canRedeemDelegationsOnChain) {
        const limits = activeDelegations
          .flatMap((del) => del.caveats)
          .map(describeCaveat)
          .filter(Boolean);
        const base =
          limits.length > 0
            ? `autonomous within limits: ${limits.join('; ')}`
            : 'autonomous (no spending limits)';
        if (canRedeemViaRelay) {
          autonomy = `${base} (relay, requires home online)`;
        } else {
          autonomy =
            cachedPeerAccounts.length > 0 ? `${base} (offline-capable)` : base;
        }
      I} else if (peerWallet) {
        autonomy = 'requires peer wallet approval for each action';
      } else {
        autonomy = 'no signing authority';
      }
 
      let capabilityChainId: number | undefined;
      try {
        capabilityChainId = await resolveChainId();
      } catch (error) {
        logger.warn('Failed to resolve chain ID for capabilities', error);
      }
 
      return harden({
        hasLocalKeys,
        localAccounts,
        delegationCount: activeDelegations.length,
        delegations: delegationInfos,
        hasPeerWallet: peerWallet !== undefined,
        hasExternalSigner: externalSigner !== undefined,
        hasBundlerConfig: bundlerConfig !== undefined,
        smartAccountAddress: smartAccountConfig?.address,
        chainId: capabilityChainId,
        signingMode,
        autonomy,
        peerAccountsCached: cachedPeerAccounts.length > 0,
        cachedPeerAccounts,
        hasAwayWallet: awayWallet !== undefined,
      });
    },
  });
  return coordinator;
}