ccxt-base 4.5.78

CCXT – CryptoCurrency eXchange Trading Library (Rust) – untyped engine (runtime, Value, REST/prediction Cores, WS infra)
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
// Native Rust – hand-written Value type.
//
// The ast-transpiler emits `Value::Map(...)`, `Value::Str(...)`, etc.
// This module defines those variants so generated code compiles without
// requiring serde_json macros in every file.
//
// At the HTTP boundary (exchange.rs) we convert between Value and
// serde_json::Value for serialisation / deserialisation.

// Value::Map uses `IndexMap` (re-exported here as `HashMap` so the rest
// of the codebase — including transpiler-emitted `std::collections::
// HashMap::new()` calls swapped to `indexmap::IndexMap::new()` by a
// post-pass — keeps building literals via the same API). Insertion
// order matters for JSON / URL-encoded payloads: exchanges like bingx /
// digifinex / mexc reject (and the static request fixtures assert)
// specific key orders such as `{symbol,type,side,quantity,price}`.
pub use indexmap::IndexMap as HashMap;
use std::sync::Arc;
#[cfg(feature = "transpiled-base")]
use crate::exchange_generated::ExchangeBase;

/// A dynamic value type that mirrors the CCXT JavaScript Value semantics.
///
/// `Dict`/`Arr` hold their containers behind an `Arc` so that `clone()` is
/// an O(1) refcount bump instead of a deep copy — the transpiled parsers
/// and the static-test assertions clone Values pervasively (every
/// `safeString`/`safeNumber`, every recursion level), which dominated
/// runtime. Mutation goes through `Arc::make_mut` (copy-on-write): it
/// only deep-copies when the container is actually shared.
///
/// NOTE: the variants are named `Dict`/`Arr`, but construction uses the
/// associated functions `Value::Map(..)` / `Value::Array(..)` /
/// `Value::List(..)` (which wrap the `Arc`) so the ~18k transpiler-emitted
/// `Value::Map({..})` / `Value::List(vec![..])` call sites need no change.
/// Pattern matches use `Value::Dict(..)` / `Value::Arr(..)`.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    Str(String),
    Dict(Arc<HashMap<String, Value>>),
    Arr(Arc<Vec<Value>>),
}

impl Default for Value {
    fn default() -> Self {
        Value::Null
    }
}

impl Value {
    /// Mirrors TS `Precise.reduce()`: when this Value is a
    /// `Precise::new(...)` Map (carries the `__precise` marker), strip
    /// trailing zeros from `integer` and bump `decimals` down to match.
    /// Used by phemex's `to_en` after it shifts `decimals` by the
    /// market's `valueScale`: subtracts decimals, then reduce balances
    /// the integer side so the final `stringify_param` renders the
    /// scaled integer correctly (`0.1` × 10^8 → `10000000`).
    pub fn reduce(&mut self) {
        let m = match self { Value::Dict(m) if m.contains_key("__precise") => Arc::make_mut(m), _ => return };
        let mut decimals: i64 = match m.get("decimals") {
            Some(Value::Int(n)) => *n,
            _ => return,
        };
        let mut integer: String = match m.get("integer") {
            Some(Value::Str(s)) => s.clone(),
            _ => return,
        };
        // Negative decimals → pad zeros onto the integer.
        if decimals < 0 {
            // careful: a leading '-' (negative number) stays at the front.
            let (sign, digits) = if let Some(rest) = integer.strip_prefix('-') {
                ("-", rest.to_string())
            } else { ("", integer.clone()) };
            let padded = format!("{digits}{:0<width$}", "", width = (-decimals) as usize);
            integer = format!("{sign}{padded}");
            decimals = 0;
        }
        // Trim trailing zeros while there are decimal places to consume.
        while decimals > 0 && integer.ends_with('0') && integer.len() > 1 {
            integer.pop();
            decimals -= 1;
        }
        m.insert("integer".to_string(),  Value::Str(integer));
        m.insert("decimals".to_string(), Value::Int(decimals));
    }

    /// `append(item)` on an Array — pushes the item. Mirrors TS
    /// `array.push` shape (single arg, no return).
    ///
    /// On a WS-cache Map (carrying a `__cacheKind` marker; see
    /// `crate::pro::cache`) it dispatches to the per-kind logic below.
    pub fn append(&mut self, item: Value) {
        match self {
            Value::Arr(a) => Arc::make_mut(a).push(item),
            Value::Dict(m) if m.contains_key("__cacheKind") => {
                cache_append(self, item);
            }
            _ => {}
        }
    }

    /// `clear()` — resets the rolling buffer for a cache marker (or
    /// truncates the inner array of an `Arr` value).
    pub fn clear(&mut self) {
        match self {
            Value::Arr(a) => Arc::make_mut(a).clear(),
            Value::Dict(m) if m.contains_key("__cacheKind") => {
                if let Some(id) = cache_id_of_m(m) {
                    with_cache_cell(id, |c| {
                        if let Some(Value::Arr(data)) = c.get_mut("_data") { Arc::make_mut(data).clear(); }
                        cache_reset_bookkeeping(c);
                    });
                } else {
                    let m = Arc::make_mut(m);
                    if let Some(Value::Arr(data)) = m.get_mut("_data") {
                        Arc::make_mut(data).clear();
                    }
                    cache_reset_bookkeeping(m);
                }
            }
            _ => {}
        }
    }

    /// `getLimit(symbol, limit)` for the cache markers. Returns the
    /// count of new updates since the last call (clamped by `limit`
    /// when supplied) and arms the per-symbol / global reset flag so
    /// the next `append` zeroes the counter.
    pub fn get_limit(&mut self, symbol: Value, limit: Value) -> Value {
        if matches!(self, Value::Dict(d) if d.contains_key("__cacheKind")) {
            cache_get_limit(self, symbol, limit)
        } else {
            limit
        }
    }

    /// Constructor named to match the ast-transpiler's emission shape:
    /// `Value::List(vec![...])`. Aliases `Value::Array`. Note that this
    /// is a function, not a variant — so pattern matches still use
    /// `Value::Array(_)`, not `Value::List(_)`.
    #[allow(non_snake_case)]
    pub fn List(items: Vec<Value>) -> Value {
        Value::Arr(Arc::new(items))
    }

    /// Construction shim — the transpiler emits `Value::Map({..IndexMap..})`
    /// in ~18k places; this wraps the map in the `Arc` the `Dict` variant
    /// now holds. (An associated fn, not a variant — patterns use `Dict`.)
    #[allow(non_snake_case)]
    pub fn Map(m: HashMap<String, Value>) -> Value {
        Value::Dict(Arc::new(m))
    }

    /// Construction shim for `Value::Array(vec)` call sites.
    #[allow(non_snake_case)]
    pub fn Array(a: Vec<Value>) -> Value {
        Value::Arr(Arc::new(a))
    }

    // ── constructors ──────────────────────────────────────────────────────────

    pub fn str(s: impl Into<String>) -> Self {
        Value::Str(s.into())
    }

    pub fn int(n: i64) -> Self {
        Value::Int(n)
    }

    pub fn float(f: f64) -> Self {
        Value::Float(f)
    }

    pub fn bool(b: bool) -> Self {
        Value::Bool(b)
    }

    pub fn map(m: HashMap<String, Value>) -> Self {
        Value::Map(m)
    }

    pub fn array(a: Vec<Value>) -> Self {
        Value::Array(a)
    }

    // ── type checks ───────────────────────────────────────────────────────────

    pub fn is_null(&self)   -> bool { matches!(self, Value::Null) }
    pub fn is_str(&self)    -> bool { matches!(self, Value::Str(_)) }
    pub fn is_int(&self)    -> bool { matches!(self, Value::Int(_)) }
    pub fn is_float(&self)  -> bool { matches!(self, Value::Float(_)) }
    pub fn is_number(&self) -> bool { matches!(self, Value::Int(_) | Value::Float(_)) }
    pub fn is_bool(&self)   -> bool { matches!(self, Value::Bool(_)) }
    pub fn is_map(&self)    -> bool { matches!(self, Value::Dict(_)) }
    pub fn is_array(&self)  -> bool { matches!(self, Value::Arr(_)) }
    pub fn is_truthy(&self) -> bool {
        match self {
            Value::Null       => false,
            Value::Bool(b)    => *b,
            Value::Int(n)     => *n != 0,
            Value::Float(f)   => *f != 0.0,
            Value::Str(s)     => !s.is_empty(),
            Value::Dict(m)    => !m.is_empty(),
            Value::Arr(a)     => !a.is_empty(),
        }
    }

    // ── accessors ─────────────────────────────────────────────────────────────

    pub fn as_str(&self)   -> Option<&str>  { if let Value::Str(s) = self { Some(s) } else { None } }
    pub fn as_i64(&self)   -> Option<i64>   { if let Value::Int(n) = self { Some(*n) } else { None } }
    pub fn as_f64(&self)   -> Option<f64> {
        match self {
            Value::Float(f) => Some(*f),
            Value::Int(n)   => Some(*n as f64),
            _               => None,
        }
    }
    pub fn as_bool(&self)  -> Option<bool>  { if let Value::Bool(b) = self { Some(*b) } else { None } }
    pub fn as_map(&self)   -> Option<&HashMap<String, Value>> {
        if let Value::Dict(m) = self { Some(&**m) } else { None }
    }
    pub fn as_array(&self) -> Option<&Vec<Value>> {
        if let Value::Arr(a) = self { Some(&**a) } else { None }
    }

    /// Length of array, map, or string; 0 for everything else.
    /// String length counts Unicode chars (matches TS `String#length`
    /// closely enough for ASCII-only API addresses/identifiers).
    pub fn len(&self) -> usize {
        match self {
            Value::Arr(a)   => a.len(),
            Value::Dict(m)  => m.len(),
            Value::Str(s)   => s.chars().count(),
            _               => 0,
        }
    }

    pub fn is_empty(&self) -> bool { self.len() == 0 }

    // ── duck-typed method stubs that transpiled code calls on a Value ────
    // These exist so transpiled code that calls methods on Value-typed
    // locals (e.g. `parentRestInstance.describe()`) compiles. They return
    // `Value::Null` and are placeholders for richer dispatch.

    pub fn describe(&self) -> Value { Value::Null }
    /// `client.reject(error, messageHash)` — stores a rejection the `watch`
    /// drive loop delivers to the awaiting caller. Routes by the client
    /// handle's `url` to the WS registry (no-op on a non-client Value).
    pub fn reject(&self, args: &[Value]) -> Value {
        crate::pro::ws_client::value_reject(self, args)
    }
    /// `client.resolve(value, messageHash)` — stores the resolved value the
    /// `watch` drive loop returns. Routes by the client handle's `url`.
    pub fn resolve(&self, args: &[Value]) -> Value {
        crate::pro::ws_client::value_resolve(self, args)
    }
    /// `client.future(messageHash)` — TS's atomic check-and-insert: opens a
    /// single-flight for the hash (or joins the open one) and hands back a
    /// handle. Registering is the whole point — it is what makes a concurrent
    /// caller's `messageHash in client.futures` test true, so only one of them
    /// does the work (venue `authenticate` leader election). Await the handle
    /// with `exchange_stubs::ws_await_flight`; the transpiler emits that
    /// wherever the TS source awaits.
    pub fn future(&self, args: &[Value]) -> Value {
        self.open_flight(args.get(0).cloned().unwrap_or(Value::Null))
    }
    /// `client.reusable_future(messageHash)` — shared flight per hash, i.e. the
    /// same registry and handle as `future`.
    pub fn reusable_future(&self, msg_hash: Value) -> Value {
        self.open_flight(msg_hash)
    }
    /// Shared body of `future` / `reusable_future`: open-or-join the flight on
    /// the client this handle names, and return a handle to it. A non-client
    /// receiver (or a non-string hash) degrades to the old pass-the-hash-back
    /// behaviour so unrelated transpiled code keeps compiling.
    fn open_flight(&self, msg_hash: Value) -> Value {
        let hash = match &msg_hash {
            Value::Str(h) => h.clone(),
            _ => return msg_hash,
        };
        match crate::pro::ws_client::url_of(self) {
            Some(url) => {
                let led = crate::pro::ws_client::begin_flight(&url, &hash);
                crate::pro::ws_client::flight_handle(&url, &hash, led)
            }
            None => msg_hash,
        }
    }
    /// Field accessor: `cache.hashmap` — same as the WS Cache marker's
    /// hashmap sub-dict. Some transpiled WS code reads this directly
    /// via the JS field-access syntax rather than going through
    /// `get_value`.
    pub fn hashmap(&self) -> Value {
        if let Value::Dict(d) = self {
            // Cache marker: the live hashmap lives in the shared CACHE_STORE
            // (keyed by __cache_id), not on the marker Dict. Return a copy with
            // each symbol bucket tagged with a `__cache_backref` so that a
            // transpiled write-back like `cache.hashmap[symbol][id] = order`
            // (the JS reference write) persists through to the store — see
            // try_cache_hashmap_write.
            if let Some(id) = cache_id_of(self) {
                let hm = with_cache_cell(id, |m| m.get("hashmap").cloned().unwrap_or(Value::Null));
                return tag_cache_hashmap_buckets(hm, id);
            }
            if let Some(v) = d.get("hashmap") { return v.clone(); }
        }
        Value::Null
    }
    /// `client.send(payload)` — queues a frame on the WS connection (routed by
    /// the client handle's `url`). No-op on a non-client Value.
    pub fn send(&self, args: &[Value]) -> Value {
        crate::pro::ws_client::value_send(self, args)
    }
    /// `client.decode_proto_msg(...)` — exchange-specific protobuf
    /// decode helper; stubbed to `Value::Null`.
    pub fn decode_proto_msg(&self, _args: &[Value]) -> Value { Value::Null }
    /// `client.on_pong(...)` — WS heartbeat hook; records the pong time.
    pub fn on_pong(&self, _args: &[Value]) -> Value {
        crate::pro::ws_client::value_on_pong(self)
    }
    /// WS stub — transpiled `fn(...args)` over a Value-typed callable.
    pub fn call(&self, _args: &[Value]) -> Value { Value::Null }
    /// `exchange.isDictionary(value)` — transpiled tests treat `exchange`
    /// as `Value` instead of the typed `Exchange`, so we mirror the
    /// dict-typecheck method here.
    pub fn is_dictionary(&self, value: Value) -> Value {
        Value::Bool(matches!(value, Value::Dict(_)))
    }
    /// Lifts this snapshot's `options` + `currencies` onto a throwaway base
    /// `Exchange` so the *transpiled* conversion methods can run against it.
    /// The afterConstruct test transpiles its call sites with `exchange:
    /// Value`, so these methods have to exist on `Value` — but the logic
    /// must stay in the transpiled base, not be duplicated here.
    #[cfg(feature = "transpiled-base")]
    fn snapshot_as_exchange(&self) -> crate::exchange::Exchange {
        let mut ex = crate::exchange::Exchange::new(None);
        ex.options = crate::runtime::get_value(self, &Value::Str("options".to_string()));
        ex.currencies = crate::runtime::get_value(self, &Value::Str("currencies".to_string()));
        ex
    }

    /// `exchange.networkCodeToId(code, currency)` on a snapshot `Value` —
    /// delegates to the transpiled `Exchange::network_code_to_id`.
    pub fn network_code_to_id(&self, code: Value, args: &[Value]) -> Value {
        #[cfg(feature = "transpiled-base")]
        {
            let currency = args.first().cloned().unwrap_or(Value::Null);
            return crate::exchange::BaseCore::new(self.snapshot_as_exchange()).network_code_to_id(code, &[currency]);
        }
        #[cfg(not(feature = "transpiled-base"))]
        {
            let _ = args;
            code
        }
    }

    /// `exchange.networkIdToCode(networkId, currency)` on a snapshot `Value`
    /// — delegates to the transpiled `Exchange::network_id_to_code`.
    pub fn network_id_to_code(&self, args: &[Value]) -> Value {
        #[cfg(feature = "transpiled-base")]
        {
            return crate::exchange::BaseCore::new(self.snapshot_as_exchange()).network_id_to_code(args);
        }
        #[cfg(not(feature = "transpiled-base"))]
        {
            let _ = args;
            Value::Null
        }
    }

    /// `exchange.extend(a, b, ...)` on a snapshot `Value` — CCXT's shallow
    /// object merge. Pure (ignores exchange state), so it delegates to the
    /// transpiled `Exchange::extend`. Used by the (prediction-aware) transpiled
    /// test harness, where `exchange` is a dynamic `Value` handle.
    pub fn extend(&self, a: Value, args: &[Value]) -> Value {
        #[cfg(feature = "transpiled-base")]
        {
            return self.snapshot_as_exchange().extend(a, args);
        }
        #[cfg(not(feature = "transpiled-base"))]
        {
            let _ = args;
            a
        }
    }

    /// `exchange.setMarkets(markets)` on a snapshot `Value` — used by the
    /// prediction test harness to seed event-derived markets. Delegates the
    /// indexing to the transpiled `Exchange::set_markets`, then writes the
    /// computed `markets`/`markets_by_id`/`symbols` back onto the `Value`
    /// handle so later `get_value(exchange, "markets")` reads see them.
    pub fn set_markets(&mut self, markets: Value) -> Value {
        #[cfg(feature = "transpiled-base")]
        {
            // If this snapshot is backed by a live Core (`__live_id`), route to
            // it so the Core's own `set_markets` runs — for a prediction venue
            // that's `PredictionExchange::set_markets` (outcome→symbol aliasing +
            // populateOutcomes), populating the outcome caches on the very
            // instance the method dispatch uses. Without this, the prediction
            // static request tests seed markets onto a throwaway snapshot and the
            // live Core resolves every outcome by (re)fetching events.
            if let Value::Dict(m) = &*self {
                if let Some(Value::Str(id)) = m.get("__live_id") {
                    if let Some(cb) = live_set_markets_get() {
                        return cb(&id.clone(), markets);
                    }
                }
            }
            let mut ex = crate::exchange::BaseCore::new(self.snapshot_as_exchange());
            let result = ex.set_markets(markets, &[]);
            crate::runtime::add_element_to_object(self, &Value::Str("markets".to_string()), ex.markets.clone());
            crate::runtime::add_element_to_object(self, &Value::Str("markets_by_id".to_string()), ex.markets_by_id.clone());
            crate::runtime::add_element_to_object(self, &Value::Str("symbols".to_string()), ex.symbols.clone());
            return result;
        }
        #[cfg(not(feature = "transpiled-base"))]
        {
            let _ = markets;
            Value::Null
        }
    }
    /// `side.storeArray(delta)` — insert/update/delete by price (or
    /// by id for the indexed variant). Defined here (rather than next
    /// to `store`) so that derived exchange code which calls
    /// `Value::store_array` on a non-side Value still compiles as a
    /// no-op.
    pub fn store_array(&mut self, delta: Value) {
        if side_kind(self).is_some() { side_store_array(self, delta); }
    }
    pub fn append_to_array(&self, _v: Value) {}

    // ── conversion to / from serde_json ───────────────────────────────────────

    pub fn to_json(&self) -> serde_json::Value {
        match self {
            Value::Null        => serde_json::Value::Null,
            Value::Bool(b)     => serde_json::Value::Bool(*b),
            Value::Int(n)      => serde_json::json!(*n),
            Value::Float(f)    => serde_json::json!(*f),
            Value::Str(s)      => serde_json::Value::String(s.clone()),
            Value::Arr(a)      => serde_json::Value::Array(a.iter().map(Value::to_json).collect()),
            Value::Dict(m)     => {
                // A side marker keeps its entries in the shared side store —
                // serialize as the plain `[[price, amount], …]` array (CCXT's
                // orderbook.bids/asks shape), matching jsonStringify(orderbook)
                // in the other languages rather than exposing the internal side
                // struct. The WS deep-compare unwraps markers itself, so it's
                // unaffected.
                if m.contains_key("__side_id") {
                    let entries = side_entries_view(m);
                    return serde_json::Value::Array(entries.iter().map(Value::to_json).collect());
                }
                // A shared book keeps its scalar meta (nonce/timestamp/…) in the
                // book store and tags itself with internal markers — drop the
                // markers and surface the meta so the serialized book is the
                // clean { bids, asks, timestamp, datetime, nonce, symbol } form.
                let is_book = m.contains_key("__book_id") || m.contains_key("__bookKind");
                let mut obj = serde_json::Map::new();
                for (k, v) in m.iter() {
                    if is_book && matches!(k.as_str(), "__bookKind" | "__book_id" | "_depth") {
                        continue;
                    }
                    obj.insert(k.clone(), v.to_json());
                }
                if let Some(Value::Int(id)) = m.get("__book_id") {
                    for (k, v) in book_meta_snapshot(*id) { obj.insert(k, v.to_json()); }
                }
                // A cache marker keeps its rolling buffer in the shared cache
                // store — surface it under `_data` for serialization.
                if m.contains_key("__cacheKind") {
                    let data = cache_data_snapshot(m);
                    obj.insert("_data".to_string(),
                        serde_json::Value::Array(data.iter().map(Value::to_json).collect()));
                }
                serde_json::Value::Object(obj)
            }
        }
    }

    pub fn from_json(v: &serde_json::Value) -> Self {
        match v {
            serde_json::Value::Null        => Value::Null,
            serde_json::Value::Bool(b)     => Value::Bool(*b),
            serde_json::Value::Number(n)   => {
                if let Some(i) = n.as_i64()  {
                    Value::Int(i)
                } else if n.is_u64() {
                    // Integer in (i64::MAX, u64::MAX] — a large order/trade/
                    // account id. `Value::Int` is i64 and `f64` would round it,
                    // so preserve the exact digits as a string (Go does the
                    // same). CCXT's safe_integer/safe_number read it back as a
                    // number when needed.
                    Value::Str(n.to_string())
                } else if let Some(f) = n.as_f64() {
                    Value::Float(f)
                } else {
                    Value::Null
                }
            }
            serde_json::Value::String(s)   => Value::Str(s.clone()),
            serde_json::Value::Array(a)    => Value::Array(a.iter().map(Value::from_json).collect()),
            serde_json::Value::Object(m)   => Value::Map(
                m.iter().map(|(k, v)| (k.clone(), Value::from_json(v))).collect()
            ),
        }
    }
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Null        => write!(f, "null"),
            Value::Bool(b)     => write!(f, "{b}"),
            Value::Int(n)      => write!(f, "{n}"),
            Value::Float(fl)   => write!(f, "{fl}"),
            Value::Str(s)      => write!(f, "{s}"),
            Value::Arr(a)      => write!(f, "[{} items]", a.len()),
            Value::Dict(m)     => write!(f, "{{{}  keys}}", m.len()),
        }
    }
}

// ── From / Into conversions ───────────────────────────────────────────────────

// Operator overloads so transpiled code's `!x`, `x && y`, `x || y` over
// Value compile. They follow JS-style truthiness on the Value, not value
// equality. Result type is `Value::Bool`.

impl std::ops::Not for Value {
    type Output = Value;
    fn not(self) -> Value { Value::Bool(!self.is_truthy()) }
}

impl std::ops::Not for &Value {
    type Output = Value;
    fn not(self) -> Value { Value::Bool(!self.is_truthy()) }
}

impl std::ops::BitAnd for Value {
    type Output = Value;
    fn bitand(self, rhs: Value) -> Value {
        Value::Bool(self.is_truthy() && rhs.is_truthy())
    }
}

impl std::ops::BitOr for Value {
    type Output = Value;
    fn bitor(self, rhs: Value) -> Value {
        Value::Bool(self.is_truthy() || rhs.is_truthy())
    }
}

impl From<&str>    for Value { fn from(s: &str)   -> Self { Value::Str(s.to_owned()) } }
impl From<String>  for Value { fn from(s: String) -> Self { Value::Str(s) } }
impl From<i64>     for Value { fn from(n: i64)    -> Self { Value::Int(n) } }
impl From<f64>     for Value { fn from(f: f64)    -> Self { Value::Float(f) } }
impl From<bool>    for Value { fn from(b: bool)   -> Self { Value::Bool(b) } }
/// `From<ExchangeError>` makes `error.clone()` flow into `&[Value]`
/// slices without an explicit conversion — surfaces the typed error
/// as a `[Kind] message`-shaped string Value, matching how
/// `runtime::panic_msg_to_error` round-trips it back into a typed
/// `ExchangeError` for the caller.
impl From<crate::ExchangeError> for Value {
    fn from(e: crate::ExchangeError) -> Self {
        Value::Str(format!("[{}] {}", e.kind, e.message))
    }
}
impl From<HashMap<String, Value>> for Value {
    fn from(m: HashMap<String, Value>) -> Self { Value::Map(m) }
}
impl From<Vec<Value>> for Value {
    fn from(a: Vec<Value>) -> Self { Value::Array(a) }
}
impl From<serde_json::Value> for Value {
    fn from(v: serde_json::Value) -> Self { Value::from_json(&v) }
}

// ── Helper free-functions (generated code calls these) ────────────────────────

/// Optional live-snapshot accessor. Installed by `ccxt_tests::live_dispatch`
/// so reads of the heavy fields (`markets`, `markets_by_id`, `symbols`, …)
/// on the test-runner's snapshot don't deep-clone the entire ~4k-entry
/// markets Map on every helper invocation. When `get_value` sees a Map
/// carrying `__live_id`, it consults this callback to resolve the key
/// directly from the cached real `<Id>Core`. Production / non-test code
/// leaves the callback unset and falls through to the normal map lookup.
type LiveLookupFn = fn(id: &str, key: &str) -> Option<Value>;
// Plain atomic-load-style global — `tokio::main` spawns worker threads
// that wouldn't see a `thread_local!` value set in main, so the lookup
// has to be shared across all threads. Stored as a usize because
// `AtomicPtr<fn>` is awkward to express. `fn` pointers are always
// non-null when set; 0 means "not installed".
static LIVE_LOOKUP_PTR: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

pub fn set_live_lookup(f: LiveLookupFn) {
    LIVE_LOOKUP_PTR.store(f as usize, std::sync::atomic::Ordering::Release);
}

fn live_lookup_get() -> Option<LiveLookupFn> {
    let n = LIVE_LOOKUP_PTR.load(std::sync::atomic::Ordering::Acquire);
    if n == 0 { None } else {
        // SAFETY: only ever stored as `fn(&str, &str) -> Option<Value>`
        // via `set_live_lookup`; the pointer-to-fn round-trip is sound.
        Some(unsafe { std::mem::transmute::<usize, LiveLookupFn>(n) })
    }
}

// Companion to `LiveLookupFn` but for writing: routes `exchange.setMarkets(...)`
// on a `__live_id` snapshot to the registered *live* Core, so the Core's
// `PredictionExchange::set_markets` override (outcome aliasing + populateOutcomes)
// runs against the real instance the method dispatch will use. Returns the
// resulting markets. See `Value::set_markets`.
type LiveSetMarketsFn = fn(id: &str, markets: Value) -> Value;
static LIVE_SET_MARKETS_PTR: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

pub fn set_live_set_markets(f: LiveSetMarketsFn) {
    LIVE_SET_MARKETS_PTR.store(f as usize, std::sync::atomic::Ordering::Release);
}

fn live_set_markets_get() -> Option<LiveSetMarketsFn> {
    let n = LIVE_SET_MARKETS_PTR.load(std::sync::atomic::Ordering::Acquire);
    if n == 0 { None } else {
        // SAFETY: only ever stored as `fn(&str, Value) -> Value` via
        // `set_live_set_markets`; the pointer-to-fn round-trip is sound.
        Some(unsafe { std::mem::transmute::<usize, LiveSetMarketsFn>(n) })
    }
}

/// Hot-path `get_value` variant that takes the key as a `&str` directly,
/// skipping a `Value::Str` heap allocation. Used by the `safe_*_k`
/// fast-path readers the transpiler routes literal-key calls through.
#[inline]
pub fn get_value_k(obj: &Value, key: &str) -> Value {
    if let Value::Dict(m) = obj {
        // A shared order book keeps its scalar meta (nonce/timestamp/…) in the
        // book store; route those through it so the safe_* helpers (which go via
        // get_value_k) see the shared value, not the empty Dict slot.
        if is_book_meta_key(key) {
            if let Some(id) = book_id_of(m) { return book_meta_get(id, key); }
        }
        if key == "cache" {
            if let Some(id) = book_id_of(m) { return book_cache_handle(id); }
        }
        if let Some(v) = m.get(key) {
            if !matches!(v, Value::Null) {
                return v.clone();
            }
        }
        if let Some(id_val) = m.get("__live_id") {
            if let (Value::Str(id), Some(cb)) = (id_val, live_lookup_get()) {
                if let Some(v) = cb(id, key) { return v; }
            }
        }
    }
    Value::Null
}

/// Access a value in a map by string key, or array by integer key encoded as
/// a `Value::Str` / `Value::Int`. Returns `Value::Null` on miss.
pub fn get_value(obj: &Value, key: &Value) -> Value {
    // Cache / order-book / side markers expose numeric indexing as if
    // they were arrays — `cache[i]` reads `_data[i]`, `side[i]` reads
    // `_entries[i]`. Handle this before the regular dict lookup so the
    // transpiled `get_value(&cache, &Value::Int(0))` calls reach the
    // right backing buffer.
    // The index may arrive as an Int (`get_value(&side, &Value::Int(0))`) or as
    // a numeric string — the `safe_*` helpers stringify their key, so
    // `safe_value(cache, 0)` reaches here as `Str("0")`. Accept both.
    if let Value::Dict(m) = obj {
        let idx = match key {
            Value::Int(i) if *i >= 0 => Some(*i as usize),
            Value::Str(s) => s.parse::<usize>().ok(),
            _ => None,
        };
        if let Some(i) = idx {
            if let Some(id) = book_cache_id_of(m) {
                return book_cache_at(id, i);
            }
            if m.contains_key("__cacheKind") {
                return cache_at(m, i);
            }
            if m.contains_key("__sideKind") {
                return side_entry_at(m, i);
            }
        }
    }
    match (obj, key) {
        (Value::Dict(m), Value::Str(k)) => {
            // A shared order book keeps its scalar meta (nonce/timestamp/…) in
            // the book store so mutations propagate across clones.
            if is_book_meta_key(k) {
                if let Some(id) = book_id_of(m) { return book_meta_get(id, k); }
            }
            if k == "cache" {
                if let Some(id) = book_id_of(m) { return book_cache_handle(id); }
            }
            // A cache marker's `hashmap` (bucket index) lives in the shared
            // CACHE_STORE cell, not the marker Dict — route the read there so a
            // transpiled `cache.hashmap` sees live bucket state (the base-ws
            // eviction test counts `Object.keys(cache.hashmap)`).
            if k == "hashmap" && m.contains_key("__cacheKind") {
                if let Some(id) = cache_id_of_m(m) {
                    return with_cache_cell(id, |c| c.get("hashmap").cloned().unwrap_or(Value::Null));
                }
                return m.get("hashmap").cloned().unwrap_or(Value::Null);
            }
            // A client handle (`Map{url, subscriptions, futures}`) serves its
            // subscriptions/futures live from the WS registry, so a read after a
            // write (upbit sets subs then reads them back to build its subscribe
            // frame) is coherent rather than a stale embedded snapshot.
            if (k == "subscriptions" || k == "futures")
                && m.contains_key("subscriptions") && m.contains_key("futures")
            {
                if let Some(Value::Str(url)) = m.get("url") {
                    return crate::pro::ws_client::client_field_live(url, k);
                }
            }
            // Snapshot value wins WHEN PRESENT AND NON-NULL. Tests that
            // mutate `exchange.options` (e.g. kucoin broker-id test) need
            // the snapshot view to take precedence; but `to_value`
            // pre-populates heavy fields like `markets` with `Null`
            // before `load_markets` runs, so we still need to fall back
            // to the live-lookup if the snapshot value is null.
            let snapshot_val = m.get(k);
            if let Some(v) = snapshot_val {
                if !matches!(v, Value::Null) {
                    return v.clone();
                }
            }
            if let Some(id_val) = m.get("__live_id") {
                if let (Value::Str(id), Some(cb)) = (id_val, live_lookup_get()) {
                    if let Some(v) = cb(id, k) { return v; }
                }
            }
            Value::Null
        }
        (Value::Arr(a), Value::Int(i)) => a.get(*i as usize).cloned().unwrap_or(Value::Null),
        (Value::Arr(a), Value::Str(k)) => {
            if let Ok(i) = k.parse::<usize>() {
                a.get(i).cloned().unwrap_or(Value::Null)
            } else {
                Value::Null
            }
        }
        // JS string indexing: `s[i]` returns the i-th character as a
        // 1-char string (e.g. bitfinex `amountString[0] === '-'` to detect
        // a negative). Char-based so multi-byte UTF-8 is handled.
        (Value::Str(s), Value::Int(i)) => {
            if *i < 0 {
                return Value::Null;
            }
            match s.chars().nth(*i as usize) {
                Some(c) => Value::Str(c.to_string()),
                None    => Value::Null,
            }
        }
        _ => Value::Null,
    }
}

/// Set a key/index in a map or array value.
pub fn set_value(obj: &mut Value, key: &Value, val: Value) {
    match (obj, key) {
        (Value::Dict(m), Value::Str(k)) => {
            if try_book_meta_write(m, k, &val) { return; }
            // Persist to the live client AND keep the local snapshot coherent so
            // code that reads back what it just wrote (upbit builds its subscribe
            // frame from `object_keys(client.subscriptions)`) sees the new entry.
            try_ws_subs_write(m, k, &val);
            try_ws_sub_field_write(m, k, &val);
            Arc::make_mut(m).insert(k.clone(), val);
        }
        (Value::Arr(a), Value::Int(i)) => {
            let idx = *i as usize;
            let a = Arc::make_mut(a);
            if idx < a.len() { a[idx] = val; }
        }
        _ => {}
    }
}

// ── safeXxx helpers (mirrors Exchange.ts safe helpers) ─────────────────────

pub fn safe_string(obj: &Value, key: &str, default: Option<&str>) -> Option<String> {
    let v = get_value(obj, &Value::Str(key.to_owned()));
    match v {
        Value::Str(s)  => Some(s),
        Value::Int(n)  => Some(n.to_string()),
        Value::Float(f)=> Some(f.to_string()),
        // Booleans are not strings/finite numbers → TS `safeString` returns the
        // default for them (not "true"/"false"), same as lists/dicts.
        Value::Null    => default.map(str::to_owned),
        _              => default.map(str::to_owned),
    }
}

pub fn safe_number(obj: &Value, key: &str, default: Option<f64>) -> Option<f64> {
    let v = get_value(obj, &Value::Str(key.to_owned()));
    match v {
        Value::Float(f) => Some(f),
        Value::Int(n)   => Some(n as f64),
        Value::Str(s)   => s.parse::<f64>().ok().or(default),
        _               => default,
    }
}

pub fn safe_integer(obj: &Value, key: &str, default: Option<i64>) -> Option<i64> {
    let v = get_value(obj, &Value::Str(key.to_owned()));
    match v {
        Value::Int(n)   => Some(n),
        Value::Float(f) => Some(f as i64),
        Value::Str(s)   => s.parse::<i64>().ok().or(default),
        _               => default,
    }
}

pub fn safe_bool(obj: &Value, key: &str, default: Option<bool>) -> Option<bool> {
    let v = get_value(obj, &Value::Str(key.to_owned()));
    match v {
        Value::Bool(b)  => Some(b),
        Value::Int(n)   => Some(n != 0),
        Value::Str(s)   => match s.to_lowercase().as_str() {
            "true" | "1" | "yes" => Some(true),
            "false"| "0" | "no"  => Some(false),
            _                    => default,
        },
        _               => default,
    }
}

/// Recursively merges `src` into `dst`.
/// For map/map overlaps the source fields win (deep extend).
pub fn deep_extend(dst: Value, src: Value) -> Value {
    match (dst, src) {
        (Value::Dict(mut d), Value::Dict(s)) => {
            let dm = Arc::make_mut(&mut d);
            let sm = Arc::try_unwrap(s).unwrap_or_else(|arc| (*arc).clone());
            for (k, v) in sm {
                let entry = dm.shift_remove(&k).unwrap_or(Value::Null);
                dm.insert(k, deep_extend(entry, v));
            }
            Value::Dict(d)
        }
        (_, src) => src,
    }
}

// ────────────────────────────────────────────────────────────────────────────
// WS cache helpers — operate on the `Value::Dict` marker maps produced by
// `crate::pro::cache`. Logic mirrors `ts/src/base/ws/Cache.ts`.
// ────────────────────────────────────────────────────────────────────────────

fn cache_str_field(item: &Value, key: &str) -> Option<String> {
    match item {
        Value::Dict(d) => match d.get(key) {
            // Coerce to the string the TS uses as an object key: exchanges send
            // integer order ids, and JS `byId[1]` / `byId["1"]` are the same slot,
            // so a numeric id must dedupe like its string form (else the bucket
            // lookup and the _data removal disagree and a duplicate row leaks).
            Some(Value::Str(s)) => Some(s.clone()),
            Some(Value::Int(n)) => Some(n.to_string()),
            Some(Value::Float(f)) => Some(f.to_string()),
            Some(Value::Bool(b)) => Some(b.to_string()),
            _ => None,
        },
        _ => None,
    }
}

/// Tag every symbol bucket of a cache hashmap copy with a `__cache_backref`
/// = [cache_id, symbol] so a later `bucket[id] = order` write can be routed
/// back into the shared CACHE_STORE (see `try_cache_hashmap_write`). Mirrors
/// the JS reference semantics where `cache.hashmap[symbol]` is the live row.
fn tag_cache_hashmap_buckets(hm: Value, id: i64) -> Value {
    if let Value::Dict(d) = &hm {
        let mut out: HashMap<String, Value> = HashMap::new();
        for (sym, bucket) in d.iter() {
            if let Value::Dict(bd) = bucket {
                let mut nb: HashMap<String, Value> = (**bd).clone();
                nb.insert(
                    "__cache_backref".to_string(),
                    Value::Arr(std::sync::Arc::new(vec![Value::Int(id), Value::Str(sym.clone())])),
                );
                out.insert(sym.clone(), Value::Dict(std::sync::Arc::new(nb)));
            } else {
                out.insert(sym.clone(), bucket.clone());
            }
        }
        return Value::Dict(std::sync::Arc::new(out));
    }
    hm
}

/// When a transpiled `bucket[key] = item` write lands on a cache-hashmap bucket
/// tagged by `tag_cache_hashmap_buckets`, persist `item` into the shared
/// CACHE_STORE: update `hashmap[symbol][key]` and the matching `_data` row.
/// This is how cross-handler mutations of a cached order (fee/trades
/// accumulation in handleMyTrade, later read by handleOrder) survive Rust's
/// copy-on-write `Value` semantics. Returns true if a write-through happened.
pub(crate) fn try_cache_hashmap_write(bucket: &HashMap<String, Value>, key: &str, item: &Value) -> bool {
    let (id, sym) = match bucket.get("__cache_backref") {
        Some(Value::Arr(a)) => match (a.first(), a.get(1)) {
            (Some(Value::Int(id)), Some(Value::Str(s))) => (*id, s.clone()),
            _ => return false,
        },
        _ => return false,
    };
    with_cache_cell(id, |m| {
        // hashmap[sym][key] = item
        {
            let hm = cache_dict_field_mut(m, "hashmap");
            let b = hm.entry(sym.clone()).or_insert_with(|| Value::Map(HashMap::new()));
            if let Value::Dict(bd) = b {
                Arc::make_mut(bd).insert(key.to_string(), item.clone());
            }
        }
        // update the matching _data row (matched by symbol + id/side == key)
        let data = cache_data_mut(m);
        for x in data.iter_mut() {
            if cache_str_field(x, "symbol").as_deref() == Some(&sym)
                && (cache_str_field(x, "id").as_deref() == Some(key)
                    || cache_str_field(x, "side").as_deref() == Some(key))
            {
                *x = item.clone();
                break;
            }
        }
    });
    true
}

fn cache_kind(v: &Value) -> Option<String> {
    match v {
        Value::Dict(d) => match d.get("__cacheKind") {
            Some(Value::Str(s)) => Some(s.clone()),
            _ => None,
        },
        _ => None,
    }
}

fn cache_max_size(v: &Value) -> Option<usize> {
    match v {
        Value::Dict(d) => match d.get("maxSize") {
            Some(Value::Int(n)) if *n > 0 => Some(*n as usize),
            _ => None,
        },
        _ => None,
    }
}

/// `_data` is the rolling buffer Vec for every cache kind. Returns a
/// mutable handle to the inner Vec by going through `Arc::make_mut`.
fn cache_data_mut(m: &mut HashMap<String, Value>) -> &mut Vec<Value> {
    let entry = m.entry("_data".to_string()).or_insert_with(|| Value::Array(Vec::new()));
    if let Value::Arr(a) = entry {
        return Arc::make_mut(a);
    }
    *entry = Value::Array(Vec::new());
    if let Value::Arr(a) = entry {
        return Arc::make_mut(a);
    }
    unreachable!()
}

fn cache_dict_field_mut<'a>(m: &'a mut HashMap<String, Value>, key: &str) -> &'a mut HashMap<String, Value> {
    let entry = m.entry(key.to_string()).or_insert_with(|| Value::Map(HashMap::new()));
    if let Value::Dict(d) = entry {
        return Arc::make_mut(d);
    }
    *entry = Value::Map(HashMap::new());
    if let Value::Dict(d) = entry {
        return Arc::make_mut(d);
    }
    unreachable!()
}

fn cache_int_field(m: &HashMap<String, Value>, key: &str) -> i64 {
    match m.get(key) { Some(Value::Int(n)) => *n, _ => 0 }
}

fn cache_set_int(m: &mut HashMap<String, Value>, key: &str, value: i64) {
    m.insert(key.to_string(), Value::Int(value));
}

fn cache_bool_field(m: &HashMap<String, Value>, key: &str) -> bool {
    matches!(m.get(key), Some(Value::Bool(true)))
}

fn cache_set_bool(m: &mut HashMap<String, Value>, key: &str, value: bool) {
    m.insert(key.to_string(), Value::Bool(value));
}

// Reset the per-kind bookkeeping that a `clear()` must drop, mirroring the TS
// `ArrayCache` / `ArrayCacheByTimestamp` `clear()` overrides (base/ws/Cache.ts):
// the keyed caches find rows through the hashmap and report new-update counts,
// so a `clear()` that only truncates `_data` leaves the hashmap + counters
// claiming rows that are gone — `getLimit()` then keeps reporting phantom
// updates and the next `append` merges into an orphaned reference. Only fields
// already present are reset (guards the bare-marker fallback path). The caller
// truncates `_data` separately.
fn cache_reset_bookkeeping(state: &mut HashMap<String, Value>) {
    for k in ["hashmap", "_newUpdatesBySymbol", "_seenUpdatesBySymbol", "_seenUpdatesAll",
              "_clearUpdatesBySymbol", "_sizeTracker"] {
        if state.contains_key(k) {
            state.insert(k.to_string(), Value::Map(HashMap::new()));
        }
    }
    if state.contains_key("_allNewUpdates") { cache_set_int(state, "_allNewUpdates", 0); }
    if state.contains_key("_newUpdates") { cache_set_int(state, "_newUpdates", 0); }
    if state.contains_key("_clearAllUpdates") { cache_set_bool(state, "_clearAllUpdates", false); }
    if state.contains_key("_clearUpdates") { cache_set_bool(state, "_clearUpdates", false); }
}

// ── ArrayCache update-counter scopes ────────────────────────────────────────
// The keyed caches (BySymbolById / ByOutcomeById / BySymbolBySide) count the
// distinct second-level keys (id / side) seen since the last poll, kept in TWO
// independent scopes so a symbol-scoped poll and a global poll clear each other
// without interfering (mirrors `seenUpdatesBySymbol` / `seenUpdatesAll` in
// base/ws/Cache.ts). A "set" is a `Map<key2, Bool>` nested under `field[key1]`.

// Apply a pending global-scope clear at the top of `append` (TS `clearAllUpdates`).
fn cache_apply_clear_all(m: &mut HashMap<String, Value>) {
    if cache_bool_field(m, "_clearAllUpdates") {
        cache_set_bool(m, "_clearAllUpdates", false);
        cache_set_int(m, "_allNewUpdates", 0);
        cache_dict_field_mut(m, "_seenUpdatesAll").clear();
    }
}

// Take (and reset) the pending symbol-scoped clear flag for `key1`.
fn cache_take_symbol_clear(m: &mut HashMap<String, Value>, key1: &str) -> bool {
    let cs = cache_dict_field_mut(m, "_clearUpdatesBySymbol");
    if matches!(cs.get(key1), Some(Value::Bool(true))) {
        cs.insert(key1.to_string(), Value::Bool(false));
        true
    } else {
        false
    }
}

// Add `key2` to the seen-set `field[key1]`; returns the resulting set size.
fn cache_seen_add(m: &mut HashMap<String, Value>, field: &str, key1: &str, key2: &str) -> i64 {
    let outer = cache_dict_field_mut(m, field);
    let set = outer.entry(key1.to_string()).or_insert_with(|| Value::Map(HashMap::new()));
    if let Value::Dict(sd) = set {
        let sd = Arc::make_mut(sd);
        sd.insert(key2.to_string(), Value::Bool(true));
        sd.len() as i64
    } else {
        0
    }
}

// Size of the seen-set `field[key1]` (0 if absent).
fn cache_seen_size(m: &mut HashMap<String, Value>, field: &str, key1: &str) -> i64 {
    match cache_dict_field_mut(m, field).get(key1) {
        Some(Value::Dict(sd)) => sd.len() as i64,
        _ => 0,
    }
}

// Empty the seen-set `field[key1]` (leaves the bucket in place).
fn cache_seen_clear(m: &mut HashMap<String, Value>, field: &str, key1: &str) {
    if let Some(Value::Dict(sd)) = cache_dict_field_mut(m, field).get_mut(key1) {
        Arc::make_mut(sd).clear();
    }
}

// Remove `key2` from the seen-set `field[key1]`; returns whether it was present.
// Drops the outer bucket once its set is empty (TS eviction cleanup).
fn cache_seen_remove(m: &mut HashMap<String, Value>, field: &str, key1: &str, key2: &str) -> bool {
    let outer = cache_dict_field_mut(m, field);
    let (removed, empty) = if let Some(Value::Dict(sd)) = outer.get_mut(key1) {
        let sd = Arc::make_mut(sd);
        let removed = sd.shift_remove(key2).is_some();
        (removed, sd.is_empty())
    } else {
        (false, false)
    };
    if empty { outer.shift_remove(key1); }
    removed
}

// ── Shared cache backing store ──────────────────────────────────────────────
// ArrayCache & friends must survive COW clones the way order-book sides do: a
// handler creates a cache, stores a *clone* in `self.ohlcvs[sym][tf]`, appends
// to the local, then re-reads the stored clone to resolve (gate watchOHLCV).
// With the rolling buffer + hashmap + counters kept in the Dict, the clone and
// the local diverge on the first append (Arc::make_mut) and the re-read is
// empty. So hold the whole mutable cache state (`_data`, `hashmap`, counters)
// in a registry keyed by a stable `__cache_id`; every COW clone shares it.
static CACHE_STORE: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, HashMap<String, Value>>>> =
    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static NEXT_CACHE_ID: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);

/// Register a cache's initial mutable state, returning its shared id.
pub(crate) fn alloc_cache_id(initial: HashMap<String, Value>) -> i64 {
    let id = NEXT_CACHE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    CACHE_STORE.lock().unwrap().insert(id, initial);
    id
}

fn cache_id_of(v: &Value) -> Option<i64> {
    match v {
        Value::Dict(d) => match d.get("__cache_id") { Some(Value::Int(n)) => Some(*n), _ => None },
        _ => None,
    }
}
fn cache_id_of_m(m: &HashMap<String, Value>) -> Option<i64> {
    match m.get("__cache_id") { Some(Value::Int(n)) => Some(*n), _ => None }
}

fn with_cache_cell<R>(id: i64, f: impl FnOnce(&mut HashMap<String, Value>) -> R) -> R {
    let mut g = CACHE_STORE.lock().unwrap();
    let cell = g.entry(id).or_insert_with(HashMap::new);
    f(cell)
}

/// Snapshot a cache marker's rolling buffer (from the shared cell if it carries
/// a `__cache_id`, else the inline `_data` field for legacy markers).
fn cache_data_snapshot(m: &HashMap<String, Value>) -> Vec<Value> {
    if let Some(id) = cache_id_of_m(m) {
        return with_cache_cell(id, |c| match c.get("_data") {
            Some(Value::Arr(a)) => (**a).clone(),
            _ => Vec::new(),
        });
    }
    match m.get("_data") { Some(Value::Arr(a)) => (**a).clone(), _ => Vec::new() }
}

fn cache_len_of(m: &HashMap<String, Value>) -> usize {
    if let Some(id) = cache_id_of_m(m) {
        return with_cache_cell(id, |c| match c.get("_data") { Some(Value::Arr(a)) => a.len(), _ => 0 });
    }
    match m.get("_data") { Some(Value::Arr(a)) => a.len(), _ => 0 }
}

fn cache_at(m: &HashMap<String, Value>, i: usize) -> Value {
    if let Some(id) = cache_id_of_m(m) {
        return with_cache_cell(id, |c| match c.get("_data") {
            Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null),
            _ => Value::Null,
        });
    }
    match m.get("_data") { Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null), _ => Value::Null }
}

/// Public: cache buffer length, or None when `m` isn't a cache marker.
pub(crate) fn cache_len_of_marker(m: &HashMap<String, Value>) -> Option<usize> {
    if m.contains_key("__cacheKind") { Some(cache_len_of(m)) } else { None }
}

pub(crate) fn cache_append(target: &mut Value, item: Value) {
    let kind = cache_kind(target).unwrap_or_default();
    let cap = cache_max_size(target);
    if let Some(id) = cache_id_of(target) {
        with_cache_cell(id, |m| cache_append_inner(m, &kind, cap, item));
    } else if let Value::Dict(m_arc) = target {
        let m = Arc::make_mut(m_arc);
        cache_append_inner(m, &kind, cap, item);
    }
}

fn cache_append_inner(m: &mut HashMap<String, Value>, kind: &str, cap: Option<usize>, item: Value) {
    {
        match kind {
            "ArrayCache" => {
                let data = cache_data_mut(m);
                if let Some(cap) = cap { if data.len() == cap { data.remove(0); } }
                data.push(item.clone());
                // Base ArrayCache counts every append (not distinct ids), per scope.
                cache_apply_clear_all(m);
                let sym = cache_str_field(&item, "symbol").unwrap_or_default();
                if cache_take_symbol_clear(m, &sym) {
                    cache_dict_field_mut(m, "_newUpdatesBySymbol").insert(sym.clone(), Value::Int(0));
                }
                {
                    let nubs = cache_dict_field_mut(m, "_newUpdatesBySymbol");
                    let cur = match nubs.get(&sym) { Some(Value::Int(n)) => *n, _ => 0 };
                    nubs.insert(sym, Value::Int(cur + 1));
                }
                let all = cache_int_field(m, "_allNewUpdates");
                cache_set_int(m, "_allNewUpdates", all + 1);
            }
            "ArrayCacheByTimestamp" => {
                let ts_key = match item {
                    Value::Arr(ref a) => match a.first() {
                        Some(Value::Int(n))   => n.to_string(),
                        Some(Value::Float(f)) => f.to_string(),
                        Some(Value::Str(s))   => s.clone(),
                        _ => String::new(),
                    },
                    _ => String::new(),
                };
                let existing_idx = {
                    let hm = cache_dict_field_mut(m, "hashmap");
                    match hm.get(&ts_key) { Some(Value::Int(n)) => Some(*n as usize), _ => None }
                };
                if let Some(idx) = existing_idx {
                    let data = cache_data_mut(m);
                    if idx < data.len() && data[idx] != item { data[idx] = item.clone(); }
                } else {
                    // Evict if at cap; shift hashmap indices down.
                    let evicting = match cap { Some(c) => {
                        let data_len = cache_data_mut(m).len();
                        data_len == c
                    }, None => false };
                    if evicting {
                        let removed = {
                            let data = cache_data_mut(m);
                            if data.is_empty() { Value::Null } else { data.remove(0) }
                        };
                        let removed_key = match &removed {
                            Value::Arr(a) => match a.first() {
                                Some(Value::Int(n))   => n.to_string(),
                                Some(Value::Float(f)) => f.to_string(),
                                Some(Value::Str(s))   => s.clone(),
                                _ => String::new(),
                            },
                            _ => String::new(),
                        };
                        let hm = cache_dict_field_mut(m, "hashmap");
                        hm.shift_remove(&removed_key);
                        for v in hm.values_mut() {
                            if let Value::Int(n) = v { *n = n.saturating_sub(1); }
                        }
                    }
                    let new_idx = {
                        let data = cache_data_mut(m);
                        let i = data.len();
                        data.push(item);
                        i
                    };
                    let hm = cache_dict_field_mut(m, "hashmap");
                    hm.insert(ts_key.clone(), Value::Int(new_idx as i64));
                }
                // size tracker / new updates
                if cache_bool_field(m, "_clearUpdates") {
                    cache_set_bool(m, "_clearUpdates", false);
                    let st = cache_dict_field_mut(m, "_sizeTracker");
                    st.clear();
                }
                {
                    let st = cache_dict_field_mut(m, "_sizeTracker");
                    st.insert(ts_key, Value::Bool(true));
                }
                let st_len = match m.get("_sizeTracker") {
                    Some(Value::Dict(d)) => d.len() as i64,
                    _ => 0,
                };
                cache_set_int(m, "_newUpdates", st_len);
            }
            "ArrayCacheBySymbolById" | "ArrayCacheBySymbolBySide" | "ArrayCacheByOutcomeById" => {
                // ArrayCacheByOutcomeById keys the outer bucket on `outcome` — prediction
                // markets stream several outcomes of one market that can share an order id,
                // so a symbol-keyed lookup would merge two distinct outcomes into one row.
                // The others key on `symbol`. Second level is `id` except BySymbolBySide.
                let key1_name = if kind == "ArrayCacheByOutcomeById" { "outcome" } else { "symbol" };
                let symbol = cache_str_field(&item, key1_name).unwrap_or_default();
                let key2_name = if kind == "ArrayCacheBySymbolBySide" { "side" } else { "id" };
                let key2 = cache_str_field(&item, key2_name).unwrap_or_default();
                let was_duplicate = {
                    let hm = cache_dict_field_mut(m, "hashmap");
                    let bucket = hm.entry(symbol.clone())
                        .or_insert_with(|| Value::Map(HashMap::new()));
                    if let Value::Dict(bd) = bucket {
                        Arc::make_mut(bd);
                    }
                    if let Some(Value::Dict(bd)) = hm.get(&symbol) {
                        bd.contains_key(&key2)
                    } else { false }
                };
                let item_to_store = if was_duplicate {
                    let merged = {
                        let hm = cache_dict_field_mut(m, "hashmap");
                        let bucket = hm.get(&symbol).cloned();
                        let existing = match bucket {
                            Some(Value::Dict(bd)) => bd.get(&key2).cloned(),
                            _ => None,
                        };
                        match (existing, item.clone()) {
                            (Some(Value::Dict(old)), Value::Dict(new_)) => {
                                let mut merged = (*old).clone();
                                for (k, v) in new_.iter() { merged.insert(k.clone(), v.clone()); }
                                Value::Dict(Arc::new(merged))
                            }
                            (_, new_) => new_,
                        }
                    };
                    {
                        let hm = cache_dict_field_mut(m, "hashmap");
                        let bucket = hm.entry(symbol.clone())
                            .or_insert_with(|| Value::Map(HashMap::new()));
                        if let Value::Dict(bd) = bucket {
                            Arc::make_mut(bd).insert(key2.clone(), merged.clone());
                        }
                    }
                    // Remove the existing slot from _data.
                    {
                        let data = cache_data_mut(m);
                        if let Some(pos) = data.iter().position(|x| {
                            cache_str_field(x, key2_name).as_deref() == Some(&key2)
                                && cache_str_field(x, key1_name).as_deref() == Some(&symbol)
                        }) { data.remove(pos); }
                    }
                    merged
                } else {
                    let hm = cache_dict_field_mut(m, "hashmap");
                    let bucket = hm.entry(symbol.clone())
                        .or_insert_with(|| Value::Map(HashMap::new()));
                    if let Value::Dict(bd) = bucket {
                        Arc::make_mut(bd).insert(key2.clone(), item.clone());
                    }
                    item.clone()
                };
                // Evict from front if at cap.
                let evicting = match cap { Some(c) => {
                    cache_data_mut(m).len() == c
                }, None => false };
                if evicting {
                    let removed = {
                        let data = cache_data_mut(m);
                        if data.is_empty() { Value::Null } else { data.remove(0) }
                    };
                    let r_sym = cache_str_field(&removed, key1_name).unwrap_or_default();
                    let r_key2 = cache_str_field(&removed, key2_name).unwrap_or_default();
                    {
                        let hm = cache_dict_field_mut(m, "hashmap");
                        let now_empty = if let Some(Value::Dict(bd)) = hm.get_mut(&r_sym) {
                            let bd = Arc::make_mut(bd);
                            bd.shift_remove(&r_key2);
                            bd.is_empty()
                        } else { false };
                        // Drop the emptied outer bucket, else a stream of short-lived
                        // keys leaks one empty object per key forever (mirrors TS
                        // `delete this.hashmap[deleteKey]` when its last id is gone).
                        if now_empty { hm.shift_remove(&r_sym); }
                    }
                    // The evicted key2 leaves both update scopes; a single-scope
                    // poller never fires the other scope's clear, so decrement the
                    // counts here or they would report the evicted id forever.
                    if cache_seen_remove(m, "_seenUpdatesBySymbol", &r_sym, &r_key2) {
                        let nubs = cache_dict_field_mut(m, "_newUpdatesBySymbol");
                        if let Some(Value::Int(n)) = nubs.get(&r_sym).cloned() {
                            nubs.insert(r_sym.clone(), Value::Int(n - 1));
                        }
                    }
                    if cache_seen_remove(m, "_seenUpdatesAll", &r_sym, &r_key2) {
                        let all = cache_int_field(m, "_allNewUpdates");
                        cache_set_int(m, "_allNewUpdates", all - 1);
                    }
                }
                cache_data_mut(m).push(item_to_store);

                // Keyed caches count the distinct second-level keys (id / side)
                // seen per scope. Mirror ArrayCacheBySymbolById/BySymbolBySide
                // .append (base/ws/Cache.ts): symbol scope and global scope keep
                // independent seen-sets, each cleared only by its own poll.
                cache_apply_clear_all(m);
                if cache_take_symbol_clear(m, &symbol) {
                    cache_seen_clear(m, "_seenUpdatesBySymbol", &symbol);
                }
                let sz = cache_seen_add(m, "_seenUpdatesBySymbol", &symbol, &key2);
                cache_dict_field_mut(m, "_newUpdatesBySymbol").insert(symbol.clone(), Value::Int(sz));
                let before = cache_seen_size(m, "_seenUpdatesAll", &symbol);
                let after = cache_seen_add(m, "_seenUpdatesAll", &symbol, &key2);
                let all = cache_int_field(m, "_allNewUpdates");
                cache_set_int(m, "_allNewUpdates", all + (after - before));
            }
            _ => {}
        }
    }
}


pub(crate) fn cache_get_limit(target: &mut Value, symbol: Value, limit: Value) -> Value {
    let kind = cache_kind(target).unwrap_or_default();
    if let Some(id) = cache_id_of(target) {
        return with_cache_cell(id, |m| cache_get_limit_inner(m, &kind, symbol, limit));
    }
    if let Value::Dict(m_arc) = target {
        let m = Arc::make_mut(m_arc);
        cache_get_limit_inner(m, &kind, symbol, limit)
    } else {
        limit
    }
}

// Mirrors `ArrayCache.getLimit` (base/ws/Cache.ts). A `symbol` arg polls the
// symbol scope and arms its clear; `undefined` (Null) polls the global scope.
// The count is `undefined` only when the key was never seen — then the caller's
// `limit` passes through unclamped.
fn cache_get_limit_inner(m: &mut HashMap<String, Value>, kind: &str, symbol: Value, limit: Value) -> Value {
    {
        // `ArrayCacheByTimestamp` doesn't track per-symbol updates —
        // both `getLimit(undefined, …)` and `getLimit(sym, …)` return
        // `this.newUpdates` and arm a single global `clearUpdates` flag.
        if kind == "ArrayCacheByTimestamp" {
            let v = cache_int_field(m, "_newUpdates");
            cache_set_bool(m, "_clearUpdates", true);
            return match limit {
                Value::Int(l) => Value::Int(v.min(l)),
                _             => Value::Int(v),
            };
        }
        let new_updates_value: Option<i64> = match &symbol {
            Value::Null => {
                cache_set_bool(m, "_clearAllUpdates", true);
                Some(cache_int_field(m, "_allNewUpdates"))
            }
            Value::Str(sym) => {
                let v = match cache_dict_field_mut(m, "_newUpdatesBySymbol").get(sym) {
                    Some(Value::Int(n)) => Some(*n),
                    _ => None,
                };
                cache_dict_field_mut(m, "_clearUpdatesBySymbol")
                    .insert(sym.clone(), Value::Bool(true));
                v
            }
            _ => None,
        };
        match (new_updates_value, &limit) {
            (None,    _)              => limit.clone(),
            (Some(v), Value::Int(l))  => Value::Int(v.min(*l)),
            (Some(v), _)              => Value::Int(v),
        }
    }
}

// ────────────────────────────────────────────────────────────────────────────
// WS order-book helpers — operate on the `Value::Dict` markers from
// `crate::pro::order_book`. Tag layout:
//   * `__bookKind`  ∈ {OrderBook, IndexedOrderBook, CountedOrderBook}
//   * `__sideKind`  ∈ {OrderBookSide, IndexedOrderBookSide,
//                      CountedOrderBookSide}  (carried under `bids`/`asks`)
// ────────────────────────────────────────────────────────────────────────────

fn as_f64(v: &Value) -> f64 {
    match v {
        Value::Float(f) => *f,
        Value::Int(n)   => *n as f64,
        Value::Str(s)   => s.parse().unwrap_or(0.0),
        _ => 0.0,
    }
}

fn book_kind(v: &Value) -> Option<String> {
    match v { Value::Dict(d) => match d.get("__bookKind") {
        Some(Value::Str(s)) => Some(s.clone()), _ => None,
    }, _ => None }
}

// ────────────────────────────────────────────────────────────────────────────
// Shared book scalar-metadata store.
//
// Like side entries, an OrderBook's scalar fields must be shared across clones:
// WS handlers mutate a book pulled out of `self.orderbooks` (a COW clone) and
// expect the write visible on the next message — okx's per-message seqId nonce
// check reads the book's `nonce`, written inside `handle_order_book_message` on
// a clone. These fields live in a store keyed by a stable `__book_id`; bids/asks
// stay in the Dict (their entries are already shared via `__side_id`).
static BOOK_META: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, HashMap<String, Value>>>> =
    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static NEXT_BOOK_ID: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);

/// Scalar book fields that live in the shared meta store (not the Dict).
fn is_book_meta_key(k: &str) -> bool {
    matches!(k, "timestamp" | "datetime" | "nonce" | "symbol" | "checksum")
}

pub(crate) fn alloc_book_id() -> i64 {
    let id = NEXT_BOOK_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    BOOK_META.lock().unwrap().insert(id, HashMap::new());
    id
}

fn book_id_of(m: &HashMap<String, Value>) -> Option<i64> {
    match m.get("__book_id") { Some(Value::Int(n)) => Some(*n), _ => None }
}

fn book_meta_get(id: i64, k: &str) -> Value {
    BOOK_META.lock().unwrap().get(&id).and_then(|m| m.get(k).cloned()).unwrap_or(Value::Null)
}

pub(crate) fn book_meta_set(id: i64, k: &str, v: Value) {
    let mut g = BOOK_META.lock().unwrap();
    g.entry(id).or_default().insert(k.to_string(), v);
}

fn book_meta_snapshot(id: i64) -> Vec<(String, Value)> {
    BOOK_META.lock().unwrap().get(&id)
        .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
        .unwrap_or_default()
}

// A JS `OrderBook` also carries a mutable `cache` array — venues that fetch a
// REST/`req` snapshot buffer live deltas into `orderbook.cache` while the
// snapshot is in flight (binance, htx, …). Like the sides/meta, the cache must
// be shared across clones: `orderbook.cache.push(msg)` transpiles to
// `append_to_array(get_value(&book, "cache"), msg)`, and get_value returns a COW
// clone. So `get_value(book, "cache")` returns a lightweight handle carrying
// `__book_cache_id`, and length/index/append/clear route through this store.
static BOOK_CACHE: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, Vec<Value>>>> =
    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));

/// Build a cache handle for a book id (returned by `get_value(book, "cache")`).
fn book_cache_handle(id: i64) -> Value {
    let mut h = HashMap::new();
    h.insert("__book_cache_id".to_string(), Value::Int(id));
    Value::Dict(Arc::new(h))
}

fn book_cache_id_of(m: &HashMap<String, Value>) -> Option<i64> {
    match m.get("__book_cache_id") { Some(Value::Int(n)) => Some(*n), _ => None }
}

pub(crate) fn book_cache_push(id: i64, v: Value) {
    BOOK_CACHE.lock().unwrap().entry(id).or_default().push(v);
}

fn book_cache_len(id: i64) -> usize {
    BOOK_CACHE.lock().unwrap().get(&id).map(|c| c.len()).unwrap_or(0)
}

/// Length of a cache handle Dict's backing store, or None if `m` isn't a handle.
pub(crate) fn book_cache_len_of(m: &HashMap<String, Value>) -> Option<usize> {
    book_cache_id_of(m).map(book_cache_len)
}

/// If `m` is a tagged live-subscriptions snapshot, apply `client.subscriptions
/// [key] = val` to the live WS client and return true.
pub(crate) fn try_ws_subs_write(m: &HashMap<String, Value>, key: &str, val: &Value) -> bool {
    if key == "__ws_subs_url" { return false; }
    if let Some(Value::Str(url)) = m.get("__ws_subs_url") {
        crate::pro::ws_client::value_subs_insert(url, key, val.clone());
        return true;
    }
    false
}

/// If `m` is a tagged subscription dict (`__ws_sub_ref`), persist a field write
/// `subscription[key] = val` to the live WS client and return true.
pub(crate) fn try_ws_sub_field_write(m: &HashMap<String, Value>, key: &str, val: &Value) -> bool {
    if key == "__ws_sub_ref" { return false; }
    if let Some(Value::Str(subref)) = m.get("__ws_sub_ref") {
        crate::pro::ws_client::value_sub_field_write(subref, key, val.clone());
        return true;
    }
    false
}

/// If `m` is a tagged live-subscriptions snapshot, apply `delete
/// client.subscriptions[key]` to the live WS client and return true.
pub(crate) fn try_ws_subs_remove(m: &HashMap<String, Value>, key: &str) -> bool {
    if let Some(Value::Str(url)) = m.get("__ws_subs_url") {
        crate::pro::ws_client::value_subs_remove(url, key);
        return true;
    }
    false
}

/// If `obj` is a cache handle, push `v` into its store and return true.
pub(crate) fn try_book_cache_push(obj: &Value, v: &Value) -> bool {
    if let Value::Dict(m) = obj {
        if let Some(id) = book_cache_id_of(m) { book_cache_push(id, v.clone()); return true; }
    }
    false
}

fn book_cache_at(id: i64, i: usize) -> Value {
    BOOK_CACHE.lock().unwrap().get(&id).and_then(|c| c.get(i).cloned()).unwrap_or(Value::Null)
}

/// Replace a book's cache contents (from `book.cache = [...]`, usually to clear).
pub(crate) fn book_cache_set(id: i64, items: Vec<Value>) {
    BOOK_CACHE.lock().unwrap().insert(id, items);
}

/// Snapshot a WS cache's rolling buffer as a plain array. Handles both the
/// `_data`-backed ArrayCache / ArrayCacheByTimestamp (trades, ohlcv, tickers)
/// and the registry-backed order-book cache handle. Returns `None` when `v`
/// isn't a cache — `to_array` then falls back to its generic Dict handling.
/// Without this, `to_array(cache)` would surface the cache's meta fields
/// (`__cacheKind`, counters, boolean flags) as if they were entries.
pub fn cache_entries_as_value(v: &Value) -> Option<Value> {
    if let Value::Dict(m) = v {
        if let Some(id) = book_cache_id_of(m) {
            let items = BOOK_CACHE.lock().unwrap().get(&id).cloned().unwrap_or_default();
            return Some(Value::Array(items));
        }
        if m.contains_key("__cacheKind") {
            return Some(Value::Array(cache_data_snapshot(m)));
        }
    }
    None
}

/// If `m` is a shared book and `k` a meta key, write `v` to the book store and
/// return true (the caller should skip its own Dict insert); else false.
pub(crate) fn try_book_meta_write(m: &HashMap<String, Value>, k: &str, v: &Value) -> bool {
    if is_book_meta_key(k) {
        if let Some(id) = book_id_of(m) { book_meta_set(id, k, v.clone()); return true; }
    }
    // `book.cache = [...]` — replace the shared cache store (usually a clear).
    if k == "cache" {
        if let Some(id) = book_id_of(m) {
            let items = match v { Value::Arr(a) => a.as_ref().clone(), _ => Vec::new() };
            book_cache_set(id, items);
            return true;
        }
    }
    false
}

/// Expand a shared book Dict into a plain Dict carrying its meta fields (for
/// serialization / equality). Strips `__book_id` so the result is inert.
pub fn book_fields_as_value(v: &Value) -> Option<Value> {
    match v {
        Value::Dict(d) if d.contains_key("__book_id") => {
            let mut out: HashMap<String, Value> = (**d).clone();
            out.shift_remove("__book_id");
            if let Some(Value::Int(id)) = d.get("__book_id") {
                if let Some(meta) = BOOK_META.lock().unwrap().get(id) {
                    for (k, val) in meta.iter() { out.insert(k.clone(), val.clone()); }
                }
            }
            Some(Value::Dict(Arc::new(out)))
        }
        _ => None,
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Shared side backing store.
//
// In JS an `OrderBookSide` is a mutable object; the WS handlers routinely do
// `const bookside = book['asks']; storeDeltas(bookside, deltas)` where the
// helper mutates `bookside` in place and the change is visible through `book`.
// Our `Value` is copy-on-write (Arc), so cloning the side Dict and mutating the
// clone (the transpiled `handle_deltas(side.clone(), …)` shape) would lose the
// writes. To restore shared mutability we keep the side's `_entries` (and the
// indexed-side `hashmap`) OUTSIDE the Dict, in a global store keyed by a stable
// `__side_id` that survives cloning. All reads and writes go through the store,
// so every clone of a side Dict points at the same buffer — matching JS.
/// One order-book level. The price sort-key is stored inline so the bisect
/// reads it straight from the contiguous `entries` Vec instead of chasing a
/// per-level `Arc<Vec<Value>>` (the scattered-allocation cache cost L1nkus
/// flagged). `entry` keeps the full original level Value (extra columns, string
/// forms) so reads, checksums and serialization stay byte-identical.
struct Level {
    price: f64,   // raw price; the sort key (bids sort on -price)
    entry: Value, // the full [price, amount, …] level as delivered
}
struct SideCell {
    entries: Vec<Level>,
    hashmap: HashMap<String, Value>,
}

static SIDE_STORE: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, SideCell>>> =
    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static NEXT_SIDE_ID: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);

/// Allocate a fresh, empty side cell and return its id.
fn alloc_side_id() -> i64 {
    let id = NEXT_SIDE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    SIDE_STORE.lock().unwrap().insert(id, SideCell { entries: Vec::new(), hashmap: HashMap::new() });
    id
}

/// Clear (but keep) an existing side cell — used on reset so the id stays
/// stable across reseeds instead of leaking a new cell each time.
fn clear_side_cell(id: i64) {
    let mut g = SIDE_STORE.lock().unwrap();
    let cell = g.entry(id).or_insert_with(|| SideCell { entries: Vec::new(), hashmap: HashMap::new() });
    cell.entries.clear();
    cell.hashmap.clear();
}

fn side_id_of(m: &HashMap<String, Value>) -> Option<i64> {
    match m.get("__side_id") { Some(Value::Int(n)) => Some(*n), _ => None }
}

/// Snapshot a side's entries (clone) — for read paths (indexing, length, JSON).
fn side_entries_view(m: &HashMap<String, Value>) -> Vec<Value> {
    match side_id_of(m) {
        Some(id) => SIDE_STORE.lock().unwrap().get(&id)
            .map(|c| c.entries.iter().map(|l| l.entry.clone()).collect()).unwrap_or_default(),
        // Legacy fallback: a side Dict that still carries an inline `_entries`.
        None => match m.get("_entries") { Some(Value::Arr(a)) => a.as_ref().clone(), _ => Vec::new() },
    }
}

fn side_entry_at(m: &HashMap<String, Value>, i: usize) -> Value {
    match side_id_of(m) {
        Some(id) => SIDE_STORE.lock().unwrap().get(&id)
            .and_then(|c| c.entries.get(i).map(|l| l.entry.clone())).unwrap_or(Value::Null),
        None => match m.get("_entries") {
            Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null), _ => Value::Null },
    }
}

pub(crate) fn side_entries_len(m: &HashMap<String, Value>) -> usize {
    match side_id_of(m) {
        Some(id) => SIDE_STORE.lock().unwrap().get(&id).map(|c| c.entries.len()).unwrap_or(0),
        None => match m.get("_entries") { Some(Value::Arr(a)) => a.len(), _ => 0 },
    }
}

/// Mutate a side's cell (entries + hashmap) under the store lock. No-op if the
/// side carries no `__side_id`.
fn with_side_cell<R>(m: &HashMap<String, Value>, f: impl FnOnce(&mut SideCell) -> R) -> Option<R> {
    let id = side_id_of(m)?;
    let mut g = SIDE_STORE.lock().unwrap();
    let cell = g.entry(id).or_insert_with(|| SideCell { entries: Vec::new(), hashmap: HashMap::new() });
    Some(f(cell))
}

/// Public: snapshot a side marker's entries as a `Value` array, or `None` when
/// `v` is not a side marker. Entries live in the shared side store (not the
/// Dict), so callers that need the raw `[[price, size, …], …]` list — test
/// helpers, serializers — go through this.
pub fn side_entries_as_value(v: &Value) -> Option<Value> {
    match v {
        Value::Dict(d) if d.contains_key("__sideKind") => Some(Value::List(side_entries_view(d))),
        _ => None,
    }
}

/// `[price, amount]` for one level row (`Value::Arr`), coercing Str/Int/Float.
/// Returns `None` for a short/non-numeric row so it can be dropped.
fn row_price_amount(row: &Value) -> Option<[f64; 2]> {
    let r = match row { Value::Arr(a) => a, _ => return None };
    let num = |cell: Option<&Value>| -> f64 {
        match cell {
            Some(Value::Float(f)) => *f,
            Some(Value::Int(n)) => *n as f64,
            Some(Value::Str(s)) => s.parse().unwrap_or(f64::NAN),
            _ => f64::NAN,
        }
    };
    let p = num(r.first());
    let a = num(r.get(1));
    if p.is_nan() || a.is_nan() { None } else { Some([p, a]) }
}

/// Read a side marker's levels as `[price, amount]` pairs straight from the
/// shared side store — no intermediate `Value` list is materialised, so the
/// typed `OrderBook::from_value` decode reads the book without cloning every
/// level. Returns `None` when `v` is not a side marker (the caller then reads a
/// plain `Value::Arr`). NaN/short rows are dropped (not valid book levels).
pub fn side_price_amounts(v: &Value) -> Option<Vec<[f64; 2]>> {
    let d = match v {
        Value::Dict(d) if d.contains_key("__sideKind") => d,
        _ => return None,
    };
    let out = match side_id_of(d) {
        Some(id) => match SIDE_STORE.lock().unwrap().get(&id) {
            Some(cell) => cell.entries.iter().filter_map(|l| row_price_amount(&l.entry)).collect(),
            None => Vec::new(),
        },
        None => match d.get("_entries") {
            Some(Value::Arr(a)) => a.iter().filter_map(row_price_amount).collect(),
            _ => Vec::new(),
        },
    };
    Some(out)
}

/// Build a fresh side marker Dict backed by a new (empty) shared cell.
pub(crate) fn make_side_marker(side_kind: &str, is_bid: bool, depth: i64) -> Value {
    let sid = alloc_side_id();
    let mut m = HashMap::new();
    m.insert("__sideKind".to_string(), Value::Str(side_kind.to_string()));
    m.insert("_isBid".to_string(),     Value::Bool(is_bid));
    m.insert("_depth".to_string(),     Value::Int(depth));
    m.insert("__side_id".to_string(),  Value::Int(sid));
    Value::Dict(Arc::new(m))
}

fn side_kind(v: &Value) -> Option<String> {
    match v { Value::Dict(d) => match d.get("__sideKind") {
        Some(Value::Str(s)) => Some(s.clone()), _ => None,
    }, _ => None }
}

fn side_is_bid(m: &HashMap<String, Value>) -> bool {
    matches!(m.get("_isBid"), Some(Value::Bool(true)))
}

fn side_depth(m: &HashMap<String, Value>) -> usize {
    match m.get("_depth") {
        Some(Value::Int(n)) if *n > 0 => *n as usize,
        _ => usize::MAX / 2,
    }
}

fn level_price(entries: &[Level]) -> impl Fn(usize) -> f64 + '_ {
    move |i: usize| entries[i].price
}

fn bisect_left_by(len: usize, target: f64, is_bid: bool, get_price: impl Fn(usize) -> f64) -> usize {
    let mut lo = 0usize;
    let mut hi = len;
    while lo < hi {
        let mid = (lo + hi) / 2;
        let p = get_price(mid);
        let ip = if is_bid { -p } else { p };
        if ip < target { lo = mid + 1; } else { hi = mid; }
    }
    lo
}

fn delta_field<T>(d: &Value, idx: usize, parse: impl Fn(&Value) -> T, default: T) -> T {
    match d {
        Value::Arr(a) => match a.get(idx) { Some(v) => parse(v), None => default },
        _ => default,
    }
}

fn entry_id(entries: &[Level], i: usize) -> String {
    if let Value::Arr(a) = &entries[i].entry {
        if let Some(v) = a.get(2) {
            return match v {
                Value::Str(s) => s.clone(),
                Value::Int(n) => n.to_string(),
                _ => String::new(),
            };
        }
    }
    String::new()
}

fn side_store_array(side: &Value, delta: Value) {
    let kind = side_kind(side).unwrap_or_default();
    let m = match side { Value::Dict(d) => d.as_ref(), _ => return };
    let is_bid = side_is_bid(m);
    with_side_cell(m, |cell| {
    match kind.as_str() {
        "OrderBookSide" => {
            let price = delta_field(&delta, 0, as_f64, 0.0);
            let size  = delta_field(&delta, 1, as_f64, 0.0);
            let target = if is_bid { -price } else { price };
            let entries = &mut cell.entries;
            let idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
            let matches_here = idx < entries.len()
                && (if is_bid { -entries[idx].price } else { entries[idx].price }) == target;
            if size != 0.0 {
                if matches_here {
                    entries[idx] = Level { price, entry: delta };
                } else {
                    entries.insert(idx, Level { price, entry: delta });
                }
            } else if matches_here {
                entries.remove(idx);
            }
        }
        "CountedOrderBookSide" => {
            let price = delta_field(&delta, 0, as_f64, 0.0);
            let size  = delta_field(&delta, 1, as_f64, 0.0);
            let count = delta_field(&delta, 2, as_f64, 0.0);
            // JS gates a counted store on `size && count`, but some venues drive
            // a counted book with no numeric count in slot 2 — bitget stores
            // `[price, size, [rawPrice, rawSize]]` (the raw pair, for checksums).
            // Only treat slot 2 as a count when it's actually a number; otherwise
            // gate on size alone so the entry stores.
            let has_count = matches!(&delta,
                Value::Arr(a) if matches!(a.get(2), Some(Value::Int(_)) | Some(Value::Float(_))));
            let store_it = if has_count { size != 0.0 && count != 0.0 } else { size != 0.0 };
            let target = if is_bid { -price } else { price };
            let entries = &mut cell.entries;
            let idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
            let matches_here = idx < entries.len()
                && (if is_bid { -entries[idx].price } else { entries[idx].price }) == target;
            if store_it {
                if matches_here {
                    entries[idx] = Level { price, entry: delta };
                } else {
                    entries.insert(idx, Level { price, entry: delta });
                }
            } else if matches_here {
                entries.remove(idx);
            }
        }
        "IndexedOrderBookSide" => {
            let price_opt = match &delta {
                Value::Arr(a) => a.first().and_then(|v| match v {
                    Value::Float(f) => Some(*f),
                    Value::Int(n)   => Some(*n as f64),
                    _ => None,
                }),
                _ => None,
            };
            let size = delta_field(&delta, 1, as_f64, 0.0);
            let id = match &delta {
                Value::Arr(a) => match a.get(2) {
                    Some(Value::Str(s)) => s.clone(),
                    Some(Value::Int(n)) => n.to_string(),
                    _ => String::new(),
                },
                _ => String::new(),
            };
            let mut index_price = price_opt.map(|p| if is_bid { -p } else { p });
            let old_price_opt = {
                match cell.hashmap.get(&id) {
                    Some(Value::Float(f)) => Some(*f),
                    Some(Value::Int(n))   => Some(*n as f64),
                    _ => None,
                }
            };
            if size != 0.0 {
                if let Some(old_price) = old_price_opt {
                    index_price = index_price.or(Some(old_price));
                    if Some(old_price) == index_price {
                        // Find slot by walking from bisect_left
                        let target = old_price;
                        let raw = if is_bid { -old_price } else { old_price };
                        let entries = &mut cell.entries;
                        let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
                        while idx < entries.len() && entry_id(entries, idx) != id { idx += 1; }
                        if idx < entries.len() { entries[idx] = Level { price: raw, entry: delta }; }
                        return;
                    }
                    // Different price — remove old slot
                    let target = old_price;
                    let entries = &mut cell.entries;
                    let mut old_idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
                    while old_idx < entries.len() && entry_id(entries, old_idx) != id { old_idx += 1; }
                    if old_idx < entries.len() { entries.remove(old_idx); }
                }
                let target = match index_price { Some(p) => p, None => return };
                let raw = if is_bid { -target } else { target };
                // Insert sorted with secondary id tiebreaker
                let entries = &mut cell.entries;
                let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
                while idx < entries.len() {
                    let ip = if is_bid { -entries[idx].price } else { entries[idx].price };
                    if ip != target { break; }
                    if entry_id(entries, idx) >= id { break; }
                    idx += 1;
                }
                entries.insert(idx, Level { price: raw, entry: delta });
                cell.hashmap.insert(id, Value::Float(target));
            } else if let Some(old_price) = old_price_opt {
                // Delete by id
                let target = old_price;
                let entries = &mut cell.entries;
                let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
                while idx < entries.len() && entry_id(entries, idx) != id { idx += 1; }
                if idx < entries.len() { entries.remove(idx); }
                cell.hashmap.shift_remove(&id);
            }
        }
        _ => {}
    }
    });
}

fn side_limit(side: &Value) {
    let m = match side { Value::Dict(d) => d.as_ref(), _ => return };
    let depth = side_depth(m);
    with_side_cell(m, |cell| {
        if cell.entries.len() > depth { cell.entries.truncate(depth); }
    });
}

fn book_reseed_sides(book: &mut Value, snapshot: &Value) {
    let kind = book_kind(book).unwrap_or_default();
    let side_kind_str = match kind.as_str() {
        "IndexedOrderBook" => "IndexedOrderBookSide",
        "CountedOrderBook" => "CountedOrderBookSide",
        _                  => "OrderBookSide",
    };
    let bids_deltas = crate::get_value(snapshot, &Value::Str("bids".to_string()));
    let asks_deltas = crate::get_value(snapshot, &Value::Str("asks".to_string()));
    if let Value::Dict(book_arc) = book {
        let book_m = Arc::make_mut(book_arc);
        let depth = match book_m.get("_depth") {
            Some(Value::Int(n)) => *n,
            _ => i64::MAX / 2,
        };
        // Rebuild bids/asks. Reuse the existing side's `__side_id` (clearing its
        // backing cell) so repeated resets don't leak a fresh cell each time.
        for (side_key, deltas, is_bid) in [
            ("bids", &bids_deltas, true),
            ("asks", &asks_deltas, false),
        ] {
            let sid = match book_m.get(side_key) {
                Some(Value::Dict(d)) => match d.get("__side_id") {
                    Some(Value::Int(n)) => { clear_side_cell(*n); *n }
                    _ => alloc_side_id(),
                },
                _ => alloc_side_id(),
            };
            let mut m = HashMap::new();
            m.insert("__sideKind".to_string(),  Value::Str(side_kind_str.to_string()));
            m.insert("_isBid".to_string(),      Value::Bool(is_bid));
            m.insert("_depth".to_string(),      Value::Int(depth));
            m.insert("__side_id".to_string(),   Value::Int(sid));
            let side = Value::Map(m);
            if let Value::Arr(rows) = deltas {
                for row in rows.iter() {
                    if let Value::Arr(_) = row { side_store_array(&side, row.clone()); }
                }
            }
            book_m.insert(side_key.to_string(), side);
        }
    }
}

pub(crate) fn book_limit(book: &mut Value) {
    if book_kind(book).is_none() { return; }
    if let Value::Dict(arc) = book {
        let m = Arc::make_mut(arc);
        if let Some(side) = m.get_mut("bids") { side_limit(side); }
        if let Some(side) = m.get_mut("asks") { side_limit(side); }
    }
}

pub(crate) fn book_reset(book: &mut Value, snapshot: Value) {
    if book_kind(book).is_none() { return; }
    book_reseed_sides(book, &snapshot);
    let id = match book { Value::Dict(d) => book_id_of(d), _ => None };
    if let Some(id) = id {
        let ts = match crate::get_value(&snapshot, &Value::Str("timestamp".to_string())) {
            Value::Int(n)   => Some(n),
            Value::Float(f) => Some(f as i64),
            _ => None,
        };
        let dt = ts.and_then(|n| chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n)
            .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)));
        book_meta_set(id, "timestamp", ts.map(Value::Int).unwrap_or(Value::Null));
        book_meta_set(id, "datetime",  dt.map(Value::Str).unwrap_or(Value::Null));
        book_meta_set(id, "nonce",     crate::get_value(&snapshot, &Value::Str("nonce".to_string())));
        book_meta_set(id, "symbol",    crate::get_value(&snapshot, &Value::Str("symbol".to_string())));
    }
}

pub(crate) fn book_update(book: &mut Value, snapshot: Value) {
    if book_kind(book).is_none() { return; }
    // Skip stale updates.
    let new_nonce = match crate::get_value(&snapshot, &Value::Str("nonce".to_string())) {
        Value::Int(n) => Some(n), _ => None,
    };
    let cur_nonce = match book {
        Value::Dict(d) => match book_id_of(d).map(|id| book_meta_get(id, "nonce")) {
            Some(Value::Int(n)) => Some(n), _ => None,
        },
        _ => None,
    };
    if let (Some(n), Some(cur)) = (new_nonce, cur_nonce) {
        if n <= cur { return; }
    }
    book_reset(book, snapshot);
}

pub(crate) fn book_store_array_side(book: &mut Value, side_key: &str, delta: Value) {
    if let Value::Dict(arc) = book {
        let m = Arc::make_mut(arc);
        if let Some(side) = m.get_mut(side_key) {
            side_store_array(side, delta);
        }
    }
}


// ─── Value method API exposed to the transpiled tests ─────────────────────

impl Value {
    /// `book.limit()` — trim both sides to `_depth`. Returns a clone
    /// of `self` so transpiled `return book.limit();` lines still
    /// match the `-> Value` signature.
    pub fn limit(&mut self) -> Value {
        book_limit(self);
        self.clone()
    }

    /// `book.reset(snapshot)` — wipe + reseed bids/asks + metadata.
    /// Returns self for the same reason as `limit()`. A bare
    /// `book.reset()` is also valid (matches the TS `OrderBook` shape);
    /// when called without a snapshot, we just rebind the existing one
    /// (effectively a no-op metadata refresh).
    pub fn reset(&mut self, snapshot: Value) -> Value {
        // `client.reset(error)` — a WS client handle (carries "url") resets its
        // registry entry; everything else is an OrderBook snapshot reset.
        if matches!(&self, Value::Dict(d) if d.contains_key("url") && d.contains_key("subscriptions")) {
            return crate::pro::ws_client::value_reset(self);
        }
        book_reset(self, snapshot);
        self.clone()
    }
    /// Zero-arg `reset()` form used by per-exchange WS code that just
    /// wants to clear the rolling buffers.
    pub fn reset0(&mut self) -> Value {
        book_reset(self, Value::Null);
        self.clone()
    }

    /// `book.update(snapshot)` — same as reset but only when the
    /// supplied nonce moves forward.
    pub fn update(&mut self, snapshot: Value) -> Value {
        book_update(self, snapshot);
        self.clone()
    }

    /// `side.store(price, size)` — convenience that builds a 2-element
    /// delta. Routed through the side's `store_array`. Only useful on a
    /// side marker (returned by `book['bids']`), not the book itself.
    pub fn store(&mut self, price: Value, size: Value) {
        if side_kind(self).is_some() {
            let delta = Value::List(vec![price, size]);
            side_store_array(self, delta);
        }
    }

    /// Book-level side mutators — the transpiler rewrites side-extraction
    /// patterns (`let bids = book['bids']; bids.X(...)`) into calls on
    /// these methods so the mutation reaches the book's actual side
    /// dict rather than a COW-cloned copy of it.
    pub fn store_to_bids(&mut self, price: Value, size: Value) {
        let delta = Value::List(vec![price, size]);
        book_store_array_side(self, "bids", delta);
    }
    pub fn store_to_asks(&mut self, price: Value, size: Value) {
        let delta = Value::List(vec![price, size]);
        book_store_array_side(self, "asks", delta);
    }
    pub fn store_array_to_bids(&mut self, delta: Value) {
        book_store_array_side(self, "bids", delta);
    }
    pub fn store_array_to_asks(&mut self, delta: Value) {
        book_store_array_side(self, "asks", delta);
    }
}

#[cfg(test)]
mod json_int_precision_tests {
    use super::Value;

    #[test]
    fn preserves_large_u64_ids_losslessly() {
        // 12345678901234567890 > i64::MAX but ≤ u64::MAX — must not round.
        let v: serde_json::Value = serde_json::from_str(r#"{"id": 12345678901234567890}"#).unwrap();
        let parsed = Value::from_json(&v);
        let id = crate::runtime::get_value(&parsed, &Value::Str("id".to_string()));
        assert_eq!(id, Value::Str("12345678901234567890".to_string()));
    }

    #[test]
    fn small_ints_stay_ints_floats_stay_floats() {
        let v: serde_json::Value = serde_json::from_str(r#"{"a": 42, "b": -7, "c": 1.5}"#).unwrap();
        let p = Value::from_json(&v);
        assert_eq!(crate::runtime::get_value(&p, &Value::Str("a".to_string())), Value::Int(42));
        assert_eq!(crate::runtime::get_value(&p, &Value::Str("b".to_string())), Value::Int(-7));
        assert_eq!(crate::runtime::get_value(&p, &Value::Str("c".to_string())), Value::Float(1.5));
    }
}