nexus-sdk 2.1.1

Rust SDK for Nexus protocol types, RPC access, and transaction construction.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
//! Tool inspection, owner configuration, and cashier operations.

use {
    crate::{
        events::NexusEventKind,
        move_bindings::{
            interface::{payment::PaymentSourceKind, verifier::ToolVerifierSupport},
            move_std::{ascii, type_name::TypeName},
            registry::network_auth::IdentityKey,
            sui_framework::{clock::Clock as SuiClock, linked_table::Node, object::ID},
            tool::{
                external_verifier::ExternalVerifier,
                finite_credits,
                invocation::Invocation,
                time_pass,
                tool_cashier::{CashierDeposit, PolicyKey, ToolCashier, ToolCashierInnerV1},
                tool_registry::{
                    Tool as ToolAnchor,
                    ToolInnerV1,
                    ToolRegistry,
                    ToolRegistryInnerV1,
                },
            },
            FiniteCredits,
            TimePass,
        },
        move_boundary,
        nexus::{
            client::NexusClient,
            error::NexusError,
            registry::preflight_external_verifier_registration,
        },
        sui,
        transactions::{tool, tool_cashier},
        types::{NexusContext, PackageRole, ToolState},
        ToolFqn,
    },
    std::{collections::HashSet, sync::Arc, time::Duration},
};

/// Compatibility of one Tool with this SDK and the current Registry authority.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ToolCompatibility {
    /// The Tool selects the same package graph as the current Registry.
    Current,
    /// The SDK understands the Tool, and no live Registry mutation is required.
    LegacyUnderstood,
    /// The SDK understands the Tool, but live Registry use requires migration.
    MigrationRequired,
    /// The observed era and inner pair has no adapter in this SDK.
    Unsupported,
    /// The Tool could not be observed or decoded independently.
    Unavailable,
}

/// Confirmed entitlement purchase with both discoverable object IDs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntitlementPurchaseResult {
    pub tx_digest: sui::types::Digest,
    pub entitlement_id: sui::types::Address,
    pub deposit_id: sui::types::Address,
}

/// Confirmed entitlement state change with its canonical object ID.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntitlementIssueResult {
    pub tx_digest: sui::types::Digest,
    pub entitlement_id: sui::types::Address,
}

/// Current sale terms for canonical finite Tool invocation credits.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct FiniteCreditOffer {
    pub issuance_enabled: bool,
    pub price_per_credit: u64,
    pub minimum_credits: u64,
    pub maximum_credits: u64,
}

impl FiniteCreditOffer {
    fn purchase_price(&self, credits: u64) -> Result<u64, NexusError> {
        if !self.issuance_enabled {
            return Err(NexusError::Configuration(
                "Finite credit purchases are closed".to_owned(),
            ));
        }
        if credits < self.minimum_credits || credits > self.maximum_credits {
            return Err(NexusError::Configuration(format!(
                "Credit count '{credits}' must be between '{}' and '{}'",
                self.minimum_credits, self.maximum_credits,
            )));
        }
        self.price_per_credit.checked_mul(credits).ok_or_else(|| {
            NexusError::Configuration(
                "Finite credit purchase price exceeds the maximum MIST value".to_owned(),
            )
        })
    }
}

/// Current sale terms for canonical time based Tool access.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct TimePassOffer {
    pub issuance_enabled: bool,
    pub price_per_ms: u64,
    pub minimum_duration_ms: u64,
    pub maximum_duration_ms: u64,
}

impl TimePassOffer {
    fn purchase_price(&self, duration_ms: u64) -> Result<u64, NexusError> {
        if !self.issuance_enabled {
            return Err(NexusError::Configuration(
                "Time pass purchases are closed".to_owned(),
            ));
        }
        if duration_ms < self.minimum_duration_ms || duration_ms > self.maximum_duration_ms {
            return Err(NexusError::Configuration(format!(
                "Duration '{duration_ms}' must be between '{}' and '{}' milliseconds",
                self.minimum_duration_ms, self.maximum_duration_ms,
            )));
        }
        self.price_per_ms.checked_mul(duration_ms).ok_or_else(|| {
            NexusError::Configuration(
                "Time pass purchase price exceeds the maximum MIST value".to_owned(),
            )
        })
    }
}

/// Discoverable economic policies accepted by one [`ToolCashier`].
///
/// [`ToolEconomy::policies`] preserves every owner supplied policy type.
/// Canonical offers are decoded into stable SDK values for direct use by
/// clients and command line tools.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct ToolEconomy {
    pub tool_id: sui::types::Address,
    pub cashier_id: sui::types::Address,
    pub policies: Vec<TypeName>,
    pub fixed_price_mist: u64,
    pub finite_credits: Option<FiniteCreditOffer>,
    pub time_pass: Option<TimePassOffer>,
}

/// User facing finite credit state for one Tool and beneficiary.
///
/// This combines the shared account with refunded child [Invocation] objects,
/// which no single Move value exposes as one serializable view.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct FiniteCreditAccess {
    pub account_id: sui::types::Address,
    pub remaining: u64,
    pub refunded_invocations: Vec<sui::types::Address>,
}

/// User facing time pass state for one Tool and beneficiary.
///
/// The active flag is evaluated against the onchain clock used by admission,
/// so clients do not need to compare local time with Move state.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct TimePassAccess {
    pub account_id: sui::types::Address,
    pub valid_from_ms: u64,
    pub valid_until_ms: u64,
    pub active: bool,
}

/// Complete user facing access for one Tool and payment beneficiary.
///
/// The account IDs are derived from canonical Move keys. This stable view
/// combines those identities with typed state for RPC, CLI, and index users.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct ToolAccess {
    pub tool_id: sui::types::Address,
    pub cashier_id: sui::types::Address,
    pub beneficiary: PaymentSourceKind,
    pub observed_at_ms: u64,
    pub finite_credits: Option<FiniteCreditAccess>,
    pub time_pass: Option<TimePassAccess>,
}

/// One finalized Invocation waiting in a [`ToolCashier`] inbox.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct CollectableInvocation {
    pub object_ref: sui::types::ObjectReference,
    pub policy: TypeName,
    pub sources: Vec<sui::types::Address>,
    pub amount_mist: u64,
}

/// One prepaid sale deposit waiting in a [`ToolCashier`] inbox.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct CollectableDeposit {
    pub object_ref: sui::types::ObjectReference,
    pub amount_mist: u64,
}

/// Indexed economic objects currently owned by one [`ToolCashier`].
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct ToolCashierInbox {
    pub invocations: Vec<CollectableInvocation>,
    pub deposits: Vec<CollectableDeposit>,
}

/// Result of [`ToolActions::inspect_tool`].
///
/// The object IDs are derived locally even when the Tool does not exist.
/// An existing Tool includes its complete [`ToolState`] record.
#[derive(Clone, Debug)]
pub struct ToolInspection {
    /// Requested fully qualified name.
    pub fqn: ToolFqn,
    /// Stable Tool object ID.
    pub tool_id: sui::types::Address,
    /// Stable cashier object ID.
    pub tool_cashier_id: sui::types::Address,
    /// Whether the stable Tool object exists.
    pub exists: bool,
    /// Current owner when the Tool was observed.
    pub owner: Option<sui::types::Owner>,
    /// Exact era type observed below the Tool anchor.
    pub witness_type: Option<sui::types::StructTag>,
    /// Exact inner type observed below the Tool anchor.
    pub inner_type: Option<sui::types::StructTag>,
    /// Compatibility classification isolated to this Tool.
    pub compatibility: ToolCompatibility,
    /// Complete supported Tool state.
    pub tool: Option<ToolState>,
    /// Current Registry verifier support while the Tool is registered.
    pub verifier_support: Option<ToolVerifierSupport>,
    /// Current external verifier record, when configured.
    pub external_verifier: Option<ExternalVerifier>,
    /// Current Registry timeout while the Tool is registered.
    pub timeout_ms: Option<u64>,
    /// Current invocation price while the Tool is registered.
    pub invocation_cost_mist: Option<u64>,
    /// Diagnostic detail for unsupported or unavailable state.
    pub detail: Option<String>,
}

/// Result of a Tool owner or cashier transaction.
pub struct ToolActionResult {
    /// Digest of the submitted transaction.
    pub tx_digest: sui::types::Digest,
}

/// Compatibility preserving alias for cashier callers.
pub type ToolCashierActionResult = ToolActionResult;

/// Operations over Tool state, Registry projections, and payment state.
pub struct ToolActions {
    pub(super) client: NexusClient,
}

fn canonical_policy_accepted(
    context: &NexusContext,
    policies: &[TypeName],
    module: &str,
) -> Result<bool, NexusError> {
    let origin = context
        .type_origin(PackageRole::Tool, module, "Policy")
        .map_err(NexusError::Parsing)?;
    let expected = format!("{origin}::{module}::Policy");
    Ok(policies
        .iter()
        .any(|policy| policy.matches_qualified_name(&expected)))
}

impl ToolActions {
    async fn fetch_finite_credit_offer(
        client: &NexusClient,
        context: &NexusContext,
        cashier_id: sui::types::Address,
        tool_fqn: &ToolFqn,
    ) -> Result<FiniteCreditOffer, NexusError> {
        let config = client
            .crawler()
            .get_dynamic_field_by_key::<PolicyKey<finite_credits::Policy>, finite_credits::Config>(
                cashier_id,
                PolicyKey::new(false),
                &crate::move_bindings::type_tag::<PolicyKey<finite_credits::Policy>>(context),
            )
            .await
            .map_err(NexusError::Rpc)?
            .ok_or_else(|| {
                NexusError::Configuration(format!(
                    "Finite credits policy for Tool '{tool_fqn}' has no config"
                ))
            })?;
        Ok(FiniteCreditOffer {
            issuance_enabled: config.issuance_enabled,
            price_per_credit: config.price_per_credit,
            minimum_credits: config.minimum_credits,
            maximum_credits: config.maximum_credits,
        })
    }

    async fn fetch_time_pass_offer(
        client: &NexusClient,
        context: &NexusContext,
        cashier_id: sui::types::Address,
        tool_fqn: &ToolFqn,
    ) -> Result<TimePassOffer, NexusError> {
        let config = client
            .crawler()
            .get_dynamic_field_by_key::<PolicyKey<time_pass::Policy>, time_pass::Config>(
                cashier_id,
                PolicyKey::new(false),
                &crate::move_bindings::type_tag::<PolicyKey<time_pass::Policy>>(context),
            )
            .await
            .map_err(NexusError::Rpc)?
            .ok_or_else(|| {
                NexusError::Configuration(format!(
                    "Time pass policy for Tool '{tool_fqn}' has no config"
                ))
            })?;
        Ok(TimePassOffer {
            issuance_enabled: config.issuance_enabled,
            price_per_ms: config.price_per_ms,
            minimum_duration_ms: config.minimum_duration_ms,
            maximum_duration_ms: config.maximum_duration_ms,
        })
    }

    async fn resolve_tool_cashier_and_cap(
        client: &NexusClient,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
    ) -> Result<
        (
            Arc<NexusContext>,
            sui::types::ObjectReference,
            sui::types::ObjectReference,
        ),
        NexusError,
    > {
        let tool_cashier = client.fetch_tool_cashier(tool_fqn).await?;
        let context = client.context_for_object(*tool_cashier.object_id()).await?;
        let cashier_admin = client
            .crawler()
            .get_object_metadata(cashier_admin)
            .await
            .map_err(|error| {
                NexusError::Configuration(format!(
                    "Tool '{tool_fqn}' cashier admin capability '{cashier_admin}' could not be resolved: {error}"
                ))
            })?
            .object_ref();
        Ok((context, tool_cashier, cashier_admin))
    }

    /// Lists every currently registered Tool.
    ///
    /// A Tool that cannot be decoded remains in the result with its own
    /// compatibility status. One bad Tool cannot hide the rest of the Registry.
    pub async fn list_tools(&self) -> Result<Vec<ToolInspection>, NexusError> {
        let (context, registry) = self.registry_state().await?;
        let entries = self.tool_directory(&context, &registry).await?;
        let mut tools = Vec::with_capacity(entries.len());
        for (fqn, tool_id) in entries {
            tools.push(
                self.inspect_tool_id(&context, &registry, fqn, tool_id)
                    .await,
            );
        }
        Ok(tools)
    }

    /// Inspects one stable Tool ID derived from its FQN.
    ///
    /// Missing, unsupported, and unavailable Tool state is represented in the
    /// returned value so callers can make compatibility decisions explicitly.
    pub async fn inspect_tool(&self, fqn: &ToolFqn) -> Result<ToolInspection, NexusError> {
        let (context, registry) = self.registry_state().await?;
        let tool_id = crate::move_bindings::derive_tool_id(context.tool_registry.object_id(), fqn)
            .map_err(NexusError::Parsing)?;
        Ok(self
            .inspect_tool_id(&context, &registry, fqn.clone(), tool_id)
            .await)
    }

    /// Updates the execution timeout for a registered Tool.
    pub async fn update_timeout(
        &self,
        fqn: &ToolFqn,
        timeout: Duration,
        owner_cap: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let (context, tool_ref, owner_cap) = self.current_tool_inputs(fqn, owner_cap, true).await?;
        let transaction = tool::update_tool_timeout_ptb(&context, &tool_ref, &owner_cap, timeout)
            .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Updates the HTTP endpoint for a registered off chain Tool.
    pub async fn update_url(
        &self,
        fqn: &ToolFqn,
        url: &str,
        owner_cap: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let (context, tool_ref, owner_cap) =
            self.current_tool_inputs(fqn, owner_cap, false).await?;
        let transaction = tool::update_off_chain_tool_url_ptb(&context, &tool_ref, &owner_cap, url)
            .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Updates the description for a registered Tool.
    pub async fn update_metadata(
        &self,
        fqn: &ToolFqn,
        description: &str,
        owner_cap: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let (context, tool_ref, owner_cap) =
            self.current_tool_inputs(fqn, owner_cap, false).await?;
        let transaction =
            tool::update_tool_metadata_ptb(&context, &tool_ref, &owner_cap, description)
                .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Updates the invocation price for a registered Tool.
    pub async fn set_invocation_cost(
        &self,
        fqn: &ToolFqn,
        cost_mist: u64,
        cashier_admin: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let tool_ref = self.client.fetch_tool(fqn).await?;
        let context = self
            .client
            .context_for_object_with_roots(
                *tool_ref.object_id(),
                std::slice::from_ref(&self.client.nexus_objects.tool_registry),
            )
            .await?;
        let cashier_admin = self.client.object_reference(cashier_admin).await?;
        let transaction =
            tool::set_invocation_cost_ptb(&context, &tool_ref, &cashier_admin, cost_mist)
                .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Changes the Registry verification status of a registered Tool.
    ///
    /// The configured [`crate::types::NexusObjects::tool_registry_admin_cap`]
    /// must be owned by this client's signer.
    pub async fn set_verified(
        &self,
        fqn: &ToolFqn,
        verified: bool,
    ) -> Result<ToolActionResult, NexusError> {
        let tool_ref = self.client.fetch_tool(fqn).await?;
        let objects = self.client.get_nexus_objects();
        let context = self
            .client
            .context_for_object_with_roots(
                *tool_ref.object_id(),
                std::slice::from_ref(&objects.tool_registry),
            )
            .await?;
        let admin = self
            .client
            .object_reference(objects.tool_registry_admin_cap.object_id())
            .await?;
        let transaction = tool::set_verified_ptb(&context, &tool_ref, &admin, verified)
            .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Enables registered key verification for a registered off chain Tool.
    pub async fn configure_registered_key_verifier(
        &self,
        fqn: &ToolFqn,
        owner_cap: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let tool_ref = self.client.fetch_tool(fqn).await?;
        let tool_id = *tool_ref.object_id();
        let binding_id = self
            .client
            .network_auth()
            .binding_object_id(&IdentityKey::tool(tool_id))
            .await?;
        let objects = self.client.get_nexus_objects();
        let context = self
            .client
            .context_for_object_with_roots(
                objects.network_auth.object_id(),
                std::slice::from_ref(&objects.tool_registry),
            )
            .await?;
        let (owner_cap, tool_key_binding) = tokio::try_join!(
            self.client.object_reference(owner_cap),
            self.client.object_reference(binding_id),
        )?;
        let transaction = tool::configure_registered_key_verifier_ptb(
            &context,
            &tool_ref,
            &owner_cap,
            &tool_key_binding,
        )
        .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Validates and installs one external verifier for an off chain Tool.
    pub async fn configure_external_verifier(
        &self,
        fqn: &ToolFqn,
        owner_cap: sui::types::Address,
        package_id: sui::types::Address,
        module_name: &str,
        function_name: &str,
        verifier_object_ids: &[sui::types::Address],
    ) -> Result<ToolActionResult, NexusError> {
        let (context, tool_ref, owner_cap) = self.current_tool_inputs(fqn, owner_cap, true).await?;
        let registration = preflight_external_verifier_registration(
            self.client.crawler(),
            &context,
            package_id,
            module_name,
            function_name,
            verifier_object_ids,
        )
        .await
        .map_err(|error| NexusError::Configuration(error.to_string()))?;
        let transaction =
            tool::register_external_verifier_ptb(&context, &tool_ref, &owner_cap, &registration)
                .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Points a registered on chain Tool at a new package.
    pub async fn migrate_on_chain_package(
        &self,
        fqn: &ToolFqn,
        target_package: sui::types::Address,
        owner_cap: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let (context, tool_ref, owner_cap) =
            self.current_tool_inputs(fqn, owner_cap, false).await?;
        let transaction = tool::migrate_on_chain_tool_package_ptb(
            &context,
            &tool_ref,
            &owner_cap,
            target_package,
        )
        .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Unregisters a Tool from every live Registry lookup.
    pub async fn unregister(
        &self,
        fqn: &ToolFqn,
        owner_cap: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let (context, tool_ref, owner_cap) = self.unregister_inputs(fqn, owner_cap).await?;
        let transaction = tool::unregister_ptb(&context, &tool_ref, &owner_cap)
            .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Claims unlocked US collateral after Tool unregistration.
    pub async fn claim_collateral(
        &self,
        fqn: &ToolFqn,
        owner_cap: sui::types::Address,
    ) -> Result<ToolActionResult, NexusError> {
        let (context, tool_ref, owner_cap) =
            self.current_tool_inputs(fqn, owner_cap, false).await?;
        let transaction = tool::claim_collateral_for_self_ptb(&context, &tool_ref, &owner_cap)
            .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Enables time pass sales and admission for a [`crate::types::Tool`].
    pub async fn enable_time_passes(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        price_per_ms: u64,
        minimum_duration_ms: u64,
        maximum_duration_ms: u64,
    ) -> Result<ToolCashierActionResult, NexusError> {
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let transaction = tool_cashier::enable_time_pass_ptb(
            &context,
            &tool_cashier,
            &cashier_admin,
            price_per_ms,
            minimum_duration_ms,
            maximum_duration_ms,
        )
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Closes time pass issuance for a [`crate::types::Tool`] without invalidating existing passes.
    pub async fn close_time_pass_issuance(
        &self,
        fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
    ) -> Result<ToolCashierActionResult, NexusError> {
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, fqn, cashier_admin).await?;
        let transaction =
            tool_cashier::close_time_pass_issuance_ptb(&context, &tool_cashier, &cashier_admin)
                .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Opens time pass issuance for a [`crate::types::Tool`] using its current terms.
    pub async fn open_time_pass_issuance(
        &self,
        fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
    ) -> Result<ToolCashierActionResult, NexusError> {
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, fqn, cashier_admin).await?;
        let transaction =
            tool_cashier::open_time_pass_issuance_ptb(&context, &tool_cashier, &cashier_admin)
                .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Updates time pass terms for a [`crate::types::Tool`] without invalidating existing passes.
    pub async fn update_time_pass_terms(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        price_per_ms: u64,
        minimum_duration_ms: u64,
        maximum_duration_ms: u64,
    ) -> Result<ToolCashierActionResult, NexusError> {
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let transaction = tool_cashier::update_time_pass_terms_ptb(
            &context,
            &tool_cashier,
            &cashier_admin,
            price_per_ms,
            minimum_duration_ms,
            maximum_duration_ms,
        )
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Buys time access for the signer beneficiary from its SUI address balance.
    pub async fn buy_time_pass(
        &self,
        tool_fqn: &ToolFqn,
        duration_ms: u64,
    ) -> Result<EntitlementPurchaseResult, NexusError> {
        let client = &self.client;
        let beneficiary = PaymentSourceKind::user_funded(client.owner()?);
        self.buy_time_pass_with(client, tool_fqn, duration_ms, beneficiary)
            .await
    }

    /// Buys time access for an explicit beneficiary from the signer address balance.
    pub async fn buy_time_pass_for(
        &self,
        tool_fqn: &ToolFqn,
        duration_ms: u64,
        beneficiary: PaymentSourceKind,
    ) -> Result<EntitlementPurchaseResult, NexusError> {
        let client = &self.client;
        self.buy_time_pass_with(client, tool_fqn, duration_ms, beneficiary)
            .await
    }

    async fn buy_time_pass_with(
        &self,
        client: &NexusClient,
        tool_fqn: &ToolFqn,
        duration_ms: u64,
        beneficiary: PaymentSourceKind,
    ) -> Result<EntitlementPurchaseResult, NexusError> {
        if duration_ms == 0 {
            return Err(NexusError::Configuration(
                "Time pass duration must be greater than zero".to_owned(),
            ));
        }
        let address = client.owner()?;
        let tool_cashier = client.fetch_tool_cashier(tool_fqn).await?;
        let context = client.context_for_object(*tool_cashier.object_id()).await?;
        let price =
            Self::fetch_time_pass_offer(client, &context, *tool_cashier.object_id(), tool_fqn)
                .await?
                .purchase_price(duration_ms)?;
        let entitlement_id = crate::move_bindings::derive_time_pass_id(
            &context,
            *tool_cashier.object_id(),
            beneficiary.clone(),
        )
        .map_err(NexusError::Parsing)?;
        let pass = client
            .crawler()
            .get_optional_object::<TimePass>(entitlement_id)
            .await
            .map_err(NexusError::Rpc)?;
        let account = match pass {
            Some(pass) => {
                if pass.data.cashier.bytes != *tool_cashier.object_id()
                    || pass.data.beneficiary != beneficiary
                    || !pass.is_shared()
                {
                    return Err(NexusError::Configuration(format!(
                        "Time pass '{entitlement_id}' does not match its canonical account"
                    )));
                }
                Some(pass.object_ref())
            }
            None => None,
        };
        let transaction = tool_cashier::buy_time_pass_from_balance_ptb(
            &context,
            &tool_cashier,
            account.as_ref(),
            beneficiary,
            duration_ms,
            price,
        )
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        let deposit_id = response
            .events
            .iter()
            .find_map(|event| match &event.data {
                NexusEventKind::CashierDepositCreated(created)
                    if created.cashier.bytes == *tool_cashier.object_id() =>
                {
                    Some(created.deposit.bytes)
                }
                _ => None,
            })
            .ok_or_else(|| {
                NexusError::Parsing(anyhow::anyhow!(
                    "Time pass purchase '{}' emitted no CashierDepositCreatedEvent",
                    response.digest
                ))
            })?;
        Ok(EntitlementPurchaseResult {
            tx_digest: response.digest,
            entitlement_id,
            deposit_id,
        })
    }

    /// Sets the canonical time pass window under Tool owner authority.
    pub async fn issue_time_pass(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        beneficiary: PaymentSourceKind,
        valid_from_ms: u64,
        valid_until_ms: u64,
    ) -> Result<EntitlementIssueResult, NexusError> {
        if valid_from_ms >= valid_until_ms {
            return Err(NexusError::Configuration(
                "Time pass end must be after its start".to_owned(),
            ));
        }
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let entitlement_id = crate::move_bindings::derive_time_pass_id(
            &context,
            *tool_cashier.object_id(),
            beneficiary.clone(),
        )
        .map_err(NexusError::Parsing)?;
        let pass = client
            .crawler()
            .get_optional_object::<TimePass>(entitlement_id)
            .await
            .map_err(NexusError::Rpc)?;
        let transaction = match pass {
            Some(pass) => {
                if pass.data.cashier.bytes != *tool_cashier.object_id()
                    || pass.data.beneficiary != beneficiary
                    || !pass.is_shared()
                {
                    return Err(NexusError::Configuration(format!(
                        "Time pass '{entitlement_id}' does not match its canonical account"
                    )));
                }
                tool_cashier::update_time_pass_window_ptb(
                    &context,
                    &tool_cashier,
                    &pass.object_ref(),
                    &cashier_admin,
                    valid_from_ms,
                    valid_until_ms,
                )
            }
            None => tool_cashier::issue_time_pass_ptb(
                &context,
                &tool_cashier,
                &cashier_admin,
                beneficiary,
                valid_from_ms,
                valid_until_ms,
            ),
        }
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(EntitlementIssueResult {
            tx_digest: response.digest,
            entitlement_id,
        })
    }

    /// Enables finite credit sales and admission for a [`crate::types::Tool`].
    pub async fn enable_finite_credits(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        price_per_credit: u64,
        minimum_credits: u64,
        maximum_credits: u64,
    ) -> Result<ToolCashierActionResult, NexusError> {
        if minimum_credits == 0 {
            return Err(NexusError::Configuration(
                "Minimum credits must be at least one".to_owned(),
            ));
        }
        if minimum_credits > maximum_credits {
            return Err(NexusError::Configuration(format!(
                "Minimum credits '{minimum_credits}' cannot exceed maximum credits '{maximum_credits}'"
            )));
        }
        let client = &self.client;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let transaction = tool_cashier::enable_finite_credits_ptb(
            &context,
            &tool_cashier,
            &cashier_admin,
            price_per_credit,
            minimum_credits,
            maximum_credits,
        )
        .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    /// Closes finite credit issuance for a [`crate::types::Tool`] without invalidating existing credits.
    pub async fn close_finite_credit_issuance(
        &self,
        fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
    ) -> Result<ToolCashierActionResult, NexusError> {
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, fqn, cashier_admin).await?;
        let transaction =
            tool_cashier::close_finite_credit_issuance_ptb(&context, &tool_cashier, &cashier_admin)
                .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Opens finite credit issuance for a [`crate::types::Tool`] using its current terms.
    pub async fn open_finite_credit_issuance(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
    ) -> Result<ToolCashierActionResult, NexusError> {
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let transaction =
            tool_cashier::open_finite_credit_issuance_ptb(&context, &tool_cashier, &cashier_admin)
                .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Updates finite credit terms for a [`crate::types::Tool`] without invalidating issued credits.
    pub async fn update_finite_credit_terms(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        price_per_credit: u64,
        minimum_credits: u64,
        maximum_credits: u64,
    ) -> Result<ToolCashierActionResult, NexusError> {
        if minimum_credits == 0 {
            return Err(NexusError::Configuration(
                "Minimum credits must be at least one".to_owned(),
            ));
        }
        if minimum_credits > maximum_credits {
            return Err(NexusError::Configuration(format!(
                "Minimum credits '{minimum_credits}' cannot exceed maximum credits '{maximum_credits}'"
            )));
        }
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let transaction = tool_cashier::update_finite_credit_terms_ptb(
            &context,
            &tool_cashier,
            &cashier_admin,
            price_per_credit,
            minimum_credits,
            maximum_credits,
        )
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Buys finite credits for the signer from its SUI address balance.
    pub async fn buy_finite_credits(
        &self,
        tool_fqn: &ToolFqn,
        credits: u64,
    ) -> Result<EntitlementPurchaseResult, NexusError> {
        let client = &self.client;
        let address = client.owner()?;
        self.buy_finite_credits_with(
            client,
            tool_fqn,
            credits,
            PaymentSourceKind::user_funded(address),
        )
        .await
    }

    /// Buys finite credits for an explicit beneficiary from the signer address balance.
    pub async fn buy_finite_credits_for(
        &self,
        tool_fqn: &ToolFqn,
        credits: u64,
        beneficiary: PaymentSourceKind,
    ) -> Result<EntitlementPurchaseResult, NexusError> {
        let client = &self.client;
        self.buy_finite_credits_with(client, tool_fqn, credits, beneficiary)
            .await
    }

    async fn buy_finite_credits_with(
        &self,
        client: &NexusClient,
        tool_fqn: &ToolFqn,
        credits: u64,
        beneficiary: PaymentSourceKind,
    ) -> Result<EntitlementPurchaseResult, NexusError> {
        if credits == 0 {
            return Err(NexusError::Configuration(
                "Credits must be at least one".to_owned(),
            ));
        }
        let address = client.owner()?;
        let tool_cashier = client.fetch_tool_cashier(tool_fqn).await?;
        let context = client.context_for_object(*tool_cashier.object_id()).await?;
        let price =
            Self::fetch_finite_credit_offer(client, &context, *tool_cashier.object_id(), tool_fqn)
                .await?
                .purchase_price(credits)?;
        let entitlement_id = crate::move_bindings::derive_finite_credits_id(
            &context,
            *tool_cashier.object_id(),
            beneficiary.clone(),
        )
        .map_err(NexusError::Parsing)?;
        let credit_account = client
            .crawler()
            .get_optional_object::<FiniteCredits>(entitlement_id)
            .await
            .map_err(NexusError::Rpc)?;
        let account = match credit_account {
            Some(account) => {
                if account.data.cashier.bytes != *tool_cashier.object_id()
                    || account.data.beneficiary != beneficiary
                    || !account.is_shared()
                {
                    return Err(NexusError::Configuration(format!(
                        "Finite credit account '{entitlement_id}' does not match its canonical account"
                    )));
                }
                Some(account.object_ref())
            }
            None => None,
        };
        let transaction = tool_cashier::buy_finite_credits_from_balance_ptb(
            &context,
            &tool_cashier,
            account.as_ref(),
            beneficiary,
            credits,
            price,
        )
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        let deposit_id = response
            .events
            .iter()
            .find_map(|event| match &event.data {
                NexusEventKind::CashierDepositCreated(created)
                    if created.cashier.bytes == *tool_cashier.object_id() =>
                {
                    Some(created.deposit.bytes)
                }
                _ => None,
            })
            .ok_or_else(|| {
                NexusError::Parsing(anyhow::anyhow!(
                    "Finite credit purchase '{}' emitted no CashierDepositCreatedEvent",
                    response.digest
                ))
            })?;
        Ok(EntitlementPurchaseResult {
            tx_digest: response.digest,
            entitlement_id,
            deposit_id,
        })
    }

    /// Issues shared finite credits under Tool owner authority.
    pub async fn issue_finite_credits(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        beneficiary: PaymentSourceKind,
        credits: u64,
    ) -> Result<EntitlementIssueResult, NexusError> {
        if credits == 0 {
            return Err(NexusError::Configuration(
                "Credits must be at least one".to_owned(),
            ));
        }
        let client = &self.client;
        let address = client.owner()?;
        let (context, tool_cashier, cashier_admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let entitlement_id = crate::move_bindings::derive_finite_credits_id(
            &context,
            *tool_cashier.object_id(),
            beneficiary.clone(),
        )
        .map_err(NexusError::Parsing)?;
        let credit_account = client
            .crawler()
            .get_optional_object::<FiniteCredits>(entitlement_id)
            .await
            .map_err(NexusError::Rpc)?;
        let transaction = match credit_account {
            Some(account) => {
                if account.data.cashier.bytes != *tool_cashier.object_id()
                    || account.data.beneficiary != beneficiary
                    || !account.is_shared()
                {
                    return Err(NexusError::Configuration(format!(
                        "Finite credit account '{entitlement_id}' does not match its canonical account"
                    )));
                }
                tool_cashier::issue_more_finite_credits_ptb(
                    &context,
                    &tool_cashier,
                    &account.object_ref(),
                    &cashier_admin,
                    credits,
                )
            }
            None => tool_cashier::issue_finite_credits_ptb(
                &context,
                &tool_cashier,
                &cashier_admin,
                beneficiary,
                credits,
            ),
        }
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(EntitlementIssueResult {
            tx_digest: response.digest,
            entitlement_id,
        })
    }

    /// Restores one refunded Invocation to its exact finite credit account.
    pub async fn restore_finite_credit_refund(
        &self,
        tool_fqn: &ToolFqn,
        invocation_id: sui::types::Address,
    ) -> Result<EntitlementIssueResult, NexusError> {
        let client = &self.client;
        let sender = client.owner()?;
        let cashier = client.fetch_tool_cashier(tool_fqn).await?;
        let context = client.context_for_object(*cashier.object_id()).await?;
        let refunded = client
            .crawler()
            .get_object::<Invocation>(invocation_id)
            .await
            .map_err(NexusError::Rpc)?;
        let expected_policy =
            crate::transactions::invocation::InvocationPolicyCall::finite_credits_policy(&context)
                .map_err(NexusError::Parsing)?;
        if refunded.data.cashier_id.bytes != *cashier.object_id()
            || refunded.data.policy != expected_policy
        {
            return Err(NexusError::Configuration(format!(
                "Invocation '{invocation_id}' is not a finite credit refund for this Tool"
            )));
        }
        let [credits_source] = refunded.data.sources.as_slice() else {
            return Err(NexusError::Configuration(format!(
                "Invocation '{invocation_id}' does not name one finite credit account"
            )));
        };
        let credits_id = credits_source.bytes;
        if refunded.owner != sui::types::Owner::Address(credits_id)
            || refunded.data.refund_to.copied_option() != Some(credits_id)
        {
            return Err(NexusError::Configuration(format!(
                "Invocation '{invocation_id}' was not refunded to credit account '{credits_id}'"
            )));
        }
        let credits = client
            .crawler()
            .get_object::<FiniteCredits>(credits_id)
            .await
            .map_err(NexusError::Rpc)?;
        if credits.data.cashier.bytes != *cashier.object_id() || !credits.is_shared() {
            return Err(NexusError::Configuration(format!(
                "Finite credit account '{credits_id}' does not match this Tool"
            )));
        }
        let transaction = tool_cashier::restore_finite_credit_refund_ptb(
            &context,
            &credits.object_ref(),
            &refunded.object_ref(),
        )
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, sender).await?;
        Ok(EntitlementIssueResult {
            tx_digest: response.digest,
            entitlement_id: credits_id,
        })
    }

    /// Reads the canonical access accounts for one Tool and beneficiary.
    ///
    /// Account IDs are derived from the Tool cashier, beneficiary, and policy.
    /// The returned finite credit refunds are exact [Invocation] objects that
    /// can be passed to [`ToolActions::restore_finite_credit_refund`].
    pub async fn inspect_access(
        &self,
        tool_fqn: &ToolFqn,
        beneficiary: PaymentSourceKind,
    ) -> Result<ToolAccess, NexusError> {
        let client = &self.client;
        let context = client
            .context_for_root(&client.nexus_objects.tool_registry)
            .await?;
        let crawler = client.crawler();
        let tool_id = crate::move_bindings::derive_tool_id(
            client.nexus_objects.tool_registry.object_id(),
            tool_fqn,
        )
        .map_err(NexusError::Parsing)?;
        let cashier_origin = context
            .type_origin(PackageRole::Tool, "tool_cashier", "ToolCashierKey")
            .map_err(NexusError::Parsing)?;
        let cashier_id = crate::move_bindings::derive_tool_cashier_id(cashier_origin, tool_id)
            .map_err(NexusError::Parsing)?;
        crawler
            .get_object_metadata(cashier_id)
            .await
            .map_err(NexusError::Rpc)?;

        let observed_at_ms = crawler
            .get_object::<SuiClock>(move_boundary::CLOCK_OBJECT_ID)
            .await
            .map_err(NexusError::Rpc)?
            .data
            .timestamp_ms;
        let credits_id = crate::move_bindings::derive_finite_credits_id(
            &context,
            cashier_id,
            beneficiary.clone(),
        )
        .map_err(NexusError::Parsing)?;
        let pass_id =
            crate::move_bindings::derive_time_pass_id(&context, cashier_id, beneficiary.clone())
                .map_err(NexusError::Parsing)?;

        let finite_credits = match crawler
            .get_optional_object::<FiniteCredits>(credits_id)
            .await
            .map_err(NexusError::Rpc)?
        {
            Some(credits) => {
                if !credits.is_shared()
                    || credits.data.cashier.bytes != cashier_id
                    || credits.data.beneficiary != beneficiary
                {
                    return Err(NexusError::Configuration(format!(
                        "Finite credit account '{credits_id}' does not match Tool '{tool_fqn}' and its beneficiary"
                    )));
                }
                let policy =
                    crate::transactions::invocation::InvocationPolicyCall::finite_credits_policy(
                        &context,
                    )
                    .map_err(NexusError::Parsing)?;
                let mut refunded_invocations = crawler
                    .get_owned_objects::<Invocation>(
                        credits_id,
                        crate::move_bindings::struct_tag::<Invocation>(&context),
                    )
                    .await
                    .map_err(NexusError::Rpc)?
                    .into_iter()
                    .filter(|invocation| {
                        invocation.data.cashier_id.bytes == cashier_id
                            && invocation.data.policy == policy
                            && invocation.data.sources.as_slice()
                                == [crate::move_bindings::sui_framework::object::ID::new(
                                    credits_id,
                                )]
                            && invocation.data.refund_to.copied_option() == Some(credits_id)
                    })
                    .map(|invocation| invocation.object_id)
                    .collect::<Vec<_>>();
                refunded_invocations.sort_unstable();
                Some(FiniteCreditAccess {
                    account_id: credits_id,
                    remaining: credits.data.state.remaining,
                    refunded_invocations,
                })
            }
            None => None,
        };

        let time_pass = match crawler
            .get_optional_object::<TimePass>(pass_id)
            .await
            .map_err(NexusError::Rpc)?
        {
            Some(pass) => {
                if !pass.is_shared()
                    || pass.data.cashier.bytes != cashier_id
                    || pass.data.beneficiary != beneficiary
                {
                    return Err(NexusError::Configuration(format!(
                        "Time pass account '{pass_id}' does not match Tool '{tool_fqn}' and its beneficiary"
                    )));
                }
                let valid_from_ms = pass.data.state.valid_from_ms;
                let valid_until_ms = pass.data.state.valid_until_ms;
                Some(TimePassAccess {
                    account_id: pass_id,
                    valid_from_ms,
                    valid_until_ms,
                    active: observed_at_ms >= valid_from_ms && observed_at_ms < valid_until_ms,
                })
            }
            None => None,
        };

        Ok(ToolAccess {
            tool_id,
            cashier_id,
            beneficiary,
            observed_at_ms,
            finite_credits,
            time_pass,
        })
    }

    /// Reads every accepted policy and the canonical offers for one [`crate::types::Tool`].
    ///
    /// Custom policy witness types remain visible in [`ToolEconomy::policies`]
    /// even when this SDK does not know how to decode their private configs.
    pub async fn inspect_economy(&self, tool_fqn: &ToolFqn) -> Result<ToolEconomy, NexusError> {
        let client = &self.client;
        Self::inspect_economy_with(client, tool_fqn).await
    }

    async fn inspect_economy_with(
        client: &NexusClient,
        tool_fqn: &ToolFqn,
    ) -> Result<ToolEconomy, NexusError> {
        let crawler = client.crawler();
        let cashier_ref = client.fetch_tool_cashier(tool_fqn).await?;
        let cashier_id = *cashier_ref.object_id();
        let context = client.context_for_object(cashier_id).await?;
        let cashier = client
            .state_resolver()
            .load_inner_for_supported_witness::<ToolCashier, ToolCashierInnerV1>(
                cashier_id, &context,
            )
            .await?;
        let tool_id = crate::move_bindings::derive_tool_id(
            client.nexus_objects.tool_registry.object_id(),
            tool_fqn,
        )
        .map_err(NexusError::Parsing)?;
        if cashier.data.tool.bytes != tool_id
            || cashier.data.tool_fqn.as_str() != tool_fqn.to_string()
        {
            return Err(NexusError::Configuration(format!(
                "Tool cashier '{cashier_id}' does not describe Tool '{tool_fqn}'"
            )));
        }

        let policies = cashier.data.policies.contents;
        if !canonical_policy_accepted(&context, &policies, "fixed_price")? {
            return Err(NexusError::Configuration(format!(
                "Tool '{tool_fqn}' is missing its mandatory fixed price policy"
            )));
        }
        let registry_root = &client.nexus_objects.tool_registry;
        let registry_context = client.context_for_root(registry_root).await?;
        let registry = client
            .state_resolver()
            .load_inner_for_supported_witness::<ToolRegistry, ToolRegistryInnerV1>(
                registry_root.object_id(),
                &registry_context,
            )
            .await?;
        let fqn_key = ascii::String::from(tool_fqn.to_string());
        let fqn_type = crate::move_bindings::type_tag::<ascii::String>(&registry_context);
        let fixed_price_mist = crawler
            .get_dynamic_field_by_key::<ascii::String, u64>(
                registry.data.invocation_costs_mist.id(),
                fqn_key,
                &fqn_type,
            )
            .await
            .map_err(NexusError::Rpc)?
            .ok_or_else(|| {
                NexusError::Configuration(format!(
                    "Fixed price policy for Tool '{tool_fqn}' has no price"
                ))
            })?;
        let finite_credits = if canonical_policy_accepted(&context, &policies, "finite_credits")? {
            Some(Self::fetch_finite_credit_offer(client, &context, cashier_id, tool_fqn).await?)
        } else {
            None
        };
        let time_pass = if canonical_policy_accepted(&context, &policies, "time_pass")? {
            Some(Self::fetch_time_pass_offer(client, &context, cashier_id, tool_fqn).await?)
        } else {
            None
        };

        Ok(ToolEconomy {
            tool_id,
            cashier_id,
            policies,
            fixed_price_mist,
            finite_credits,
            time_pass,
        })
    }

    /// Lists finalized Invocations and prepaid deposits waiting for collection.
    ///
    /// Transfer to Object indexes these objects under the [`ToolCashier`] ID as
    /// an address owner. Discovery therefore needs neither a mutable on chain
    /// registry nor a global usage counter.
    pub async fn inspect_cashier_inbox(
        &self,
        tool_fqn: &ToolFqn,
    ) -> Result<ToolCashierInbox, NexusError> {
        let client = &self.client;
        let cashier = client.fetch_tool_cashier(tool_fqn).await?;
        let cashier_id = *cashier.object_id();
        let context = client.context_for_object(cashier_id).await?;
        let invocations = client
            .crawler()
            .get_owned_objects::<Invocation>(
                cashier_id,
                crate::move_bindings::struct_tag::<Invocation>(&context),
            )
            .await
            .map_err(NexusError::Rpc)?
            .into_iter()
            .map(|response| CollectableInvocation {
                object_ref: response.object_ref(),
                policy: response.data.policy,
                sources: response
                    .data
                    .sources
                    .into_iter()
                    .map(|source| source.bytes)
                    .collect(),
                amount_mist: response.data.amount,
            })
            .collect();
        let deposits = client
            .crawler()
            .get_owned_objects::<CashierDeposit>(
                cashier_id,
                crate::move_bindings::struct_tag::<CashierDeposit>(&context),
            )
            .await
            .map_err(NexusError::Rpc)?
            .into_iter()
            .map(|response| CollectableDeposit {
                object_ref: response.object_ref(),
                amount_mist: response.data.funds.value,
            })
            .collect();
        Ok(ToolCashierInbox {
            invocations,
            deposits,
        })
    }

    /// Collects one same policy batch of finalized Invocations.
    pub async fn collect_invocations(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        invocation_ids: &[sui::types::Address],
        recipient: sui::types::Address,
    ) -> Result<ToolCashierActionResult, NexusError> {
        if invocation_ids.is_empty() {
            return Err(NexusError::Configuration(
                "Invocation collection requires at least one object ID".to_owned(),
            ));
        }
        let client = &self.client;
        let address = client.owner()?;
        let (context, cashier, admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let tool_id = crate::move_bindings::derive_tool_id(
            client.nexus_objects.tool_registry.object_id(),
            tool_fqn,
        )
        .map_err(NexusError::Parsing)?;
        let invocations = client
            .crawler()
            .get_objects::<Invocation>(invocation_ids)
            .await
            .map_err(NexusError::Rpc)?;
        let policy = invocations
            .first()
            .map(|invocation| invocation.data.policy.clone())
            .ok_or_else(|| {
                NexusError::Configuration(
                    "Invocation collection requires at least one object".to_owned(),
                )
            })?;
        let references = invocations
            .into_iter()
            .map(|response| {
                if response.owner != sui::types::Owner::Address(*cashier.object_id())
                    || response.data.cashier_id.bytes != *cashier.object_id()
                    || response.data.tool_id.bytes != tool_id
                {
                    return Err(NexusError::Configuration(format!(
                        "Invocation '{}' is not in Tool cashier '{}'",
                        response.object_id,
                        cashier.object_id()
                    )));
                }
                if response.data.policy != policy {
                    return Err(NexusError::Configuration(format!(
                        "Invocation '{}' uses policy '{}', not '{}'",
                        response.object_id, response.data.policy, policy
                    )));
                }
                Ok(response.object_ref())
            })
            .collect::<Result<Vec<_>, _>>()?;
        let transaction = tool_cashier::collect_invocations_ptb(
            &context,
            &cashier,
            &admin,
            &policy,
            &references,
            recipient,
        )
        .map_err(NexusError::TransactionBuilding)?;
        let response = client.submit_transaction(transaction, address).await?;
        Ok(ToolCashierActionResult {
            tx_digest: response.digest,
        })
    }

    /// Collects one batch of prepaid sale deposits.
    pub async fn collect_deposits(
        &self,
        tool_fqn: &ToolFqn,
        cashier_admin: sui::types::Address,
        deposit_ids: &[sui::types::Address],
        recipient: sui::types::Address,
    ) -> Result<ToolCashierActionResult, NexusError> {
        let client = &self.client;
        let (context, cashier, admin) =
            Self::resolve_tool_cashier_and_cap(client, tool_fqn, cashier_admin).await?;
        let references = client
            .crawler()
            .get_objects_metadata(deposit_ids)
            .await
            .map_err(NexusError::Rpc)?
            .into_iter()
            .map(|response| {
                if response.owner != sui::types::Owner::Address(*cashier.object_id()) {
                    return Err(NexusError::Configuration(format!(
                        "Deposit '{}' is not in Tool cashier '{}'",
                        response.object_id,
                        cashier.object_id()
                    )));
                }
                Ok(response.object_ref())
            })
            .collect::<Result<Vec<_>, _>>()?;
        let transaction =
            tool_cashier::collect_deposits_ptb(&context, &cashier, &admin, &references, recipient)
                .map_err(NexusError::TransactionBuilding)?;
        self.submit_action(transaction).await
    }

    async fn registry_state(&self) -> Result<(Arc<NexusContext>, ToolRegistryInnerV1), NexusError> {
        let root = &self.client.nexus_objects.tool_registry;
        let (snapshot, context) = self
            .client
            .state_resolver()
            .resolve_context_snapshot(self.client.get_nexus_objects(), root.object_id())
            .await?;
        let context = Arc::new(context);
        let state = self
            .client
            .state_resolver()
            .load_inner_for_supported_witness_from_snapshot::<ToolRegistry, ToolRegistryInnerV1>(
                &snapshot, &context,
            )?;
        Ok((context, state.data))
    }

    async fn tool_directory(
        &self,
        context: &NexusContext,
        registry: &ToolRegistryInnerV1,
    ) -> Result<Vec<(ToolFqn, sui::types::Address)>, NexusError> {
        let mut next = registry.tool_ids.head.cloned_option();
        let mut seen = HashSet::with_capacity(registry.tool_ids.size());
        let mut entries = Vec::with_capacity(registry.tool_ids.size());
        let key_type = crate::move_bindings::type_tag::<ascii::String>(context);

        while let Some(key) = next {
            let raw = std::str::from_utf8(&key.bytes).map_err(|error| {
                NexusError::Parsing(anyhow::anyhow!(
                    "Tool Registry contains a non UTF8 name: {error}"
                ))
            })?;
            let fqn = raw.parse::<ToolFqn>().map_err(|error| {
                NexusError::Parsing(anyhow::anyhow!(
                    "Tool Registry contains invalid FQN '{raw}': {error}"
                ))
            })?;
            if !seen.insert(key.clone()) {
                return Err(NexusError::InvalidObjectState {
                    object: context.tool_registry.object_id(),
                    reason: "Tool directory contains a cycle".to_owned(),
                });
            }
            let node = self
                .client
                .crawler()
                .get_dynamic_field_by_key::<ascii::String, Node<ascii::String, ID>>(
                    registry.tool_ids.id(),
                    key,
                    &key_type,
                )
                .await
                .map_err(NexusError::Rpc)?
                .ok_or_else(|| NexusError::InvalidObjectState {
                    object: context.tool_registry.object_id(),
                    reason: format!("Tool directory node for '{fqn}' is missing"),
                })?;
            entries.push((fqn, node.value.bytes));
            next = node.next.into_option();
        }

        if entries.len() != registry.tool_ids.size() {
            return Err(NexusError::InvalidObjectState {
                object: context.tool_registry.object_id(),
                reason: format!(
                    "Tool directory reports {} entries but contains {}",
                    registry.tool_ids.size(),
                    entries.len()
                ),
            });
        }
        Ok(entries)
    }

    async fn inspect_tool_id(
        &self,
        registry_context: &NexusContext,
        registry: &ToolRegistryInnerV1,
        fqn: ToolFqn,
        tool_id: sui::types::Address,
    ) -> ToolInspection {
        let current_package = registry_context.packages().get(PackageRole::Tool);
        let fallback_origin = current_package
            .and_then(|package| package.type_origin("tool_cashier", "ToolCashierKey").ok())
            .unwrap_or(sui::types::Address::ZERO);
        let mut inspection = ToolInspection {
            fqn,
            tool_id,
            tool_cashier_id: crate::move_bindings::derive_tool_cashier_id(fallback_origin, tool_id)
                .unwrap_or(sui::types::Address::ZERO),
            exists: false,
            owner: None,
            witness_type: None,
            inner_type: None,
            compatibility: ToolCompatibility::Unavailable,
            tool: None,
            verifier_support: None,
            external_verifier: None,
            timeout_ms: None,
            invocation_cost_mist: None,
            detail: None,
        };

        match self
            .client
            .crawler()
            .get_optional_object::<ToolAnchor>(tool_id)
            .await
        {
            Ok(Some(anchor)) => {
                inspection.exists = true;
                inspection.owner = Some(anchor.owner);
            }
            Ok(None) => return inspection,
            Err(error) => {
                inspection.detail = Some(format!("Tool object is unavailable: {error}"));
                return inspection;
            }
        }

        let snapshot = match self.client.state_resolver().observe_snapshot(tool_id).await {
            Ok(snapshot) => snapshot,
            Err(error) => {
                inspection.detail = Some(error.to_string());
                return inspection;
            }
        };
        let observed = snapshot.observed();
        inspection.owner = Some(observed.owner);
        inspection.witness_type = Some(observed.witness_type().clone());
        inspection.inner_type = Some(observed.inner_type().clone());

        let packages = match self
            .client
            .state_resolver()
            .resolve_package_graph(observed)
            .await
        {
            Ok(packages) => packages,
            Err(error) => {
                inspection.compatibility = ToolCompatibility::Unsupported;
                inspection.detail = Some(error.to_string());
                return inspection;
            }
        };
        let context = NexusContext::new(self.client.get_nexus_objects(), packages);
        if let Ok(origin) = context
            .require_package(PackageRole::Tool)
            .and_then(|package| package.type_origin("tool_cashier", "ToolCashierKey"))
        {
            if let Ok(cashier_id) = crate::move_bindings::derive_tool_cashier_id(origin, tool_id) {
                inspection.tool_cashier_id = cashier_id;
            }
        }

        let inner = match self
            .client
            .state_resolver()
            .load_inner_for_supported_witness_from_snapshot::<ToolAnchor, ToolInnerV1>(
                &snapshot, &context,
            ) {
            Ok(inner) => inner.data,
            Err(error) => {
                inspection.compatibility = ToolCompatibility::Unsupported;
                inspection.detail = Some(error.to_string());
                return inspection;
            }
        };

        let registered = inner.unregistered_at_ms.vec.is_empty();
        let selected = context.packages().get(PackageRole::Tool);
        let is_current = current_package
            .zip(selected)
            .is_some_and(|(current, selected)| {
                current.storage_id == selected.storage_id && current.version == selected.version
            });
        inspection.compatibility = if is_current {
            ToolCompatibility::Current
        } else if registered {
            ToolCompatibility::MigrationRequired
        } else {
            ToolCompatibility::LegacyUnderstood
        };
        inspection.tool = Some(ToolState::new(tool_id, inner));

        if registered {
            if let Err(error) = self
                .load_registry_projections(registry_context, registry, &mut inspection)
                .await
            {
                inspection.detail = Some(error.to_string());
            }
        }
        inspection
    }

    async fn load_registry_projections(
        &self,
        context: &NexusContext,
        registry: &ToolRegistryInnerV1,
        inspection: &mut ToolInspection,
    ) -> Result<(), NexusError> {
        let fqn_key = ascii::String::from(inspection.fqn.to_string());
        let fqn_type = crate::move_bindings::type_tag::<ascii::String>(context);
        let id_type = crate::move_bindings::type_tag::<ID>(context);
        let crawler = self.client.crawler();
        let (timeout, invocation_cost, verifier_support, external_verifier) = tokio::try_join!(
            crawler.get_dynamic_field_by_key::<ascii::String, Node<ascii::String, u64>>(
                registry.timeouts.id(),
                fqn_key.clone(),
                &fqn_type,
            ),
            crawler.get_dynamic_field_by_key::<ascii::String, u64>(
                registry.invocation_costs_mist.id(),
                fqn_key,
                &fqn_type,
            ),
            crawler.get_dynamic_field_by_key::<ID, ToolVerifierSupport>(
                registry.verifier_support.id(),
                ID::new(inspection.tool_id),
                &id_type,
            ),
            crawler.get_dynamic_field_by_key::<ID, ExternalVerifier>(
                registry.external_verifiers.id(),
                ID::new(inspection.tool_id),
                &id_type,
            )
        )
        .map_err(NexusError::Rpc)?;
        inspection.timeout_ms = timeout.map(|node| node.value);
        inspection.invocation_cost_mist = invocation_cost;
        inspection.verifier_support = verifier_support;
        inspection.external_verifier = external_verifier;
        Ok(())
    }

    async fn current_tool_inputs(
        &self,
        fqn: &ToolFqn,
        owner_cap: sui::types::Address,
        uses_registry: bool,
    ) -> Result<
        (
            Arc<NexusContext>,
            sui::types::ObjectReference,
            sui::types::ObjectReference,
        ),
        NexusError,
    > {
        let tool = self.client.fetch_tool(fqn).await?;
        let context = if uses_registry {
            self.client
                .context_for_object_with_roots(
                    *tool.object_id(),
                    std::slice::from_ref(&self.client.nexus_objects.tool_registry),
                )
                .await?
        } else {
            self.client.context_for_object(*tool.object_id()).await?
        };
        let owner_cap = self.client.object_reference(owner_cap).await?;
        Ok((context, tool, owner_cap))
    }

    /// Resolves [`Self::unregister`] from stable IDs and current Registry authority.
    ///
    /// Unregistration is the recovery path for a Tool whose inner value this
    /// SDK cannot decode. The transaction therefore reads only object metadata
    /// for the Tool and owner capability. The current [`ToolRegistry`] selects
    /// the call target, and the Move transition remains authoritative for the
    /// Tool state and ownership checks.
    async fn unregister_inputs(
        &self,
        fqn: &ToolFqn,
        owner_cap: sui::types::Address,
    ) -> Result<
        (
            Arc<NexusContext>,
            sui::types::ObjectReference,
            sui::types::ObjectReference,
        ),
        NexusError,
    > {
        let registry = &self.client.nexus_objects.tool_registry;
        let context = self.client.context_for_root(registry).await?;
        let tool_id = crate::move_bindings::derive_tool_id(registry.object_id(), fqn)
            .map_err(NexusError::Parsing)?;
        let tool = self.client.object_reference(tool_id).await?;
        let owner_cap = self.client.object_reference(owner_cap).await?;
        Ok((context, tool, owner_cap))
    }

    async fn submit_action(
        &self,
        transaction: sui::types::ProgrammableTransaction,
    ) -> Result<ToolActionResult, NexusError> {
        let response = self
            .client
            .submit_transaction(transaction, self.client.owner()?)
            .await?;
        Ok(ToolActionResult {
            tx_digest: response.digest,
        })
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::{
            move_bindings::{
                interface::meta_schema::MetaSchema,
                move_std::option::Option as MoveOption,
                sui_framework::{
                    balance::Balance,
                    linked_table::LinkedTable,
                    object::UID,
                    table::Table,
                    vec_set::VecSet,
                },
                tool::{era::V1 as ToolWitnessV1, tool_registry::ToolRef},
            },
            test_utils::{nexus_mocks, sui_mocks},
        },
        std::collections::HashMap,
    };

    fn registry_inner(
        directory_id: sui::types::Address,
        keys: &[ascii::String],
    ) -> ToolRegistryInnerV1 {
        let mut directory = LinkedTable::new(directory_id, keys.len() as u64);
        directory.head = MoveOption::from_option(keys.first().cloned());
        directory.tail = MoveOption::from_option(keys.last().cloned());
        ToolRegistryInnerV1::new(
            directory,
            Table::new(sui::types::Address::from_static("0xd2"), keys.len() as u64),
            Table::new(sui::types::Address::from_static("0xd3"), keys.len() as u64),
            LinkedTable::new(sui::types::Address::from_static("0xd4"), keys.len() as u64),
            Table::new(sui::types::Address::from_static("0xd5"), 0),
            Table::new(sui::types::Address::from_static("0xd6"), 0),
            Table::new(sui::types::Address::from_static("0xd7"), keys.len() as u64),
            LinkedTable::new(sui::types::Address::from_static("0xd8"), 0),
            LinkedTable::new(sui::types::Address::from_static("0xd9"), 0),
            0,
            0,
        )
    }

    fn tool_inner(registry_id: sui::types::Address, fqn: &ToolFqn) -> ToolInnerV1 {
        ToolInnerV1::new(
            ID::new(registry_id),
            ascii::String::from(fqn.to_string()),
            ToolRef::Http {
                url: b"https://example.com/tool".to_vec(),
            },
            b"Compatibility fixture".to_vec(),
            MetaSchema::new(vec![], vec![]),
            false,
            Balance {
                value: 0,
                phantom_t0: std::marker::PhantomData,
            },
            false,
            0,
            0,
            MoveOption::from(Some(1)),
        )
    }

    struct EconomyActionFixture {
        client: NexusClient,
        fqn: ToolFqn,
        cashier_admin: sui::types::Address,
    }

    async fn economy_action_fixture_with<F>(configure: F) -> EconomyActionFixture
    where
        F: FnOnce(
            &NexusContext,
            sui::types::Address,
            &mut sui_mocks::grpc::MockLedgerService,
            &mut sui_mocks::grpc::MockStateService,
        ),
    {
        let context = sui_mocks::mock_nexus_context();
        let registry_id = context.tool_registry.object_id();
        let fqn = "xyz.taluslabs.economy.action@1"
            .parse::<ToolFqn>()
            .expect("Tool FQN parses");
        let tool_id =
            crate::move_bindings::derive_tool_id(registry_id, &fqn).expect("Tool ID derives");
        let cashier_origin = context
            .type_origin(PackageRole::Tool, "tool_cashier", "ToolCashierKey")
            .expect("cashier origin resolves");
        let cashier_id = crate::move_bindings::derive_tool_cashier_id(cashier_origin, tool_id)
            .expect("cashier ID derives");
        let cashier_admin = sui::types::Address::from_static("0xca");
        let policies = vec![
            crate::transactions::invocation::InvocationPolicyCall::fixed_price(&context)
                .expect("fixed price policy resolves")
                .policy,
            crate::transactions::invocation::InvocationPolicyCall::finite_credits_policy(&context)
                .expect("finite credit policy resolves"),
            crate::transactions::invocation::InvocationPolicyCall::time_pass(
                &context,
                sui::types::Address::ZERO,
                1,
            )
            .expect("time pass policy resolves")
            .policy,
        ];
        let mut ledger = sui_mocks::grpc::MockLedgerService::new();
        let mut packages = sui_mocks::grpc::MockMovePackageService::new();
        let mut state = sui_mocks::grpc::MockStateService::new();
        mock_registry(
            &mut ledger,
            &mut state,
            &context,
            registry_inner(sui::types::Address::from_static("0xd1"), &[]),
        );
        sui_mocks::grpc::mock_object_state::<ToolAnchor, ToolWitnessV1, ToolInnerV1>(
            &mut ledger,
            &mut state,
            &context,
            sui_mocks::object_ref_for_id(tool_id),
            sui::types::Owner::Shared(1),
            ToolAnchor::new(UID::new(tool_id)),
            tool_inner(registry_id, &fqn),
        );
        sui_mocks::grpc::mock_nexus_package_graph(&mut ledger, &mut packages, context.packages());
        sui_mocks::grpc::mock_object_state::<ToolCashier, ToolWitnessV1, ToolCashierInnerV1>(
            &mut ledger,
            &mut state,
            &context,
            sui_mocks::object_ref_for_id(cashier_id),
            sui::types::Owner::Shared(2),
            ToolCashier::new(UID::new(cashier_id)),
            ToolCashierInnerV1::new(
                ID::new(tool_id),
                ascii::String::from(fqn.to_string()),
                VecSet { contents: policies },
            ),
        );
        sui_mocks::grpc::mock_get_object_metadata_exact(
            &mut ledger,
            sui_mocks::object_ref_for_id(cashier_admin),
            sui::types::Owner::Address(sui::types::Address::from_static("0xa")),
            None,
        );
        configure(&context, cashier_id, &mut ledger, &mut state);
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger),
            package_service_mock: Some(packages),
            state_service_mock: Some(state),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client_without_coins(&context, &rpc_url).await;

        EconomyActionFixture {
            client,
            fqn,
            cashier_admin,
        }
    }

    async fn economy_action_fixture() -> EconomyActionFixture {
        economy_action_fixture_with(|_, _, _, _| {}).await
    }

    fn assert_missing_gas<T>(result: Result<T, NexusError>) {
        assert!(matches!(result, Err(NexusError::Configuration(message)) if
            message.contains("a gas source is required")));
    }

    fn mock_registry(
        ledger_service: &mut sui_mocks::grpc::MockLedgerService,
        state_service: &mut sui_mocks::grpc::MockStateService,
        context: &NexusContext,
        registry: ToolRegistryInnerV1,
    ) {
        let registry_id = context.tool_registry.object_id();
        sui_mocks::grpc::mock_object_state::<ToolRegistry, ToolWitnessV1, ToolRegistryInnerV1>(
            ledger_service,
            state_service,
            context,
            sui_mocks::object_ref_for_id(registry_id),
            sui::types::Owner::Shared(context.tool_registry.initial_shared_version),
            ToolRegistry::new(UID::new(registry_id)),
            registry,
        );
    }

    #[test]
    fn compatibility_states_are_distinct() {
        let states = [
            ToolCompatibility::Current,
            ToolCompatibility::LegacyUnderstood,
            ToolCompatibility::MigrationRequired,
            ToolCompatibility::Unsupported,
            ToolCompatibility::Unavailable,
        ];
        assert_eq!(states.into_iter().collect::<HashSet<_>>().len(), 5);
    }

    #[test]
    fn canonical_offer_prices_enforce_sale_terms_and_overflow() {
        let finite = FiniteCreditOffer {
            issuance_enabled: true,
            price_per_credit: 3,
            minimum_credits: 2,
            maximum_credits: 4,
        };
        assert_eq!(finite.purchase_price(3).unwrap(), 9);
        assert!(finite.purchase_price(1).is_err());
        assert!(finite.purchase_price(5).is_err());
        assert!(FiniteCreditOffer {
            issuance_enabled: false,
            ..finite.clone()
        }
        .purchase_price(3)
        .is_err());
        assert!(FiniteCreditOffer {
            price_per_credit: u64::MAX,
            ..finite
        }
        .purchase_price(2)
        .is_err());

        let pass = TimePassOffer {
            issuance_enabled: true,
            price_per_ms: 3,
            minimum_duration_ms: 2,
            maximum_duration_ms: 4,
        };
        assert_eq!(pass.purchase_price(3).unwrap(), 9);
        assert!(pass.purchase_price(1).is_err());
        assert!(pass.purchase_price(5).is_err());
        assert!(TimePassOffer {
            issuance_enabled: false,
            ..pass.clone()
        }
        .purchase_price(3)
        .is_err());
        assert!(TimePassOffer {
            price_per_ms: u64::MAX,
            ..pass
        }
        .purchase_price(2)
        .is_err());
    }

    #[tokio::test]
    async fn policy_administration_reaches_submission_after_resolving_live_inputs() {
        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .enable_time_passes(&fixture.fqn, fixture.cashier_admin, 2, 1, 10)
                .await,
        );

        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .close_time_pass_issuance(&fixture.fqn, fixture.cashier_admin)
                .await,
        );

        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .open_time_pass_issuance(&fixture.fqn, fixture.cashier_admin)
                .await,
        );

        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .update_time_pass_terms(&fixture.fqn, fixture.cashier_admin, 3, 2, 20)
                .await,
        );

        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .enable_finite_credits(&fixture.fqn, fixture.cashier_admin, 2, 1, 10)
                .await,
        );

        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .close_finite_credit_issuance(&fixture.fqn, fixture.cashier_admin)
                .await,
        );

        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .open_finite_credit_issuance(&fixture.fqn, fixture.cashier_admin)
                .await,
        );

        let fixture = economy_action_fixture().await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .update_finite_credit_terms(&fixture.fqn, fixture.cashier_admin, 3, 2, 20)
                .await,
        );
    }

    #[tokio::test]
    async fn economy_actions_reject_invalid_values_before_chain_reads() {
        let context = sui_mocks::mock_nexus_context();
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = nexus_mocks::mock_nexus_client_without_coins(&context, &rpc_url).await;
        let fqn = "xyz.taluslabs.validation@1"
            .parse::<ToolFqn>()
            .expect("Tool FQN parses");
        let admin = sui::types::Address::from_static("0xca");
        let beneficiary = PaymentSourceKind::user_funded(client.owner().unwrap());

        assert!(client.tool().buy_time_pass(&fqn, 0).await.is_err());
        assert!(client.tool().buy_finite_credits(&fqn, 0).await.is_err());
        assert!(client
            .tool()
            .issue_time_pass(&fqn, admin, beneficiary.clone(), 10, 10)
            .await
            .is_err());
        assert!(client
            .tool()
            .issue_finite_credits(&fqn, admin, beneficiary, 0)
            .await
            .is_err());
        assert!(client
            .tool()
            .enable_finite_credits(&fqn, admin, 1, 0, 10)
            .await
            .is_err());
        assert!(client
            .tool()
            .enable_finite_credits(&fqn, admin, 1, 10, 1)
            .await
            .is_err());
        assert!(client
            .tool()
            .update_finite_credit_terms(&fqn, admin, 1, 0, 10)
            .await
            .is_err());
        assert!(client
            .tool()
            .update_finite_credit_terms(&fqn, admin, 1, 10, 1)
            .await
            .is_err());
        assert!(client
            .tool()
            .collect_invocations(&fqn, admin, &[], sui::types::Address::from_static("0xcb"),)
            .await
            .is_err());
    }

    #[tokio::test]
    async fn entitlement_purchase_and_issuance_reach_submission_with_canonical_accounts() {
        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb1"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                ledger,
                cashier_id,
                &crate::move_bindings::type_tag::<PolicyKey<time_pass::Policy>>(context),
                PolicyKey::<time_pass::Policy>::new(false),
                time_pass::Config::new(true, 2, 1, 100),
            );
            let pass_id =
                crate::move_bindings::derive_time_pass_id(context, cashier_id, expected.clone())
                    .expect("pass ID derives");
            sui_mocks::grpc::mock_get_object_not_found(ledger, pass_id);
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .buy_time_pass_for(&fixture.fqn, 10, beneficiary)
                .await,
        );

        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb2"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                ledger,
                cashier_id,
                &crate::move_bindings::type_tag::<PolicyKey<finite_credits::Policy>>(context),
                PolicyKey::<finite_credits::Policy>::new(false),
                finite_credits::Config::new(true, 2, 1, 100),
            );
            let credits_id = crate::move_bindings::derive_finite_credits_id(
                context,
                cashier_id,
                expected.clone(),
            )
            .expect("credit ID derives");
            sui_mocks::grpc::mock_get_object_not_found(ledger, credits_id);
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .buy_finite_credits_for(&fixture.fqn, 10, beneficiary)
                .await,
        );

        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb3"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            let pass_id =
                crate::move_bindings::derive_time_pass_id(context, cashier_id, expected.clone())
                    .expect("pass ID derives");
            sui_mocks::grpc::mock_get_object_not_found(ledger, pass_id);
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .issue_time_pass(&fixture.fqn, fixture.cashier_admin, beneficiary, 10, 20)
                .await,
        );

        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb4"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            let credits_id = crate::move_bindings::derive_finite_credits_id(
                context,
                cashier_id,
                expected.clone(),
            )
            .expect("credit ID derives");
            sui_mocks::grpc::mock_get_object_not_found(ledger, credits_id);
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .issue_finite_credits(&fixture.fqn, fixture.cashier_admin, beneficiary, 10)
                .await,
        );
    }

    #[tokio::test]
    async fn existing_entitlements_are_extended_without_replacing_their_accounts() {
        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb5"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                ledger,
                cashier_id,
                &crate::move_bindings::type_tag::<PolicyKey<time_pass::Policy>>(context),
                PolicyKey::<time_pass::Policy>::new(false),
                time_pass::Config::new(true, 2, 1, 100),
            );
            let pass_id =
                crate::move_bindings::derive_time_pass_id(context, cashier_id, expected.clone())
                    .expect("pass ID derives");
            let pass = TimePass::new(
                UID::new(pass_id),
                ID::new(cashier_id),
                expected,
                time_pass::State::new(10, 20),
            );
            sui_mocks::grpc::mock_get_object_bcs(
                ledger,
                sui_mocks::object_ref_for_id(pass_id),
                sui::types::Owner::Shared(3),
                bcs::to_bytes(&pass).expect("pass serializes"),
            );
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .buy_time_pass_for(&fixture.fqn, 10, beneficiary)
                .await,
        );

        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb6"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                ledger,
                cashier_id,
                &crate::move_bindings::type_tag::<PolicyKey<finite_credits::Policy>>(context),
                PolicyKey::<finite_credits::Policy>::new(false),
                finite_credits::Config::new(true, 2, 1, 100),
            );
            let credits_id = crate::move_bindings::derive_finite_credits_id(
                context,
                cashier_id,
                expected.clone(),
            )
            .expect("credit ID derives");
            let credits = FiniteCredits::new(
                UID::new(credits_id),
                ID::new(cashier_id),
                expected,
                finite_credits::State::new(7),
            );
            sui_mocks::grpc::mock_get_object_bcs(
                ledger,
                sui_mocks::object_ref_for_id(credits_id),
                sui::types::Owner::Shared(4),
                bcs::to_bytes(&credits).expect("credits serialize"),
            );
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .buy_finite_credits_for(&fixture.fqn, 10, beneficiary)
                .await,
        );

        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb7"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            let pass_id =
                crate::move_bindings::derive_time_pass_id(context, cashier_id, expected.clone())
                    .expect("pass ID derives");
            let pass = TimePass::new(
                UID::new(pass_id),
                ID::new(cashier_id),
                expected,
                time_pass::State::new(10, 20),
            );
            sui_mocks::grpc::mock_get_object_bcs(
                ledger,
                sui_mocks::object_ref_for_id(pass_id),
                sui::types::Owner::Shared(5),
                bcs::to_bytes(&pass).expect("pass serializes"),
            );
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .issue_time_pass(&fixture.fqn, fixture.cashier_admin, beneficiary, 20, 30)
                .await,
        );

        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb8"));
        let expected = beneficiary.clone();
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            let credits_id = crate::move_bindings::derive_finite_credits_id(
                context,
                cashier_id,
                expected.clone(),
            )
            .expect("credit ID derives");
            let credits = FiniteCredits::new(
                UID::new(credits_id),
                ID::new(cashier_id),
                expected,
                finite_credits::State::new(7),
            );
            sui_mocks::grpc::mock_get_object_bcs(
                ledger,
                sui_mocks::object_ref_for_id(credits_id),
                sui::types::Owner::Shared(6),
                bcs::to_bytes(&credits).expect("credits serialize"),
            );
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .issue_finite_credits(&fixture.fqn, fixture.cashier_admin, beneficiary, 10)
                .await,
        );
    }

    #[tokio::test]
    async fn finite_credit_refund_restoration_uses_the_exact_recorded_account() {
        let invocation_id = sui::types::Address::from_static("0x91");
        let credits_id = sui::types::Address::from_static("0x92");
        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0xb9"));
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            let policy =
                crate::transactions::invocation::InvocationPolicyCall::finite_credits_policy(
                    context,
                )
                .expect("finite credit policy resolves");
            let invocation = Invocation::new(
                UID::new(invocation_id),
                sui::types::Address::from_static("0xe1"),
                b"vertex".to_vec(),
                ID::new(sui::types::Address::from_static("0xe2")),
                ID::new(cashier_id),
                beneficiary.clone(),
                policy,
                vec![ID::new(credits_id)],
                0,
                MoveOption::from_option(Some(credits_id)),
                Balance {
                    value: 0,
                    phantom_t0: std::marker::PhantomData,
                },
            );
            let credits = FiniteCredits::new(
                UID::new(credits_id),
                ID::new(cashier_id),
                beneficiary,
                finite_credits::State::new(0),
            );
            sui_mocks::grpc::mock_get_object_bcs(
                ledger,
                sui_mocks::object_ref_for_id(invocation_id),
                sui::types::Owner::Address(credits_id),
                bcs::to_bytes(&invocation).expect("Invocation serializes"),
            );
            sui_mocks::grpc::mock_get_object_bcs(
                ledger,
                sui_mocks::object_ref_for_id(credits_id),
                sui::types::Owner::Shared(7),
                bcs::to_bytes(&credits).expect("credits serialize"),
            );
        })
        .await;

        assert_missing_gas(
            fixture
                .client
                .tool()
                .restore_finite_credit_refund(&fixture.fqn, invocation_id)
                .await,
        );
    }

    #[tokio::test]
    async fn economy_inspection_decodes_every_canonical_offer() {
        let fixture = economy_action_fixture_with(|context, cashier_id, ledger, _state| {
            let fqn = "xyz.taluslabs.economy.action@1"
                .parse::<ToolFqn>()
                .expect("Tool FQN parses");
            let fqn_key = ascii::String::from(fqn.to_string());
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                ledger,
                sui::types::Address::from_static("0xd7"),
                &crate::move_bindings::type_tag::<ascii::String>(context),
                fqn_key,
                17_u64,
            );
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                ledger,
                cashier_id,
                &crate::move_bindings::type_tag::<PolicyKey<finite_credits::Policy>>(context),
                PolicyKey::<finite_credits::Policy>::new(false),
                finite_credits::Config::new(true, 2, 1, 100),
            );
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                ledger,
                cashier_id,
                &crate::move_bindings::type_tag::<PolicyKey<time_pass::Policy>>(context),
                PolicyKey::<time_pass::Policy>::new(false),
                time_pass::Config::new(true, 3, 4, 200),
            );
        })
        .await;

        let economy = fixture
            .client
            .tool()
            .inspect_economy(&fixture.fqn)
            .await
            .expect("economy inspection succeeds");

        assert_eq!(economy.fixed_price_mist, 17);
        assert_eq!(
            economy.finite_credits,
            Some(FiniteCreditOffer {
                issuance_enabled: true,
                price_per_credit: 2,
                minimum_credits: 1,
                maximum_credits: 100,
            })
        );
        assert_eq!(
            economy.time_pass,
            Some(TimePassOffer {
                issuance_enabled: true,
                price_per_ms: 3,
                minimum_duration_ms: 4,
                maximum_duration_ms: 200,
            })
        );
    }

    #[tokio::test]
    async fn empty_cashier_inbox_is_discovered_without_a_mutable_index() {
        let fixture = economy_action_fixture_with(|_, _, _ledger, state| {
            state.expect_list_owned_objects().times(2).returning(|_| {
                Ok(tonic::Response::new(
                    sui::grpc::ListOwnedObjectsResponse::default(),
                ))
            });
        })
        .await;

        let inbox = fixture
            .client
            .tool()
            .inspect_cashier_inbox(&fixture.fqn)
            .await
            .expect("cashier inbox inspection succeeds");

        assert!(inbox.invocations.is_empty());
        assert!(inbox.deposits.is_empty());
    }

    #[tokio::test]
    async fn owner_collection_validates_exact_cashier_objects_before_submission() {
        let invocation_id = sui::types::Address::from_static("0x93");
        let fixture = economy_action_fixture_with(move |context, cashier_id, ledger, _state| {
            let fqn = "xyz.taluslabs.economy.action@1"
                .parse::<ToolFqn>()
                .expect("Tool FQN parses");
            let tool_id =
                crate::move_bindings::derive_tool_id(context.tool_registry.object_id(), &fqn)
                    .expect("Tool ID derives");
            let policy =
                crate::transactions::invocation::InvocationPolicyCall::fixed_price(context)
                    .expect("fixed price policy resolves")
                    .policy;
            let invocation = Invocation::new(
                UID::new(invocation_id),
                sui::types::Address::from_static("0xe1"),
                b"vertex".to_vec(),
                ID::new(tool_id),
                ID::new(cashier_id),
                PaymentSourceKind::user_funded(sui::types::Address::from_static("0xba")),
                policy,
                vec![ID::new(sui::types::Address::from_static("0xe3"))],
                9,
                MoveOption::from_option(None),
                Balance {
                    value: 9,
                    phantom_t0: std::marker::PhantomData,
                },
            );
            sui_mocks::grpc::mock_get_objects_bcs(
                ledger,
                vec![(
                    sui_mocks::object_ref_for_id(invocation_id),
                    sui::types::Owner::Address(cashier_id),
                    bcs::to_bytes(&invocation).expect("Invocation serializes"),
                    crate::move_bindings::struct_tag::<Invocation>(context),
                )],
            );
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .collect_invocations(
                    &fixture.fqn,
                    fixture.cashier_admin,
                    &[invocation_id],
                    sui::types::Address::from_static("0xbb"),
                )
                .await,
        );

        let deposit_id = sui::types::Address::from_static("0x94");
        let fixture = economy_action_fixture_with(move |_, cashier_id, ledger, _state| {
            sui_mocks::grpc::mock_get_objects_metadata(
                ledger,
                vec![(
                    sui_mocks::object_ref_for_id(deposit_id),
                    sui::types::Owner::Address(cashier_id),
                    None,
                )],
            );
        })
        .await;
        assert_missing_gas(
            fixture
                .client
                .tool()
                .collect_deposits(
                    &fixture.fqn,
                    fixture.cashier_admin,
                    &[deposit_id],
                    sui::types::Address::from_static("0xbb"),
                )
                .await,
        );
    }

    #[tokio::test]
    async fn inspect_tool_reports_missing_when_neither_object_exists() {
        let context = sui_mocks::mock_nexus_context();
        let fqn = "xyz.taluslabs.missing.tool@1".parse::<ToolFqn>().unwrap();
        let tool_id =
            crate::move_bindings::derive_tool_id(context.tool_registry.object_id(), &fqn).unwrap();
        let mut ledger_service = sui_mocks::grpc::MockLedgerService::new();
        let mut package_service = sui_mocks::grpc::MockMovePackageService::new();
        let mut state_service = sui_mocks::grpc::MockStateService::new();
        mock_registry(
            &mut ledger_service,
            &mut state_service,
            &context,
            registry_inner(sui::types::Address::from_static("0xd1"), &[]),
        );
        sui_mocks::grpc::mock_get_object_not_found(&mut ledger_service, tool_id);
        sui_mocks::grpc::mock_package_versions(
            &mut ledger_service,
            &mut package_service,
            context.packages().all().cloned(),
        );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service),
            package_service_mock: Some(package_service),
            state_service_mock: Some(state_service),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client_without_coins(&context, &rpc_url).await;

        let inspection = client.tool().inspect_tool(&fqn).await.unwrap();

        assert!(!inspection.exists);
        assert!(inspection.tool.is_none());
        assert_eq!(inspection.tool_id, tool_id);
    }

    #[tokio::test]
    async fn mixed_tool_versions_are_classified_without_aborting_the_inventory() {
        let context = sui_mocks::mock_nexus_context();
        let registry_id = context.tool_registry.object_id();
        let directory_id = sui::types::Address::from_static("0xd1");
        let entries = [
            (
                "xyz.taluslabs.current.tool@1".parse::<ToolFqn>().unwrap(),
                sui::types::Address::from_static("0xc1"),
            ),
            (
                "xyz.taluslabs.unavailable.tool@1"
                    .parse::<ToolFqn>()
                    .unwrap(),
                sui::types::Address::from_static("0xf1"),
            ),
        ];
        let keys = entries
            .iter()
            .map(|(fqn, _)| ascii::String::from(fqn.to_string()))
            .collect::<Vec<_>>();
        let mut ledger_service = sui_mocks::grpc::MockLedgerService::new();
        let mut package_service = sui_mocks::grpc::MockMovePackageService::new();
        let mut state_service = sui_mocks::grpc::MockStateService::new();
        mock_registry(
            &mut ledger_service,
            &mut state_service,
            &context,
            registry_inner(directory_id, &keys),
        );
        let key_type = crate::move_bindings::type_tag::<ascii::String>(&context);
        for (index, ((_, tool_id), key)) in entries.iter().zip(&keys).enumerate() {
            sui_mocks::grpc::mock_get_dynamic_field_by_key(
                &mut ledger_service,
                directory_id,
                &key_type,
                key.clone(),
                Node::<ascii::String, ID>::new(
                    MoveOption::from_option(index.checked_sub(1).map(|i| keys[i].clone())),
                    MoveOption::from_option(keys.get(index + 1).cloned()),
                    ID::new(*tool_id),
                ),
            );
        }
        let current_ref = sui_mocks::object_ref_for_id(entries[0].1);
        sui_mocks::grpc::mock_object_state::<ToolAnchor, ToolWitnessV1, ToolInnerV1>(
            &mut ledger_service,
            &mut state_service,
            &context,
            current_ref,
            sui::types::Owner::Shared(1),
            ToolAnchor::new(UID::new(entries[0].1)),
            tool_inner(registry_id, &entries[0].0),
        );
        sui_mocks::grpc::mock_get_object_not_found(&mut ledger_service, entries[1].1);
        sui_mocks::grpc::mock_package_versions(
            &mut ledger_service,
            &mut package_service,
            context.packages().all().cloned(),
        );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service),
            package_service_mock: Some(package_service),
            state_service_mock: Some(state_service),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client_without_coins(&context, &rpc_url).await;

        let inspections = client.tool().list_tools().await.unwrap();
        let by_fqn = inspections
            .iter()
            .map(|inspection| (inspection.fqn.to_string(), inspection))
            .collect::<HashMap<_, _>>();

        assert_eq!(inspections.len(), 2);
        assert_eq!(
            by_fqn["xyz.taluslabs.current.tool@1"].compatibility,
            ToolCompatibility::Current
        );
        assert!(by_fqn["xyz.taluslabs.current.tool@1"].tool.is_some());
        assert_eq!(
            by_fqn["xyz.taluslabs.unavailable.tool@1"].compatibility,
            ToolCompatibility::Unavailable
        );
        assert!(by_fqn["xyz.taluslabs.unavailable.tool@1"].tool.is_none());
    }

    #[tokio::test]
    async fn access_inspection_derives_and_reads_canonical_accounts() {
        let context = sui_mocks::mock_nexus_context();
        let tool_fqn = "xyz.taluslabs.access@1"
            .parse::<ToolFqn>()
            .expect("Tool FQN parses");
        let tool_id =
            crate::move_bindings::derive_tool_id(context.tool_registry.object_id(), &tool_fqn)
                .expect("tool id derives");
        let cashier_origin = context
            .type_origin(PackageRole::Tool, "tool_cashier", "ToolCashierKey")
            .expect("cashier origin resolves");
        let cashier_id = crate::move_bindings::derive_tool_cashier_id(cashier_origin, tool_id)
            .expect("cashier id derives");
        let beneficiary = PaymentSourceKind::user_funded(sui::types::Address::from_static("0x31"));
        let credits_id = crate::move_bindings::derive_finite_credits_id(
            &context,
            cashier_id,
            beneficiary.clone(),
        )
        .expect("credit account id derives");
        let pass_id =
            crate::move_bindings::derive_time_pass_id(&context, cashier_id, beneficiary.clone())
                .expect("time pass id derives");
        let credits = FiniteCredits::new(
            UID::new(credits_id),
            ID::new(cashier_id),
            beneficiary.clone(),
            finite_credits::State::new(7),
        );
        let pass = TimePass::new(
            UID::new(pass_id),
            ID::new(cashier_id),
            beneficiary.clone(),
            time_pass::State::new(10, 90),
        );

        let mut ledger = sui_mocks::grpc::MockLedgerService::new();
        let mut packages = sui_mocks::grpc::MockMovePackageService::new();
        let mut state = sui_mocks::grpc::MockStateService::new();
        mock_registry(
            &mut ledger,
            &mut state,
            &context,
            registry_inner(sui::types::Address::from_static("0xd1"), &[]),
        );
        sui_mocks::grpc::mock_nexus_package_graph(&mut ledger, &mut packages, context.packages());
        sui_mocks::grpc::mock_get_object_metadata(
            &mut ledger,
            sui_mocks::object_ref_for_id(cashier_id),
            sui::types::Owner::Shared(1),
            None,
        );
        sui_mocks::grpc::mock_get_object_bcs(
            &mut ledger,
            sui_mocks::object_ref_for_id(move_boundary::CLOCK_OBJECT_ID),
            sui::types::Owner::Shared(1),
            bcs::to_bytes(&SuiClock::new(move_boundary::CLOCK_OBJECT_ID, 50))
                .expect("clock serializes"),
        );
        sui_mocks::grpc::mock_get_object_bcs(
            &mut ledger,
            sui_mocks::object_ref_for_id(credits_id),
            sui::types::Owner::Shared(4),
            bcs::to_bytes(&credits).expect("credits serialize"),
        );
        sui_mocks::grpc::mock_get_object_bcs(
            &mut ledger,
            sui_mocks::object_ref_for_id(pass_id),
            sui::types::Owner::Shared(5),
            bcs::to_bytes(&pass).expect("pass serializes"),
        );
        state
            .expect_list_owned_objects()
            .times(1)
            .return_once(move |request| {
                assert_eq!(
                    request.get_ref().owner.as_deref(),
                    Some(credits_id.to_string().as_str())
                );
                Ok(tonic::Response::new(
                    sui::grpc::ListOwnedObjectsResponse::default(),
                ))
            });
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger),
            package_service_mock: Some(packages),
            state_service_mock: Some(state),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client_without_coins(&context, &rpc_url).await;

        let access = client
            .tool()
            .inspect_access(&tool_fqn, beneficiary.clone())
            .await
            .expect("access inspection succeeds");

        assert_eq!(access.tool_id, tool_id);
        assert_eq!(access.cashier_id, cashier_id);
        assert_eq!(access.beneficiary, beneficiary);
        assert_eq!(access.observed_at_ms, 50);
        assert_eq!(
            access.finite_credits,
            Some(FiniteCreditAccess {
                account_id: credits_id,
                remaining: 7,
                refunded_invocations: vec![],
            })
        );
        assert_eq!(
            access.time_pass,
            Some(TimePassAccess {
                account_id: pass_id,
                valid_from_ms: 10,
                valid_until_ms: 90,
                active: true,
            })
        );
    }

    #[tokio::test]
    async fn unregister_inputs_do_not_decode_tool_state() {
        let context = sui_mocks::mock_nexus_context();
        let fqn = "xyz.taluslabs.legacy.tool@1".parse::<ToolFqn>().unwrap();
        let tool_id =
            crate::move_bindings::derive_tool_id(context.tool_registry.object_id(), &fqn).unwrap();
        let tool_ref = sui_mocks::object_ref_for_id(tool_id);
        let owner_cap_ref = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0xc4"));
        let mut ledger_service = sui_mocks::grpc::MockLedgerService::new();
        let mut package_service = sui_mocks::grpc::MockMovePackageService::new();
        let mut state_service = sui_mocks::grpc::MockStateService::new();
        mock_registry(
            &mut ledger_service,
            &mut state_service,
            &context,
            registry_inner(sui::types::Address::from_static("0xd1"), &[]),
        );
        sui_mocks::grpc::mock_nexus_package_graph(
            &mut ledger_service,
            &mut package_service,
            context.packages(),
        );
        sui_mocks::grpc::mock_get_object_metadata(
            &mut ledger_service,
            tool_ref.clone(),
            sui::types::Owner::Shared(1),
            None,
        );
        sui_mocks::grpc::mock_get_object_metadata(
            &mut ledger_service,
            owner_cap_ref.clone(),
            sui::types::Owner::Address(sui::types::Address::from_static("0xa")),
            None,
        );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service),
            package_service_mock: Some(package_service),
            state_service_mock: Some(state_service),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client_without_coins(&context, &rpc_url).await;

        let (selected, selected_tool, selected_cap) = client
            .tool()
            .unregister_inputs(&fqn, *owner_cap_ref.object_id())
            .await
            .unwrap();

        assert_eq!(selected_tool, tool_ref);
        assert_eq!(selected_cap, owner_cap_ref);
        assert_eq!(
            selected.packages().get(PackageRole::Tool),
            context.packages().get(PackageRole::Tool),
        );
    }
}