battleware-execution 0.0.1

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

mod elo;
mod fixed;
pub mod state_transition;

#[cfg(any(test, feature = "mocks"))]
pub mod mocks;

pub type Adb<E, T> = Any<E, Digest, Value, Sha256, T>;

pub trait State {
    fn get(&self, key: &Key) -> impl Future<Output = Option<Value>>;
    fn insert(&mut self, key: Key, value: Value) -> impl Future<Output = ()>;
    fn delete(&mut self, key: &Key) -> impl Future<Output = ()>;

    fn apply(&mut self, changes: Vec<(Key, Status)>) -> impl Future<Output = ()> {
        async {
            for (key, status) in changes {
                match status {
                    Status::Update(value) => self.insert(key, value).await,
                    Status::Delete => self.delete(&key).await,
                }
            }
        }
    }
}

impl<E: Spawner + Metrics + Clock + Storage, T: Translator> State for Adb<E, T> {
    async fn get(&self, key: &Key) -> Option<Value> {
        let key = Sha256::hash(&key.encode());
        self.get(&key).await.unwrap()
    }

    async fn insert(&mut self, key: Key, value: Value) {
        let key = Sha256::hash(&key.encode());
        self.update(key, value).await.unwrap();
    }

    async fn delete(&mut self, key: &Key) {
        let key = Sha256::hash(&key.encode());
        self.delete(key).await.unwrap();
    }
}

#[derive(Default)]
pub struct Memory {
    state: HashMap<Key, Value>,
}

impl State for Memory {
    async fn get(&self, key: &Key) -> Option<Value> {
        self.state.get(key).cloned()
    }

    async fn insert(&mut self, key: Key, value: Value) {
        self.state.insert(key, value);
    }

    async fn delete(&mut self, key: &Key) {
        self.state.remove(key);
    }
}

#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Status {
    Update(Value),
    Delete,
}

impl Write for Status {
    fn write(&self, writer: &mut impl BufMut) {
        match self {
            Status::Update(value) => {
                0u8.write(writer);
                value.write(writer);
            }
            Status::Delete => 1u8.write(writer),
        }
    }
}

impl Read for Status {
    type Cfg = ();

    fn read_cfg(reader: &mut impl Buf, _: &Self::Cfg) -> Result<Self, Error> {
        let kind = u8::read(reader)?;
        match kind {
            0 => Ok(Status::Update(Value::read(reader)?)),
            1 => Ok(Status::Delete),
            _ => Err(Error::InvalidEnum(kind)),
        }
    }
}

impl EncodeSize for Status {
    fn encode_size(&self) -> usize {
        1 + match self {
            Status::Update(value) => value.encode_size(),
            Status::Delete => 0,
        }
    }
}

pub async fn nonce<S: State>(state: &S, public: &PublicKey) -> u64 {
    let account =
        if let Some(Value::Account(account)) = state.get(&Key::Account(public.clone())).await {
            account
        } else {
            Account::default()
        };
    account.nonce
}

pub struct Noncer<'a, S: State> {
    state: &'a S,
    pending: BTreeMap<Key, Status>,
}

impl<'a, S: State> Noncer<'a, S> {
    pub fn new(state: &'a S) -> Self {
        Self {
            state,
            pending: BTreeMap::new(),
        }
    }

    pub async fn prepare(&mut self, transaction: &Transaction) -> bool {
        let mut account = if let Some(Value::Account(account)) =
            self.get(&Key::Account(transaction.public.clone())).await
        {
            account
        } else {
            Account::default()
        };

        // Ensure nonce is correct
        if account.nonce != transaction.nonce {
            return false;
        }

        // Increment nonce
        account.nonce += 1;
        self.insert(
            Key::Account(transaction.public.clone()),
            Value::Account(account),
        )
        .await;

        true
    }
}

impl<'a, S: State> State for Noncer<'a, S> {
    async fn get(&self, key: &Key) -> Option<Value> {
        match self.pending.get(key) {
            Some(Status::Update(value)) => Some(value.clone()),
            Some(Status::Delete) => None,
            None => self.state.get(key).await,
        }
    }

    async fn insert(&mut self, key: Key, value: Value) {
        self.pending.insert(key, Status::Update(value));
    }

    async fn delete(&mut self, key: &Key) {
        self.pending.insert(key.clone(), Status::Delete);
    }
}

#[derive(Hash, Eq, PartialEq)]
#[allow(clippy::large_enum_variant)]
enum Task {
    Seed(Seed),
    Decrypt(Seed, Ciphertext<MinSig>),
}

enum TaskResult {
    Seed(bool),
    Decrypt([u8; 32]),
}

pub struct Layer<'a, S: State> {
    state: &'a S,
    pending: BTreeMap<Key, Status>,

    master: <MinSig as Variant>::Public,
    namespace: Vec<u8>,

    seed: Seed,

    precomputations: HashMap<Task, TaskResult>,
}

impl<'a, S: State> Layer<'a, S> {
    pub fn new(
        state: &'a S,
        master: <MinSig as Variant>::Public,
        namespace: &[u8],
        seed: Seed,
    ) -> Self {
        let mut verified_seeds = HashSet::new();
        verified_seeds.insert(seed.clone());
        Self {
            state,
            pending: BTreeMap::new(),

            master,
            namespace: namespace.to_vec(),

            seed,

            precomputations: HashMap::new(),
        }
    }

    fn insert(&mut self, key: Key, value: Value) {
        self.pending.insert(key, Status::Update(value));
    }

    fn delete(&mut self, key: Key) {
        self.pending.insert(key, Status::Delete);
    }

    pub fn view(&self) -> View {
        self.seed.view
    }

    async fn prepare(&mut self, transaction: &Transaction) -> bool {
        // Get account
        let mut account = if let Some(Value::Account(account)) =
            self.get(&Key::Account(transaction.public.clone())).await
        {
            account
        } else {
            Account::default()
        };

        // Ensure nonce is correct
        if account.nonce != transaction.nonce {
            return false;
        }

        // Increment nonce
        account.nonce += 1;
        self.insert(
            Key::Account(transaction.public.clone()),
            Value::Account(account),
        );

        true
    }

    async fn extract(&mut self, transaction: &Transaction) -> Vec<Task> {
        match &transaction.instruction {
            Instruction::Generate => vec![],
            Instruction::Match => vec![],
            Instruction::Move(_) => vec![],
            Instruction::Settle(signature) => {
                // Get account
                let Some(Value::Account(account)) =
                    self.get(&Key::Account(transaction.public.clone())).await
                else {
                    return vec![];
                };

                // If not in a battle, not valid
                let Some(battle) = account.battle else {
                    return vec![];
                };

                // Get battle
                let Some(Value::Battle {
                    expiry,
                    player_a_pending,
                    player_b_pending,
                    ..
                }) = self.get(&Key::Battle(battle)).await
                else {
                    return vec![];
                };

                // If turn has not expired, not valid
                if expiry > self.seed.view {
                    return vec![];
                }

                // Extract seed and decryptions
                let seed = Seed::new(expiry, *signature);
                let mut ops = vec![Task::Seed(seed.clone())];
                if let Some(pending) = player_a_pending {
                    ops.push(Task::Decrypt(seed.clone(), pending));
                }
                if let Some(pending) = player_b_pending {
                    ops.push(Task::Decrypt(seed, pending));
                }

                ops
            }
        }
    }

    async fn apply(&mut self, transaction: &Transaction) -> Vec<Event> {
        // Get account
        let Some(Value::Account(mut account)) =
            self.get(&Key::Account(transaction.public.clone())).await
        else {
            panic!("Account should exist");
        };

        // Execute instruction
        let mut events = vec![];
        match &transaction.instruction {
            Instruction::Generate => {
                // If in a battle, not valid
                if account.battle.is_some() {
                    return events;
                }

                // Generate a new creature
                let creature = Creature::new(
                    transaction.public.clone(),
                    transaction.nonce,
                    self.seed.signature,
                );
                account.creature = Some(creature.clone());

                // Store update in account
                self.insert(
                    Key::Account(transaction.public.clone()),
                    Value::Account(account),
                );
                events.push(Event::Generated {
                    account: transaction.public.clone(),
                    creature,
                });
            }
            Instruction::Match => {
                // If not locked on a creature, not valid
                if account.creature.is_none() {
                    return events;
                }

                // If already in a battle, not valid
                if account.battle.is_some() {
                    return events;
                }

                // Get lobby
                let Some(Value::Lobby {
                    expiry,
                    mut players,
                }) = self.get(&Key::Lobby).await
                else {
                    // Create lobby
                    let mut players = BTreeSet::new();
                    players.insert(transaction.public.clone());
                    let lobby = Value::Lobby {
                        expiry: self
                            .seed
                            .view
                            .checked_add(LOBBY_EXPIRY)
                            .expect("view overflow"),
                        players,
                    };
                    self.insert(Key::Lobby, lobby);
                    return events;
                };

                // Add to lobby.
                //
                // If already in lobby, that's fine (may trigger matching).
                players.insert(transaction.public.clone());

                // If lobby has expired or is full, create matches
                if expiry < self.seed.view || players.len() >= MAX_LOBBY_SIZE {
                    // Get players
                    let mut players = players.iter().collect::<Vec<_>>();

                    // Randomly select trainers
                    let seed = Sha256::hash(self.seed.encode().as_ref());
                    let mut rng = StdRng::from_seed(seed.as_ref().try_into().unwrap());
                    players.shuffle(&mut rng);

                    // Create match
                    let iter = players.chunks_exact(2).map(|chunk| (chunk[0], chunk[1]));
                    let mut hasher = Sha256::new();
                    for (player_a, player_b) in iter {
                        // Compute battle key
                        hasher.update(self.seed.encode().as_ref());
                        hasher.update(player_a.as_ref());
                        hasher.update(player_b.as_ref());
                        let key = hasher.finalize();

                        // Add battle to player A
                        let Some(Value::Account(mut account_a)) =
                            self.get(&Key::Account(player_a.clone())).await
                        else {
                            panic!("Player A should have an account");
                        };
                        let player_a_creature = account_a.creature.as_ref().unwrap().clone();
                        let player_a_stats = account_a.stats.clone();
                        let player_a_health = player_a_creature.health();
                        account_a.battle = Some(key);
                        self.insert(Key::Account(player_a.clone()), Value::Account(account_a));

                        // Add battle to player B
                        let Some(Value::Account(mut account_b)) =
                            self.get(&Key::Account(player_b.clone())).await
                        else {
                            panic!("Player B should have an account");
                        };
                        let player_b_creature = account_b.creature.as_ref().unwrap().clone();
                        let player_b_stats = account_b.stats.clone();
                        let player_b_health = player_b_creature.health();
                        account_b.battle = Some(key);
                        self.insert(Key::Account(player_b.clone()), Value::Account(account_b));

                        // Add battle to state
                        let expiry = self
                            .seed
                            .view
                            .checked_add(MOVE_EXPIRY)
                            .expect("view overflow");
                        let value = Value::Battle {
                            expiry,
                            round: 0,
                            player_a: (*player_a).clone(),
                            player_a_max_health: player_a_health,
                            player_a_health,
                            player_a_pending: None,
                            player_a_move_counts: [0; TOTAL_MOVES],
                            player_b: (*player_b).clone(),
                            player_b_max_health: player_b_health,
                            player_b_health,
                            player_b_pending: None,
                            player_b_move_counts: [0; TOTAL_MOVES],
                        };
                        self.insert(Key::Battle(key), value);
                        events.push(Event::Matched {
                            battle: key,
                            expiry,
                            player_a: (*player_a).clone(),
                            player_a_creature,
                            player_a_stats,
                            player_b: (*player_b).clone(),
                            player_b_creature,
                            player_b_stats,
                        });
                    }

                    // If there are any remaining trainers, add them to the lobby for the next matching
                    let remainder = players.chunks_exact(2).remainder();
                    let mut new_players = BTreeSet::new();
                    if !remainder.is_empty() {
                        for player in remainder {
                            new_players.insert((*player).clone());
                        }
                    }

                    // Start lobby as soon as possible
                    let lobby = Value::Lobby {
                        expiry: self
                            .seed
                            .view
                            .checked_add(LOBBY_EXPIRY)
                            .expect("view overflow"),
                        players: new_players,
                    };
                    self.insert(Key::Lobby, lobby);
                } else {
                    // Update existing lobby with new trainer
                    let lobby = Value::Lobby { expiry, players };
                    self.insert(Key::Lobby, lobby);
                }
            }
            Instruction::Move(encrypted_move) => {
                // If not in a battle, not valid
                let Some(battle) = account.battle else {
                    return events;
                };

                // If the player has not yet moved, store the move
                let Some(Value::Battle {
                    expiry,
                    round,
                    player_a,
                    player_a_max_health,
                    player_a_health,
                    mut player_a_pending,
                    player_a_move_counts,
                    player_b,
                    player_b_max_health,
                    player_b_health,
                    mut player_b_pending,
                    player_b_move_counts,
                }) = self.get(&Key::Battle(battle)).await
                else {
                    panic!("Battle should exist");
                };

                // If the turn has expired, not valid
                if expiry < self.seed.view {
                    return events;
                }

                // Store the move (ok to update encrypted value)
                if player_a == transaction.public && player_a_pending.is_none() {
                    player_a_pending = Some(encrypted_move.clone());
                } else if player_b == transaction.public && player_b_pending.is_none() {
                    player_b_pending = Some(encrypted_move.clone());
                } else {
                    return events;
                }

                // Emit event
                events.push(Event::Locked {
                    battle,
                    round,
                    locker: transaction.public.clone(),
                    observer: if player_a == transaction.public {
                        player_b.clone()
                    } else {
                        player_a.clone()
                    },
                    ciphertext: encrypted_move.clone(),
                });

                // Store update in battle
                let value = Value::Battle {
                    expiry,
                    round,
                    player_a,
                    player_a_max_health,
                    player_a_health,
                    player_a_pending,
                    player_a_move_counts,
                    player_b,
                    player_b_max_health,
                    player_b_health,
                    player_b_pending,
                    player_b_move_counts,
                };
                self.insert(Key::Battle(battle), value);
            }
            Instruction::Settle(signature) => {
                // If not in a battle, return false
                let Some(battle) = account.battle else {
                    return events; // Not in battle, no-op
                };

                // Get battle
                let Some(Value::Battle {
                    expiry,
                    mut round,
                    player_a,
                    player_a_max_health,
                    mut player_a_health,
                    player_a_pending,
                    mut player_a_move_counts,
                    player_b,
                    player_b_max_health,
                    mut player_b_health,
                    player_b_pending,
                    mut player_b_move_counts,
                }) = self.get(&Key::Battle(battle)).await
                else {
                    panic!("Battle should exist");
                };

                // If turn has not expired, not valid
                if expiry > self.seed.view {
                    return events;
                }

                // If the signature is not valid, return false
                let seed = Seed::new(expiry, *signature);
                if seed != self.seed {
                    match self.precomputations.get(&Task::Seed(seed.clone())) {
                        Some(TaskResult::Seed(result)) => {
                            if !result {
                                return events;
                            }
                        }
                        None => {
                            if !seed.verify(&self.namespace, &self.master) {
                                return events; // Invalid signature, no-op
                            }
                        }
                        _ => unreachable!(),
                    }
                }

                // Decrypt player A move
                let mut player_a_move = if let Some(player_a_pending) = player_a_pending {
                    // Use the signature that was verified for the battle expiry
                    match self
                        .precomputations
                        .get(&Task::Decrypt(seed.clone(), player_a_pending.clone()))
                    {
                        Some(TaskResult::Decrypt(result)) => result[0],
                        None => {
                            let raw: [u8; 32] = decrypt::<MinSig>(signature, &player_a_pending)
                                .map(|block| block.as_ref().try_into().unwrap())
                                .unwrap_or_else(|| [0; 32]);
                            raw[0]
                        }
                        _ => unreachable!(),
                    }
                } else {
                    // If no move, return 0
                    0
                };
                if player_a_move >= TOTAL_MOVES as u8 {
                    player_a_move = 0;
                }

                // Get player A creature
                let Some(Value::Account(account)) = self.get(&Key::Account(player_a.clone())).await
                else {
                    panic!("Player A should have an account");
                };
                let player_a_creature = account.creature.as_ref().unwrap();

                // Check move usage limit for player A
                let player_a_limits = player_a_creature.get_move_usage_limits();
                if player_a_move_counts[player_a_move as usize]
                    >= player_a_limits[player_a_move as usize]
                {
                    player_a_move = 0;
                }

                // Apply move
                let (player_a_defense, player_a_power) =
                    player_a_creature.action(player_a_move, self.seed.signature);

                // Decrypt player B move
                let mut player_b_move = if let Some(player_b_pending) = player_b_pending {
                    // If can't decrypt, return 0
                    match self
                        .precomputations
                        .get(&Task::Decrypt(seed, player_b_pending.clone()))
                    {
                        Some(TaskResult::Decrypt(result)) => result[0],
                        None => {
                            let raw: [u8; 32] = decrypt::<MinSig>(signature, &player_b_pending)
                                .map(|block| block.as_ref().try_into().unwrap())
                                .unwrap_or_else(|| [0; 32]);
                            raw[0]
                        }
                        _ => unreachable!(),
                    }
                } else {
                    // If no move, return 0
                    0
                };
                if player_b_move >= TOTAL_MOVES as u8 {
                    player_b_move = 0;
                }

                // Get player B creature
                let Some(Value::Account(account)) = self.get(&Key::Account(player_b.clone())).await
                else {
                    panic!("Player B should have an account");
                };
                let player_b_creature = account.creature.as_ref().unwrap();

                // Check move usage limit for player B
                let player_b_limits = player_b_creature.get_move_usage_limits();
                if player_b_move_counts[player_b_move as usize]
                    >= player_b_limits[player_b_move as usize]
                {
                    player_b_move = 0;
                }

                // Apply move
                let (player_b_defense, player_b_power) =
                    player_b_creature.action(player_b_move, self.seed.signature);

                // Apply impact
                // Track effective health (can go negative) for overkill calculation
                let mut player_a_effective_health = player_a_health as i16;
                let mut player_b_effective_health = player_b_health as i16;

                if player_a_defense && !player_b_defense {
                    // Player A restores health, then takes damage
                    player_a_health = player_a_health
                        .saturating_add(player_a_power)
                        .min(player_a_max_health);
                    player_a_effective_health = (player_a_health as i16) - (player_b_power as i16);
                    player_a_health = player_a_health.saturating_sub(player_b_power);
                } else if !player_a_defense && player_b_defense {
                    // Player B restores health, then takes damage
                    player_b_health = player_b_health
                        .saturating_add(player_b_power)
                        .min(player_b_max_health);
                    player_b_effective_health = (player_b_health as i16) - (player_a_power as i16);
                    player_b_health = player_b_health.saturating_sub(player_a_power);
                } else if player_a_defense && player_b_defense {
                    // Player A and B restore health
                    player_a_health = player_a_health
                        .saturating_add(player_a_power)
                        .min(player_a_max_health);
                    player_b_health = player_b_health
                        .saturating_add(player_b_power)
                        .min(player_b_max_health);
                    player_a_effective_health = player_a_health as i16;
                    player_b_effective_health = player_b_health as i16;
                } else {
                    // Player A and B take damage
                    player_a_effective_health = (player_a_health as i16) - (player_b_power as i16);
                    player_b_effective_health = (player_b_health as i16) - (player_a_power as i16);
                    player_a_health = player_a_health.saturating_sub(player_b_power);
                    player_b_health = player_b_health.saturating_sub(player_a_power);
                }
                // Increment move counts
                //
                // We should timeout before we ever overflow but might as well be defensive.
                player_a_move_counts[player_a_move as usize] =
                    player_a_move_counts[player_a_move as usize].saturating_add(1);
                player_b_move_counts[player_b_move as usize] =
                    player_b_move_counts[player_b_move as usize].saturating_add(1);

                // Increment round counter
                round += 1;

                // Compute next expiry
                let next_expiry = self
                    .seed
                    .view
                    .checked_add(MOVE_EXPIRY)
                    .expect("view overflow");
                events.push(Event::Moved {
                    battle,
                    round,
                    expiry: next_expiry,
                    player_a: player_a.clone(),
                    player_a_health,
                    player_a_move,
                    player_a_move_counts,
                    player_a_power,
                    player_b: player_b.clone(),
                    player_b_health,
                    player_b_move,
                    player_b_move_counts,
                    player_b_power,
                });

                // Determine whether the battle is over
                if player_a_health == 0 && player_b_health > 0 {
                    // Player B wins
                    self.delete(Key::Battle(battle));

                    // Get original stats
                    let Some(Value::Account(mut account_a)) =
                        self.get(&Key::Account(player_a.clone())).await
                    else {
                        panic!("Player A should have an account");
                    };
                    let old_account_a_stats = account_a.stats.clone();
                    let Some(Value::Account(mut account_b)) =
                        self.get(&Key::Account(player_b.clone())).await
                    else {
                        panic!("Player B should have an account");
                    };
                    let old_account_b_stats = account_b.stats.clone();

                    // Update losses
                    account_a.stats.losses = account_a.stats.losses.saturating_add(1);
                    account_a.battle = None;

                    // Update wins
                    account_b.stats.wins = account_b.stats.wins.saturating_add(1);
                    account_b.battle = None;

                    // Update ELO scores (player A has 0 or negative health, player B has some)
                    let max_health_a = account_a.creature.as_ref().unwrap().health();
                    let max_health_b = account_b.creature.as_ref().unwrap().health();
                    let (new_elo_a, new_elo_b) = elo::update(
                        account_a.stats.elo,
                        player_a_effective_health,
                        max_health_a,
                        account_b.stats.elo,
                        player_b_effective_health,
                        max_health_b,
                    );
                    account_a.stats.elo = new_elo_a;
                    let new_account_a_stats = account_a.stats.clone();
                    account_b.stats.elo = new_elo_b;
                    let new_account_b_stats = account_b.stats.clone();
                    self.insert(Key::Account(player_a.clone()), Value::Account(account_a));
                    self.insert(Key::Account(player_b.clone()), Value::Account(account_b));

                    // Update leaderboard
                    let mut leaderboard = match self.get(&Key::Leaderboard).await {
                        Some(Value::Leaderboard(lb)) => lb,
                        _ => Leaderboard::default(),
                    };
                    leaderboard.update(player_a.clone(), new_account_a_stats.clone());
                    leaderboard.update(player_b.clone(), new_account_b_stats.clone());
                    self.insert(Key::Leaderboard, Value::Leaderboard(leaderboard.clone()));

                    // Add event
                    events.push(Event::Settled {
                        battle,
                        round,
                        player_a,
                        player_a_old: old_account_a_stats,
                        player_a_new: new_account_a_stats,
                        player_b,
                        player_b_old: old_account_b_stats,
                        player_b_new: new_account_b_stats,
                        outcome: Outcome::PlayerB,
                        leaderboard,
                    });
                } else if player_b_health == 0 && player_a_health > 0 {
                    // Player A wins
                    self.delete(Key::Battle(battle));

                    // Get original stats
                    let Some(Value::Account(mut account_a)) =
                        self.get(&Key::Account(player_a.clone())).await
                    else {
                        panic!("Player A should have an account");
                    };
                    let old_account_a_stats = account_a.stats.clone();
                    let Some(Value::Account(mut account_b)) =
                        self.get(&Key::Account(player_b.clone())).await
                    else {
                        panic!("Player B should have an account");
                    };
                    let old_account_b_stats = account_b.stats.clone();

                    // Update losses
                    account_b.stats.losses = account_b.stats.losses.saturating_add(1);
                    account_b.battle = None;

                    // Update wins
                    account_a.stats.wins = account_a.stats.wins.saturating_add(1);
                    account_a.battle = None;

                    // Update ELO scores (player B has 0 or negative health, player A has some)
                    let max_health_a = account_a.creature.as_ref().unwrap().health();
                    let max_health_b = account_b.creature.as_ref().unwrap().health();
                    let (new_elo_a, new_elo_b) = elo::update(
                        account_a.stats.elo,
                        player_a_effective_health,
                        max_health_a,
                        account_b.stats.elo,
                        player_b_effective_health,
                        max_health_b,
                    );
                    account_a.stats.elo = new_elo_a;
                    let new_account_a_stats = account_a.stats.clone();
                    account_b.stats.elo = new_elo_b;
                    let new_account_b_stats = account_b.stats.clone();
                    self.insert(Key::Account(player_a.clone()), Value::Account(account_a));
                    self.insert(Key::Account(player_b.clone()), Value::Account(account_b));

                    // Update leaderboard
                    let mut leaderboard = match self.get(&Key::Leaderboard).await {
                        Some(Value::Leaderboard(lb)) => lb,
                        _ => Leaderboard::default(),
                    };
                    leaderboard.update(player_a.clone(), new_account_a_stats.clone());
                    leaderboard.update(player_b.clone(), new_account_b_stats.clone());
                    self.insert(Key::Leaderboard, Value::Leaderboard(leaderboard.clone()));

                    // Add event
                    events.push(Event::Settled {
                        battle,
                        round,
                        player_a,
                        player_a_old: old_account_a_stats,
                        player_a_new: new_account_a_stats,
                        player_b,
                        player_b_old: old_account_b_stats,
                        player_b_new: new_account_b_stats,
                        outcome: Outcome::PlayerA,
                        leaderboard,
                    });
                } else if round >= MAX_BATTLE_ROUNDS
                    || (player_a_health == 0 && player_b_health == 0)
                {
                    // Draw
                    self.delete(Key::Battle(battle));

                    // Get original stats
                    let Some(Value::Account(mut account_a)) =
                        self.get(&Key::Account(player_a.clone())).await
                    else {
                        panic!("Player A should have an account");
                    };
                    let old_account_a_stats = account_a.stats.clone();
                    let Some(Value::Account(mut account_b)) =
                        self.get(&Key::Account(player_b.clone())).await
                    else {
                        panic!("Player B should have an account");
                    };
                    let old_account_b_stats = account_b.stats.clone();

                    // Update draws
                    account_a.stats.draws = account_a.stats.draws.saturating_add(1);
                    account_a.battle = None;

                    // Update draws
                    account_b.stats.draws = account_b.stats.draws.saturating_add(1);
                    account_b.battle = None;

                    // Update ELO scores based on effective health (including overkill)
                    let max_health_a = account_a.creature.as_ref().unwrap().health();
                    let max_health_b = account_b.creature.as_ref().unwrap().health();
                    let (new_elo_a, new_elo_b) = elo::update(
                        account_a.stats.elo,
                        player_a_effective_health,
                        max_health_a,
                        account_b.stats.elo,
                        player_b_effective_health,
                        max_health_b,
                    );
                    account_a.stats.elo = new_elo_a;
                    let new_account_a_stats = account_a.stats.clone();
                    account_b.stats.elo = new_elo_b;
                    let new_account_b_stats = account_b.stats.clone();
                    self.insert(Key::Account(player_a.clone()), Value::Account(account_a));
                    self.insert(Key::Account(player_b.clone()), Value::Account(account_b));

                    // Update leaderboard
                    let mut leaderboard = match self.get(&Key::Leaderboard).await {
                        Some(Value::Leaderboard(lb)) => lb,
                        _ => Leaderboard::default(),
                    };
                    leaderboard.update(player_a.clone(), new_account_a_stats.clone());
                    leaderboard.update(player_b.clone(), new_account_b_stats.clone());
                    self.insert(Key::Leaderboard, Value::Leaderboard(leaderboard.clone()));

                    // Add event
                    events.push(Event::Settled {
                        battle,
                        round,
                        player_a,
                        player_a_old: old_account_a_stats,
                        player_a_new: new_account_a_stats,
                        player_b,
                        player_b_old: old_account_b_stats,
                        player_b_new: new_account_b_stats,
                        outcome: Outcome::Draw,
                        leaderboard,
                    });
                } else {
                    // Battle continues
                    self.insert(
                        Key::Battle(battle),
                        Value::Battle {
                            expiry: next_expiry,
                            round,
                            player_a,
                            player_a_max_health,
                            player_a_health,
                            player_a_pending: None,
                            player_a_move_counts,
                            player_b,
                            player_b_max_health,
                            player_b_health,
                            player_b_pending: None,
                            player_b_move_counts,
                        },
                    );
                }
            }
        }

        events
    }

    pub async fn execute(
        &mut self,
        #[cfg(feature = "parallel")] pool: ThreadPool,
        transactions: Vec<Transaction>,
    ) -> (Vec<Output>, BTreeMap<PublicKey, u64>) {
        // Iterate over all transactions with valid nonces (applying in the process) and extract expensive cryptographic operations
        let mut processed_nonces = BTreeMap::new();
        let mut seed_ops = HashSet::new();
        let mut decrypt_ops = HashSet::new();
        let mut valid_transactions = Vec::new();
        for tx in transactions {
            // Must be applied in order to ensure blocks with multiple transactions from same
            // account are handled properly.
            if !self.prepare(&tx).await {
                continue;
            }

            // Track the next nonce for this public key
            processed_nonces.insert(tx.public.clone(), tx.nonce.saturating_add(1));

            // Extract operations
            let ops = self.extract(&tx).await;
            for op in ops {
                match op {
                    Task::Seed(_) => seed_ops.insert(op),
                    Task::Decrypt(_, _) => decrypt_ops.insert(op),
                };
            }
            valid_transactions.push(tx);
        }

        // Execute operations
        macro_rules! process_ops {
            ($iter:ident) => {{
                // Verify all seeds
                let mut results: HashMap<Task, TaskResult> = seed_ops
                    .$iter()
                    .map(|op| match op {
                        Task::Seed(ref seed) => {
                            if self.seed == *seed {
                                return (op, TaskResult::Seed(true));
                            }
                            let result = seed.verify(&self.namespace, &self.master);
                            (op, TaskResult::Seed(result))
                        }
                        _ => unreachable!(),
                    })
                    .collect();

                // Only decrypt for valid signatures
                let decrypt_results: HashMap<Task, TaskResult> = decrypt_ops
                    .$iter()
                    .flat_map(|op| match op {
                        Task::Decrypt(ref seed, ref ciphertext) => {
                            // If seed is invalid, skip decryption (decryption won't be needed)
                            if !matches!(
                                results.get(&Task::Seed(seed.clone())).unwrap(), // we should never be missing a seed
                                TaskResult::Seed(true)
                            ) {
                                return None;
                            }

                            // If seed is valid, decrypt
                            let result = decrypt::<MinSig>(&seed.signature, ciphertext)
                                .map(|block| block.as_ref().try_into().unwrap())
                                .unwrap_or_else(|| [0; 32]);
                            Some((op, TaskResult::Decrypt(result)))
                        }
                        _ => unreachable!(),
                    })
                    .collect();

                // Merge results
                results.extend(decrypt_results);
                results
            }};
        }
        #[cfg(feature = "parallel")]
        let precomputations = pool.install(|| process_ops!(into_par_iter));
        #[cfg(not(feature = "parallel"))]
        let precomputations = process_ops!(into_iter);

        // Store precomputations
        self.precomputations = precomputations;

        // Apply transactions (using cached operation results)
        let mut events = Vec::new();
        for tx in valid_transactions {
            events.extend(self.apply(&tx).await.into_iter().map(Output::Event));
            events.push(Output::Transaction(tx));
        }

        (events, processed_nonces)
    }

    pub fn commit(self) -> Vec<(Key, Status)> {
        self.pending.into_iter().collect()
    }
}

impl<'a, S: State> State for Layer<'a, S> {
    async fn get(&self, key: &Key) -> Option<Value> {
        match self.pending.get(key) {
            Some(Status::Update(value)) => Some(value.clone()),
            Some(Status::Delete) => None,
            None => self.state.get(key).await,
        }
    }

    async fn insert(&mut self, key: Key, value: Value) {
        self.pending.insert(key, Status::Update(value));
    }

    async fn delete(&mut self, key: &Key) {
        self.pending.insert(key.clone(), Status::Delete);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use commonware_cryptography::bls12381::tle::{encrypt, Block, Ciphertext};
    use commonware_cryptography::{
        bls12381::primitives::{ops, variant::MinSig},
        ed25519, PrivateKeyExt, Signer,
    };
    use commonware_runtime::deterministic::Runner;
    use commonware_runtime::Runner as _;
    use rand::{rngs::StdRng, SeedableRng};
    use std::collections::HashMap;

    const TEST_NAMESPACE: &[u8] = b"test-namespace";

    struct MockState {
        data: HashMap<Key, Value>,
    }

    impl MockState {
        fn new() -> Self {
            Self {
                data: HashMap::new(),
            }
        }
    }

    impl State for MockState {
        async fn get(&self, key: &Key) -> Option<Value> {
            self.data.get(key).cloned()
        }

        async fn insert(&mut self, key: Key, value: Value) {
            self.data.insert(key, value);
        }

        async fn delete(&mut self, key: &Key) {
            self.data.remove(key);
        }
    }

    // Master keypair for all timelock operations in tests
    fn create_network_keypair() -> (
        commonware_cryptography::bls12381::primitives::group::Private,
        <MinSig as commonware_cryptography::bls12381::primitives::variant::Variant>::Public,
    ) {
        let mut rng = StdRng::seed_from_u64(0);
        ops::keypair::<_, MinSig>(&mut rng)
    }

    fn create_seed(
        network_secret: &commonware_cryptography::bls12381::primitives::group::Private,
        view: u64,
    ) -> Seed {
        use commonware_consensus::threshold_simplex::types::{seed_namespace, view_message};
        let seed_namespace = seed_namespace(TEST_NAMESPACE);
        let message = view_message(view);
        Seed::new(
            view,
            ops::sign_message::<MinSig>(network_secret, Some(&seed_namespace), &message),
        )
    }

    fn create_test_move_ciphertext(
        master_public: <MinSig as commonware_cryptography::bls12381::primitives::variant::Variant>::Public,
        next_expiry: u64,
        move_data: u8,
    ) -> Ciphertext<MinSig> {
        use commonware_consensus::threshold_simplex::types::{seed_namespace, view_message};

        // Target needs to match what the seed signature signs over
        let seed_namespace = seed_namespace(TEST_NAMESPACE);
        let view_msg = view_message(next_expiry);

        // Create a 32-byte move message with the move data
        let mut message = [0u8; 32];
        message[0] = move_data; // First byte is the actual move

        let mut rng = StdRng::seed_from_u64(42); // Different seed for encryption randomness
        encrypt::<_, MinSig>(
            &mut rng,
            master_public,
            (Some(&seed_namespace), &view_msg),
            &Block::new(message),
        )
    }

    #[allow(dead_code)]
    fn decrypt_test_move(
        network_secret: &commonware_cryptography::bls12381::primitives::group::Private,
        next_expiry: u64,
        ciphertext: &Ciphertext<MinSig>,
    ) -> Option<u8> {
        use commonware_cryptography::bls12381::tle::decrypt;

        let seed = create_seed(network_secret, next_expiry);
        decrypt::<MinSig>(&seed.signature, ciphertext).map(|block| block.as_ref()[0])
    }

    fn create_test_actor(seed: u64) -> (ed25519::PrivateKey, ed25519::PublicKey) {
        let private = ed25519::PrivateKey::from_seed(seed);
        let public = private.public_key();
        (private, public)
    }

    #[test]
    fn test_invalid_nonce_dropped() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer, _) = create_test_actor(1);

            // Try to prepare with wrong nonce (should fail)
            let tx = Transaction::sign(&signer, 1, Instruction::Generate);
            assert!(!layer.prepare(&tx).await);

            // Prepare with correct nonce
            let tx = Transaction::sign(&signer, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);

            // The nonce should now be 1 in the pending state
            // Try to use old nonce again in the same layer (should fail)
            let tx = Transaction::sign(&signer, 0, Instruction::Generate);
            assert!(!layer.prepare(&tx).await);

            // Should succeed with new nonce
            let tx = Transaction::sign(&signer, 1, Instruction::Generate);
            assert!(layer.prepare(&tx).await);

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_must_have_creature_before_battle() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer, _) = create_test_actor(1);

            // Prepare account
            let tx = Transaction::sign(&signer, 0, Instruction::Match);
            assert!(layer.prepare(&tx).await);

            // Try to match without creature
            let events = layer.apply(&tx).await;
            assert!(events.is_empty()); // Should produce no events

            // Generate creature first
            let tx = Transaction::sign(&signer, 1, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);
            assert!(matches!(events[0], Event::Generated { .. }));

            // Now matching should work (adds to lobby)
            // Continue with the same layer - nonce is already incremented from prepare
            let tx = Transaction::sign(&signer, 2, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert!(events.is_empty()); // Just adds to lobby, no match yet

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_cannot_enter_multiple_concurrent_battles() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Prepare accounts and generate creatures
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Match both players - first player creates lobby
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view to expire the lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);
            assert!(matches!(events[0], Event::Matched { .. }));

            // Try to match again while in battle (should fail)
            let tx = Transaction::sign(&signer_a, 2, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert!(events.is_empty()); // Should not be able to match again

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_can_only_swap_creatures_when_not_in_battle() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Prepare and generate creature for actor A
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Can generate new creature when not in battle
            let tx = Transaction::sign(&signer_a, 1, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);
            assert!(matches!(events[0], Event::Generated { .. }));

            // Prepare actor B and match them
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_a, 2, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view to expire the lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);
            assert!(matches!(events[0], Event::Matched { .. }));

            // Try to generate new creature while in battle (should fail)
            let tx = Transaction::sign(&signer_a, 3, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert!(events.is_empty());

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_cannot_send_multiple_moves_in_single_round() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view to expire the lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);

            // Send first move - use the battle expiry as the timelock target
            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");
            let move1 = create_test_move_ciphertext(master_public, battle_expiry, 1);
            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(move1.clone()));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Try to send second move in same round (should fail)
            let move2 = create_test_move_ciphertext(master_public, battle_expiry, 2);
            let tx = Transaction::sign(&signer_a, 3, Instruction::Move(move2));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert!(events.is_empty());

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_one_player_can_win_if_other_doesnt_play() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view to expire the lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);

            // Get the battle expiry
            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");

            // Only player A sends a move (offensive move)
            let move_a = create_test_move_ciphertext(master_public, battle_expiry, 2);
            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(move_a));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view past expiry
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, battle_expiry + 1);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let signature = create_seed(&network_secret, battle_expiry);
            let tx = Transaction::sign(&signer_a, 3, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Should have a move event (player B defaults to no move)
            assert!(events.iter().any(|e| matches!(e, Event::Moved { .. })));

            // Continue playing until someone wins
            // Player B still doesn't play, so eventually they should lose

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_scores_update_correctly_on_game_over() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, actor_a) = create_test_actor(1);
            let (signer_b, actor_b) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Get initial account states
            let account_a_initial = layer.get(&Key::Account(actor_a.clone())).await.unwrap();
            let account_b_initial = layer.get(&Key::Account(actor_b.clone())).await.unwrap();

            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view to expire the lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);

            let _battle_digest = if let Event::Matched { battle, .. } = &events[0] {
                *battle
            } else {
                panic!("Expected matched event");
            };

            // Play until someone loses all health
            let mut round = 0;
            loop {
                // Get current battle expiry
                let battle_expiry = layer
                    .view()
                    .checked_add(MOVE_EXPIRY)
                    .expect("view overflow");

                // Both players make offensive moves
                let move_a = create_test_move_ciphertext(master_public, battle_expiry, 3);
                let move_b = create_test_move_ciphertext(master_public, battle_expiry, 3);

                let tx = Transaction::sign(&signer_a, 2 + round * 2, Instruction::Move(move_a));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;

                let tx = Transaction::sign(&signer_b, 2 + round, Instruction::Move(move_b));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;

                // Commit and create new layer with advanced view past expiry
                let changes = layer.commit();
                state.apply(changes).await;
                let new_seed = create_seed(&network_secret, battle_expiry + 1);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

                let signature = create_seed(&network_secret, battle_expiry);
                let tx = Transaction::sign(
                    &signer_a,
                    3 + round * 2,
                    Instruction::Settle(signature.signature),
                );
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;

                // Check if game ended
                if let Some(settled_event) =
                    events.iter().find(|e| matches!(e, Event::Settled { .. }))
                {
                    // Verify scores updated
                    let account_a_final = layer.get(&Key::Account(actor_a.clone())).await.unwrap();
                    let account_b_final = layer.get(&Key::Account(actor_b.clone())).await.unwrap();

                    if let (
                        Value::Account(mut acc_a_init),
                        Value::Account(mut acc_a_final),
                        Value::Account(mut acc_b_init),
                        Value::Account(mut acc_b_final),
                    ) = (
                        account_a_initial.clone(),
                        account_a_final,
                        account_b_initial.clone(),
                        account_b_final,
                    ) {
                        // Check win/loss/draw counters
                        assert!(
                            acc_a_final.stats.wins > acc_a_init.stats.wins
                                || acc_a_final.stats.losses > acc_a_init.stats.losses
                                || acc_a_final.stats.draws > acc_a_init.stats.draws
                        );
                        assert!(
                            acc_b_final.stats.wins > acc_b_init.stats.wins
                                || acc_b_final.stats.losses > acc_b_init.stats.losses
                                || acc_b_final.stats.draws > acc_b_init.stats.draws
                        );

                        // Check ELO changed
                        assert!(
                            acc_a_final.stats.elo != acc_a_init.stats.elo
                                || acc_b_final.stats.elo != acc_b_init.stats.elo
                        );

                        // Battle should be cleared
                        assert!(acc_a_final.battle.is_none());
                        assert!(acc_b_final.battle.is_none());

                        // Verify old/new Elo scores in Settled event are properly populated
                        if let Event::Settled {
                            player_a,
                            player_a_old,
                            player_a_new,
                            player_b_old,
                            player_b_new,
                            ..
                        } = settled_event
                        {
                            // Swap results if player A is not the signer
                            if player_a != &signer_a.public_key() {
                                let acc_temp_init = acc_a_init;
                                let acc_temp_final = acc_a_final;
                                acc_a_init = acc_b_init;
                                acc_a_final = acc_b_final;
                                acc_b_init = acc_temp_init;
                                acc_b_final = acc_temp_final;
                            }

                            // Verify old Elo scores match initial account states
                            assert_eq!(
                                player_a_old.elo, acc_a_init.stats.elo,
                                "Player A old Elo should match initial Elo"
                            );
                            assert_eq!(
                                player_b_old.elo, acc_b_init.stats.elo,
                                "Player B old Elo should match initial Elo"
                            );

                            // Verify new Elo scores match final account states
                            assert_eq!(
                                player_a_new.elo, acc_a_final.stats.elo,
                                "Player A new Elo should match final Elo"
                            );
                            assert_eq!(
                                player_b_new.elo, acc_b_final.stats.elo,
                                "Player B new Elo should match final Elo"
                            );

                            // Verify Elo scores actually changed
                            assert_ne!(
                                player_a_old.elo, player_a_new.elo,
                                "Player A Elo should have changed"
                            );
                            assert_ne!(
                                player_b_old.elo, player_b_new.elo,
                                "Player B Elo should have changed"
                            );
                        }
                    }
                    break;
                }

                round += 1;
                if round > 10 {
                    panic!("Game should have ended by now");
                }
            }

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_invalid_signature_does_nothing() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, actor_a) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle with moves
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view to expire the lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);

            // Get the battle expiry
            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");

            // Send moves
            let move_a = create_test_move_ciphertext(master_public, battle_expiry, 1);
            let move_b = create_test_move_ciphertext(master_public, battle_expiry, 2);

            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(move_a));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 2, Instruction::Move(move_b));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view past expiry
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, battle_expiry + 1);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let wrong_signature =
                ops::sign_message::<MinSig>(&network_secret, Some(b"test"), b"wrong");

            let tx = Transaction::sign(&signer_a, 3, Instruction::Settle(wrong_signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert!(events.is_empty()); // Should produce no events

            // Battle should still be active with pending moves
            let battle_key = layer.get(&Key::Account(actor_a.clone())).await.unwrap();
            if let Value::Account(account) = battle_key {
                assert!(account.battle.is_some());
            }

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_decryption_failure_defaults_to_no_move() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view to expire the lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);

            // Extract battle info from the event to know actual player assignments
            let (_, actual_player_a, _) = match &events[0] {
                Event::Matched {
                    battle,
                    expiry: _,
                    player_a,
                    player_a_creature: _,
                    player_a_stats: _,
                    player_b,
                    player_b_creature: _,
                    player_b_stats: _,
                } => (*battle, player_a.clone(), player_b.clone()),
                _ => panic!("Expected Matched event"),
            };

            // Get the battle expiry
            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");

            // Create moves based on actual player assignments
            // We want the player in position A to have a bad move that fails decryption
            let (bad_move_signer, bad_move_nonce, good_move_signer, good_move_nonce) =
                if actual_player_a == signer_a.public_key() {
                    // signer_a is in position A, signer_b is in position B
                    (&signer_a, 2, &signer_b, 2)
                } else {
                    // signer_b is in position A, signer_a is in position B
                    (&signer_b, 2, &signer_a, 2)
                };

            // Create a ciphertext that will fail decryption (wrong target)
            let bad_move = create_test_move_ciphertext(master_public, 9999, 3); // Wrong expiry
            let good_move = create_test_move_ciphertext(master_public, battle_expiry, 2);

            let tx =
                Transaction::sign(bad_move_signer, bad_move_nonce, Instruction::Move(bad_move));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(
                good_move_signer,
                good_move_nonce,
                Instruction::Move(good_move),
            );
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and create new layer with advanced view past expiry
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, battle_expiry + 1);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let signature = create_seed(&network_secret, battle_expiry);

            let tx = Transaction::sign(&signer_a, 3, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Find the move event
            let move_event = events
                .iter()
                .find(|e| matches!(e, Event::Moved { .. }))
                .unwrap();

            if let Event::Moved {
                player_a_move,
                player_b_move,
                ..
            } = move_event
            {
                // Player A's move should default to 0 (decryption failed)
                assert_eq!(*player_a_move, 0);
                // Player B's move should be 2 (successful decryption)
                assert_eq!(*player_b_move, 2);
            }

            // Consume the layer at the end of the test
            let _ = layer.commit();
        });
    }

    #[test]
    fn test_move_usage_limits_respected() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let changes = layer.commit();
            state.apply(changes).await;

            // Match
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let changes = layer.commit();
            state.apply(changes).await;

            // Commit and create new layer with advanced view to expire the lobby
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            let Some(Event::Matched { player_a, .. }) = events.first() else {
                panic!("Expected Matched event");
            };
            let mut nonce_a = 2;
            let mut nonce_b = 2;

            // Determine which signer is player_a in the battle
            let is_signer_a_player_a = signer_a.public_key() == *player_a;

            // We'll have player_a use their strongest move repeatedly
            // Get player_a's account and find their strongest move
            let Some(Value::Account(account_player_a)) =
                layer.get(&Key::Account(player_a.clone())).await
            else {
                panic!("Player A account should exist");
            };
            let creature_player_a = account_player_a.creature.as_ref().unwrap();
            let move_limits = creature_player_a.get_move_usage_limits();

            // Find the strongest move for player_a (non-zero, lowest limit)
            let mut strongest_move = 0;
            let mut min_limit = u8::MAX;
            for (i, &limit) in move_limits.iter().enumerate().skip(1) {
                if limit < min_limit {
                    min_limit = limit;
                    strongest_move = i as u8;
                }
            }

            // Play rounds using the strongest move until we exceed its limit
            let battle_key = account_player_a.battle.unwrap();

            // Play rounds up to the limit
            for _ in 0..min_limit {
                let battle_expiry = layer
                    .view()
                    .checked_add(MOVE_EXPIRY)
                    .expect("view overflow");

                // player_a always uses their strongest move, player_b uses defense
                let (move_signer_a, move_signer_b) = if is_signer_a_player_a {
                    // signer_a is player_a, uses strongest move
                    // signer_b is player_b, uses defense (1)
                    (
                        create_test_move_ciphertext(master_public, battle_expiry, strongest_move),
                        create_test_move_ciphertext(master_public, battle_expiry, 1),
                    )
                } else {
                    // signer_a is player_b, uses defense (1)
                    // signer_b is player_a, uses strongest move
                    (
                        create_test_move_ciphertext(master_public, battle_expiry, 1),
                        create_test_move_ciphertext(master_public, battle_expiry, strongest_move),
                    )
                };

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(move_signer_a));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));
                nonce_a += 1;
                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(move_signer_b));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));
                nonce_b += 1;

                // Settle the round
                let changes = layer.commit();
                state.apply(changes).await;
                let new_seed = create_seed(&network_secret, battle_expiry + 1);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
                let signature = create_seed(&network_secret, battle_expiry);
                let tx =
                    Transaction::sign(&signer_a, nonce_a, Instruction::Settle(signature.signature));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                nonce_a += 1;

                // Verify move was applied
                let move_event = events
                    .iter()
                    .find(|e| matches!(e, Event::Moved { .. }))
                    .unwrap();
                if let Event::Moved {
                    player_a_move,
                    player_b_move,
                    ..
                } = move_event
                {
                    // player_a always uses strongest_move, player_b always uses 1
                    assert_eq!(*player_a_move, strongest_move);
                    assert_eq!(*player_b_move, 1);
                }

                // Check if battle is over
                if layer.get(&Key::Battle(battle_key)).await.is_none() {
                    break;
                }
            }

            // If battle is still ongoing, try to use the strongest move one more time
            if let Some(Value::Battle { .. }) = layer.get(&Key::Battle(battle_key)).await {
                let battle_expiry = layer
                    .view()
                    .checked_add(MOVE_EXPIRY)
                    .expect("view overflow");

                // Try to use the strongest move again (should exceed limit)
                let (move_signer_a, move_signer_b) = if is_signer_a_player_a {
                    // signer_a is player_a, tries to use strongest move again
                    // signer_b is player_b, uses defense (1)
                    (
                        create_test_move_ciphertext(master_public, battle_expiry, strongest_move),
                        create_test_move_ciphertext(master_public, battle_expiry, 1),
                    )
                } else {
                    // signer_a is player_b, uses defense (1)
                    // signer_b is player_a, tries to use strongest move again
                    (
                        create_test_move_ciphertext(master_public, battle_expiry, 1),
                        create_test_move_ciphertext(master_public, battle_expiry, strongest_move),
                    )
                };

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(move_signer_a));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_a += 1;
                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(move_signer_b));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;

                // Settle the round
                let changes = layer.commit();
                state.apply(changes).await;
                let new_seed = create_seed(&network_secret, battle_expiry + 1);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
                let signature = create_seed(&network_secret, battle_expiry);
                let tx =
                    Transaction::sign(&signer_a, nonce_a, Instruction::Settle(signature.signature));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;

                // Verify move was defaulted to 0 (no move) due to limit exceeded
                let move_event = events
                    .iter()
                    .find(|e| matches!(e, Event::Moved { .. }))
                    .unwrap();
                if let Event::Moved {
                    player_a_move,
                    player_b_move,
                    ..
                } = move_event
                {
                    // player_a's move should be 0 (exceeded limit), player_b should still use 1
                    assert_eq!(*player_a_move, 0);
                    assert_eq!(*player_b_move, 1);
                }
            }

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_move_usage_counts_persist_across_rounds() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, actor_a) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            let Some(Event::Matched { player_a, .. }) = events.first() else {
                panic!("Expected Matched event");
            };

            let Some(Value::Account(account)) = layer.get(&Key::Account(actor_a.clone())).await
            else {
                panic!("Account should exist");
            };
            let battle_key = account.battle.unwrap();

            // Play first round with move 2
            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");
            let move_a = create_test_move_ciphertext(master_public, battle_expiry, 3);
            let move_b = create_test_move_ciphertext(master_public, battle_expiry, 1);

            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(move_a));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));
            let tx = Transaction::sign(&signer_b, 2, Instruction::Move(move_b));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, battle_expiry + 1);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let signature = create_seed(&network_secret, battle_expiry);
            let tx = Transaction::sign(&signer_a, 3, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Check if battle ended
            let battle_ended = events.iter().any(|e| matches!(e, Event::Settled { .. }));
            if battle_ended {
                // Battle ended after first round, test is complete
                let _ = layer.commit();
                return;
            }

            // Check move counts are updated
            let Some(Value::Battle {
                player_a_move_counts,
                player_b_move_counts,
                ..
            }) = layer.get(&Key::Battle(battle_key)).await
            else {
                panic!("Battle should exist");
            };
            if signer_a.public_key() == *player_a {
                assert_eq!(
                    player_a_move_counts[3], 1,
                    "Move 2 should have been used once"
                );
            } else {
                assert_eq!(
                    player_b_move_counts[3], 1,
                    "Move 2 should have been used once"
                );
            }

            // Play second round with move 3
            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");
            let move_a = create_test_move_ciphertext(master_public, battle_expiry, 4);
            let move_b = create_test_move_ciphertext(master_public, battle_expiry, 1);

            let tx = Transaction::sign(&signer_a, 4, Instruction::Move(move_a));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 3, Instruction::Move(move_b));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, battle_expiry + 1);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let signature = create_seed(&network_secret, battle_expiry);
            let tx = Transaction::sign(&signer_a, 5, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Check move counts persist
            if let Some(Value::Battle {
                player_a_move_counts,
                player_b_move_counts,
                ..
            }) = layer.get(&Key::Battle(battle_key)).await
            {
                if signer_a.public_key() == *player_a {
                    assert_eq!(player_a_move_counts[3], 1, "Move 2 count should persist");
                    assert_eq!(
                        player_a_move_counts[4], 1,
                        "Move 3 should have been used once"
                    );
                } else {
                    assert_eq!(player_b_move_counts[3], 1, "Move 2 count should persist");
                    assert_eq!(
                        player_b_move_counts[4], 1,
                        "Move 3 should have been used once"
                    );
                }
            }

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_creature_strength_method() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let (network_secret, _) = create_network_keypair();
            let (_, actor) = create_test_actor(1);
            let seed = create_seed(&network_secret, 1);
            let creature = Creature::new(actor, 0, seed.signature);

            // Test that health() returns the first trait
            assert_eq!(creature.health(), creature.traits[0]);
        });
    }

    #[test]
    fn test_creature_get_move_strengths() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let (network_secret, _) = create_network_keypair();
            let (_, actor) = create_test_actor(1);
            let seed = create_seed(&network_secret, 1);
            let creature = Creature::new(actor, 0, seed.signature);

            let move_strengths = creature.get_move_strengths();

            // Verify correct mapping
            assert_eq!(move_strengths[0], 0); // No-op
            assert_eq!(move_strengths[1], creature.traits[1]); // Defense
            assert_eq!(move_strengths[2], creature.traits[2]); // Attack 1
            assert_eq!(move_strengths[3], creature.traits[3]); // Attack 2
            assert_eq!(move_strengths[4], creature.traits[4]); // Attack 3
        });
    }

    #[test]
    fn test_creature_actions() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let (network_secret, _) = create_network_keypair();
            let (_, actor) = create_test_actor(1);
            let seed = create_seed(&network_secret, 1);
            let creature = Creature::new(actor, 0, seed.signature);

            assert_eq!(creature.action(0, seed.signature), (false, 0));
            assert_eq!(
                creature.action(TOTAL_MOVES as u8, seed.signature),
                (false, 0)
            );
            assert_eq!(creature.action(u8::MAX, seed.signature), (false, 0));
        });
    }

    #[test]
    fn test_creature_action_minimum_effectiveness() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let (network_secret, _) = create_network_keypair();
            let (_, actor) = create_test_actor(1);
            let seed = create_seed(&network_secret, 1);
            let creature = Creature::new(actor, 0, seed.signature);

            // Test multiple seeds to ensure minimum is 1/2 of max
            for i in 0..100 {
                // Create different signatures for testing
                let (sk, _) = create_network_keypair();
                let test_seed = ops::sign_message::<MinSig>(&sk, Some(b"test"), &[i; 32]);

                // Check all moves
                for move_idx in 1..TOTAL_MOVES as u8 {
                    let (is_defense, power) = creature.action(move_idx, test_seed);
                    let max_power = creature.traits[move_idx as usize];
                    let min_expected = max_power / 2;

                    // Verify the power is at least half of max
                    assert!(power >= min_expected);

                    // Verify the power doesn't exceed max
                    assert!(power <= max_power);

                    // Verify defense flag is correct
                    assert_eq!(is_defense, move_idx == 1);
                }
            }
        });
    }

    #[test]
    fn test_generate_multiple_times() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer, _) = create_test_actor(1);

            // Generate first creature
            let tx = Transaction::sign(&signer, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);
            assert!(matches!(events[0], Event::Generated { .. }));

            // Try to generate again (should replace existing)
            let tx = Transaction::sign(&signer, 1, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);
            assert!(matches!(events[0], Event::Generated { .. }));

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_match_with_empty_lobby() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer, actor) = create_test_actor(1);

            // Generate creature first
            let tx = Transaction::sign(&signer, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Try to match with empty lobby
            let tx = Transaction::sign(&signer, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Should be added to lobby
            assert_eq!(events.len(), 0); // No match event, just added to lobby

            // Verify actor is in lobby
            if let Some(Value::Lobby { players, .. }) = layer.get(&Key::Lobby).await {
                assert!(players.contains(&actor));
            } else {
                panic!("Lobby should exist");
            }

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_move_with_no_battle() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer, _) = create_test_actor(1);

            // Generate creature
            let tx = Transaction::sign(&signer, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Try to move without being in battle
            let encrypted_move = create_test_move_ciphertext(master_public, 100, 1);
            let tx = Transaction::sign(&signer, 1, Instruction::Move(encrypted_move));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Should return empty events (no-op)
            assert_eq!(events.len(), 0);

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_settle_with_no_battle() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer, _) = create_test_actor(1);

            // Generate creature
            let tx = Transaction::sign(&signer, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Try to settle without being in battle
            let signature = create_seed(&network_secret, 100);
            let tx = Transaction::sign(&signer, 1, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Should return empty events (no-op)
            assert_eq!(events.len(), 0);

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_move_when_turn_expired() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Advance time past move expiry
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 202);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed); // Past MOVE_EXPIRY

            // Try to submit move after expiry
            let encrypted_move = create_test_move_ciphertext(master_public, 102 + MOVE_EXPIRY, 1);
            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(encrypted_move));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Should return empty events (expired)
            assert_eq!(events.len(), 0);

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_settle_before_turn_expired() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");

            // Submit moves
            let move_a = create_test_move_ciphertext(master_public, battle_expiry, 1);
            let move_b = create_test_move_ciphertext(master_public, battle_expiry, 2);
            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(move_a));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 2, Instruction::Move(move_b));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Try to settle before expiry (should fail)
            let signature = create_seed(&network_secret, battle_expiry);
            let tx = Transaction::sign(&signer_a, 3, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Should return empty events (not expired yet)
            assert_eq!(events.len(), 0);

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_double_move_submission() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");

            // Submit first move
            let move_a1 = create_test_move_ciphertext(master_public, battle_expiry, 1);
            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(move_a1));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Try to submit second move (should fail)
            let move_a2 = create_test_move_ciphertext(master_public, battle_expiry, 2);
            let tx = Transaction::sign(&signer_a, 3, Instruction::Move(move_a2));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Should return empty events (already moved)
            assert_eq!(events.len(), 0);

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_battle_with_all_health_scenarios() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, actor_a) = create_test_actor(1);
            let (signer_b, actor_b) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Get initial healths to calculate number of rounds needed
            let Some(Value::Account(account_a)) = layer.get(&Key::Account(actor_a.clone())).await
            else {
                panic!("Account A should exist");
            };
            let Some(Value::Account(account_b)) = layer.get(&Key::Account(actor_b.clone())).await
            else {
                panic!("Account B should exist");
            };

            let _max_health_a = account_a.creature.as_ref().unwrap().health();
            let _max_health_b = account_b.creature.as_ref().unwrap().health();

            // Play rounds with both players attacking
            let mut nonce_a = 2;
            let mut nonce_b = 2;
            let mut round = 0;

            loop {
                let battle_expiry = layer
                    .view()
                    .checked_add(MOVE_EXPIRY)
                    .expect("view overflow");

                // Both players attack (not defend)
                let move_a = create_test_move_ciphertext(master_public, battle_expiry, 2);
                let move_b = create_test_move_ciphertext(master_public, battle_expiry, 3);

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(move_a));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_a += 1;
                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(move_b));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_b += 1;

                // Settle
                let changes = layer.commit();
                state.apply(changes).await;
                let new_seed = create_seed(&network_secret, battle_expiry + 1);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
                let signature = create_seed(&network_secret, battle_expiry);
                let tx =
                    Transaction::sign(&signer_a, nonce_a, Instruction::Settle(signature.signature));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                nonce_a += 1;

                // Check if battle ended
                let settled = events.iter().any(|e| matches!(e, Event::Settled { .. }));
                if settled {
                    // Verify proper ELO update occurred
                    let Some(Value::Account(final_a)) =
                        layer.get(&Key::Account(actor_a.clone())).await
                    else {
                        panic!("Account A should exist");
                    };
                    let Some(Value::Account(final_b)) =
                        layer.get(&Key::Account(actor_b.clone())).await
                    else {
                        panic!("Account B should exist");
                    };

                    // Check that ELO changed
                    assert_ne!(
                        final_a.stats.elo, account_a.stats.elo,
                        "ELO should have changed for player A"
                    );
                    assert_ne!(
                        final_b.stats.elo, account_b.stats.elo,
                        "ELO should have changed for player B"
                    );

                    // Check win/loss/draw counters
                    let total_games_a =
                        final_a.stats.wins + final_a.stats.losses + final_a.stats.draws;
                    let total_games_b =
                        final_b.stats.wins + final_b.stats.losses + final_b.stats.draws;
                    assert_eq!(total_games_a, 1, "Player A should have exactly 1 game");
                    assert_eq!(total_games_b, 1, "Player B should have exactly 1 game");

                    break;
                }

                round += 1;
                if round > 100 {
                    panic!("Battle should have ended by now");
                }
            }

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_player_a_defends_player_b_attacks() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            let Some(Event::Matched { player_a, .. }) = events.first() else {
                panic!("Expected Matched event");
            };

            let battle_expiry = layer
                .view()
                .checked_add(MOVE_EXPIRY)
                .expect("view overflow");

            // Player A defends (move 0), Player B attacks (move 2)
            let move_a = create_test_move_ciphertext(master_public, battle_expiry, 1);
            let move_b = create_test_move_ciphertext(master_public, battle_expiry, 3);

            let tx = Transaction::sign(&signer_a, 2, Instruction::Move(move_a));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 2, Instruction::Move(move_b));
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, battle_expiry + 1);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let signature = create_seed(&network_secret, battle_expiry);
            let tx = Transaction::sign(&signer_a, 3, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Find the move event to verify impacts
            let move_event = events
                .iter()
                .find(|e| matches!(e, Event::Moved { .. }))
                .unwrap();
            if let Event::Moved {
                player_a_power,
                player_b_power,
                ..
            } = move_event
            {
                // Player A defended (positive impact), Player B attacked (negative impact)
                if signer_a.public_key() == *player_a {
                    assert!(*player_a_power > 0, "Defense should have positive impact");
                    assert!(*player_b_power > 0, "Attack should have negative impact");
                } else {
                    assert!(*player_b_power > 0, "Attack should have positive impact");
                    assert!(*player_a_power > 0, "Defense should have negative impact");
                }
            }

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_battle_times_out_after_max_rounds() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, actor_a) = create_test_actor(1);
            let (signer_b, actor_b) = create_test_actor(2);

            // Generate creatures
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let changes = layer.commit();
            state.apply(changes).await;

            // Match players
            let seed = create_seed(&network_secret, 2);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let changes = layer.commit();
            state.apply(changes).await;

            // Jump ahead to view 3
            let view = 2 + LOBBY_EXPIRY + 1;
            let seed = create_seed(&network_secret, view);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            let Some(Event::Matched { battle, .. }) =
                events.iter().find(|e| matches!(e, Event::Matched { .. }))
            else {
                panic!("Battle should be matched");
            };
            let changes = layer.commit();
            state.apply(changes).await;

            // Simulate MAX_BATTLE_ROUNDS rounds where both players do nothing (move 0)
            let mut nonce_a = 2;
            let mut nonce_b = 2;

            let mut view = view + 1;
            for round in 0..MAX_BATTLE_ROUNDS {
                // Get battle expiry
                let Some(Value::Battle { expiry, .. }) = state.get(&Key::Battle(*battle)).await
                else {
                    panic!("Battle should exist");
                };

                // Both players make no move (move 0)
                let seed = create_seed(&network_secret, view);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
                let move_a = create_test_move_ciphertext(master_public, expiry, 0);
                let move_b = create_test_move_ciphertext(master_public, expiry, 0);

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(move_a));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));
                nonce_a += 1;

                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(move_b));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));
                nonce_b += 1;
                let changes = layer.commit();
                state.apply(changes).await;

                // Advance time and settle
                view = expiry + 1;
                let new_seed = create_seed(&network_secret, view);
                let new_layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
                layer = new_layer;

                let expiry_seed = create_seed(&network_secret, expiry);
                let tx = Transaction::sign(
                    &signer_a,
                    nonce_a,
                    Instruction::Settle(expiry_seed.signature),
                );
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                nonce_a += 1;

                // Check if battle ended
                if let Some(Event::Settled { round, outcome, .. }) =
                    events.iter().find(|e| matches!(e, Event::Settled { .. }))
                {
                    assert_eq!(*round, MAX_BATTLE_ROUNDS);
                    assert_eq!(*outcome, Outcome::Draw);

                    // Verify both players' draw counts increased
                    let Some(Value::Account(account_a_final)) =
                        layer.get(&Key::Account(actor_a.clone())).await
                    else {
                        panic!("Account A should exist");
                    };
                    let Some(Value::Account(account_b_final)) =
                        layer.get(&Key::Account(actor_b.clone())).await
                    else {
                        panic!("Account B should exist");
                    };

                    assert_eq!(account_a_final.stats.draws, 1);
                    assert_eq!(account_b_final.stats.draws, 1);
                    assert!(account_a_final.battle.is_none());
                    assert!(account_b_final.battle.is_none());

                    return; // Test passed
                }

                // If we haven't reached MAX_BATTLE_ROUNDS yet, continue
                if round < MAX_BATTLE_ROUNDS - 1 {
                    assert!(
                        events.iter().any(|e| matches!(e, Event::Moved { .. })),
                        "Round {round}: Expected Moved event but got {events:?}",
                    );
                }

                // Update view and state for next iteration
                let changes = layer.commit();
                state.apply(changes).await;
                view += 1;
            }

            panic!("Battle should have ended in a draw after MAX_BATTLE_ROUNDS");
        });
    }

    #[test]
    fn test_out_of_range_moves_handled_as_no_move() {
        let executor = Runner::default();
        executor.start(|_| async move {
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, actor_a) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Setup battle
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let changes = layer.commit();
            state.apply(changes).await;

            // Get the battle key and determine player positions
            let Some(Value::Account(account_a)) = state.get(&Key::Account(actor_a.clone())).await
            else {
                panic!("Account A should exist");
            };
            let battle_key = account_a.battle.unwrap();

            // Get battle to determine player positions
            let Some(Value::Battle { player_a, .. }) = state.get(&Key::Battle(battle_key)).await
            else {
                panic!("Battle should exist");
            };

            // Submit out-of-range moves
            let Some(Value::Battle { expiry, .. }) = state.get(&Key::Battle(battle_key)).await
            else {
                panic!("Battle should exist");
            };

            // Test various out-of-range values
            let out_of_range_moves = vec![
                5,   // Just past ALLOWED_MOVES (4)
                10,  // Way out of range
                100, // Very large
                255, // u8::MAX
            ];

            // Test each out-of-range move
            let mut next_expiry = expiry;
            let mut nonce_a = 2;
            let mut nonce_b = 2;
            for out_of_range_move in out_of_range_moves {
                // Create new layer
                let new_seed = create_seed(&network_secret, next_expiry);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

                // Player A (whichever signer is in that position) submits out-of-range move
                let move_out_of_range =
                    create_test_move_ciphertext(master_public, next_expiry, out_of_range_move);
                let tx =
                    Transaction::sign(&signer_a, nonce_a, Instruction::Move(move_out_of_range));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));
                nonce_a += 1;

                // Player B submits valid defense move
                let move_valid = create_test_move_ciphertext(master_public, next_expiry, 1);
                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(move_valid));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                assert!(events.iter().any(|e| matches!(e, Event::Locked { .. })));
                nonce_b += 1;
                let changes = layer.commit();
                state.apply(changes).await;

                // Settle the round
                let settle_seed = create_seed(&network_secret, next_expiry + 1);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, settle_seed);
                let signature = create_seed(&network_secret, next_expiry);
                let tx =
                    Transaction::sign(&signer_a, nonce_a, Instruction::Settle(signature.signature));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                nonce_a += 1;

                // Check that the move was treated as no-op
                let Some(Event::Moved {
                    expiry,
                    player_a_move,
                    player_b_move,
                    ..
                }) = events.first()
                else {
                    panic!("Expected Moved event");
                };
                if signer_a.public_key() == player_a {
                    // Player A's out-of-range move should be treated as 0 (no move)
                    assert_eq!(*player_a_move, 0);
                    // Player B's valid move should remain unchanged
                    assert_eq!(*player_b_move, 1);
                } else {
                    assert_eq!(*player_a_move, 1);
                    assert_eq!(*player_b_move, 0);
                }
                next_expiry = *expiry;

                // Check that the battle is still ongoing (no one should have won from a no-op)
                let Some(Value::Account(account)) = layer.get(&Key::Account(actor_a.clone())).await
                else {
                    panic!("Account should exist");
                };
                assert!(account.battle.is_some(), "Battle should still be ongoing");

                // Update state
                let changes = layer.commit();
                state.apply(changes).await;
            }
        });
    }

    #[test]
    fn test_prefer_result_over_draw_when_player_killed_in_last_round() {
        let executor = Runner::default();
        executor.start(|_| async move {
            // Setup battle
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let (signer_a, actor_a) = create_test_actor(1);
            let (signer_b, actor_b) = create_test_actor(2);

            // Generate creatures
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;
            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Match players
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and advance view to expire lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);
            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Get battle info and determine which signer is which player
            let (battle, actual_player_a, _actual_player_b) = if let Event::Matched {
                battle,
                player_a,
                player_b,
                ..
            } = &events[0]
            {
                (*battle, player_a.clone(), player_b.clone())
            } else {
                panic!("Expected Matched event");
            };

            // Determine which signer corresponds to which battle position
            let is_signer_a_player_a = actual_player_a == actor_a;

            // Commit the state and directly modify the battle to set both players' health to 1
            let changes = layer.commit();
            state.apply(changes).await;

            // Get the battle and modify health values
            let Some(Value::Battle {
                expiry,
                round,
                player_a,
                player_a_max_health,
                player_a_pending,
                player_a_move_counts,
                player_b,
                player_b_max_health,
                player_b_pending,
                player_b_move_counts,
                ..
            }) = state.get(&Key::Battle(battle)).await
            else {
                panic!("Battle should exist");
            };
            state
                .insert(
                    Key::Battle(battle),
                    Value::Battle {
                        expiry,
                        round,
                        player_a: player_a.clone(),
                        player_a_max_health,
                        player_a_health: 1,
                        player_a_pending,
                        player_a_move_counts,
                        player_b: player_b.clone(),
                        player_b_max_health,
                        player_b_health: 1,
                        player_b_pending,
                        player_b_move_counts,
                    },
                )
                .await;

            // Simulate rounds until we're at the last round
            let mut nonce_a = 2;
            let mut nonce_b = 2;
            let mut view = 103;

            // Skip to just before the last round
            for _ in 0..(MAX_BATTLE_ROUNDS - 1) {
                let seed = create_seed(&network_secret, view);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

                let Some(Value::Battle { expiry, .. }) = layer.get(&Key::Battle(battle)).await
                else {
                    panic!("Battle should exist");
                };
                let battle_expiry = expiry;

                // Both players do nothing
                let move_a = create_test_move_ciphertext(master_public, battle_expiry, 0);
                let move_b = create_test_move_ciphertext(master_public, battle_expiry, 0);

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(move_a));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_a += 1;

                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(move_b));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_b += 1;

                // Commit and advance to settle
                let changes = layer.commit();
                state.apply(changes).await;
                view = battle_expiry + 1;
                let seed = create_seed(&network_secret, view);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

                // Settle the round
                let signature = create_seed(&network_secret, battle_expiry);
                let tx =
                    Transaction::sign(&signer_a, nonce_a, Instruction::Settle(signature.signature));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                nonce_a += 1;

                // Verify battle continues
                assert!(events.iter().any(|e| matches!(e, Event::Moved { .. })));
                assert!(!events.iter().any(|e| matches!(e, Event::Settled { .. })));

                let changes = layer.commit();
                state.apply(changes).await;
                view += 1;
            }

            // Now we're at round MAX_BATTLE_ROUNDS (the last round)
            // Both players have health = 1
            let seed = create_seed(&network_secret, view);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);
            let Some(Value::Battle { expiry, .. }) = layer.get(&Key::Battle(battle)).await else {
                panic!("Battle should exist");
            };

            // We want battle's player_a to attack and player_b to do nothing
            // This should result in player_a winning (not a draw)
            if is_signer_a_player_a {
                // signer_a is player_a (the attacker)
                let attack_move = create_test_move_ciphertext(master_public, expiry, 2); // Any attack move
                let no_move = create_test_move_ciphertext(master_public, expiry, 0); // No action

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(attack_move));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_a += 1;

                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(no_move));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
            } else {
                // signer_b is player_a (the attacker)
                let no_move = create_test_move_ciphertext(master_public, expiry, 0); // No action
                let attack_move = create_test_move_ciphertext(master_public, expiry, 2); // Any attack move

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(no_move));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_a += 1;

                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(attack_move));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
            }

            // Commit and advance to settle
            let changes = layer.commit();
            state.apply(changes).await;
            view = expiry + 1;
            let new_seed = create_seed(&network_secret, view);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            // Settle the final round
            let signature = create_seed(&network_secret, expiry);
            let tx =
                Transaction::sign(&signer_a, nonce_a, Instruction::Settle(signature.signature));
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;

            // Verify the outcome
            let settled_event = events.iter().find(|e| matches!(e, Event::Settled { .. }));
            assert!(settled_event.is_some(), "Battle should have been settled");
            if let Some(Event::Settled { outcome, round, .. }) = settled_event {
                assert_eq!(
                    *round, MAX_BATTLE_ROUNDS,
                    "Battle should end at MAX_BATTLE_ROUNDS"
                );
                assert_eq!(
                    *outcome,
                    Outcome::PlayerA,
                    "Player A should win by killing Player B in the last round"
                );
            }

            // Verify final account states
            let final_account_a =
                if let Some(Value::Account(acc)) = layer.get(&Key::Account(actor_a)).await {
                    acc
                } else {
                    panic!("Account A not found after battle");
                };
            let final_account_b =
                if let Some(Value::Account(acc)) = layer.get(&Key::Account(actor_b)).await {
                    acc
                } else {
                    panic!("Account B not found after battle");
                };
            if is_signer_a_player_a {
                // signer_a was player_a (winner)
                assert_eq!(
                    final_account_a.stats.wins, 1,
                    "Signer A (as Player A) should have won"
                );
                assert_eq!(final_account_a.stats.draws, 0);
                assert_eq!(
                    final_account_b.stats.losses, 1,
                    "Signer B (as Player B) should have lost"
                );
                assert_eq!(final_account_b.stats.draws, 0);
            } else {
                // signer_b was player_a (winner)
                assert_eq!(
                    final_account_b.stats.wins, 1,
                    "Signer B (as Player A) should have won"
                );
                assert_eq!(final_account_b.stats.draws, 0);
                assert_eq!(
                    final_account_a.stats.losses, 1,
                    "Signer A (as Player B) should have lost"
                );
                assert_eq!(final_account_a.stats.draws, 0);
            }

            let _ = layer.commit();
        });
    }

    #[test]
    fn test_defense_moves_never_exceed_max_health() {
        let executor = Runner::default();
        executor.start(|_| async move {
            // This test verifies that using defense moves never causes health to exceed the creature's maximum health
            let mut state = MockState::new();
            let (network_secret, master_public) = create_network_keypair();
            let seed = create_seed(&network_secret, 1);
            let mut layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

            let (signer_a, _) = create_test_actor(1);
            let (signer_b, _) = create_test_actor(2);

            // Generate creatures
            let tx = Transaction::sign(&signer_a, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            let tx = Transaction::sign(&signer_b, 0, Instruction::Generate);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Match players
            let tx = Transaction::sign(&signer_a, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            layer.apply(&tx).await;

            // Commit and advance view to expire lobby
            let changes = layer.commit();
            state.apply(changes).await;
            let new_seed = create_seed(&network_secret, 102);
            layer = Layer::new(&state, master_public, TEST_NAMESPACE, new_seed);

            let tx = Transaction::sign(&signer_b, 1, Instruction::Match);
            assert!(layer.prepare(&tx).await);
            let events = layer.apply(&tx).await;
            assert_eq!(events.len(), 1);

            // Get battle info
            let Some(Event::Matched { battle, .. }) = events.first() else {
                panic!("Expected Matched event");
            };

            // Play several rounds where both players use defense moves
            let mut nonce_a = 2;
            let mut nonce_b = 2;
            let mut view = 103;
            let changes = layer.commit();
            state.apply(changes).await;

            for round in 0..5 {
                let seed = create_seed(&network_secret, view);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

                let Some(Value::Battle { expiry, .. }) = layer.get(&Key::Battle(*battle)).await
                else {
                    panic!("Battle should exist");
                };
                let battle_expiry = expiry;

                // Both players use defense moves (move 1)
                let defense_move_a = create_test_move_ciphertext(master_public, battle_expiry, 1);
                let defense_move_b = create_test_move_ciphertext(master_public, battle_expiry, 1);

                let tx = Transaction::sign(&signer_a, nonce_a, Instruction::Move(defense_move_a));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_a += 1;

                let tx = Transaction::sign(&signer_b, nonce_b, Instruction::Move(defense_move_b));
                assert!(layer.prepare(&tx).await);
                layer.apply(&tx).await;
                nonce_b += 1;

                // Commit and advance to settle
                let changes = layer.commit();
                state.apply(changes).await;
                view = battle_expiry + 1;
                let seed = create_seed(&network_secret, view);
                layer = Layer::new(&state, master_public, TEST_NAMESPACE, seed);

                // Settle the round
                let signature = create_seed(&network_secret, battle_expiry);
                let tx =
                    Transaction::sign(&signer_a, nonce_a, Instruction::Settle(signature.signature));
                assert!(layer.prepare(&tx).await);
                let events = layer.apply(&tx).await;
                nonce_a += 1;

                // Check health values after the round
                assert!(
                    events.iter().any(|e| matches!(e, Event::Moved { .. })),
                    "Should have a Moved event"
                );

                // Check the battle state to verify health values
                if let Some(Value::Battle {
                    player_a_health,
                    player_a_max_health,
                    player_b_health,
                    player_b_max_health,
                    ..
                }) = layer.get(&Key::Battle(*battle)).await
                {
                    // Verify that health never exceeds maximum
                    assert!(player_a_health <= player_a_max_health);
                    assert!(player_b_health <= player_b_max_health);
                } else {
                    panic!("Battle should exist after round {round}");
                }

                let changes = layer.commit();
                state.apply(changes).await;
                view += 1;
            }
        });
    }
}