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
//! A [`NexusClient`] combines a [`Signer`], object crawling, owned-coin
//! selection, and an optional shared [`Gas`] source.

use {
    crate::{
        events::{NexusEventDecoder, NexusEventIngestor, NexusEventQuery},
        nexus::{
            address_balance::{fetch_submission_context, finish_transaction, NonceAllocator},
            crawler::Crawler,
            error::NexusError,
            network::NetworkActions,
            scheduler::Scheduler,
            signer::{ExecutedTransaction, Signer},
            state::StateResolver,
            transaction::NexusTransaction,
            workflow::WorkflowActions,
        },
        sui,
        types::{NexusContext, NexusObjects, PackageRole, SharedRoot},
        ToolFqn,
    },
    std::sync::Arc,
    tokio::{
        sync::{Mutex, Notify, OnceCell},
        time::Duration,
    },
};

/// Default transaction gas budget used by clients that select a default.
pub const DEFAULT_GAS_BUDGET: u64 = sui::MIST_PER_SUI / 10;

fn sort_coins_for_ordinal_selection(coins: &mut [(sui::types::ObjectReference, u64)]) {
    coins.sort_by(|(left_coin, left_balance), (right_coin, right_balance)| {
        right_balance
            .cmp(left_balance)
            .then_with(|| left_coin.object_id().cmp(right_coin.object_id()))
    });
}

/// Gas source used to configure a [`NexusClient`] for transactions.
#[derive(Clone, Debug)]
pub enum GasSource {
    /// Owned coin-object gas with a transaction budget.
    Coin(CoinGasPool),
    /// Address-balance gas with a reusable nonce authority.
    AddressBalance(AddressBalanceGas),
}

/// Configured gas inspected from a [`NexusClient`].
pub type Gas = GasSource;

impl GasSource {
    /// Creates an owned coin-object gas source with a transaction budget.
    pub fn coin(coins: Vec<sui::types::ObjectReference>, budget: u64) -> Self {
        Self::Coin(CoinGasPool {
            coins: Arc::new(Mutex::new(coins)),
            notify: Arc::new(Notify::new()),
            budget,
            reference_gas_price: None,
        })
    }

    /// Returns the configured gas budget.
    pub fn get_budget(&self) -> u64 {
        match self {
            Self::Coin(pool) => pool.budget,
            Self::AddressBalance(gas) => gas.budget,
        }
    }

    /// Returns the shared pool when coin based gas is configured.
    #[cfg(test)]
    pub(crate) fn coin_pool(&self) -> Option<&CoinGasPool> {
        match self {
            Self::Coin(pool) => Some(pool),
            Self::AddressBalance(_) => None,
        }
    }

    fn reference_gas_price(&self) -> Option<u64> {
        match self {
            Self::Coin(pool) => pool.reference_gas_price,
            Self::AddressBalance(_) => None,
        }
    }
}

/// Shared owned coin source used for coin based gas.
#[derive(Clone, Debug)]
pub struct CoinGasPool {
    coins: Arc<Mutex<Vec<sui::types::ObjectReference>>>,
    notify: Arc<Notify>,
    budget: u64,
    reference_gas_price: Option<u64>,
}

impl CoinGasPool {
    /// Acquires an owned gas coin, waiting until one is available.
    pub(crate) async fn acquire_gas_coin(&self) -> sui::types::ObjectReference {
        loop {
            if let Some(coin) = self.coins.lock().await.pop() {
                return coin;
            }

            self.notify.notified().await;
        }
    }

    /// Returns an owned gas coin to the pool and wakes one waiter.
    pub(crate) async fn release_gas_coin(&self, coin: sui::types::ObjectReference) {
        self.coins.lock().await.push(coin);
        self.notify.notify_one();
    }
}

/// Reusable address balance gas configuration.
///
/// Clones share one [`NonceAllocator`] so transactions from the same sender use
/// distinct nonces.
#[derive(Clone, Debug)]
pub struct AddressBalanceGas {
    budget: u64,
    nonces: NonceAllocator,
}

impl AddressBalanceGas {
    /// Creates a configuration backed by the process nonce authority.
    pub fn new(budget: u64) -> Self {
        Self::with_nonce_allocator(budget, NonceAllocator::default())
    }

    /// Creates a configuration backed by an existing [`NonceAllocator`].
    pub fn with_nonce_allocator(budget: u64, nonces: NonceAllocator) -> Self {
        Self { budget, nonces }
    }

    fn allocate_nonce(&self) -> Result<u32, NexusError> {
        self.nonces.allocate()
    }
}

/// Builder for [`NexusClient`].
#[derive(Default)]
pub struct NexusClientBuilder {
    wallet: Option<super::wallet::WalletClient>,
    pk: Option<sui::crypto::Ed25519PrivateKey>,
    rpc_url: Option<String>,
    state_catalog_rpc_url: Option<String>,
    gas_coins: Vec<sui::types::ObjectReference>,
    gas_budget: Option<u64>,
    address_balance_gas: Option<AddressBalanceGas>,
    nexus_objects: Option<NexusObjects>,
    transaction_timeout: Option<Duration>,
}

impl NexusClientBuilder {
    /// Create a new builder instance.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a private key to the builder.
    pub fn with_private_key(mut self, pk: sui::crypto::Ed25519PrivateKey) -> Self {
        self.pk = Some(pk);
        self
    }

    /// Reuses the wallet authority used by other domain clients such as Walrus.
    /// Its RPC endpoint becomes the default and must not be overridden with a
    /// different endpoint. Supplying a second private key is an error.
    pub fn with_wallet(mut self, wallet: super::wallet::WalletClient) -> Self {
        self.wallet = Some(wallet);
        self
    }

    /// Which RPC to connect to.
    pub fn with_rpc_url(mut self, rpc_url: &str) -> Self {
        self.rpc_url = Some(rpc_url.to_string());
        self
    }

    /// Uses an indexed Sui service to discover dynamic field collections.
    ///
    /// Exact object state, simulation, signing, and submission continue to use
    /// the service configured by [`Self::with_rpc_url`].
    pub fn with_state_catalog_rpc_url(mut self, rpc_url: &str) -> Self {
        self.state_catalog_rpc_url = Some(rpc_url.to_owned());
        self
    }

    /// Configures coin based gas with owned coins and a budget.
    pub fn with_gas(mut self, coins: Vec<sui::types::ObjectReference>, budget: u64) -> Self {
        self.gas_coins = coins;
        self.gas_budget = Some(budget);
        self
    }

    /// Configures address balance based gas with the process nonce authority.
    ///
    /// Independently constructed clients in this process allocate from the
    /// same nonce sequence. Use [`Self::with_address_balance_gas_config`] when
    /// the caller must supply a distinct nonce authority explicitly.
    pub fn with_address_balance_gas(mut self, budget: u64) -> Self {
        self.address_balance_gas = Some(AddressBalanceGas::new(budget));
        self
    }

    /// Configures address balance based gas using a reusable
    /// [`AddressBalanceGas`].
    pub fn with_address_balance_gas_config(mut self, gas: AddressBalanceGas) -> Self {
        self.address_balance_gas = Some(gas);
        self
    }

    /// Configures stable Nexus environment identities.
    pub fn with_nexus_objects(mut self, nexus_objects: NexusObjects) -> Self {
        self.nexus_objects = Some(nexus_objects);
        self
    }

    /// Set transaction timeout duration.
    pub fn with_transaction_timeout(mut self, timeout: Duration) -> Self {
        self.transaction_timeout = Some(timeout);
        self
    }

    /// Builds the [`NexusClient`].
    ///
    /// When no gas strategy is configured, the client is built without gas.
    /// Attach gas later with [`NexusClient::set_gas_source`] before submitting
    /// a transaction.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::Configuration`] when required configuration is
    /// missing, both gas sources are configured, or coin based gas is
    /// explicitly configured without a coin. Returns [`NexusError::Rpc`] when
    /// the client or coin based gas context cannot be initialized.
    /// Returns [`NexusError::MissingPrivateKey`] when a gas source is
    /// configured without a signing key.
    pub async fn build(self) -> Result<NexusClient, NexusError> {
        if self.wallet.is_some() && self.pk.is_some() {
            return Err(NexusError::Configuration(
                "provide either a wallet or a private key".into(),
            ));
        }
        let rpc_url = self
            .rpc_url
            .or_else(|| {
                self.wallet
                    .as_ref()
                    .map(|wallet| wallet.rpc_url().to_owned())
            })
            .ok_or_else(|| NexusError::Configuration("RPC URL is required".into()))?;
        if self
            .wallet
            .as_ref()
            .is_some_and(|wallet| wallet.grpc_client().uri() != rpc_url.as_str())
        {
            return Err(NexusError::Configuration(
                "RPC URL differs from the supplied wallet".into(),
            ));
        }
        let nexus_objects = self
            .nexus_objects
            .ok_or_else(|| NexusError::Configuration("Nexus objects are required".into()))?;
        let coin_gas_requested = self.gas_budget.is_some() || !self.gas_coins.is_empty();
        let gas_source = match (coin_gas_requested, self.address_balance_gas) {
            (true, Some(_)) => {
                return Err(NexusError::Configuration(
                    "coin based gas and address balance based gas cannot both be configured".into(),
                ));
            }
            (true, None) if self.gas_coins.is_empty() => {
                return Err(NexusError::Configuration(
                    "at least one gas coin is required for coin based gas".into(),
                ));
            }
            (true, None) => Some(GasSource::coin(
                self.gas_coins,
                self.gas_budget
                    .ok_or_else(|| NexusError::Configuration("gas budget is required".into()))?,
            )),
            (false, Some(gas)) => Some(GasSource::AddressBalance(gas)),
            (false, None) => None,
        };
        if gas_source.is_some() && self.pk.is_none() && self.wallet.is_none() {
            return Err(NexusError::MissingPrivateKey);
        }

        let client = match self.wallet.as_ref() {
            Some(wallet) => wallet.grpc_client(),
            None => Arc::new(sui::grpc::client(&rpc_url).map_err(NexusError::Rpc)?),
        };
        let wallet = self.wallet.or_else(|| {
            self.pk.map(|pk| {
                super::wallet::WalletClient::from_client(
                    Arc::clone(&client),
                    pk,
                    self.transaction_timeout.unwrap_or(Duration::from_secs(5)),
                )
            })
        });
        let actual_chain = match wallet.as_ref() {
            Some(wallet) => wallet.validate_chain().await?.to_owned(),
            None => client
                .as_ref()
                .clone()
                .ledger_client()
                .get_service_info(sui::grpc::GetServiceInfoRequest::default())
                .await
                .map_err(|error| NexusError::Rpc(error.into()))?
                .into_inner()
                .chain_id
                .ok_or_else(|| {
                    NexusError::Rpc(anyhow::anyhow!("Sui service omitted its chain ID"))
                })?,
        };
        if actual_chain != nexus_objects.chain_id {
            return Err(NexusError::ChainMismatch {
                expected: nexus_objects.chain_id,
                actual: actual_chain,
            });
        }
        let catalog = match self.state_catalog_rpc_url {
            Some(catalog_url) if catalog_url != rpc_url => {
                let catalog_client =
                    Arc::new(sui::grpc::client(&catalog_url).map_err(NexusError::Rpc)?);
                let catalog_chain = catalog_client
                    .as_ref()
                    .clone()
                    .ledger_client()
                    .get_service_info(sui::grpc::GetServiceInfoRequest::default())
                    .await
                    .map_err(|error| NexusError::Rpc(error.into()))?
                    .into_inner()
                    .chain_id
                    .ok_or_else(|| {
                        NexusError::Rpc(anyhow::anyhow!("Sui state catalog omitted its chain ID"))
                    })?;
                if catalog_chain != nexus_objects.chain_id {
                    return Err(NexusError::ChainMismatch {
                        expected: nexus_objects.chain_id,
                        actual: catalog_chain,
                    });
                }
                catalog_client
            }
            _ => Arc::clone(&client),
        };
        let nexus_objects = Arc::new(nexus_objects);
        let crawler = Arc::new(Crawler::with_state_catalog(Arc::clone(&client), catalog));
        let state_resolver = StateResolver::new(Arc::clone(&crawler));

        let signer = wallet.map(|wallet| {
            Signer::with_wallet(
                match self.transaction_timeout {
                    Some(timeout) => wallet.with_transaction_timeout(timeout),
                    None => wallet,
                },
                crate::events::NexusEventDecoder::new(
                    state_resolver.clone(),
                    Arc::clone(&nexus_objects),
                ),
            )
        });

        let nexus_client = NexusClient {
            signer,
            gas: Arc::new(OnceCell::new()),
            nexus_objects,
            crawler,
            state_resolver,
            rpc_url,
        };
        if let Some(gas_source) = gas_source {
            nexus_client.set_gas_source(gas_source).await?;
        }

        Ok(nexus_client)
    }
}

#[derive(Clone)]
pub struct NexusClient {
    /// The wallet context to use for transactions. This defines the TX sender
    /// address when a private key was configured.
    pub(super) signer: Option<Signer>,
    /// Shared optional gas configuration for Nexus operations.
    gas: Arc<OnceCell<GasSource>>,
    /// Nexus objects to use.
    pub(super) nexus_objects: Arc<NexusObjects>,
    /// Provide access to an instantiated object crawler.
    pub(super) crawler: Arc<Crawler>,
    /// Resolves live state and immutable package graphs.
    pub(super) state_resolver: StateResolver,
    /// RPC URL used by the client.
    pub(super) rpc_url: String,
}

impl NexusClient {
    /// Return a [`NexusClientBuilder`] instance for building a Nexus client.
    pub fn builder() -> NexusClientBuilder {
        NexusClientBuilder::new()
    }

    /// Return a [`NetworkActions`] instance for Nexus network fee operations.
    pub fn network(&self) -> NetworkActions {
        NetworkActions {
            client: self.clone(),
        }
    }

    /// Return a [`WorkflowActions`] instance for performing workflow-related operations.
    pub fn workflow(&self) -> WorkflowActions {
        WorkflowActions {
            client: self.clone(),
        }
    }

    /// Returns the scheduler facade for this client.
    pub fn scheduler(&self) -> Scheduler {
        Scheduler {
            client: self.clone(),
        }
    }

    /// Starts a programmable transaction for effects on an existing object.
    ///
    /// The object witness is validated for SDK compatibility, while the fixed
    /// runtime authority selects the package graph. This prevents a historical
    /// Task or execution from routing effects back through historical code.
    ///
    /// # Errors
    ///
    /// Returns compatibility, object state, or RPC errors reported by
    /// [`Self::context_for_object`] and [`Self::runtime_context`].
    pub async fn transaction_for_object(
        &self,
        object_id: sui::types::Address,
        required_roots: &[SharedRoot],
    ) -> Result<NexusTransaction, NexusError> {
        self.context_for_object(object_id).await?;
        let context = self.runtime_context(required_roots).await?;
        Ok(NexusTransaction::for_object(
            self.clone(),
            context,
            object_id,
        ))
    }

    /// Starts a programmable transaction whose package graph is selected by
    /// an explicit creator package.
    ///
    /// # Errors
    ///
    /// Returns compatibility, package metadata, or RPC errors reported by
    /// [`Self::context_for_creator`].
    pub async fn transaction_for_creator(
        &self,
        creator_package: sui::types::Address,
        creator_role: PackageRole,
        required_roots: &[SharedRoot],
    ) -> Result<NexusTransaction, NexusError> {
        let context = self
            .context_for_creator(creator_package, creator_role, required_roots)
            .await?;
        Ok(NexusTransaction::for_creator(
            self.clone(),
            context,
            creator_package,
            creator_role,
        ))
    }

    /// Returns a
    /// [`NetworkAuthActions`](crate::nexus::network_auth::NetworkAuthActions)
    /// instance for tool network authorization operations.
    pub fn network_auth(&self) -> crate::nexus::network_auth::NetworkAuthActions {
        crate::nexus::network_auth::NetworkAuthActions {
            client: self.clone(),
        }
    }

    /// Returns a [`ToolActions`](crate::nexus::tool::ToolActions) instance for
    /// tool operations.
    pub fn tool(&self) -> crate::nexus::tool::ToolActions {
        crate::nexus::tool::ToolActions {
            client: self.clone(),
        }
    }

    /// Returns a [`TapActions`](crate::nexus::tap::TapActions) instance for
    /// standard TAP operations.
    pub fn tap(&self) -> crate::nexus::tap::TapActions {
        crate::nexus::tap::TapActions {
            client: self.clone(),
        }
    }

    /// Return a [`Crawler`] instance for object crawling operations.
    pub fn crawler(&self) -> &Crawler {
        &self.crawler
    }

    /// Returns the live object and package state resolver.
    pub fn state_resolver(&self) -> &StateResolver {
        &self.state_resolver
    }

    /// Resolves the operation context selected by one live object witness.
    ///
    /// Package metadata is resolved only for this request. Stable environment
    /// identity remains shared by all contexts created by this client.
    ///
    /// # Errors
    ///
    /// Returns compatibility, object state, or RPC errors reported by
    /// [`StateResolver::resolve_context`].
    pub async fn context_for_object(
        &self,
        object_id: sui::types::Address,
    ) -> Result<Arc<NexusContext>, NexusError> {
        let (_, context) = self
            .state_resolver
            .resolve_context(Arc::clone(&self.nexus_objects), object_id)
            .await?;
        Ok(Arc::new(context))
    }

    /// Resolves the operation context selected by a canonical shared root.
    ///
    /// # Errors
    ///
    /// Returns compatibility, object state, or RPC errors reported by
    /// [`Self::context_for_object`].
    pub async fn context_for_root(
        &self,
        root: &SharedRoot,
    ) -> Result<Arc<NexusContext>, NexusError> {
        self.context_for_object(root.object_id()).await
    }

    /// Resolves one source object and validates every canonical root used by
    /// the operation.
    ///
    /// # Errors
    ///
    /// Returns compatibility, object state, or RPC errors reported by
    /// [`StateResolver::resolve_context_with_roots`].
    pub async fn context_for_object_with_roots(
        &self,
        object_id: sui::types::Address,
        required_roots: &[SharedRoot],
    ) -> Result<Arc<NexusContext>, NexusError> {
        let (_, context) = self
            .state_resolver
            .resolve_context_with_roots(Arc::clone(&self.nexus_objects), object_id, required_roots)
            .await?;
        Ok(Arc::new(context))
    }

    /// Resolves an explicit creator package after validating every root it
    /// will use.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::IncompatiblePackage`] when creator linkage does
    /// not match current root authority. Other resolver and RPC failures are
    /// returned unchanged.
    pub async fn context_for_creator(
        &self,
        creator_package: sui::types::Address,
        creator_role: PackageRole,
        required_roots: &[SharedRoot],
    ) -> Result<Arc<NexusContext>, NexusError> {
        let context = self
            .state_resolver
            .resolve_creator_context(
                Arc::clone(&self.nexus_objects),
                creator_package,
                creator_role,
                required_roots,
            )
            .await?;
        Ok(Arc::new(context))
    }

    /// Resolves the package graph preferred for new proposal construction.
    ///
    /// This context remains available while runtime effects are paused. It is
    /// a routing decision only and does not confer protocol effect authority.
    ///
    /// # Errors
    ///
    /// Returns routing, package compatibility, object state, or RPC errors
    /// reported by [`StateResolver::resolve_routing_context`].
    pub async fn routing_context(
        &self,
        required_roots: &[SharedRoot],
    ) -> Result<Arc<NexusContext>, NexusError> {
        let context = self
            .state_resolver
            .resolve_routing_context(Arc::clone(&self.nexus_objects), required_roots)
            .await?;
        Ok(Arc::new(context))
    }

    /// Resolves the only package graph currently allowed to produce protocol effects.
    ///
    /// # Errors
    ///
    /// Returns runtime authority, package compatibility, object state, or RPC
    /// errors reported by [`StateResolver::resolve_runtime_context`].
    pub async fn runtime_context(
        &self,
        required_roots: &[SharedRoot],
    ) -> Result<Arc<NexusContext>, NexusError> {
        let context = self
            .state_resolver
            .resolve_runtime_context(Arc::clone(&self.nexus_objects), required_roots)
            .await?;
        Ok(Arc::new(context))
    }

    /// Fetches the current transaction input reference for a stable object ID.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::Rpc`] when the object metadata cannot be fetched.
    pub(crate) async fn object_reference(
        &self,
        object_id: sui::types::Address,
    ) -> Result<sui::types::ObjectReference, NexusError> {
        self.crawler
            .get_object_metadata(object_id)
            .await
            .map(|object| object.object_ref())
            .map_err(NexusError::Rpc)
    }

    /// Return the owner address derived from this client's signing key.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::MissingPrivateKey`] for a query-only client.
    pub fn owner(&self) -> Result<sui::types::Address, NexusError> {
        Ok(self.signer()?.get_active_address())
    }

    /// Return a shared handle to the gRPC client used by this client.
    pub fn grpc_client(&self) -> Arc<sui::grpc::Client> {
        self.crawler.grpc_client()
    }

    /// Clone the inner gRPC client for independently mutable or long-lived operations.
    ///
    /// The clone reuses the configured transport and does not reconstruct a connection from the
    /// stored RPC URL.
    pub fn clone_grpc_client(&self) -> sui::grpc::Client {
        self.crawler.clone_grpc_client()
    }

    /// Fetch every coin owned by this client's signing address with the exact
    /// requested Move struct tag.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::Rpc`] when the owned-object query fails.
    /// Returns [`NexusError::MissingPrivateKey`] for a query-only client.
    pub async fn fetch_coins_by_type(
        &self,
        object_type: sui::types::StructTag,
    ) -> Result<Vec<(sui::types::ObjectReference, u64)>, NexusError> {
        let owner = self.owner()?;
        self.crawler
            .fetch_coins_for_address_by_type(owner, object_type)
            .await
            .map_err(NexusError::Rpc)
    }

    /// Fetch an owned SUI coin by object ID.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::Wallet`] when the signing address owns no SUI
    /// coins or does not own `coin_id`. Returns [`NexusError::Rpc`] when the
    /// owned-object query fails.
    /// Returns [`NexusError::MissingPrivateKey`] for a query-only client.
    pub async fn fetch_coin(
        &self,
        coin_id: sui::types::Address,
    ) -> Result<sui::types::ObjectReference, NexusError> {
        self.fetch_coin_with_balance(coin_id)
            .await
            .map(|(coin, _)| coin)
    }

    /// Fetch an owned SUI coin and its balance by object ID.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::Wallet`] when the signing address owns no SUI
    /// coins or does not own `coin_id`. Returns [`NexusError::Rpc`] when the
    /// owned-object query fails.
    /// Returns [`NexusError::MissingPrivateKey`] for a query-only client.
    pub async fn fetch_coin_with_balance(
        &self,
        coin_id: sui::types::Address,
    ) -> Result<(sui::types::ObjectReference, u64), NexusError> {
        let coins = self
            .fetch_coins_by_type(sui::types::StructTag::gas_coin())
            .await?;

        if coins.is_empty() {
            return Err(NexusError::Wallet(anyhow::anyhow!(
                "The wallet does not have enough coins to submit the transaction"
            )));
        }

        coins
            .into_iter()
            .find(|(coin, _)| *coin.object_id() == coin_id)
            .ok_or_else(|| {
                NexusError::Wallet(anyhow::anyhow!("Coin '{coin_id}' not found in wallet"))
            })
    }

    /// Fetch an owned coin with the requested Move type by object ID or
    /// deterministic ordinal.
    ///
    /// An explicit object ID uses an exact ledger read and does not require an
    /// owned object index. When `coin_id` is [`None`], coins are ordered by
    /// balance descending and object ID ascending before selecting `ordinal`.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::Wallet`] when no matching coin exists or the
    /// ordinal is out of range. Returns [`NexusError::Rpc`] when the
    /// owned-object query fails.
    /// Returns [`NexusError::MissingPrivateKey`] for a query-only client.
    pub async fn fetch_coin_by_type(
        &self,
        coin_id: Option<sui::types::Address>,
        ordinal: usize,
        object_type: sui::types::StructTag,
    ) -> Result<sui::types::ObjectReference, NexusError> {
        let label = format!("coins of type '{object_type}'");
        if let Some(coin_id) = coin_id {
            let owner = self.owner()?;
            let object = self
                .crawler
                .get_object_update_reference(coin_id, None)
                .await
                .map_err(NexusError::Rpc)?;
            if object.owner != sui::types::Owner::Address(owner) {
                return Err(NexusError::Wallet(anyhow::anyhow!(
                    "Object '{coin_id}' with {label} is not owned by wallet '{owner}'"
                )));
            }
            if object.object_type != object_type {
                return Err(NexusError::Wallet(anyhow::anyhow!(
                    "Object '{coin_id}' has type '{}', expected '{object_type}'",
                    object.object_type
                )));
            }
            return Ok(sui::types::ObjectReference::new(
                coin_id,
                object.version,
                object.digest,
            ));
        }

        let mut coins = self.fetch_coins_by_type(object_type).await?;

        if coins.is_empty() {
            return Err(NexusError::Wallet(anyhow::anyhow!(
                "The wallet does not have enough {label}"
            )));
        }

        sort_coins_for_ordinal_selection(&mut coins);
        if ordinal >= coins.len() {
            return Err(NexusError::Wallet(anyhow::anyhow!(
                "The wallet does not have enough {label} to select object #{ordinal}"
            )));
        }

        Ok(coins.swap_remove(ordinal).0)
    }

    /// Return the RPC URL configured for this client.
    pub fn rpc_url(&self) -> &str {
        &self.rpc_url
    }

    /// Shares the signing wallet with storage and other domain clients.
    /// Returns `MissingPrivateKey` when the client has no signer.
    pub fn wallet(&self) -> Result<&super::wallet::WalletClient, NexusError> {
        self.signer().map(Signer::wallet)
    }

    /// Returns the configured signer, or `MissingPrivateKey` for a reader client.
    pub fn signer(&self) -> Result<&Signer, NexusError> {
        self.signer.as_ref().ok_or(NexusError::MissingPrivateKey)
    }

    /// Returns a [`NexusEventIngestor`] whose server filter is selected by the
    /// witness on `filter_source`.
    ///
    /// Event decoding still resolves each emitter package independently. The
    /// source controls only the exact wrapper types sent to the Sui server.
    ///
    /// # Errors
    ///
    /// Returns compatibility, object state, or RPC errors reported by
    /// [`Self::context_for_object`].
    pub async fn event_ingestor(
        &self,
        filter_source: sui::types::Address,
    ) -> Result<NexusEventIngestor, NexusError> {
        self.event_ingestor_inner(filter_source, None).await
    }

    /// Returns a [`NexusEventIngestor`] that omits compiled protocol events
    /// rejected by `filter` before resolving emitter packages or decoding BCS.
    ///
    /// Events unknown to this SDK are retained so consumers still fail closed
    /// when a compatible package introduces unsupported protocol behavior.
    ///
    /// # Errors
    ///
    /// Returns compatibility, object state, or RPC errors reported by
    /// [`Self::context_for_object`].
    pub async fn filtered_event_ingestor(
        &self,
        filter_source: sui::types::Address,
        filter: fn(&str) -> bool,
    ) -> Result<NexusEventIngestor, NexusError> {
        self.event_ingestor_inner(filter_source, Some(filter)).await
    }

    /// Returns an event ingestor whose server filter uses the complete package
    /// graph selected by the current runtime authority.
    ///
    /// Use this when accepted event types span package roles that are not
    /// dependencies of one canonical root. Historical emitter metadata still
    /// selects the decoder for each event.
    ///
    /// Events unknown to this SDK are retained so consumers still fail closed
    /// when a compatible package introduces unsupported protocol behavior.
    ///
    /// # Errors
    ///
    /// Returns runtime authority, package compatibility, object state, or RPC
    /// errors reported by [`Self::runtime_context`].
    pub async fn filtered_runtime_event_ingestor(
        &self,
        filter: fn(&str) -> bool,
    ) -> Result<NexusEventIngestor, NexusError> {
        let context = self.runtime_context(&[]).await?;
        Ok(self.filtered_event_ingestor_for_context(context, filter))
    }

    /// Returns a filtered event ingestor for an already verified package graph.
    ///
    /// This avoids reading [`crate::move_bindings::kernel::runtime_authority::RuntimeAuthority`]
    /// again when a caller has just established runtime compatibility. Event
    /// decoding still resolves each historical emitter independently.
    pub fn filtered_event_ingestor_for_context(
        &self,
        context: Arc<NexusContext>,
        filter: fn(&str) -> bool,
    ) -> NexusEventIngestor {
        self.event_ingestor_for_context(context, Some(filter))
    }

    async fn event_ingestor_inner(
        &self,
        filter_source: sui::types::Address,
        filter: Option<fn(&str) -> bool>,
    ) -> Result<NexusEventIngestor, NexusError> {
        let context = self.context_for_object(filter_source).await?;
        Ok(self.event_ingestor_for_context(context, filter))
    }

    fn event_ingestor_for_context(
        &self,
        context: Arc<NexusContext>,
        filter: Option<fn(&str) -> bool>,
    ) -> NexusEventIngestor {
        let decoder =
            NexusEventDecoder::new(self.state_resolver.clone(), Arc::clone(&self.nexus_objects));
        let mut query = NexusEventQuery::new(context, decoder);
        if let Some(filter) = filter {
            query = query.with_supported_event_filter(filter);
        }
        NexusEventIngestor::new(&self.rpc_url, query)
    }

    /// Attaches the gas source shared by this client, its clones, and action facades.
    ///
    /// Coin based gas validates that at least one coin is present and fetches
    /// the current reference gas price before the shared write-once transition.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError::GasSourceAlreadyConfigured`] when gas is already
    /// attached, [`NexusError::MissingPrivateKey`] when no signing key is
    /// configured, or [`NexusError::Configuration`] when coin based gas has no
    /// coins. Returns [`NexusError::Rpc`] when the reference gas price cannot be fetched.
    pub async fn set_gas_source(&self, mut source: GasSource) -> Result<(), NexusError> {
        self.signer()?;
        if self.gas.get().is_some() {
            return Err(NexusError::GasSourceAlreadyConfigured);
        }

        match &mut source {
            GasSource::Coin(pool) => {
                if pool.coins.lock().await.is_empty() {
                    return Err(NexusError::Configuration(
                        "at least one gas coin is required for coin based gas".into(),
                    ));
                }
                let mut client = self.clone_grpc_client();
                let reference_gas_price = client
                    .get_reference_gas_price()
                    .await
                    .map_err(|error| NexusError::Rpc(error.into()))?;
                pool.reference_gas_price = Some(reference_gas_price);
            }
            GasSource::AddressBalance(_) => {}
        }

        self.gas
            .set(source)
            .map_err(|_| NexusError::GasSourceAlreadyConfigured)
    }

    /// Returns a clone of the configured [`Gas`], or `None` when unattached.
    pub fn gas_config(&self) -> Option<Gas> {
        self.gas.get().cloned()
    }

    /// Returns the cached reference gas price for coin based submissions.
    ///
    /// Missing gas and address balance based gas return `None`.
    pub fn get_reference_gas_price(&self) -> Option<u64> {
        self.gas.get().and_then(GasSource::reference_gas_price)
    }

    /// Get the Nexus objects.
    pub fn get_nexus_objects(&self) -> Arc<NexusObjects> {
        Arc::clone(&self.nexus_objects)
    }

    /// Submits a programmable transaction through this client's configured
    /// [`Gas`] source.
    ///
    /// # Errors
    ///
    /// Returns [`NexusError`] when transaction construction, signing, or
    /// execution fails.
    pub async fn submit_transaction(
        &self,
        tx: sui::types::ProgrammableTransaction,
        address: sui::types::Address,
    ) -> Result<ExecutedTransaction, NexusError> {
        let signer = self.signer()?;
        let gas = self.gas_configured()?;
        let response = match &gas {
            GasSource::Coin(pool) => {
                let reference_gas_price = pool.reference_gas_price.ok_or_else(|| {
                    NexusError::Configuration("coin gas source is not prepared".into())
                })?;
                let mut gas_coin = pool.acquire_gas_coin().await;
                let tx = sui::types::Transaction {
                    kind: sui::types::TransactionKind::ProgrammableTransaction(tx),
                    sender: address,
                    gas_payment: sui::types::GasPayment {
                        objects: vec![gas_coin.clone()],
                        owner: address,
                        price: reference_gas_price,
                        budget: pool.budget,
                    },
                    expiration: sui::types::TransactionExpiration::None,
                };
                let signature = signer.sign_tx(&tx).await?;
                let response = signer.execute_tx(tx, signature, &mut gas_coin).await;
                pool.release_gas_coin(gas_coin).await;
                response
            }
            GasSource::AddressBalance(gas) => {
                let mut client = self.clone_grpc_client();
                let context = fetch_submission_context(&mut client).await?;
                let nonce = gas.allocate_nonce()?;
                let tx = finish_transaction(tx, address, gas.budget, context, nonce);
                let signature = signer.sign_tx(&tx).await?;
                signer.execute_tx_without_gas_coin(tx, signature).await
            }
        };

        response
    }

    pub(crate) fn gas_configured(&self) -> Result<Gas, NexusError> {
        self.gas_config().ok_or_else(|| {
            NexusError::Configuration("a gas source is required for transaction operations".into())
        })
    }

    /// Derive and fetch a [`Tool`] object based on the provided tool FQN.
    pub(crate) async fn fetch_tool(
        &self,
        tool_fqn: &ToolFqn,
    ) -> anyhow::Result<sui::types::ObjectReference, NexusError> {
        let crawler = self.crawler();
        let tool_registry_object_id = self.nexus_objects.tool_registry.object_id();

        let tool_id = crate::move_bindings::derive_tool_id(tool_registry_object_id, tool_fqn)
            .map_err(NexusError::Parsing)?;
        let tool = crawler
            .get_object_metadata(tool_id)
            .await
            .map_err(NexusError::Rpc)?;

        Ok(tool.object_ref())
    }

    /// Derive and fetch a [`ToolCashier`] object based on the provided tool FQN.
    pub(crate) async fn fetch_tool_cashier(
        &self,
        tool_fqn: &ToolFqn,
    ) -> anyhow::Result<sui::types::ObjectReference, NexusError> {
        let crawler = self.crawler();
        let tool_registry_object_id = self.nexus_objects.tool_registry.object_id();
        let tool_id = crate::move_bindings::derive_tool_id(tool_registry_object_id, tool_fqn)
            .map_err(NexusError::Parsing)?;
        let context = self.context_for_object(tool_id).await?;
        let tool_package = context
            .require_package(PackageRole::Tool)
            .map_err(|error| NexusError::Configuration(error.to_string()))?;
        let tool_cashier_origin = tool_package
            .type_origin("tool_cashier", "ToolCashierKey")
            .map_err(|error| NexusError::Configuration(error.to_string()))?;
        let tool_cashier_id =
            crate::move_bindings::derive_tool_cashier_id(tool_cashier_origin, tool_id)
                .map_err(NexusError::Parsing)?;
        let tool_cashier = crawler
            .get_object_metadata(tool_cashier_id)
            .await
            .map_err(NexusError::Rpc)?;

        Ok(tool_cashier.object_ref())
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::test_utils::{
            nexus_mocks,
            sui_mocks::{self},
        },
    };

    fn owned_coin_object(
        object_ref: sui::types::ObjectReference,
        owner: sui::types::Address,
        balance: u64,
        object_type: &sui::types::StructTag,
    ) -> sui::grpc::Object {
        let mut object = sui::grpc::Object::default();
        object.set_object_id(*object_ref.object_id());
        object.set_owner(sui::grpc::Owner::from(sui::types::Owner::Address(owner)));
        object.set_version(object_ref.version());
        object.set_digest(*object_ref.digest());
        object.set_balance(balance);
        object.set_object_type(object_type.to_string());
        object
    }

    async fn client_with_owned_coins(
        pk: sui::crypto::Ed25519PrivateKey,
        object_type: sui::types::StructTag,
        objects: Vec<sui::grpc::Object>,
    ) -> NexusClient {
        let owner = pk.public_key().derive_address();
        let expected_owner = owner.to_string();
        let expected_object_type = object_type.to_string();
        let mut state_service_mock = sui_mocks::grpc::MockStateService::new();
        state_service_mock
            .expect_list_owned_objects()
            .times(1)
            .return_once(move |request| {
                assert_eq!(
                    request.get_ref().owner.as_deref(),
                    Some(expected_owner.as_str())
                );
                assert_eq!(
                    request.get_ref().object_type.as_deref(),
                    Some(expected_object_type.as_str())
                );
                let mut response = sui::grpc::ListOwnedObjectsResponse::default();
                response.set_objects(objects);
                Ok(response.into())
            });
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            state_service_mock: Some(state_service_mock),
            ..Default::default()
        });

        NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build")
    }

    async fn client_with_exact_object(
        pk: sui::crypto::Ed25519PrivateKey,
        object: sui::grpc::Object,
    ) -> NexusClient {
        let expected_id = object
            .object_id_opt()
            .expect("test object has an ID")
            .to_owned();
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        ledger_service_mock
            .expect_get_object()
            .withf(move |request| {
                request.get_ref().object_id.as_deref() == Some(expected_id.as_str())
            })
            .times(1)
            .return_once(move |_| {
                let mut response = sui::grpc::GetObjectResponse::default();
                response.set_object(object);
                Ok(response.into())
            });
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            ..Default::default()
        });

        NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build")
    }

    async fn keyless_client(rpc_url: &str) -> NexusClient {
        NexusClientBuilder::new()
            .with_rpc_url(rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("query-only client should build without a private key")
    }

    #[tokio::test]
    async fn stable_environment_identity_is_shared_by_client_clones() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = keyless_client(&rpc_url).await;
        let cloned = client.clone();

        assert!(Arc::ptr_eq(
            &client.get_nexus_objects(),
            &cloned.get_nexus_objects(),
        ));
        assert_eq!(client.get_nexus_objects(), cloned.get_nexus_objects());
    }

    #[tokio::test]
    async fn released_coin_can_be_acquired_again() {
        let coin1 = sui_mocks::mock_sui_object_ref();
        let coin2 = sui_mocks::mock_sui_object_ref();

        let gas = CoinGasPool {
            coins: Arc::new(Mutex::new(vec![coin1.clone(), coin2.clone()])),
            notify: Arc::new(Notify::new()),
            budget: 1000,
            reference_gas_price: Some(1),
        };

        // Acquire coins
        let acquired1 = gas.acquire_gas_coin().await;
        let acquired2 = gas.acquire_gas_coin().await;

        assert!(acquired1 == coin2 || acquired1 == coin1);
        assert!(acquired2 == coin2 || acquired2 == coin1);
        assert_ne!(acquired1, acquired2);

        // Release coin
        gas.release_gas_coin(acquired1.clone()).await;

        // Acquire again
        let acquired3 = gas.acquire_gas_coin().await;
        assert_eq!(acquired3, acquired1);
    }

    #[test]
    fn gas_reports_coin_budget() {
        let gas = GasSource::coin(vec![sui_mocks::mock_sui_object_ref()], 5000);
        assert_eq!(gas.get_budget(), 5000);
    }

    #[tokio::test]
    async fn coin_acquisition_waits_for_release() {
        let coin = sui_mocks::mock_sui_object_ref();
        let gas = CoinGasPool {
            coins: Arc::new(Mutex::new(vec![])),
            notify: Arc::new(Notify::new()),
            budget: 100,
            reference_gas_price: Some(1),
        };

        let gas_clone = gas.clone();

        let handle = tokio::spawn(async move { gas_clone.acquire_gas_coin().await });

        // Wait a moment to ensure acquire_gas_coin is waiting
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Release coin
        gas.release_gas_coin(coin.clone()).await;

        let acquired = handle.await.unwrap();
        assert_eq!(acquired, coin);
    }

    #[tokio::test]
    async fn builder_reuses_the_wallet_and_rejects_a_second_authority() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let wallet = super::super::wallet::WalletClient::connect(
            &rpc_url,
            sui::crypto::Ed25519PrivateKey::new([23; 32]),
        )
        .await
        .unwrap();
        for override_url in [None, Some(rpc_url.as_str()), Some(wallet.rpc_url())] {
            let mut builder = NexusClient::builder()
                .with_wallet(wallet.clone())
                .with_nexus_objects(sui_mocks::mock_nexus_objects())
                .with_address_balance_gas(7_000);
            if let Some(url) = override_url {
                builder = builder.with_rpc_url(url);
            }
            let client = builder.build().await.unwrap();
            assert_eq!(client.owner().unwrap(), wallet.owner());
            assert_eq!(client.rpc_url(), override_url.unwrap_or(wallet.rpc_url()));
            assert!(Arc::ptr_eq(
                &client.wallet().unwrap().grpc_client(),
                &wallet.grpc_client()
            ));
        }
        let error = NexusClient::builder()
            .with_wallet(wallet.clone())
            .with_private_key(sui::crypto::Ed25519PrivateKey::new([24; 32]))
            .build()
            .await
            .err()
            .expect("two signing authorities must be rejected");
        assert!(matches!(error, NexusError::Configuration(_)));
        let error = NexusClient::builder()
            .with_wallet(wallet)
            .with_rpc_url("http://different.invalid")
            .build()
            .await
            .err()
            .expect("a conflicting wallet RPC must be rejected");
        assert!(matches!(error, NexusError::Configuration(_)));
    }

    #[tokio::test]
    async fn test_builder_with_private_key() {
        let mut rng = rand::thread_rng();
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let coin = sui_mocks::mock_sui_object_ref();
        let objects = sui_mocks::mock_nexus_objects();
        let coins = vec![coin];
        let budget = 1000;

        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 1000);
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            ..Default::default()
        });

        let builder = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(objects)
            .with_gas(coins, budget);

        let client = builder.build().await.unwrap();
        assert_eq!(
            client
                .gas_config()
                .expect("legacy builder should attach coin gas")
                .get_budget(),
            budget
        );
        assert_eq!(
            client
                .signer()
                .expect("private key should configure a signer")
                .wallet()
                .transaction_timeout(),
            Duration::from_secs(5)
        );
    }

    #[tokio::test]
    async fn address_balance_builder_does_not_require_gas_coins() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());

        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .with_address_balance_gas(7_000)
            .build()
            .await
            .unwrap();

        assert_eq!(
            client
                .gas_config()
                .expect("legacy builder should attach address balance gas")
                .get_budget(),
            7_000
        );
        assert_eq!(client.get_reference_gas_price(), None);
    }

    #[tokio::test]
    async fn builder_rejects_two_gas_sources() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let coin = sui_mocks::mock_sui_object_ref();

        let result = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url("http://127.0.0.1:1")
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .with_gas(vec![coin], 1_000)
            .with_address_balance_gas(1_000)
            .build()
            .await;

        let Err(error) = result else {
            panic!("builder accepted two gas sources");
        };
        assert!(matches!(error, NexusError::Configuration(_)));
        assert!(error.to_string().contains("cannot both be configured"));
    }

    #[tokio::test]
    async fn builder_without_private_key_supports_crawler_reads() {
        let object = sui_mocks::mock_sui_object_ref();
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_get_object_metadata(
            &mut ledger_service_mock,
            object.clone(),
            sui::types::Owner::Immutable,
            None,
        );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            ..Default::default()
        });
        let client = keyless_client(&rpc_url).await;

        let response = client
            .crawler()
            .get_object_metadata(*object.object_id())
            .await
            .expect("query-only crawler read should succeed");

        assert_eq!(response.object_ref(), object);
    }

    #[tokio::test]
    async fn keyless_client_supports_read_only_construction() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = keyless_client(&rpc_url).await;

        assert!(matches!(client.owner(), Err(NexusError::MissingPrivateKey)));
        assert!(client.signer().is_err());
    }

    #[tokio::test]
    async fn builder_with_gas_without_private_key_returns_missing_private_key() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let result = NexusClientBuilder::new()
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .with_address_balance_gas(1_000)
            .build()
            .await;

        assert!(matches!(result, Err(NexusError::MissingPrivateKey)));
    }

    #[tokio::test]
    async fn keyless_owner_and_signer_return_missing_private_key() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = keyless_client(&rpc_url).await;

        assert!(matches!(client.owner(), Err(NexusError::MissingPrivateKey)));
        assert!(matches!(
            client.signer(),
            Err(NexusError::MissingPrivateKey)
        ));
    }

    #[tokio::test]
    async fn keyless_owned_coin_query_returns_missing_private_key_before_rpc() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = keyless_client(&rpc_url).await;

        let result = client
            .fetch_coins_by_type(sui::types::StructTag::gas_coin())
            .await;

        assert!(matches!(result, Err(NexusError::MissingPrivateKey)));
    }

    #[tokio::test]
    async fn keyless_gas_attachment_returns_missing_private_key_before_source_validation() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = keyless_client(&rpc_url).await;

        let result = client.set_gas_source(GasSource::coin(vec![], 1_000)).await;

        assert!(matches!(result, Err(NexusError::MissingPrivateKey)));
        assert!(client.gas_config().is_none());
    }

    #[tokio::test]
    async fn keyless_submission_returns_missing_private_key_before_missing_gas() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = keyless_client(&rpc_url).await;

        let result = client
            .submit_transaction(
                sui::types::ProgrammableTransaction {
                    inputs: vec![],
                    commands: vec![],
                },
                sui::types::Address::ZERO,
            )
            .await;

        assert!(matches!(result, Err(NexusError::MissingPrivateKey)));
    }

    #[tokio::test]
    async fn keyless_mutating_action_returns_missing_private_key_before_submission() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = keyless_client(&rpc_url).await;

        let result = client.network().configure_priority_fee_vault(1).await;

        assert!(matches!(result, Err(NexusError::MissingPrivateKey)));
    }

    #[tokio::test]
    async fn keyless_client_exposes_shared_grpc_arc() {
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("query-only client should build without a private key");
        let client_handle = client.grpc_client();
        let crawler_handle = client.crawler().grpc_client();

        assert!(Arc::ptr_eq(&client_handle, &crawler_handle));
        assert_eq!(client_handle.uri().to_string(), format!("{rpc_url}/"));
    }

    #[tokio::test]
    async fn clone_grpc_client_uses_stored_transport_without_reconstruction() {
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 42);
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            ..Default::default()
        });
        let mut client = keyless_client(&rpc_url).await;
        client.rpc_url = "not a valid URL".into();

        let mut grpc_client = client.clone_grpc_client();

        assert_eq!(
            grpc_client
                .get_reference_gas_price()
                .await
                .expect("cloned client should use the configured transport"),
            42
        );
    }

    #[tokio::test]
    async fn test_builder_missing_rpc_url() {
        let mut rng = rand::thread_rng();
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let coin = sui_mocks::mock_sui_object_ref();
        let coins = vec![coin];
        let objects = sui_mocks::mock_nexus_objects();
        let budget = 1000;

        let builder = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_nexus_objects(objects)
            .with_gas(coins, budget);

        let result = builder.build().await;
        assert!(matches!(result, Err(NexusError::Configuration(_))));
    }

    #[tokio::test]
    async fn builder_without_gas_supports_reads() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let object = sui_mocks::mock_sui_object_ref();
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_get_object_metadata(
            &mut ledger_service_mock,
            object.clone(),
            sui::types::Owner::Immutable,
            None,
        );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            ..Default::default()
        });

        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");
        let response = client
            .crawler()
            .get_object_metadata(*object.object_id())
            .await
            .expect("read-only query should not require gas coins");

        assert!(client.gas_config().is_none());
        assert_eq!(client.get_reference_gas_price(), None);
        assert_eq!(response.object_ref(), object);
    }

    #[tokio::test]
    async fn client_exposes_its_owner_and_shared_grpc_arc() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let owner = pk.public_key().derive_address();
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");

        assert_eq!(
            client
                .owner()
                .expect("private key should configure an owner"),
            owner
        );
        let client_handle = client.grpc_client();
        let crawler_handle = client.crawler().grpc_client();
        let signer_handle = &client
            .signer()
            .expect("private key should configure a signer")
            .client;
        assert!(Arc::ptr_eq(&client_handle, &crawler_handle));
        assert!(Arc::ptr_eq(&crawler_handle, signer_handle));
    }

    #[tokio::test]
    async fn fetch_coin_uses_client_owner_and_crawler() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let owner = pk.public_key().derive_address();
        let object_type = sui::types::StructTag::gas_coin();
        let coin = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x10"));
        let client = client_with_owned_coins(
            pk,
            object_type.clone(),
            vec![owned_coin_object(coin.clone(), owner, 50, &object_type)],
        )
        .await;

        let selected = client
            .fetch_coin(*coin.object_id())
            .await
            .expect("owned SUI coin should be selected");

        assert_eq!(selected, coin);
    }

    #[tokio::test]
    async fn fetch_coin_with_balance_returns_exact_balance() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let owner = pk.public_key().derive_address();
        let object_type = sui::types::StructTag::gas_coin();
        let coin = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x11"));
        let client = client_with_owned_coins(
            pk,
            object_type.clone(),
            vec![owned_coin_object(coin.clone(), owner, 7_654, &object_type)],
        )
        .await;

        let selected = client
            .fetch_coin_with_balance(*coin.object_id())
            .await
            .expect("owned SUI coin balance should be returned");

        assert_eq!(selected, (coin, 7_654));
    }

    #[tokio::test]
    async fn fetch_coin_rejects_an_id_missing_from_the_wallet() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let owner = pk.public_key().derive_address();
        let object_type = sui::types::StructTag::gas_coin();
        let owned_coin = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x12"));
        let missing_id = sui::types::Address::from_static("0x13");
        let client = client_with_owned_coins(
            pk,
            object_type.clone(),
            vec![owned_coin_object(owned_coin, owner, 100, &object_type)],
        )
        .await;

        let error = client
            .fetch_coin(missing_id)
            .await
            .expect_err("unowned SUI coin should be rejected");

        assert!(matches!(error, NexusError::Wallet(_)));
        assert!(error.to_string().contains("not found in wallet"));
    }

    #[tokio::test]
    async fn fetch_coin_rejects_an_empty_wallet() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let object_type = sui::types::StructTag::gas_coin();
        let client = client_with_owned_coins(pk, object_type, vec![]).await;

        let error = client
            .fetch_coin(sui::types::Address::from_static("0x14"))
            .await
            .expect_err("empty wallet should not provide a SUI coin");

        assert!(matches!(error, NexusError::Wallet(_)));
        assert!(error.to_string().contains("does not have enough coins"));
    }

    #[tokio::test]
    async fn fetch_coins_by_type_maps_crawler_failure_to_rpc() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let object_type = sui::types::StructTag::gas_coin();
        let mut state_service_mock = sui_mocks::grpc::MockStateService::new();
        state_service_mock
            .expect_list_owned_objects()
            .times(1)
            .return_once(|_| Err(tonic::Status::unavailable("state service unavailable")));
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            state_service_mock: Some(state_service_mock),
            ..Default::default()
        });
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");

        let error = client
            .fetch_coins_by_type(object_type)
            .await
            .expect_err("crawler failure should be preserved");

        assert!(matches!(error, NexusError::Rpc(_)));
        assert!(error.to_string().contains("state service unavailable"));
    }

    #[tokio::test]
    async fn fetch_coin_by_type_selects_the_explicit_id() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let owner = pk.public_key().derive_address();
        let object_type = crate::types::UsTokenConfig::new(
            sui::types::Address::from_static("0xa"),
            sui::types::Address::from_static("0xb"),
            sui::types::Address::from_static("0xc"),
        )
        .coin_type_tag();
        let requested_coin = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x21"));
        let mut object = owned_coin_object(requested_coin.clone(), owner, 100, &object_type);
        object.set_previous_transaction(sui::types::Digest::from([7; 32]));
        let client = client_with_exact_object(pk, object).await;

        let selected = client
            .fetch_coin_by_type(Some(*requested_coin.object_id()), 0, object_type)
            .await
            .expect("explicit typed coin should be selected");

        assert_eq!(selected, requested_coin);
    }

    #[test]
    fn ordinal_coin_sort_uses_balance_descending_then_object_id() {
        let smallest_balance =
            sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x1"));
        let lower_tied_id = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x2"));
        let higher_tied_id = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x3"));
        let mut coins = vec![
            (smallest_balance.clone(), 10),
            (higher_tied_id.clone(), 100),
            (lower_tied_id.clone(), 100),
        ];

        sort_coins_for_ordinal_selection(&mut coins);

        assert_eq!(
            coins,
            vec![
                (lower_tied_id, 100),
                (higher_tied_id, 100),
                (smallest_balance, 10),
            ]
        );
    }

    #[tokio::test]
    async fn fetch_coin_by_type_selects_the_deterministic_ordinal() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let owner = pk.public_key().derive_address();
        let object_type = crate::types::UsTokenConfig::new(
            sui::types::Address::from_static("0xa"),
            sui::types::Address::from_static("0xb"),
            sui::types::Address::from_static("0xc"),
        )
        .coin_type_tag();
        let smallest_balance =
            sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x1"));
        let lower_tied_id = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x2"));
        let higher_tied_id = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x3"));
        let client = client_with_owned_coins(
            pk,
            object_type.clone(),
            vec![
                owned_coin_object(smallest_balance, owner, 10, &object_type),
                owned_coin_object(higher_tied_id.clone(), owner, 100, &object_type),
                owned_coin_object(lower_tied_id, owner, 100, &object_type),
            ],
        )
        .await;

        let selected = client
            .fetch_coin_by_type(None, 1, object_type)
            .await
            .expect("ordinal should use deterministic typed-coin ordering");

        assert_eq!(selected, higher_tied_id);
    }

    #[tokio::test]
    async fn fetch_coin_by_type_rejects_an_out_of_range_ordinal() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let owner = pk.public_key().derive_address();
        let object_type = crate::types::UsTokenConfig::new(
            sui::types::Address::from_static("0xa"),
            sui::types::Address::from_static("0xb"),
            sui::types::Address::from_static("0xc"),
        )
        .coin_type_tag();
        let coin = sui_mocks::object_ref_for_id(sui::types::Address::from_static("0x30"));
        let client = client_with_owned_coins(
            pk,
            object_type.clone(),
            vec![owned_coin_object(coin, owner, 100, &object_type)],
        )
        .await;

        let error = client
            .fetch_coin_by_type(None, 1, object_type)
            .await
            .expect_err("ordinal beyond owned typed coins should be rejected");

        assert!(matches!(error, NexusError::Wallet(_)));
        assert!(error.to_string().contains("select object #1"));
    }

    #[tokio::test]
    async fn direct_address_balance_attachment_is_shared_with_clones_and_actions() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");
        let client_clone = client.clone();
        let workflow = client.workflow();
        let tap = client.tap();

        client
            .set_gas_source(GasSource::AddressBalance(AddressBalanceGas::new(4_321)))
            .await
            .expect("address balance gas should attach");

        assert_eq!(
            client_clone
                .gas_config()
                .expect("clone should observe attached gas")
                .get_budget(),
            4_321
        );
        assert_eq!(
            workflow
                .client
                .gas_config()
                .expect("workflow facade should observe attached gas")
                .get_budget(),
            4_321
        );
        assert_eq!(
            tap.client
                .gas_config()
                .expect("TAP facade should observe attached gas")
                .get_budget(),
            4_321
        );
    }

    #[tokio::test]
    async fn direct_coin_attachment_fetches_reference_gas_price() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let coin = sui_mocks::mock_sui_object_ref();
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 987);
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            ..Default::default()
        });
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");

        client
            .set_gas_source(GasSource::coin(vec![coin], 8_765))
            .await
            .expect("coin gas should attach");

        assert_eq!(
            client
                .gas_config()
                .expect("coin gas should be configured")
                .get_budget(),
            8_765
        );
        assert_eq!(client.get_reference_gas_price(), Some(987));
    }

    #[tokio::test]
    async fn direct_coin_attachment_rejects_empty_pool() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");

        let error = client
            .set_gas_source(GasSource::coin(vec![], 1_000))
            .await
            .expect_err("empty coin gas should fail");

        assert!(error.to_string().contains("at least one gas coin"));
        assert!(client.gas_config().is_none());
    }

    #[tokio::test]
    async fn gas_attachment_rejects_replacement() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");
        client
            .set_gas_source(GasSource::AddressBalance(AddressBalanceGas::new(1_000)))
            .await
            .expect("first gas attachment should succeed");

        let error = client
            .set_gas_source(GasSource::AddressBalance(AddressBalanceGas::new(2_000)))
            .await
            .expect_err("replacement should fail");

        assert!(matches!(&error, NexusError::GasSourceAlreadyConfigured));
        assert_eq!(error.to_string(), "a gas source is already configured");
        assert_eq!(
            client
                .gas_config()
                .expect("original gas should remain")
                .get_budget(),
            1_000
        );
    }

    #[tokio::test]
    async fn concurrent_gas_attachment_has_one_winner() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");
        let barrier = Arc::new(tokio::sync::Barrier::new(3));
        let first_client = client.clone();
        let first_barrier = Arc::clone(&barrier);
        let first = tokio::spawn(async move {
            first_barrier.wait().await;
            first_client
                .set_gas_source(GasSource::AddressBalance(AddressBalanceGas::new(1_000)))
                .await
        });
        let second_client = client.clone();
        let second_barrier = Arc::clone(&barrier);
        let second = tokio::spawn(async move {
            second_barrier.wait().await;
            second_client
                .set_gas_source(GasSource::AddressBalance(AddressBalanceGas::new(2_000)))
                .await
        });
        barrier.wait().await;
        let results = [first.await.unwrap(), second.await.unwrap()];

        assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 1);
        assert!(results
            .iter()
            .filter_map(|result| result.as_ref().err())
            .all(|error| matches!(error, NexusError::GasSourceAlreadyConfigured)));
        assert!(matches!(
            client
                .gas_config()
                .expect("one gas source should win")
                .get_budget(),
            1_000 | 2_000
        ));
    }

    #[tokio::test]
    async fn submit_transaction_without_gas_returns_configuration_error() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let sender = pk.public_key().derive_address();
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .build()
            .await
            .expect("client without gas should build");

        let result = client
            .submit_transaction(
                sui::types::ProgrammableTransaction {
                    inputs: vec![],
                    commands: vec![],
                },
                sender,
            )
            .await;
        let Err(error) = result else {
            panic!("submission without gas should fail");
        };

        assert!(matches!(error, NexusError::Configuration(_)));
        assert!(error
            .to_string()
            .contains("a gas source is required for transaction operations"));
    }

    #[tokio::test]
    async fn test_builder_with_gas_empty_coins() {
        let mut rng = rand::thread_rng();
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let coins = vec![];
        let objects = sui_mocks::mock_nexus_objects();
        let budget = 1000;

        let builder = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url("https://fullnode.testnet.sui.io:443")
            .with_nexus_objects(objects)
            .with_gas(coins, budget);

        let Err(error) = builder.build().await else {
            panic!("explicit coin gas without coins should fail");
        };
        assert!(matches!(error, NexusError::Configuration(_)));
        assert!(error.to_string().contains("at least one gas coin"));
    }

    #[tokio::test]
    async fn test_builder_missing_nexus_objects() {
        let mut rng = rand::thread_rng();
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let coin = sui_mocks::mock_sui_object_ref();
        let coins = vec![coin];
        let budget = 1000;

        let builder = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url("https://fullnode.testnet.sui.io:443")
            .with_gas(coins, budget);

        let result = builder.build().await;
        assert!(matches!(result, Err(NexusError::Configuration(_))));
    }

    #[tokio::test]
    async fn test_builder_tx_timeout() {
        let mut rng = rand::thread_rng();
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let coin = sui_mocks::mock_sui_object_ref();
        let objects = sui_mocks::mock_nexus_objects();
        let coins = vec![coin];
        let budget = 1000;

        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 1000);
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            ..Default::default()
        });

        let builder = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(objects)
            .with_gas(coins, budget)
            .with_transaction_timeout(Duration::from_secs(10));

        let client = builder.build().await.unwrap();
        assert_eq!(
            client
                .gas_config()
                .expect("legacy builder should attach coin gas")
                .get_budget(),
            budget
        );
        assert_eq!(
            client
                .signer()
                .expect("private key should configure a signer")
                .wallet()
                .transaction_timeout(),
            Duration::from_secs(10)
        );
    }

    #[tokio::test]
    async fn reusable_address_balance_builder_configuration_remains_supported() {
        let pk = sui::crypto::Ed25519PrivateKey::generate(rand::thread_rng());
        let rpc_url = sui_mocks::grpc::mock_server(Default::default());
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(sui_mocks::mock_nexus_objects())
            .with_address_balance_gas_config(AddressBalanceGas::new(6_000))
            .build()
            .await
            .expect("legacy reusable address balance configuration should build");

        assert_eq!(
            client
                .gas_config()
                .expect("legacy builder should attach reusable gas")
                .get_budget(),
            6_000
        );
    }

    #[tokio::test]
    async fn test_execute_tx_mutates_gas_coin() {
        let gas_coin_ref = sui_mocks::mock_sui_object_ref();
        let nexus_objects = sui_mocks::mock_nexus_objects();

        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        let mut tx_service_mock = sui_mocks::grpc::MockTransactionExecutionService::new();
        let mut sub_service_mock = sui_mocks::grpc::MockSubscriptionService::new();

        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 1000);

        let submitted = sui_mocks::grpc::mock_execute_transaction_and_wait_for_checkpoint(
            &mut tx_service_mock,
            &mut sub_service_mock,
            &mut ledger_service_mock,
            gas_coin_ref.clone(),
            vec![],
            vec![],
            vec![],
        );

        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            execution_service_mock: Some(tx_service_mock),
            subscription_service_mock: Some(sub_service_mock),
            ..Default::default()
        });

        let client = nexus_mocks::mock_nexus_client(&nexus_objects, &rpc_url).await;

        assert_eq!(client.get_reference_gas_price(), Some(1000));

        let gas = client
            .gas_config()
            .expect("mock client should configure coin gas");
        let mut gas_coin = gas.coin_pool().unwrap().acquire_gas_coin().await;
        let signer = client
            .signer()
            .expect("mock client should configure a signer");
        let sender = signer.get_active_address();
        let tx = sui::types::Transaction {
            kind: sui::types::TransactionKind::ProgrammableTransaction(
                sui::types::ProgrammableTransaction {
                    inputs: vec![],
                    commands: vec![],
                },
            ),
            sender,
            gas_payment: sui::types::GasPayment {
                objects: vec![gas_coin.clone()],
                owner: sender,
                price: 1000,
                budget: 1000,
            },
            expiration: sui::types::TransactionExpiration::None,
        };
        let signature = signer.sign_tx(&tx).await.unwrap();

        let response = signer
            .execute_tx(tx, signature, &mut gas_coin)
            .await
            .unwrap();

        assert_eq!(response.digest, submitted.digest());

        assert_eq!(gas_coin.version(), gas_coin_ref.version());
        assert_eq!(gas_coin.digest(), gas_coin_ref.digest());
    }

    #[tokio::test]
    async fn execute_tx_without_gas_coin_does_not_refresh_an_object() {
        let mut rng = rand::thread_rng();
        let chain = sui::types::Digest::generate(&mut rng);
        let nexus_objects = sui_mocks::mock_nexus_objects();

        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        let mut tx_service_mock = sui_mocks::grpc::MockTransactionExecutionService::new();
        let mut sub_service_mock = sui_mocks::grpc::MockSubscriptionService::new();

        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 1000);
        let submitted =
            sui_mocks::grpc::mock_execute_transaction_without_gas_and_wait_for_checkpoint(
                &mut tx_service_mock,
                &mut sub_service_mock,
                &mut ledger_service_mock,
                vec![],
                vec![],
                vec![],
                |request| {
                    let transaction = request.transaction.as_ref().unwrap();
                    let transaction = sui::types::Transaction::try_from(transaction).unwrap();
                    assert!(transaction.gas_payment.objects.is_empty());
                },
            );

        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger_service_mock),
            execution_service_mock: Some(tx_service_mock),
            subscription_service_mock: Some(sub_service_mock),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client(&nexus_objects, &rpc_url).await;
        let signer = client
            .signer()
            .expect("mock client should configure a signer");
        let sender = signer.get_active_address();
        let tx = crate::nexus::address_balance::finish_transaction(
            sui::types::ProgrammableTransaction {
                inputs: vec![],
                commands: vec![],
            },
            sender,
            1000,
            crate::nexus::address_balance::SubmissionContext {
                reference_gas_price: 1000,
                epoch: 1,
                chain,
            },
            0,
        );
        let signature = signer.sign_tx(&tx).await.unwrap();

        let response = signer
            .execute_tx_without_gas_coin(tx, signature)
            .await
            .unwrap();

        assert_eq!(response.digest, submitted.digest());
    }

    #[tokio::test]
    async fn node_checkpoint_wait_avoids_subscription_and_ledger_probe() {
        let mut rng = rand::thread_rng();
        let chain = sui::types::Digest::generate(&mut rng);
        let nexus_objects = sui_mocks::mock_nexus_objects();
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        let mut tx_service_mock = sui_mocks::grpc::MockTransactionExecutionService::new();
        let mut sub_service_mock = sui_mocks::grpc::MockSubscriptionService::new();

        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 1000);
        let submitted = sui_mocks::grpc::mock_checkpointed_execute_transaction_without_gas(
            &mut tx_service_mock,
            &mut sub_service_mock,
            &mut ledger_service_mock,
            true,
            vec![],
            vec![],
            vec![],
            |_| {},
        );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            checkpoint_wait_supported: true,
            ledger_service_mock: Some(ledger_service_mock),
            execution_service_mock: Some(tx_service_mock),
            subscription_service_mock: Some(sub_service_mock),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client(&nexus_objects, &rpc_url).await;
        let signer = client
            .signer()
            .expect("mock client should configure a signer");
        let sender = signer.get_active_address();
        let transaction = crate::nexus::address_balance::finish_transaction(
            sui::types::ProgrammableTransaction {
                inputs: vec![],
                commands: vec![],
            },
            sender,
            1000,
            crate::nexus::address_balance::SubmissionContext {
                reference_gas_price: 1000,
                epoch: 1,
                chain,
            },
            0,
        );
        let signature = signer.sign_tx(&transaction).await.unwrap();

        let response = signer
            .execute_tx_without_gas_coin(transaction, signature)
            .await
            .unwrap();

        assert_eq!(response.digest, submitted.digest());
        assert_eq!(response.checkpoint, 1);
    }

    #[tokio::test]
    async fn node_checkpoint_wait_preserves_unconfirmed_execution() {
        let mut rng = rand::thread_rng();
        let chain = sui::types::Digest::generate(&mut rng);
        let nexus_objects = sui_mocks::mock_nexus_objects();
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        let mut tx_service_mock = sui_mocks::grpc::MockTransactionExecutionService::new();
        let mut sub_service_mock = sui_mocks::grpc::MockSubscriptionService::new();

        sui_mocks::grpc::mock_reference_gas_price(&mut ledger_service_mock, 1000);
        let submitted = sui_mocks::grpc::mock_uncheckpointed_execute_transaction_without_gas(
            &mut tx_service_mock,
            &mut sub_service_mock,
            &mut ledger_service_mock,
            true,
            vec![],
            vec![],
            vec![],
            |_| {},
        );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            checkpoint_wait_supported: true,
            ledger_service_mock: Some(ledger_service_mock),
            execution_service_mock: Some(tx_service_mock),
            subscription_service_mock: Some(sub_service_mock),
            ..Default::default()
        });
        let client = nexus_mocks::mock_nexus_client(&nexus_objects, &rpc_url).await;
        let signer = client
            .signer()
            .expect("mock client should configure a signer");
        let sender = signer.get_active_address();
        let transaction = crate::nexus::address_balance::finish_transaction(
            sui::types::ProgrammableTransaction {
                inputs: vec![],
                commands: vec![],
            },
            sender,
            1000,
            crate::nexus::address_balance::SubmissionContext {
                reference_gas_price: 1000,
                epoch: 1,
                chain,
            },
            0,
        );
        let signature = signer.sign_tx(&transaction).await.unwrap();

        let Err(error) = signer
            .execute_tx_without_gas_coin(transaction, signature)
            .await
        else {
            panic!("checkpoint confirmation should be unknown");
        };

        let NexusError::Transaction(error) = error else {
            panic!("expected a transaction error");
        };
        assert_eq!(error.digest(), &submitted.digest());
        assert_eq!(
            error.state(),
            crate::nexus::error::TransactionErrorState::ConfirmationUnknown
        );
        assert!(error.response().is_some());
    }

    #[tokio::test]
    async fn address_balance_submission_fetches_fresh_context_and_uses_no_gas_object() {
        let mut rng = rand::thread_rng();
        let chain = sui::types::Digest::generate(&mut rng);
        let nexus_objects = sui_mocks::mock_nexus_objects();
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        let mut tx_service_mock = sui_mocks::grpc::MockTransactionExecutionService::new();
        let mut sub_service_mock = sui_mocks::grpc::MockSubscriptionService::new();

        sui_mocks::grpc::mock_submission_context(&mut ledger_service_mock, 17, 23);
        let submitted =
            sui_mocks::grpc::mock_execute_transaction_without_gas_and_wait_for_checkpoint(
                &mut tx_service_mock,
                &mut sub_service_mock,
                &mut ledger_service_mock,
                vec![],
                vec![],
                vec![],
                move |request| {
                    let transaction = request.transaction.as_ref().unwrap();
                    let transaction = sui::types::Transaction::try_from(transaction).unwrap();
                    assert!(transaction.gas_payment.objects.is_empty());
                    assert_eq!(transaction.gas_payment.price, 17);
                    assert_eq!(transaction.gas_payment.budget, 9_000);
                    assert_eq!(
                        transaction.expiration,
                        sui::types::TransactionExpiration::ValidDuring {
                            min_epoch: Some(23),
                            max_epoch: Some(24),
                            min_timestamp: None,
                            max_timestamp: None,
                            chain,
                            nonce: 0,
                        }
                    );
                },
            );
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            chain_id: chain,
            ledger_service_mock: Some(ledger_service_mock),
            execution_service_mock: Some(tx_service_mock),
            subscription_service_mock: Some(sub_service_mock),
            ..Default::default()
        });
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let sender = pk.public_key().derive_address();
        let mut nexus_objects = nexus_objects;
        nexus_objects.chain_id = chain.to_string();
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(nexus_objects)
            .with_address_balance_gas_config(AddressBalanceGas::with_nonce_allocator(
                9_000,
                NonceAllocator::new(0),
            ))
            .build()
            .await
            .unwrap();

        let result = client
            .submit_transaction(
                sui::types::ProgrammableTransaction {
                    inputs: vec![],
                    commands: vec![],
                },
                sender,
            )
            .await
            .unwrap();

        assert_eq!(result.digest, submitted.digest());
    }

    #[tokio::test]
    async fn attached_address_balance_failure_is_reported_at_submission() {
        let mut rng = rand::thread_rng();
        let chain = sui::types::Digest::generate(&mut rng);
        let mut ledger_service_mock = sui_mocks::grpc::MockLedgerService::new();
        let mut tx_service_mock = sui_mocks::grpc::MockTransactionExecutionService::new();
        let mut sub_service_mock = sui_mocks::grpc::MockSubscriptionService::new();

        sui_mocks::grpc::mock_submission_context(&mut ledger_service_mock, 17, 23);
        sub_service_mock
            .expect_subscribe_checkpoints()
            .times(1)
            .returning(|_| {
                Ok(tonic::Response::new(
                    Box::pin(futures::stream::empty()) as sui_mocks::grpc::BoxCheckpointStream
                ))
            });
        tx_service_mock
            .expect_execute_transaction()
            .times(1)
            .returning(|_| {
                Err(tonic::Status::failed_precondition(
                    "address balance is insufficient",
                ))
            });
        ledger_service_mock
            .expect_get_transaction()
            .withf(|request| {
                request
                    .get_ref()
                    .read_mask
                    .as_ref()
                    .is_some_and(|mask| mask.paths.iter().any(|path| path == "timestamp"))
            })
            .times(2)
            .returning(|_| Err(tonic::Status::not_found("transaction is not indexed")));
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            chain_id: chain,
            ledger_service_mock: Some(ledger_service_mock),
            execution_service_mock: Some(tx_service_mock),
            subscription_service_mock: Some(sub_service_mock),
            ..Default::default()
        });
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let sender = pk.public_key().derive_address();
        let mut nexus_objects = sui_mocks::mock_nexus_objects();
        nexus_objects.chain_id = chain.to_string();
        let client = NexusClientBuilder::new()
            .with_private_key(pk)
            .with_rpc_url(&rpc_url)
            .with_nexus_objects(nexus_objects)
            .build()
            .await
            .expect("client should build before gas attachment");
        client
            .set_gas_source(GasSource::AddressBalance(AddressBalanceGas::new(
                DEFAULT_GAS_BUDGET,
            )))
            .await
            .expect("address balance gas should attach without preflight");

        let Err(error) = client
            .submit_transaction(
                sui::types::ProgrammableTransaction {
                    inputs: vec![],
                    commands: vec![],
                },
                sender,
            )
            .await
        else {
            panic!("Sui should reject an insufficient address balance");
        };

        assert!(matches!(
            error,
            NexusError::Transaction(ref error)
                if error.state()
                    == crate::nexus::error::TransactionErrorState::SubmissionRejected
        ));
        assert!(error
            .to_string()
            .contains("address balance is insufficient"));
    }

    #[allow(dead_code)]
    async fn submit_transaction_accepts_canonical_ptb(
        client: &NexusClient,
        sender: sui::types::Address,
        ptb: sui::types::ProgrammableTransaction,
    ) {
        let _ = client.submit_transaction(ptb, sender).await;
    }

    #[tokio::test]
    async fn runtime_context_resolves_only_the_bound_scheduler_graph() {
        let context = sui_mocks::mock_nexus_context();
        let mut ledger = sui_mocks::grpc::MockLedgerService::new();
        let mut packages = sui_mocks::grpc::MockMovePackageService::new();
        sui_mocks::grpc::mock_runtime_authority(&mut ledger, &context, false);
        sui_mocks::grpc::mock_nexus_package_graph(&mut ledger, &mut packages, context.packages());
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger),
            package_service_mock: Some(packages),
            ..Default::default()
        });
        let client =
            nexus_mocks::mock_nexus_client_without_coins(context.objects(), &rpc_url).await;

        let runtime = client.runtime_context(&[]).await.expect("runtime resolves");

        assert_eq!(
            runtime
                .require_package(PackageRole::Scheduler)
                .expect("runtime graph contains Scheduler")
                .storage_id,
            context
                .require_package(PackageRole::Scheduler)
                .expect("fixture contains Scheduler")
                .storage_id,
        );
    }

    #[tokio::test]
    async fn runtime_context_rejects_a_paused_runtime_before_package_resolution() {
        let context = sui_mocks::mock_nexus_context();
        let mut ledger = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_runtime_authority(&mut ledger, &context, true);
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger),
            ..Default::default()
        });
        let client =
            nexus_mocks::mock_nexus_client_without_coins(context.objects(), &rpc_url).await;

        let error = client
            .runtime_context(&[])
            .await
            .expect_err("a paused runtime has no effect authority");

        assert!(matches!(
            error,
            NexusError::InvalidObjectState { object, ref reason }
                if object == context.runtime_authority.object_id()
                    && reason.contains("paused")
        ));
    }

    #[tokio::test]
    async fn routing_context_resolves_the_bound_graph_while_runtime_is_paused() {
        let context = sui_mocks::mock_nexus_context();
        let mut ledger = sui_mocks::grpc::MockLedgerService::new();
        let mut packages = sui_mocks::grpc::MockMovePackageService::new();
        sui_mocks::grpc::mock_runtime_authority(&mut ledger, &context, true);
        sui_mocks::grpc::mock_nexus_package_graph(&mut ledger, &mut packages, context.packages());
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger),
            package_service_mock: Some(packages),
            ..Default::default()
        });
        let client =
            nexus_mocks::mock_nexus_client_without_coins(context.objects(), &rpc_url).await;

        let routing = client
            .routing_context(&[])
            .await
            .expect("a pause removes effect authority, not package routing");

        assert_eq!(
            routing
                .package_id(PackageRole::Scheduler)
                .expect("routing graph contains Scheduler"),
            context
                .package_id(PackageRole::Scheduler)
                .expect("fixture contains Scheduler"),
        );
    }

    #[tokio::test]
    async fn runtime_context_rejects_an_unbound_authority() {
        let context = sui_mocks::mock_nexus_context();
        let mut ledger = sui_mocks::grpc::MockLedgerService::new();
        sui_mocks::grpc::mock_unbound_runtime_authority(&mut ledger, &context);
        let rpc_url = sui_mocks::grpc::mock_server(sui_mocks::grpc::ServerMocks {
            ledger_service_mock: Some(ledger),
            ..Default::default()
        });
        let client =
            nexus_mocks::mock_nexus_client_without_coins(context.objects(), &rpc_url).await;

        let error = client
            .runtime_context(&[])
            .await
            .expect_err("an unbound root has no effect authority");

        assert!(matches!(
            error,
            NexusError::InvalidObjectState { object, ref reason }
                if object == context.runtime_authority.object_id()
                    && reason.contains("not bound")
        ));
    }
}