satellite-shard 0.31.6

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

use std::cell::RefMut;

use arch_program::{input_to_sign::InputToSign, rune::RuneAmount, utxo::UtxoMeta};
use bitcoin::{ScriptBuf, Transaction};
use satellite_bitcoin::utxo_info::UtxoInfoTrait;
use satellite_bitcoin::{fee_rate::FeeRate, TransactionBuilder};

#[cfg(feature = "runes")]
use arch_program::rune::RuneId;
#[cfg(feature = "runes")]
use ordinals::Runestone;
use satellite_bitcoin::generic::fixed_set::FixedCapacitySet;

#[cfg(feature = "utxo-consolidation")]
use satellite_bitcoin::utxo_info::FixedOptionF64;

use super::error::StateShardError;

use super::StateShard;

use satellite_lang::prelude::Owner;
use satellite_lang::ZeroCopy;

/// Validates that each shard in `selected_shards` currently has a rune UTXO.
///
/// Returns `Ok(())` when all shards have a rune UTXO; otherwise returns
/// `Err(StateShardError::NotEnoughRuneUtxos)`.
pub fn ensure_rune_utxo_present_in_all<'info, RS, U, S>(
    selected_shards: &[RefMut<'info, S>],
) -> super::error::Result<()>
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
    S: StateShard<U, RS> + ZeroCopy + Owner,
{
    let all_have_rune = selected_shards
        .iter()
        .all(|shard| shard.rune_utxo().is_some());
    if all_have_rune {
        Ok(())
    } else {
        Err(StateShardError::NotEnoughRuneUtxos)
    }
}

/// Removes all specified UTXOs from the provided selected shards.
///
/// This is an internal helper function that efficiently removes UTXOs from multiple shards
/// in a single pass. It handles both BTC UTXOs (stored in the shard's UTXO vector) and
/// the optional rune UTXO (stored as a single optional field).
///
/// # Behavior
/// - Iterates through each shard exactly once to minimize borrow checker overhead
/// - For each UTXO to remove, checks both the BTC UTXO vector and rune UTXO slot
/// - Silently ignores UTXOs that are not found in a particular shard (this is expected
///   behavior since not all UTXOs exist in all shards)
/// - Uses `btc_utxos_retain` for efficient removal from the BTC UTXO vector
/// - Directly clears the rune UTXO slot if it matches the target UTXO
///
/// # Performance Considerations
/// - Designed to minimize BPF instruction count in on-chain execution
/// - Single iteration per shard reduces runtime borrow checking overhead
/// - Bulk removal is more efficient than individual remove operations
///
/// # Assumptions
/// - Called only with shards that are actually involved in the transaction
/// - The caller has already determined which UTXOs need to be removed
/// - UTXOs may or may not exist in any given shard (graceful handling of missing UTXOs)
///
/// # Arguments
/// * `selected_shards` - Mutable references to the shards that should be processed
/// * `utxos_to_remove` - Slice of UTXO metadata identifying which UTXOs to remove
///
/// # Errors
/// Currently always returns `Ok(())` but uses the `Result` type for consistency
/// with other functions in this module and potential future error conditions.
fn remove_utxos_from_shards<'info, RS, U, S>(
    selected_shards: &mut [RefMut<'info, S>],
    utxos_to_remove: &[UtxoMeta],
) -> super::error::Result<()>
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
    S: StateShard<U, RS> + ZeroCopy + Owner,
{
    // Iterate **once per shard** and perform all removals within the same
    // mutable borrow. This avoids repeatedly loading the same account and
    // therefore reduces BPF instruction count and runtime borrow checking
    // overhead.
    for shard in selected_shards.iter_mut() {
        for utxo_to_remove in utxos_to_remove {
            shard.btc_utxos_retain(&mut |utxo| utxo.meta() != utxo_to_remove);

            if let Some(rune_utxo) = shard.rune_utxo() {
                if rune_utxo.meta() == utxo_to_remove {
                    shard.clear_rune_utxo();
                }
            }
        }
    }

    Ok(())
}

/// Selects the optimal shard for adding a new BTC UTXO based on current capacity and balance.
///
/// This function implements a load-balancing strategy that prioritizes shards with:
/// 1. **Available capacity** - the shard must have room for at least one more BTC UTXO
/// 2. **Smallest total BTC value** - among eligible shards, selects the one with the least satoshis
///
/// # Selection Algorithm
/// The function iterates through all provided shards and:
/// - Calculates the total BTC value (sum of all UTXO values) for each shard
/// - Checks if the shard has spare capacity (`btc_utxos_len() < btc_utxos_max_len()`)
/// - Among shards with spare capacity, selects the one with the smallest total value
/// - Returns the **relative index** within the `selected_shards` slice (not global index)
///
/// # Load Balancing Benefits
/// - Distributes UTXOs evenly across shards to prevent concentration
/// - Maintains roughly equal BTC values across shards over time
/// - Prevents scenarios where some shards become heavily loaded while others remain empty
/// - Helps with future transaction planning and fee optimization
///
/// # Performance Characteristics
/// - O(n) time complexity where n is the number of selected shards
/// - Minimal memory allocation (only stores current best choice)
/// - Single pass through all shards for efficiency
///
/// # Arguments
/// * `selected_shards` - Slice of shard references to evaluate for UTXO insertion
///
/// # Returns
/// * `Some(index)` - The relative index of the best shard within the provided slice
/// * `None` - If all shards are at maximum capacity or no shards are provided
///
/// # Example Usage
/// ```rust,ignore
/// if let Some(target_idx) = select_best_shard_to_add_btc_to(&shards) {
///     shards[target_idx].add_btc_utxo(new_utxo);
/// } else {
///     return Err(StateShardError::ShardsAreFullOfBtcUtxos);
/// }
/// ```
fn select_best_shard_to_add_btc_to<'info, RS, U, S>(
    selected_shards: &[RefMut<'info, S>],
) -> Option<usize>
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
    S: StateShard<U, RS> + ZeroCopy + Owner,
{
    let mut best_idx: Option<usize> = None;
    let mut smallest_total: u64 = u64::MAX;

    for (idx, shard) in selected_shards.iter().enumerate() {
        let spare = shard.btc_utxos_len() < shard.btc_utxos_max_len();
        let sum: u64 = shard.btc_utxos().iter().map(|u| u.value()).sum();

        if spare && sum < smallest_total {
            smallest_total = sum;
            best_idx = Some(idx);
        }
    }

    best_idx
}

/// Performs a comprehensive update of UTXO sets across multiple shards in three phases.
///
/// This function orchestrates the complete UTXO state transition that occurs after a Bitcoin
/// transaction has been broadcast. It handles both removal of spent UTXOs and intelligent
/// distribution of newly created UTXOs across the selected shards.
///
/// # Three-Phase Operation
///
/// ## Phase 1: UTXO Removal
/// - Removes all specified UTXOs from all selected shards
/// - Handles both BTC UTXOs (from vectors) and rune UTXOs (single optional slot)
/// - Uses efficient bulk removal to minimize borrow checker overhead
///
/// ## Phase 2: Rune UTXO Distribution
/// - Distributes new rune-bearing UTXOs to shards that don't already have one
/// - Follows a simple first-available strategy for rune UTXO placement
/// - Ensures no rune UTXOs are lost (errors if excess rune UTXOs remain)
/// - Maintains the invariant that each shard has at most one rune UTXO
///
/// ## Phase 3: BTC UTXO Distribution
/// - Sorts new BTC UTXOs by value (largest first) for optimal distribution
/// - Uses load-balancing algorithm to distribute UTXOs to least-funded shards
/// - Applies UTXO consolidation flags when `utxo-consolidation` feature is enabled
/// - Ensures all UTXOs are successfully inserted or returns an error
///
/// # Feature-Dependent Behavior
///
/// ## `utxo-consolidation` Feature
/// When enabled, sets the consolidation flag on UTXOs added to shards that already
/// contain multiple UTXOs. The flag includes the current fee rate for future
/// consolidation planning.
///
/// # Load Balancing Strategy
/// - Distributes UTXOs to maintain roughly equal BTC values across shards
/// - Prevents concentration of value in a few shards
/// - Optimizes for future transaction efficiency and fee management
/// - Prioritizes shards with available capacity and smaller total values
///
/// # Arguments
/// * `selected_shards` - Mutable references to shards that should be updated
/// * `utxos_to_remove` - UTXOs that were spent in the transaction
/// * `new_rune_utxos` - New UTXOs that carry rune tokens
/// * `new_btc_utxos` - New plain BTC UTXOs (will be sorted by value internally)
/// * `fee_rate` - Current fee rate for consolidation flag setting
///
/// # Returns
/// * `Ok(())` - All UTXO updates completed successfully
/// * `Err(StateShardError::ExcessRuneUtxos)` - More rune UTXOs provided than can be stored
/// * `Err(StateShardError::ShardsAreFullOfBtcUtxos)` - No capacity for additional BTC UTXOs
///
/// # Invariants Maintained
/// - Each shard has at most one rune UTXO
/// - BTC UTXOs are distributed for optimal load balancing
/// - No UTXOs are lost during the update process
/// - Shard capacity limits are respected
///
/// # Performance Considerations
/// - Single iteration per shard for removals
/// - Efficient sorting and distribution of new UTXOs
/// - Minimal memory allocation and copying
/// - Optimized for on-chain BPF execution environment
#[allow(clippy::too_many_arguments)]
fn update_shards_utxos<'info, RS, U, S>(
    selected_shards: &mut [RefMut<'info, S>],
    utxos_to_remove: &[UtxoMeta],
    new_rune_utxos: Vec<U>,
    mut new_btc_utxos: Vec<U>,
    fee_rate: &FeeRate,
) -> super::error::Result<()>
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
    S: StateShard<U, RS> + ZeroCopy + Owner,
{
    // 1. Remove old UTXOs first.
    remove_utxos_from_shards(selected_shards, utxos_to_remove)?;

    // 2. Insert rune UTXOs where needed.
    let mut rune_utxo_iter = new_rune_utxos.into_iter();
    for shard in selected_shards.iter_mut() {
        if shard.rune_utxo().is_none() {
            if let Some(utxo) = rune_utxo_iter.next() {
                shard.set_rune_utxo(utxo);
            }
        }
    }

    // After distribution there must be **no** leftover rune-bearing UTXOs.
    // Having some left would mean that we would lose tokens on-chain.
    if rune_utxo_iter.next().is_some() {
        return Err(StateShardError::ExcessRuneUtxos.into());
    }

    // 3. Distribute BTC UTXOs – largest first – to the least funded shard.
    new_btc_utxos.sort_by(|a, b| b.value().cmp(&a.value()));

    for mut utxo in new_btc_utxos.into_iter() {
        // Select target shard.
        let target_idx = select_best_shard_to_add_btc_to(selected_shards)
            .ok_or(StateShardError::ShardsAreFullOfBtcUtxos)?;

        let shard = &mut selected_shards[target_idx];

        // Apply consolidation flag if feature enabled.
        #[cfg(feature = "utxo-consolidation")]
        {
            let has_no_consolidation = shard
                .btc_utxos()
                .iter()
                .any(|u| u.needs_consolidation().is_none());

            if has_no_consolidation {
                *utxo.needs_consolidation_mut() = FixedOptionF64::some(fee_rate.0);
            }
        }

        let success = shard.add_btc_utxo(utxo).is_some();

        if !success {
            return Err(StateShardError::ShardsAreFullOfBtcUtxos.into());
        }
    }

    Ok(())
}

/// Updates the provided `shards` to reflect the effects of a transaction that
/// has just been **broadcast and accepted**.
///
/// This is the main entry point for applying Bitcoin transaction effects to program
/// shard state. It coordinates the complete process of identifying spent/created UTXOs,
/// handling rune token logistics, and updating shard state accordingly.
///
/// # Complete Process Overview
///
/// The function performs three high-level steps:
/// 1. **UTXO Analysis** - Determine which program-owned UTXOs were **spent** and which new ones were
///    **created** by analyzing the `TransactionBuilder` and the final signed `transaction`.
/// 2. **Rune Processing** - Split the newly created outputs into *plain BTC* vs *rune carrying*
///    outputs (the latter is only compiled in when the `runes` feature is enabled).
/// 3. **State Mutation** - Call internal balancing helpers so that the new UTXOs are optimally
///    distributed across the shards involved in the call.
///
/// # Transaction Analysis Details
/// - Examines `inputs_to_sign` to identify which UTXOs were consumed
/// - Scans transaction outputs for those matching the program's script pubkey
/// - Creates UTXO metadata for all newly created program-owned outputs
/// - Handles both standard BTC outputs and rune-bearing outputs
///
/// # Rune Token Handling (with `runes` feature)
/// - Processes runestone edicts to determine rune token distributions
/// - Updates UTXO rune amounts based on explicit edict targeting
/// - Handles runestone pointer for distributing remaining rune tokens
/// - Validates that all input rune tokens are properly accounted for
/// - Separates rune-bearing UTXOs from plain BTC UTXOs for different handling
///
/// # Shard Selection and Scope
/// Only the shards contained in `shard_set.selected_indices()` are mutated,
/// allowing callers to pass references to the *entire* shards slice without
/// cloning or allocating temporaries. This enables selective updates while
/// maintaining references to all available shards.
///
/// # Load Balancing and Distribution
/// - New BTC UTXOs are distributed using a load-balancing algorithm
/// - Rune UTXOs are placed in shards that don't already have one
/// - Distribution favors shards with lower total BTC values
/// - Maintains optimal UTXO distribution for future transaction efficiency
///
/// # Feature Flags Impact
/// - `runes` - Enables rune token processing and runestone handling
/// - `utxo-consolidation` - Adds consolidation flags to UTXOs when appropriate
///
/// # Arguments
/// * `transaction_builder` - Contains the signed transaction and metadata about inputs/outputs
/// * `selected_shards` - Mutable references to shards that should be updated
/// * `program_script_pubkey` - Script pubkey used to identify program-owned outputs
/// * `fee_rate` - Current fee rate for UTXO consolidation flag setting
///
/// # Errors
/// * `StateShardError::ShardsAreFullOfBtcUtxos` - All involved shards have reached their fixed-size BTC-UTXO capacity
/// * `StateShardError::ExcessRuneUtxos` - More rune UTXOs created than can be stored in available shards
/// * `StateShardError::OutputEdictIsNotInTransaction` - Runestone edict references non-existent output
/// * `StateShardError::RunestonePointerIsNotInTransaction` - Runestone pointer references invalid output
/// * `StateShardError::RuneAmountAdditionOverflow` - Arithmetic overflow in rune amount calculations
/// * `StateShardError::NotEnoughRuneInShards` - Attempting to spend more runes than available
///
/// # Example Usage
/// ```rust,ignore
/// let mut shards = shard_set.batch_mut()?;
/// update_shards_after_transaction(
///     &mut transaction_builder,
///     shards.shards_mut(),
///     &program_script_pubkey,
///     &fee_rate,
/// )?;
/// // Shards are automatically updated when the batch is dropped
/// ```
///
/// # Atomicity Guarantees
/// - Either all shard updates succeed or none do (error handling preserves original state)
/// - No partial updates that could leave shards in inconsistent states
/// - Transaction effects are applied atomically across all selected shards
#[allow(clippy::too_many_arguments)]
pub fn update_shards_after_transaction<
    'info,
    const MAX_USER_UTXOS: usize,
    const MAX_SHARDS_PER_PROGRAM: usize,
    RS,
    U,
    S,
>(
    transaction_builder: &TransactionBuilder<MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM, RS>,
    selected_shards: &mut [RefMut<'info, S>],
    program_script_pubkey: &ScriptBuf,
    fee_rate: &FeeRate,
) -> super::error::Result<()>
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
    S: StateShard<U, RS> + ZeroCopy + Owner,
{
    // ---------------------------------------------------------------------
    // 1. Identify program-owned UTXOs that were spent/created.
    // ---------------------------------------------------------------------
    let (utxos_to_remove, mut new_program_utxos) = get_modified_program_utxos_in_transaction(
        program_script_pubkey,
        &transaction_builder.transaction,
        transaction_builder.inputs_to_sign.as_slice(),
    );

    // utxos_to_remove
    //     .iter()
    //     .for_each(|utxo| msg!("utxo_to_remove: {}", utxo.to_outpoint()));

    // new_program_utxos
    //     .iter()
    //     .for_each(|utxo: &U| msg!("new_program_utxo: {}", utxo.meta().to_outpoint()));

    // ---------------------------------------------------------------------
    // 2. Split new outputs into rune vs btc
    // ---------------------------------------------------------------------
    #[cfg(feature = "runes")]
    let (new_rune_utxos, new_btc_utxos) = {
        let runestone = &transaction_builder.runestone;

        let new_rune_utxos = update_modified_program_utxos_with_rune_amount(
            &mut new_program_utxos,
            runestone,
            &transaction_builder.total_rune_inputs,
        )?;
        (new_rune_utxos, new_program_utxos)
    };

    #[cfg(not(feature = "runes"))]
    let (new_rune_utxos, new_btc_utxos) = (Vec::<U>::new(), new_program_utxos);

    // ---------------------------------------------------------------------
    // 3. Mutate shards.
    // ---------------------------------------------------------------------
    update_shards_utxos(
        selected_shards,
        &utxos_to_remove,
        new_rune_utxos,
        new_btc_utxos,
        fee_rate,
    )
}

/// Updates shard state after a Bitcoin transaction **when the caller already holds two separate
/// mutable slices**: one for shards that should store rune-bearing UTXOs and another for shards that
/// should only store plain BTC UTXOs.
///
/// This is the most ergonomic variant when the shard selection logic has already been split by the
/// caller:
///
/// ```rust,ignore
/// let mut rune_shards = shard_set.select_with([0, 2])?.shards_mut();
/// let mut btc_shards  = shard_set.select_with([1, 3, 4])?.shards_mut();
/// update_shards_after_transaction_split(
///     &tx_builder,
///     rune_shards,
///     btc_shards,
///     &program_script_pubkey,
///     &fee_rate,
/// )?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn update_shards_after_transaction_split<
    'info,
    const MAX_USER_UTXOS: usize,
    const MAX_SHARDS_PER_PROGRAM: usize,
    RS,
    U,
    S,
>(
    transaction_builder: &TransactionBuilder<MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM, RS>,
    rune_selected_shards: &mut [RefMut<'info, S>],
    btc_selected_shards: &mut [RefMut<'info, S>],
    program_script_pubkey: &ScriptBuf,
    fee_rate: &FeeRate,
) -> super::error::Result<()>
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
    S: StateShard<U, RS> + ZeroCopy + Owner,
{
    // ---------------------------------------------------------------------
    // 1. Identify program-owned UTXOs that were spent/created.
    // ---------------------------------------------------------------------
    let (utxos_to_remove, mut new_program_utxos) = get_modified_program_utxos_in_transaction(
        program_script_pubkey,
        &transaction_builder.transaction,
        transaction_builder.inputs_to_sign.as_slice(),
    );

    // ---------------------------------------------------------------------
    // 2. Split new outputs into rune vs btc.
    // ---------------------------------------------------------------------
    #[cfg(feature = "runes")]
    let (new_rune_utxos, new_btc_utxos) = {
        let runestone = &transaction_builder.runestone;
        let new_rune_utxos = update_modified_program_utxos_with_rune_amount(
            &mut new_program_utxos,
            runestone,
            &transaction_builder.total_rune_inputs,
        )?;
        (new_rune_utxos, new_program_utxos)
    };
    #[cfg(not(feature = "runes"))]
    let (new_rune_utxos, new_btc_utxos) = (Vec::<U>::new(), new_program_utxos);

    // ---------------------------------------------------------------------
    // 3. Delegate to the existing helper to avoid code duplication.
    // ---------------------------------------------------------------------
    // First, handle rune shards: remove spent UTXOs and insert rune-bearing ones.
    update_shards_utxos::<RS, U, S>(
        rune_selected_shards,
        &utxos_to_remove,
        new_rune_utxos,
        Vec::new(), // no plain-BTC outputs go into rune shards
        fee_rate,
    )?;

    // Second, handle BTC-only shards: remove spent UTXOs and distribute BTC outputs.
    update_shards_utxos::<RS, U, S>(
        btc_selected_shards,
        &utxos_to_remove,
        Vec::new(), // rune UTXOs have already been handled
        new_btc_utxos,
        fee_rate,
    )
}

/// Analyzes a Bitcoin transaction to identify program-owned UTXOs that were spent and created.
///
/// This function performs the critical task of determining which UTXOs need to be removed
/// from shard state (because they were spent) and which new UTXOs need to be added
/// (because they were created as transaction outputs).
///
/// # Analysis Process
///
/// ## Spent UTXO Identification
/// - Examines each `InputToSign` to find program-owned UTXOs that were consumed
/// - Extracts the `previous_output` (outpoint) from each corresponding transaction input
/// - Converts transaction IDs to the big-endian byte format used in shard storage
/// - Creates `UtxoMeta` objects identifying each spent UTXO
///
/// ## Created UTXO Identification  
/// - Scans all transaction outputs for those matching the program's script pubkey
/// - Creates new `UtxoInfo` objects for each program-owned output found
/// - Assigns proper UTXO metadata (transaction ID and output index)
/// - Captures the satoshi value for each new UTXO
///
/// # UTXO Metadata Handling
/// - Uses big-endian byte representation for transaction IDs (consistent with shard storage)
/// - Maintains proper outpoint structure (txid + vout) for UTXO identification
/// - Ensures metadata compatibility with existing shard UTXO storage formats
///
/// # Return Value Structure
/// Returns a tuple containing:
/// - **Spent UTXOs** (`Vec<UtxoMeta>`) - Metadata for UTXOs that need removal from shards
/// - **Created UTXOs** (`Vec<U>`) - Complete UTXO info for newly created program-owned outputs
///
/// # Arguments
/// * `program_script_pubkey` - The script pubkey identifying program-owned outputs
/// * `transaction` - The complete Bitcoin transaction to analyze
/// * `inputs_to_sign` - Metadata about which inputs the program is responsible for signing
///
/// # Usage Context
/// This function is typically called as the first step in `update_shards_after_transaction`
/// to identify the scope of UTXO changes that need to be applied to shard state.
///
/// # Performance Characteristics
/// - Pre-allocates vectors with estimated capacity for efficiency
/// - Single pass through inputs and outputs
/// - Minimal memory allocation and copying
/// - O(n + m) complexity where n = inputs to sign, m = transaction outputs
///
/// # Example
/// ```rust,ignore
/// let (spent_utxos, created_utxos) = get_modified_program_utxos_in_transaction(
///     &program_script,
///     &signed_transaction,
///     &inputs_to_sign,
/// );
/// // spent_utxos: Vec<UtxoMeta> - remove these from shards
/// // created_utxos: Vec<UtxoInfo> - add these to shards
/// ```
fn get_modified_program_utxos_in_transaction<RS, U>(
    program_script_pubkey: &ScriptBuf,
    transaction: &Transaction,
    inputs_to_sign: &[InputToSign],
) -> (Vec<UtxoMeta>, Vec<U>)
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
{
    use satellite_bitcoin::bytes::txid_to_bytes_big_endian;

    let mut utxos_to_remove = Vec::with_capacity(inputs_to_sign.len());
    let mut program_outputs = Vec::with_capacity(transaction.output.len() / 2);

    let txid_bytes = txid_to_bytes_big_endian(&transaction.compute_txid());

    for input in inputs_to_sign {
        let outpoint = transaction.input[input.index as usize].previous_output;
        utxos_to_remove.push(UtxoMeta::from(
            txid_to_bytes_big_endian(&outpoint.txid),
            outpoint.vout,
        ));
    }

    for (index, output) in transaction.output.iter().enumerate() {
        if output.script_pubkey == *program_script_pubkey {
            program_outputs.push(U::new(
                UtxoMeta::from(txid_bytes, index as u32),
                output.value.to_sat(),
            ));
        }
    }

    (utxos_to_remove, program_outputs)
}

#[cfg(feature = "runes")]
/// Processes runestone data to assign rune token amounts to program-owned transaction outputs.
///
/// This function handles the complex task of distributing rune tokens from transaction inputs
/// to the appropriate outputs based on runestone edicts and pointer rules. It modifies the
/// provided UTXOs to include rune amounts and separates rune-bearing UTXOs from plain BTC UTXOs.
///
/// # Runestone Processing Overview
///
/// ## Edict Processing
/// The function processes each edict in the runestone which explicitly assigns rune amounts:
/// - Finds the target output by matching the edict's output index with UTXO vout
/// - Creates or updates the rune amount for the specified rune ID on that UTXO
/// - Decrements the corresponding amount from the input rune totals
/// - Handles arithmetic overflow protection for rune amount additions
/// - Validates that sufficient input runes exist for each edict assignment
///
/// ## Pointer Handling
/// After processing explicit edicts, remaining input runes are distributed via pointer:
/// - If a runestone pointer is specified, all remaining runes go to that output
/// - The pointer must reference a valid program-owned output in the transaction
/// - Multiple rune types can be assigned to the same pointer output
/// - Handles the case where pointer output already has runes from edicts
///
/// ## Remaining Rune Validation
/// - If no pointer is set, validates that no input runes remain unassigned
/// - Prevents rune token loss by requiring all input runes to be explicitly assigned
/// - Ensures conservation of rune tokens across the transaction boundary
///
/// # UTXO Separation Logic
/// After rune assignment, the function separates UTXOs into two categories:
/// - **Rune UTXOs** - UTXOs that carry any rune tokens (extracted from the vector)
/// - **BTC UTXOs** - Plain UTXOs with only satoshi value (remain in original vector)
///
/// This separation is critical because rune UTXOs and BTC UTXOs are stored differently
/// in shard state and have different handling requirements.
///
/// # Arguments
/// * `new_program_outputs` - Mutable vector of program-owned UTXOs from the transaction
/// * `runestone` - The runestone containing edicts and pointer information
/// * `prev_rune_amount` - Mutable set of input rune amounts to be consumed
///
/// # Returns
/// * `Ok(Vec<U>)` - Vector of UTXOs that carry rune tokens (separated from input vector)
/// * `Err(StateShardError::OutputEdictIsNotInTransaction)` - Edict references invalid output index
/// * `Err(StateShardError::RunestonePointerIsNotInTransaction)` - Pointer references invalid output
/// * `Err(StateShardError::RuneAmountAdditionOverflow)` - Arithmetic overflow in rune calculations
/// * `Err(StateShardError::NotEnoughRuneInShards)` - Insufficient input runes for assignments
///
/// # Rune Conservation
/// The function maintains strict rune conservation by:
/// - Tracking all input rune amounts and decrementing as they're assigned
/// - Requiring that all remaining runes be assigned via pointer or error
/// - Preventing double-spending of rune tokens
/// - Ensuring no rune tokens are lost during processing
///
/// # Example Usage
/// ```rust,ignore
/// let rune_utxos = update_modified_program_utxos_with_rune_amount(
///     &mut program_outputs,  // Modified in place
///     &runestone,
///     &mut input_runes,      // Decremented as runes are assigned
/// )?;
/// // program_outputs now contains only BTC UTXOs
/// // rune_utxos contains UTXOs with rune token assignments
/// ```
///
/// # Performance Characteristics
/// - O(e × o) complexity where e = edicts, o = outputs (due to position lookups)
/// - Minimal memory allocation (reuses existing vectors where possible)
/// - Single pass through edicts and pointer processing
/// - Efficient vector manipulation for UTXO separation
fn update_modified_program_utxos_with_rune_amount<RS, U>(
    new_program_outputs: &mut Vec<U>,
    runestone: &Runestone,
    prev_rune_amount: &RS,
) -> super::error::Result<Vec<U>>
where
    RS: FixedCapacitySet<Item = RuneAmount> + Default,
    U: UtxoInfoTrait<RS>,
{
    let mut remaining_rune_amount = prev_rune_amount.clone();
    let mut rune_utxos = vec![];

    for edict in &runestone.edicts {
        let rune_amount = edict.amount;
        let index = edict.output;

        let rune_id = RuneId::new(edict.id.block, edict.id.tx);
        let pos = new_program_outputs
            .iter()
            .position(|u| u.meta().vout() == index);

        // Edicts might go to other addresses, so we need to check if the output is in the vector
        if let Some(pos) = pos {
            let output = new_program_outputs
                .get_mut(pos)
                .ok_or(StateShardError::OutputEdictIsNotInTransaction)?;

            output.runes_mut().insert_or_modify::<StateShardError, _>(
                RuneAmount {
                    id: rune_id,
                    amount: rune_amount,
                },
                |rune_input| {
                    rune_input.amount = rune_input
                        .amount
                        .checked_add(rune_amount)
                        .ok_or(StateShardError::RuneAmountAdditionOverflow)?;
                    Ok(())
                },
            )?;
        }

        // Even though the amount might not go to the program address, we have to decrement it
        // from the remaining rune amount
        if let Some(remaining) = remaining_rune_amount
            .iter_mut()
            .find(|rune_amount| rune_amount.id == rune_id)
        {
            remaining.amount = remaining
                .amount
                .checked_sub(rune_amount)
                .ok_or(StateShardError::NotEnoughRuneInShards)?;
        }
    }

    if let Some(pointer_index) = runestone.pointer {
        for rune_amount in remaining_rune_amount.iter() {
            if let Some(output) = new_program_outputs
                .iter_mut()
                .find(|u| u.meta().vout() == pointer_index)
            {
                output.runes_mut().insert_or_modify::<StateShardError, _>(
                    RuneAmount {
                        id: rune_amount.id,
                        amount: rune_amount.amount,
                    },
                    |rune_input| {
                        rune_input.amount = rune_input
                            .amount
                            .checked_add(rune_amount.amount)
                            .ok_or(StateShardError::RuneAmountAdditionOverflow)?;
                        Ok(())
                    },
                )?;
            }
        }
    } else {
        for rune_amount in remaining_rune_amount.iter() {
            if rune_amount.amount > 0 {
                return Err(StateShardError::RunestonePointerIsNotInTransaction);
            }
        }
    }

    let mut i = new_program_outputs.len();
    while i > 0 {
        i -= 1;
        if new_program_outputs[i].runes().len() > 0 {
            let rune_utxo = new_program_outputs.swap_remove(i);
            rune_utxos.push(rune_utxo);
        }
    }

    rune_utxos.reverse();

    Ok(rune_utxos)
}

#[cfg(test)]
mod tests_loader {
    use super::*;

    use super::super::tests::common::{
        add_btc_utxos_bulk, create_shard, leak_loaders_from_vec, MockShardZc, MAX_BTC_UTXOS,
    };
    use satellite_bitcoin::utxo_info::{SingleRuneSet, UtxoInfo, UtxoInfoTrait};

    // Re-export for macro reuse – mirrors helper in split_loader tests.
    use satellite_bitcoin::TransactionBuilder as TB;

    #[allow(unused_macros)]
    macro_rules! new_tb {
        ($max_utxos:expr, $max_shards:expr) => {
            TB::<$max_utxos, $max_shards, SingleRuneSet>::new()
        };
    }

    // === Shared helpers ====================================================
    fn create_utxo(
        value: u64,
        txid_byte: u8,
        vout: u32,
    ) -> satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet> {
        let txid = [txid_byte; 32];
        let meta = UtxoMeta::from(txid, vout);
        let utxo_info = UtxoInfo::new(meta, value);
        utxo_info
    }

    fn fee_rate() -> FeeRate {
        FeeRate(1.0)
    }

    // ---------------------------------------------------------------------
    // select_best_shard_to_add_btc_to
    // ---------------------------------------------------------------------
    mod select_best_shard_to_add_btc_to {
        use super::*;

        #[test]
        fn selects_shard_with_smallest_total_btc() {
            let shard_low = create_shard(50);
            let shard_medium = create_shard(100);
            let shard_high = create_shard(200);

            let shards_vec = vec![shard_medium, shard_low, shard_high];
            let loaders = leak_loaders_from_vec(shards_vec);

            // Get RefMut objects directly from loaders
            let shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();

            let best = super::super::select_best_shard_to_add_btc_to::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&shard_refs);

            assert_eq!(best, Some(1)); // shard_low at index 1 has the fewest sats
        }

        #[test]
        fn returns_none_when_all_shards_are_full() {
            let mut shard0 = create_shard(0);
            let mut shard1 = create_shard(0);
            // Fill both shards to capacity
            add_btc_utxos_bulk(&mut shard0, &vec![1u64; MAX_BTC_UTXOS]);
            add_btc_utxos_bulk(&mut shard1, &vec![1u64; MAX_BTC_UTXOS]);

            let shards_vec = vec![shard0, shard1];
            let loaders = leak_loaders_from_vec(shards_vec);

            // Get RefMut objects directly from loaders
            let shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();

            let res = super::super::select_best_shard_to_add_btc_to::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&shard_refs);
            assert_eq!(res, None);
        }

        #[test]
        fn skips_full_shard_and_selects_available_one() {
            let mut shard_full = create_shard(0);
            add_btc_utxos_bulk(&mut shard_full, &vec![1u64; MAX_BTC_UTXOS]);
            let shard_available = create_shard(500);

            let shards_vec = vec![shard_full, shard_available];
            let loaders = leak_loaders_from_vec(shards_vec);

            // Get RefMut objects directly from loaders
            let shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();

            let res = super::super::select_best_shard_to_add_btc_to::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&shard_refs);
            assert_eq!(res, Some(1)); // second shard has spare capacity
        }
    }

    // ---------------------------------------------------------------------
    // update_shards_utxos (subset)
    // ---------------------------------------------------------------------
    mod update_shards_utxos_tests {
        use super::*;

        fn setup_shard_loaders(
            shard0: MockShardZc,
            shard1: MockShardZc,
        ) -> &'static [satellite_lang::prelude::AccountLoader<'static, MockShardZc>] {
            let shards_vec = vec![shard0, shard1];
            leak_loaders_from_vec(shards_vec)
        }

        #[test]
        fn distributes_new_utxos_and_handles_runes() {
            let loaders = setup_shard_loaders(create_shard(0), create_shard(0));

            let new_rune_utxo = create_utxo(546, 10, 0);
            let new_btc_big = create_utxo(200, 11, 0);
            let new_btc_small = create_utxo(100, 12, 0);

            // Get RefMut objects directly from loaders
            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            let result = super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![new_rune_utxo.clone()],
                vec![new_btc_big.clone(), new_btc_small.clone()],
                &fee_rate(),
            );
            assert!(result.is_ok());
            drop(shard_refs);

            // Verify shard0 (index 0) received rune utxo and larger btc value
            let shard0_ref = loaders[0].load().unwrap();
            let shard0_btc_len = shard0_ref.btc_utxos_len();
            let shard0_rune_present = shard0_ref.rune_utxo().is_some();
            assert_eq!(shard0_btc_len, 1);
            assert!(shard0_rune_present);
            drop(shard0_ref);

            // shard1 should have smaller btc and no rune
            let shard1_ref = loaders[1].load().unwrap();
            let shard1_btc_len = shard1_ref.btc_utxos_len();
            let shard1_rune_present = shard1_ref.rune_utxo().is_some();
            assert_eq!(shard1_btc_len, 1);
            assert!(!shard1_rune_present);
        }

        #[test]
        fn errors_when_btc_utxo_vector_overflows() {
            // Fill both shards
            let mut shard0 = create_shard(0);
            add_btc_utxos_bulk(&mut shard0, &vec![1u64; MAX_BTC_UTXOS]);
            let mut shard1 = create_shard(0);
            add_btc_utxos_bulk(&mut shard1, &vec![1u64; MAX_BTC_UTXOS]);

            let loaders = setup_shard_loaders(shard0, shard1);

            // Get RefMut objects directly from loaders
            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            let err = super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![],
                vec![create_utxo(1, 99, 0)],
                &fee_rate(),
            )
            .unwrap_err();

            assert_eq!(err, StateShardError::ShardsAreFullOfBtcUtxos);
        }

        #[test]
        fn succeeds_after_removal_creates_capacity() {
            // Fill shard0 to capacity (MAX_BTC_UTXOS) and shard1 empty.
            let mut shard0 = MockShardZc::default();

            // First UTXO that we will remove.
            let utxo_to_remove = create_utxo(100, 120, 0);
            shard0.add_btc_utxo(utxo_to_remove.clone());

            // Fill rest of shard0
            let filler: Vec<u64> = vec![1u64; MAX_BTC_UTXOS - 1];
            add_btc_utxos_bulk(&mut shard0, &filler);

            let shard1 = MockShardZc::default();

            let shards_vec = vec![shard0, shard1];
            let loaders = leak_loaders_from_vec(shards_vec);

            let new_utxo = create_utxo(200, 122, 0);

            // Execute update – should succeed because removal frees 1 slot.
            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[*utxo_to_remove.meta()],
                vec![],
                vec![new_utxo.clone()],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            // shard0 should still be at capacity and no longer contain utxo_to_remove
            let shard0_ref = loaders[0].load().unwrap();
            assert_eq!(shard0_ref.btc_utxos_len(), MAX_BTC_UTXOS - 1);
            assert!(!shard0_ref
                .btc_utxos()
                .iter()
                .any(|u| u.eq_meta(&utxo_to_remove)));
            drop(shard0_ref);

            // shard1 should now contain the new_utxo (least funded after removal)
            let shard1_ref = loaders[1].load().unwrap();
            assert_eq!(shard1_ref.btc_utxos_len(), 1);
            assert!(shard1_ref.btc_utxos().iter().any(|u| u.eq_meta(&new_utxo)));
        }

        #[test]
        fn replaces_rune_utxo_correctly() {
            let old_rune = create_utxo(546, 130, 0);
            let new_rune = create_utxo(546, 131, 0);

            let mut shard0 = MockShardZc::default();
            shard0.set_rune_utxo(old_rune.clone());

            let shard1 = MockShardZc::default();

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[*old_rune.meta()],
                vec![new_rune.clone()],
                vec![],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            let shard0_ref = loaders[0].load().unwrap();
            let r = shard0_ref.rune_utxo().expect("rune utxo expected");
            assert!(r.eq_meta(&new_rune));
            drop(shard0_ref);

            let shard1_ref = loaders[1].load().unwrap();
            assert!(shard1_ref.rune_utxo().is_none());
        }

        #[cfg(feature = "utxo-consolidation")]
        #[test]
        fn sets_needs_consolidation_flag_when_applicable() {
            // shard0 has 1 tiny UTXO so will receive the new one
            let mut shard0 = MockShardZc::default();
            add_btc_utxos_bulk(&mut shard0, &[1]);

            let mut shard1 = MockShardZc::default();
            add_btc_utxos_bulk(&mut shard1, &[100]);

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let new_utxo = create_utxo(5, 83, 0);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![],
                vec![new_utxo.clone()],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            let shard0_ref = loaders[0].load().unwrap();
            let inserted = shard0_ref.btc_utxos().last().unwrap();
            assert!(inserted.needs_consolidation().is_some());
            assert_eq!(inserted.needs_consolidation().get().unwrap(), fee_rate().0);
        }

        #[cfg(feature = "utxo-consolidation")]
        #[test]
        fn does_not_set_consolidation_flag_when_shard_has_zero_utxos() {
            let mut shard0 = MockShardZc::default();
            add_btc_utxos_bulk(&mut shard0, &[]);

            let shard1 = MockShardZc::default();

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let new_utxo = create_utxo(10, 151, 0);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![],
                vec![new_utxo.clone()],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            // new UTXO should go to shard1 (empty before)
            let shard1_ref = loaders[1].load().unwrap();
            assert_eq!(shard1_ref.btc_utxos_len(), 0);
        }

        #[test]
        fn skips_inserting_rune_when_already_present() {
            // shard0 already has a rune UTXO
            let existing_rune = create_utxo(546, 30, 0);
            let mut shard0 = MockShardZc::default();
            shard0.set_rune_utxo(existing_rune.clone());

            let shard1 = MockShardZc::default();

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            // Attempt to insert a new rune UTXO – should go to shard1, not replace shard0's
            let new_rune = create_utxo(546, 31, 0);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![new_rune.clone()],
                vec![],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            // Verify shard0 still has original rune
            let shard0_ref = loaders[0].load().unwrap();
            assert!(shard0_ref.rune_utxo().unwrap().eq_meta(&existing_rune));
            drop(shard0_ref);

            // shard1 received new rune
            let shard1_ref = loaders[1].load().unwrap();
            assert!(shard1_ref.rune_utxo().is_some());
            assert!(shard1_ref.rune_utxo().unwrap().eq_meta(&new_rune));
        }

        #[test]
        fn handles_no_new_runes_when_shards_have_none() {
            let shard0 = MockShardZc::default();
            let shard1 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let btc_utxo = create_utxo(1_000, 140, 0);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut shard_refs, &[], vec![], vec![btc_utxo], &fee_rate())
            .unwrap();
            drop(shard_refs);

            // Neither shard should have a rune utxo.
            for loader in loaders.iter() {
                let shard_ref = loader.load().unwrap();
                assert!(shard_ref.rune_utxo().is_none());
            }
        }

        #[cfg(feature = "utxo-consolidation")]
        #[test]
        fn first_new_btc_utxo_is_flagged_when_existing_utxos_have_none() {
            // shard0 has multiple small UTXOs but a smaller total than shard1
            let mut shard0 = MockShardZc::default();
            add_btc_utxos_bulk(&mut shard0, &[1, 1, 1, 1, 1]); // 5 sats total

            let mut shard1 = MockShardZc::default();
            add_btc_utxos_bulk(&mut shard1, &[100]); // 100 sats total

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            // Single new BTC UTXO to insert – it's the "first" (idx == 0)
            let new_utxo = create_utxo(50, 240, 0);

            // Execute update – new UTXO should go to shard0 (least funded)
            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![],
                vec![new_utxo.clone()],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            // Verify the inserted UTXO DOES have consolidation flag set (to keep a single NONE overall)
            let shard0_ref = loaders[0].load().unwrap();
            let inserted = shard0_ref.btc_utxos().last().unwrap();
            assert!(inserted.needs_consolidation().is_some());
        }

        #[cfg(feature = "utxo-consolidation")]
        #[test]
        fn case1_one_existing_without_flag_then_new_flagged_and_single_none() {
            // Start with a shard that has exactly one UTXO (no consolidation flag by default)
            let mut shard = MockShardZc::default();
            add_btc_utxos_bulk(&mut shard, &[10]);

            let loaders = leak_loaders_from_vec(vec![shard]);

            // Insert one new UTXO
            let new_utxo = create_utxo(20, 241, 0);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![],
                vec![new_utxo.clone()],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            let shard_ref = loaders[0].load().unwrap();
            // Exactly one UTXO should have no consolidation flag
            let none_count = shard_ref
                .btc_utxos()
                .iter()
                .filter(|u| u.needs_consolidation().is_none())
                .count();
            assert_eq!(none_count, 1);

            // The newly inserted one should be flagged (some)
            let inserted = shard_ref.btc_utxos().last().unwrap();
            assert!(inserted.needs_consolidation().is_some());
            assert_eq!(inserted.needs_consolidation().get().unwrap(), fee_rate().0);
        }

        #[cfg(feature = "utxo-consolidation")]
        #[test]
        fn case2_all_existing_flagged_first_new_none_second_flagged_and_single_none() {
            // Prepare shard with 2 existing UTXOs and mark them as needing consolidation
            let mut shard = MockShardZc::default();
            add_btc_utxos_bulk(&mut shard, &[5, 7]);

            let loaders = leak_loaders_from_vec(vec![shard]);

            // Mark all existing as Some(fee_rate)
            {
                use satellite_bitcoin::utxo_info::FixedOptionF64;
                let mut s = loaders[0].load_mut().unwrap();
                for u in s.btc_utxos_mut().iter_mut() {
                    *u.needs_consolidation_mut() = FixedOptionF64::some(fee_rate().0);
                }
                drop(s);
            }

            // Insert two new UTXOs in one call
            let new_a = create_utxo(30, 242, 0);
            let new_b = create_utxo(25, 243, 0);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![],
                vec![new_a, new_b],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            let shard_ref = loaders[0].load().unwrap();
            let len = shard_ref.btc_utxos_len();
            let inserted_slice = &shard_ref.btc_utxos()[len.saturating_sub(2)..];

            // Among the two inserted: exactly one none, one some
            let none_inserted = inserted_slice
                .iter()
                .filter(|u| u.needs_consolidation().is_none())
                .count();
            let some_inserted = inserted_slice
                .iter()
                .filter(|u| u.needs_consolidation().is_some())
                .count();
            assert_eq!(none_inserted, 1);
            assert_eq!(some_inserted, 1);

            // Across the whole shard there must be exactly one none
            let total_none = shard_ref
                .btc_utxos()
                .iter()
                .filter(|u| u.needs_consolidation().is_none())
                .count();
            assert_eq!(total_none, 1);
        }

        #[cfg(feature = "utxo-consolidation")]
        #[test]
        fn case3_empty_first_new_none_following_flagged_and_single_none() {
            // Start with an empty shard
            let shard = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard]);

            // Insert three new UTXOs
            let new_a = create_utxo(40, 244, 0);
            let new_b = create_utxo(35, 245, 0);
            let new_c = create_utxo(10, 246, 0);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_utxos::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut shard_refs,
                &[],
                vec![],
                vec![new_a, new_b, new_c],
                &fee_rate(),
            )
            .unwrap();
            drop(shard_refs);

            let shard_ref = loaders[0].load().unwrap();
            // Exactly one UTXO should have no consolidation flag overall
            let total_none = shard_ref
                .btc_utxos()
                .iter()
                .filter(|u| u.needs_consolidation().is_none())
                .count();
            assert_eq!(total_none, 1);
        }
    }

    // ---------------------------------------------------------------------
    // remove_utxos_from_shards
    // ---------------------------------------------------------------------
    mod remove_utxos_from_shards {
        use super::*;

        #[test]
        fn removes_btc_and_rune_utxos_across_shards() {
            // UTXO to be removed
            let utxo_to_remove = create_utxo(1_000, 200, 0);
            let meta_to_remove = *utxo_to_remove.meta();

            // Build two shards each containing the BTC + Rune UTXO to remove
            let mut shard0 = MockShardZc::default();
            shard0.add_btc_utxo(utxo_to_remove.clone());
            shard0.set_rune_utxo(utxo_to_remove.clone());

            let mut shard1 = MockShardZc::default();
            shard1.add_btc_utxo(utxo_to_remove.clone());
            shard1.set_rune_utxo(utxo_to_remove.clone());

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            // Execute helper and verify
            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::remove_utxos_from_shards::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut shard_refs, &[meta_to_remove])
            .unwrap();
            drop(shard_refs);

            for loader in loaders.iter() {
                let shard_ref = loader.load().unwrap();
                assert_eq!(shard_ref.btc_utxos_len(), 0);
                assert!(shard_ref.rune_utxo().is_none());
            }
        }

        #[test]
        fn ignores_utxo_missing_in_some_shards() {
            let utxo_to_remove = create_utxo(500, 201, 0);
            let meta_to_remove = *utxo_to_remove.meta();

            // shard0 contains the UTXO, shard1 does not
            let mut shard0 = MockShardZc::default();
            shard0.add_btc_utxo(utxo_to_remove.clone());

            let shard1 = MockShardZc::default();

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::remove_utxos_from_shards::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut shard_refs, &[meta_to_remove])
            .unwrap();
            drop(shard_refs);

            // shard0 should now be empty, shard1 unaffected
            let shard0_ref = loaders[0].load().unwrap();
            assert_eq!(shard0_ref.btc_utxos_len(), 0);
            drop(shard0_ref);

            let shard1_ref = loaders[1].load().unwrap();
            assert_eq!(shard1_ref.btc_utxos_len(), 0);
        }

        #[test]
        fn handles_empty_utxos_to_remove() {
            let shard0 = create_shard(1000);
            let shard1 = create_shard(2000);
            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            // Removing zero items should be a no-op
            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::remove_utxos_from_shards::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut shard_refs, &[])
            .unwrap();
            drop(shard_refs);

            // Verify original balances intact
            let shard0_ref = loaders[0].load().unwrap();
            assert_eq!(shard0_ref.btc_utxos_len(), 1);
            drop(shard0_ref);

            let shard1_ref = loaders[1].load().unwrap();
            assert_eq!(shard1_ref.btc_utxos_len(), 1);
        }

        #[test]
        fn works_when_shard_has_no_rune_utxo() {
            let utxo_to_remove = create_utxo(1_000, 60, 0);
            let meta = *utxo_to_remove.meta();

            let mut shard = MockShardZc::default();
            shard.add_btc_utxo(utxo_to_remove.clone());

            let loaders = leak_loaders_from_vec(vec![shard]);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::remove_utxos_from_shards::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut shard_refs, &[meta])
            .unwrap();
            drop(shard_refs);

            let shard_ref = loaders[0].load().unwrap();
            assert_eq!(shard_ref.btc_utxos_len(), 0);
        }

        #[test]
        fn removes_multiple_utxos_from_multiple_shards() {
            let utxo_a = create_utxo(500, 250, 0);
            let utxo_b = create_utxo(600, 251, 0);

            let mut shard0 = MockShardZc::default();
            shard0.add_btc_utxo(utxo_a.clone());
            shard0.add_btc_utxo(utxo_b.clone());

            let mut shard1 = MockShardZc::default();
            shard1.add_btc_utxo(utxo_a.clone());
            shard1.add_btc_utxo(utxo_b.clone());

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::remove_utxos_from_shards::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut shard_refs, &[*utxo_a.meta(), *utxo_b.meta()])
            .unwrap();
            drop(shard_refs);

            for loader in loaders.iter() {
                let shard_ref = loader.load().unwrap();
                assert_eq!(shard_ref.btc_utxos_len(), 0);
            }
        }
    }

    // ---------------------------------------------------------------------
    // get_modified_program_utxos_in_transaction
    // ---------------------------------------------------------------------
    mod get_modified_program_utxos_in_transaction {
        use super::*;
        use arch_program::input_to_sign::InputToSign;
        use bitcoin::absolute::LockTime;
        use bitcoin::transaction::Version;
        use bitcoin::{Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness};

        #[test]
        fn identifies_program_outputs_correctly() {
            let script = ScriptBuf::new();

            let tx = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: OutPoint::null(),
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![TxOut {
                    value: Amount::from_sat(1000),
                    script_pubkey: script.clone(),
                }],
            };

            let inputs = vec![InputToSign {
                index: 0,
                signer: arch_program::pubkey::Pubkey::default(),
            }];

            let (removed, added): (
                Vec<UtxoMeta>,
                Vec<satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>>,
            ) = super::super::get_modified_program_utxos_in_transaction::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
            >(&script, &tx, &inputs);

            assert_eq!(removed.len(), 1);
            assert_eq!(added.len(), 1);
            assert_eq!(added[0].value, 1000);
        }

        #[test]
        fn handles_multiple_inputs_to_sign() {
            let script = ScriptBuf::new();

            let outpoint1 = {
                let mut o = OutPoint::null();
                o.vout = 0;
                o
            };
            let outpoint2 = {
                let mut o = OutPoint::null();
                o.vout = 1;
                o
            };

            let tx = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![
                    TxIn {
                        previous_output: outpoint1,
                        script_sig: ScriptBuf::new(),
                        sequence: Sequence::MAX,
                        witness: Witness::default(),
                    },
                    TxIn {
                        previous_output: outpoint2,
                        script_sig: ScriptBuf::new(),
                        sequence: Sequence::MAX,
                        witness: Witness::default(),
                    },
                ],
                output: vec![],
            };

            let inputs = vec![
                InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                },
                InputToSign {
                    index: 1,
                    signer: arch_program::pubkey::Pubkey::default(),
                },
            ];

            let (removed, _added): (
                Vec<UtxoMeta>,
                Vec<satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>>,
            ) = super::super::get_modified_program_utxos_in_transaction::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
            >(&script, &tx, &inputs);

            assert_eq!(removed.len(), 2);
            assert!(removed.iter().any(|m| m.vout() == 0));
            assert!(removed.iter().any(|m| m.vout() == 1));
        }

        #[test]
        fn handles_multiple_program_outputs() {
            let script = ScriptBuf::new();

            let tx = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![],
                output: vec![
                    TxOut {
                        value: Amount::from_sat(1_000),
                        script_pubkey: script.clone(),
                    },
                    TxOut {
                        value: Amount::from_sat(2_000),
                        script_pubkey: ScriptBuf::from_bytes(vec![0x51]),
                    },
                    TxOut {
                        value: Amount::from_sat(3_000),
                        script_pubkey: script.clone(),
                    },
                ],
            };

            let (_removed, added): (
                Vec<UtxoMeta>,
                Vec<satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>>,
            ) = super::super::get_modified_program_utxos_in_transaction::<
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
            >(&script, &tx, &[]);

            assert_eq!(added.len(), 2);
            assert_eq!(added[0].value, 1_000);
            assert_eq!(added[0].meta.vout(), 0);
            assert_eq!(added[1].value, 3_000);
            assert_eq!(added[1].meta.vout(), 2);
        }
    }

    // ---------------------------------------------------------------------
    // update_shards_after_transaction
    // ---------------------------------------------------------------------
    mod update_shards_after_transaction {
        use super::*;
        use arch_program::input_to_sign::InputToSign;
        use bitcoin::absolute::LockTime;
        use bitcoin::hashes::sha256d::Hash as Sha256dHash;
        use bitcoin::hashes::Hash;
        use bitcoin::transaction::Version;
        use bitcoin::{Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness};

        #[test]
        fn integrates_all_helpers() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();

            // existing utxo in shard0
            let existing_utxo = create_utxo(5_000, 200, 0);
            let txid_200 =
                bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[200u8; 32]).unwrap());
            let input_outpoint = OutPoint {
                txid: txid_200,
                vout: 0,
            };

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![TxOut {
                    value: Amount::from_sat(4_500),
                    script_pubkey: program_script.clone(),
                }],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            let mut shard0 = MockShardZc::default();
            shard0.add_btc_utxo(existing_utxo.clone());
            let shard1 = MockShardZc::default();

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut builder, &mut shard_refs, &program_script, &fee_rate())
            .unwrap();
            drop(shard_refs);

            // old utxo removed
            let shard0_ref = loaders[0].load().unwrap();
            assert!(!shard0_ref
                .btc_utxos()
                .iter()
                .any(|u| u.eq_meta(&existing_utxo)));
            let shard0_len = shard0_ref.btc_utxos_len();
            drop(shard0_ref);

            let shard1_ref = loaders[1].load().unwrap();
            let shard1_len = shard1_ref.btc_utxos_len();
            drop(shard1_ref);

            let total = shard0_len + shard1_len;
            assert_eq!(total, 1);
        }

        #[cfg(feature = "runes")]
        #[test]
        fn handles_rune_utxo_spending_and_creation() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();
            let existing_rune_utxo = create_utxo(546, 210, 0);

            builder
                .total_rune_inputs
                .insert(arch_program::rune::RuneAmount {
                    id: arch_program::rune::RuneId::new(1, 0),
                    amount: 100,
                })
                .unwrap();

            let txid_210 =
                bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[210u8; 32]).unwrap());
            let input_outpoint = OutPoint {
                txid: txid_210,
                vout: 0,
            };

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                ],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            builder.runestone = Runestone {
                pointer: Some(1),
                edicts: vec![ordinals::Edict {
                    id: ordinals::RuneId { block: 1, tx: 0 },
                    amount: 60,
                    output: 0,
                }],
                ..Default::default()
            };

            let mut shard0 = MockShardZc::default();
            shard0.set_rune_utxo(existing_rune_utxo.clone());
            let shard1 = MockShardZc::default();

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(&mut builder, &mut shard_refs, &program_script, &fee_rate())
            .unwrap();
            drop(shard_refs);

            // old rune utxo removed, at least one shard has rune utxo
            let shard0_ref = loaders[0].load().unwrap();
            let shard0_has_rune = shard0_ref.rune_utxo().is_some();
            drop(shard0_ref);

            let shard1_ref = loaders[1].load().unwrap();
            let shard1_has_rune = shard1_ref.rune_utxo().is_some();
            drop(shard1_ref);

            let has_rune = shard0_has_rune || shard1_has_rune;
            assert!(has_rune);
        }

        #[test]
        fn propagates_overflow_error_when_all_shards_full() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![],
                output: vec![TxOut {
                    value: Amount::from_sat(1),
                    script_pubkey: ScriptBuf::new(),
                }],
            };

            // Fill both shards to capacity
            let mut shard0 = MockShardZc::default();
            let mut shard1 = MockShardZc::default();
            for i in 0..MockShardZc::btc_utxos_max_len(&shard0) {
                shard0.add_btc_utxo(create_utxo(1, 220, i as u32));
                shard1.add_btc_utxo(create_utxo(1, 221, i as u32));
            }

            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let mut shard_refs: Vec<_> = loaders
                .iter()
                .map(|loader| loader.load_mut().unwrap())
                .collect();
            let err = super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &ScriptBuf::new(),
                &fee_rate(),
            )
            .unwrap_err();

            assert_eq!(err, StateShardError::ShardsAreFullOfBtcUtxos);
        }

        #[cfg(feature = "runes")]
        #[test]
        fn assigns_rune_utxo_when_pointer_exists_but_remaining_is_zero() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();

            // Inputs: one dummy
            let txid_1 = bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[1u8; 32]).unwrap());
            let input_outpoint = OutPoint {
                txid: txid_1,
                vout: 0,
            };

            // Outputs:
            //  - vout 0: program output (pointer target)
            //  - vout 1: non-program output (edict target)
            let non_program_script = ScriptBuf::from_bytes(vec![0x51]); // OP_1

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: non_program_script,
                    },
                ],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            // All input runes (amount 6) are sent via an edict to a NON-program output (vout 1),
            // so remaining amount for the pointer is zero.
            builder
                .total_rune_inputs
                .insert(arch_program::rune::RuneAmount {
                    id: arch_program::rune::RuneId::new(1, 0),
                    amount: 6,
                })
                .unwrap();

            builder.runestone = Runestone {
                pointer: Some(0),
                edicts: vec![ordinals::Edict {
                    id: ordinals::RuneId { block: 1, tx: 0 },
                    amount: 6,
                    output: 1,
                }],
                ..Default::default()
            };

            // One shard selected → it should receive a rune UTXO (with zero amount)
            let shard0 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0]);

            let mut shard_refs: Vec<_> = loaders.iter().map(|l| l.load_mut().unwrap()).collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &program_script,
                &FeeRate(1.0),
            )
            .unwrap();
            drop(shard_refs);

            let shard0_ref = loaders[0].load().unwrap();
            assert!(shard0_ref.rune_utxo().is_some());
        }

        #[cfg(feature = "runes")]
        #[test]
        fn assigns_rune_utxos_when_edicts_have_zero_amounts() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();

            // Inputs: one dummy
            let txid_2 = bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[2u8; 32]).unwrap());
            let input_outpoint = OutPoint {
                txid: txid_2,
                vout: 0,
            };

            // Outputs: two program outputs (vout 0 and vout 1)
            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                ],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            // No total rune inputs necessary; edicts with zero amounts still create rune entries
            // on the target outputs.
            builder.runestone = Runestone {
                pointer: Some(0),
                edicts: vec![
                    ordinals::Edict {
                        id: ordinals::RuneId { block: 1, tx: 0 },
                        amount: 0,
                        output: 0,
                    },
                    ordinals::Edict {
                        id: ordinals::RuneId { block: 1, tx: 0 },
                        amount: 0,
                        output: 1,
                    },
                ],
                ..Default::default()
            };

            // Two shards selected → both should receive rune UTXOs (with zero amounts)
            let shard0 = MockShardZc::default();
            let shard1 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);

            let mut shard_refs: Vec<_> = loaders.iter().map(|l| l.load_mut().unwrap()).collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &program_script,
                &FeeRate(1.0),
            )
            .unwrap();
            drop(shard_refs);

            for loader in loaders.iter() {
                let shard_ref = loader.load().unwrap();
                assert!(shard_ref.rune_utxo().is_some());
            }
        }

        #[cfg(feature = "runes")]
        #[test]
        fn single_rune_id_all_consumed_pointer_zero() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();
            let txid = bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[4u8; 32]).unwrap());
            let input_outpoint = OutPoint { txid, vout: 0 };
            let non_program_script = ScriptBuf::from_bytes(vec![0x51]);

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: non_program_script,
                    },
                ],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            builder
                .total_rune_inputs
                .insert(arch_program::rune::RuneAmount {
                    id: arch_program::rune::RuneId::new(1, 0),
                    amount: 5,
                })
                .unwrap();

            builder.runestone = Runestone {
                pointer: Some(0),
                edicts: vec![ordinals::Edict {
                    id: ordinals::RuneId { block: 1, tx: 0 },
                    amount: 5,
                    output: 1,
                }],
                ..Default::default()
            };

            let shard0 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0]);
            let mut shard_refs: Vec<_> = loaders.iter().map(|l| l.load_mut().unwrap()).collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &program_script,
                &FeeRate(1.0),
            )
            .unwrap();
            drop(shard_refs);

            let shard0_ref = loaders[0].load().unwrap();
            assert!(shard0_ref.rune_utxo().is_some());
        }

        #[cfg(feature = "runes")]
        #[test]
        fn preserves_existing_rune_utxo_and_inserts_missing_only() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();
            let txid = bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[5u8; 32]).unwrap());
            let input_outpoint = OutPoint { txid, vout: 0 };

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![TxOut {
                    value: Amount::from_sat(546),
                    script_pubkey: program_script.clone(),
                }],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            builder
                .total_rune_inputs
                .insert(arch_program::rune::RuneAmount {
                    id: arch_program::rune::RuneId::new(3, 0),
                    amount: 0,
                })
                .unwrap();
            builder.runestone = Runestone {
                pointer: Some(0),
                edicts: vec![],
                ..Default::default()
            };

            let mut shard0 = MockShardZc::default();
            let existing_rune = create_utxo(546, 50, 0);
            shard0.set_rune_utxo(existing_rune.clone());
            let shard1 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0, shard1]);
            let mut shard_refs: Vec<_> = loaders.iter().map(|l| l.load_mut().unwrap()).collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &program_script,
                &FeeRate(1.0),
            )
            .unwrap();
            drop(shard_refs);

            let shard0_ref = loaders[0].load().unwrap();
            assert!(shard0_ref.rune_utxo().is_some());
            drop(shard0_ref);
            let shard1_ref = loaders[1].load().unwrap();
            assert!(shard1_ref.rune_utxo().is_some());
        }

        #[cfg(feature = "runes")]
        #[test]
        fn duplicate_zero_amount_edicts_merge_and_classify() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();
            let txid = bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[6u8; 32]).unwrap());
            let input_outpoint = OutPoint { txid, vout: 0 };

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![TxOut {
                    value: Amount::from_sat(546),
                    script_pubkey: program_script.clone(),
                }],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            builder
                .total_rune_inputs
                .insert(arch_program::rune::RuneAmount {
                    id: arch_program::rune::RuneId::new(4, 0),
                    amount: 0,
                })
                .unwrap();

            builder.runestone = Runestone {
                pointer: Some(0),
                edicts: vec![
                    ordinals::Edict {
                        id: ordinals::RuneId { block: 4, tx: 0 },
                        amount: 0,
                        output: 0,
                    },
                    ordinals::Edict {
                        id: ordinals::RuneId { block: 4, tx: 0 },
                        amount: 0,
                        output: 0,
                    },
                ],
                ..Default::default()
            };

            let shard0 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0]);
            let mut shard_refs: Vec<_> = loaders.iter().map(|l| l.load_mut().unwrap()).collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &program_script,
                &FeeRate(1.0),
            )
            .unwrap();
            drop(shard_refs);

            let shard0_ref = loaders[0].load().unwrap();
            assert!(shard0_ref.rune_utxo().is_some());
        }

        #[cfg(feature = "runes")]
        #[test]
        fn error_when_more_rune_utxos_than_available_shards() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();
            let txid = bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[7u8; 32]).unwrap());
            let input_outpoint = OutPoint { txid, vout: 0 };

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                    TxOut {
                        value: Amount::from_sat(546),
                        script_pubkey: program_script.clone(),
                    },
                ],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            builder
                .total_rune_inputs
                .insert(arch_program::rune::RuneAmount {
                    id: arch_program::rune::RuneId::new(9, 9),
                    amount: 0,
                })
                .unwrap();
            builder.runestone = Runestone {
                pointer: Some(0),
                edicts: vec![
                    ordinals::Edict {
                        id: ordinals::RuneId { block: 9, tx: 9 },
                        amount: 0,
                        output: 0,
                    },
                    ordinals::Edict {
                        id: ordinals::RuneId { block: 9, tx: 9 },
                        amount: 0,
                        output: 1,
                    },
                ],
                ..Default::default()
            };

            let shard0 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0]);
            let mut shard_refs: Vec<_> = loaders.iter().map(|l| l.load_mut().unwrap()).collect();
            let err = super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &program_script,
                &FeeRate(1.0),
            )
            .unwrap_err();
            drop(shard_refs);

            assert_eq!(err, StateShardError::ExcessRuneUtxos);
        }

        #[cfg(feature = "runes")]
        #[test]
        fn pointer_present_no_edicts_total_inputs_zero() {
            const MAX_USER_UTXOS: usize = 4;
            const MAX_SHARDS_PER_PROGRAM: usize = 4;

            let mut builder: satellite_bitcoin::TransactionBuilder<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
            > = new_tb!(MAX_USER_UTXOS, MAX_SHARDS_PER_PROGRAM);

            let program_script = ScriptBuf::new();

            let txid = bitcoin::Txid::from_raw_hash(Sha256dHash::from_slice(&[3u8; 32]).unwrap());
            let input_outpoint = OutPoint { txid, vout: 0 };

            builder.transaction = Transaction {
                version: Version::TWO,
                lock_time: LockTime::ZERO,
                input: vec![TxIn {
                    previous_output: input_outpoint,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::default(),
                }],
                output: vec![TxOut {
                    value: Amount::from_sat(546),
                    script_pubkey: program_script.clone(),
                }],
            };

            builder
                .inputs_to_sign
                .push(InputToSign {
                    index: 0,
                    signer: arch_program::pubkey::Pubkey::default(),
                })
                .unwrap();

            builder
                .total_rune_inputs
                .insert(arch_program::rune::RuneAmount {
                    id: arch_program::rune::RuneId::new(10, 1),
                    amount: 0,
                })
                .unwrap();
            builder.runestone = Runestone {
                pointer: Some(0),
                edicts: vec![],
                ..Default::default()
            };

            let shard0 = MockShardZc::default();
            let loaders = leak_loaders_from_vec(vec![shard0]);
            let mut shard_refs: Vec<_> = loaders.iter().map(|l| l.load_mut().unwrap()).collect();
            super::super::update_shards_after_transaction::<
                MAX_USER_UTXOS,
                MAX_SHARDS_PER_PROGRAM,
                SingleRuneSet,
                satellite_bitcoin::utxo_info::UtxoInfo<SingleRuneSet>,
                MockShardZc,
            >(
                &mut builder,
                &mut shard_refs,
                &program_script,
                &FeeRate(1.0),
            )
            .unwrap();
            drop(shard_refs);

            let shard0_ref = loaders[0].load().unwrap();
            assert!(shard0_ref.rune_utxo().is_some());
        }
    }
}