canton-ledger 0.3.1

Async Canton Ledger API client (gRPC): commands, streaming, de-duplication, recovery.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
//! JSON Ledger API client (HTTP).
//!
//! The JSON transport mirrors the gRPC client over Canton's HTTP JSON Ledger
//! API v2: read the version/offset, **submit commands**, read the **active
//! contract set** and **updates** as bounded JSON arrays, and — for a
//! deployment that exposes nothing else — the **package** and **party**
//! reads and writes `canton-admin` offers over gRPC. It shares the SDK error
//! model and the same [`Auth`] as the gRPC client.
//!
//! Values use the Daml-LF JSON encoding: a record is a JSON object keyed by
//! field name, a party is a string, a `TextMap` is a JSON object. Reads return
//! `serde_json::Value` (the M1 dynamic path); typed bindings land in M2.
//!
//! The blocking read endpoints are capped by the node's
//! `http-list-max-elements-limit` and return `413` past it — pass a `limit` (or
//! a bounded offset range). WebSocket streaming for unbounded tails is a
//! separate transport.

use std::sync::Arc;

use canton_auth::TokenProvider;
use canton_core::telemetry::{self, TRANSPORT_JSON};
use canton_core::{Auth, Error, Result};
use canton_proto::com::daml::ledger::api::v2::admin;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

/// A client for the Canton **JSON** Ledger API over HTTP.
#[derive(Clone)]
pub struct JsonClient {
    base_url: String,
    http: reqwest::Client,
    auth: Auth,
    /// Kept for the WebSocket handshake (feature `ws`); the HTTP client bakes
    /// its TLS settings into `http` at `with_tls` time.
    tls: Option<canton_core::TlsConfig>,
    retry: Option<canton_core::RetryConfig>,
    /// The largest WebSocket frame this client will accept, in bytes. Only the
    /// WS lane has a ceiling to raise: `reqwest` puts no limit on an HTTP
    /// response body, so the `POST` lane reads whatever the participant sends.
    max_decoding_message_size: usize,
    /// How long one HTTP attempt may take. Applied per request rather than on
    /// the `reqwest` client, so it holds however the client was built and
    /// whatever order the builders were called in.
    timeout: std::time::Duration,
}

/// How long one JSON request may take before it is abandoned.
///
/// The same 30 seconds the gRPC channel uses, and for the same reason: without
/// it there is no bound at all. `reqwest` applies no timeout unless asked, so a
/// participant that accepts the connection and then stops answering holds the
/// caller's task open for as long as the process runs.
const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Hand-written for the same reason [`Config`]'s is: a base URL can carry
/// credentials in its userinfo (`https://user:secret@host`), and the derived
/// `Debug` printed them verbatim — one `tracing` field holding a client, or one
/// `{:?}` in a log line, was enough.
///
/// The `reqwest` client is left out entirely — `finish_non_exhaustive` says so
/// rather than pretending otherwise — because its internals describe a
/// connection pool, not this client.
///
/// [`Config`]: canton_core::Config
impl std::fmt::Debug for JsonClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JsonClient")
            .field("base_url", &canton_core::redact_url(&self.base_url))
            .field("auth", &self.auth)
            .field("tls", &self.tls)
            .field("retry", &self.retry)
            .field("max_decoding_message_size", &self.max_decoding_message_size)
            .finish_non_exhaustive()
    }
}

#[derive(Deserialize)]
struct VersionResponse {
    version: String,
}

#[derive(Deserialize)]
struct LedgerEndResponse {
    offset: i64,
}

#[derive(Deserialize)]
struct PackagesResponse {
    #[serde(rename = "packageIds", default)]
    package_ids: Vec<String>,
}

#[derive(Deserialize)]
struct PackageStatusResponse {
    #[serde(rename = "packageStatus")]
    package_status: String,
}

#[derive(Deserialize)]
struct ParticipantIdResponse {
    #[serde(rename = "participantId")]
    participant_id: String,
}

/// `PartyDetails` as the JSON Ledger API spells it. Private: what leaves this
/// module is the gRPC message, so a caller switching transports keeps the
/// type as well as the vocabulary.
#[derive(Deserialize, Serialize)]
struct PartyDetailsWire {
    party: String,
    #[serde(
        rename = "isLocal",
        default,
        skip_serializing_if = "std::ops::Not::not"
    )]
    is_local: bool,
    #[serde(
        rename = "localMetadata",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    local_metadata: Option<ObjectMetaWire>,
    #[serde(
        rename = "identityProviderId",
        default,
        skip_serializing_if = "String::is_empty"
    )]
    identity_provider_id: String,
}

#[derive(Deserialize, Serialize, Default)]
struct ObjectMetaWire {
    #[serde(
        rename = "resourceVersion",
        default,
        skip_serializing_if = "String::is_empty"
    )]
    resource_version: String,
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    annotations: std::collections::HashMap<String, String>,
}

impl From<PartyDetailsWire> for admin::PartyDetails {
    fn from(wire: PartyDetailsWire) -> Self {
        admin::PartyDetails {
            party: wire.party,
            is_local: wire.is_local,
            local_metadata: wire.local_metadata.map(|meta| admin::ObjectMeta {
                resource_version: meta.resource_version,
                annotations: meta.annotations,
            }),
            identity_provider_id: wire.identity_provider_id,
        }
    }
}

impl From<&admin::PartyDetails> for PartyDetailsWire {
    fn from(details: &admin::PartyDetails) -> Self {
        PartyDetailsWire {
            party: details.party.clone(),
            is_local: details.is_local,
            local_metadata: details.local_metadata.as_ref().map(|meta| ObjectMetaWire {
                resource_version: meta.resource_version.clone(),
                annotations: meta.annotations.clone(),
            }),
            identity_provider_id: details.identity_provider_id.clone(),
        }
    }
}

#[derive(Deserialize)]
struct ListKnownPartiesResponse {
    #[serde(rename = "partyDetails", default)]
    party_details: Vec<PartyDetailsWire>,
    #[serde(rename = "nextPageToken", default)]
    next_page_token: String,
}

#[derive(Deserialize)]
struct PartiesResponse {
    #[serde(rename = "partyDetails", default)]
    party_details: Vec<PartyDetailsWire>,
}

#[derive(Deserialize)]
struct PartyDetailsResponse {
    #[serde(rename = "partyDetails")]
    party_details: PartyDetailsWire,
}

#[derive(Serialize)]
struct AllocatePartyWire<'a> {
    #[serde(rename = "partyIdHint", skip_serializing_if = "str::is_empty")]
    party_id_hint: &'a str,
    #[serde(rename = "localMetadata", skip_serializing_if = "Option::is_none")]
    local_metadata: Option<ObjectMetaWire>,
    #[serde(rename = "identityProviderId", skip_serializing_if = "str::is_empty")]
    identity_provider_id: &'a str,
    #[serde(rename = "synchronizerId", skip_serializing_if = "str::is_empty")]
    synchronizer_id: &'a str,
    #[serde(rename = "userId", skip_serializing_if = "str::is_empty")]
    user_id: &'a str,
}

#[derive(Serialize)]
struct UpdatePartyDetailsWire {
    #[serde(rename = "partyDetails")]
    party_details: PartyDetailsWire,
    #[serde(rename = "updateMask")]
    update_mask: FieldMaskWire,
}

#[derive(Serialize)]
struct FieldMaskWire {
    paths: Vec<String>,
}

/// What to allocate, for [`JsonClient::allocate_party_with`].
///
/// [`JsonClient::allocate_party`] covers the common case — a hint and nothing
/// else. This is the rest of `POST /v2/parties`: the synchronizer to allocate
/// on (required once the participant is connected to more than one), the user
/// that should be able to act as the new party, an identity provider, and
/// participant-local annotations.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct AllocateParty {
    party_id_hint: String,
    annotations: std::collections::HashMap<String, String>,
    identity_provider_id: String,
    synchronizer_id: String,
    user_id: String,
}

impl AllocateParty {
    /// An allocation with nothing chosen: the participant picks the id.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Suggest the local part of the party id (`<hint>::<fingerprint>`).
    #[must_use]
    pub fn with_hint(mut self, party_id_hint: impl Into<String>) -> Self {
        self.party_id_hint = party_id_hint.into();
        self
    }

    /// Store one participant-local annotation with the party.
    #[must_use]
    pub fn with_annotation(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.annotations.insert(key.into(), value.into());
        self
    }

    /// Manage the party under this identity provider.
    #[must_use]
    pub fn with_identity_provider_id(mut self, identity_provider_id: impl Into<String>) -> Self {
        self.identity_provider_id = identity_provider_id.into();
        self
    }

    /// Allocate on this synchronizer. Optional while the participant is
    /// connected to one; required once it is connected to several.
    #[must_use]
    pub fn with_synchronizer_id(mut self, synchronizer_id: impl Into<String>) -> Self {
        self.synchronizer_id = synchronizer_id.into();
        self
    }

    /// Grant this user the right to act as the new party.
    #[must_use]
    pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
        self.user_id = user_id.into();
        self
    }

    fn wire(&self) -> AllocatePartyWire<'_> {
        AllocatePartyWire {
            party_id_hint: &self.party_id_hint,
            local_metadata: (!self.annotations.is_empty()).then(|| ObjectMetaWire {
                resource_version: String::new(),
                annotations: self.annotations.clone(),
            }),
            identity_provider_id: &self.identity_provider_id,
            synchronizer_id: &self.synchronizer_id,
            user_id: &self.user_id,
        }
    }
}

/// A set of commands to submit over the JSON transport (dynamic path).
///
/// Build with [`JsonCommands::new`] then add commands ([`JsonCommands::add_create`]
/// or [`JsonCommands::add_command`]) and optional metadata. `command_id`
/// defaults to a fresh UUID so ledger-side de-duplication behaves correctly.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JsonCommands {
    command_id: String,
    act_as: Vec<String>,
    commands: Vec<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    user_id: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    read_as: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    workflow_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    synchronizer_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    submission_id: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    disclosed_contracts: Vec<Value>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    package_id_selection_preference: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    deduplication_period: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    min_ledger_time_abs: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    min_ledger_time_rel: Option<Value>,
}

impl JsonCommands {
    /// Start a command set acting as `act_as`, with a generated `command_id`
    /// and no commands yet.
    #[must_use]
    pub fn new(act_as: Vec<String>) -> Self {
        Self {
            command_id: format!("sdk-{}", uuid::Uuid::new_v4()),
            act_as,
            commands: Vec::new(),
            user_id: None,
            read_as: Vec::new(),
            workflow_id: None,
            synchronizer_id: None,
            submission_id: None,
            disclosed_contracts: Vec::new(),
            package_id_selection_preference: Vec::new(),
            deduplication_period: None,
            min_ledger_time_abs: None,
            min_ledger_time_rel: None,
        }
    }

    /// Set an explicit change-ID `command_id` (for exactly-once / de-duplication).
    #[must_use]
    pub fn with_command_id(mut self, command_id: impl Into<String>) -> Self {
        self.command_id = command_id.into();
        self
    }

    /// This command set's complete identity — available before it is sent, and
    /// the only way back to the outcome of a submission whose result was lost.
    #[must_use]
    pub fn change_id(&self) -> crate::ChangeId {
        crate::ChangeId::new(
            self.user_id.clone().unwrap_or_default(),
            self.act_as.clone(),
            self.command_id.clone(),
        )
    }

    /// Set the acting user id (defaults to the one derived from the token).
    #[must_use]
    pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
        self.user_id = Some(user_id.into());
        self
    }

    /// Add read-as parties.
    #[must_use]
    pub fn with_read_as(mut self, read_as: Vec<String>) -> Self {
        self.read_as = read_as;
        self
    }

    /// Set the workflow id.
    #[must_use]
    pub fn with_workflow_id(mut self, workflow_id: impl Into<String>) -> Self {
        self.workflow_id = Some(workflow_id.into());
        self
    }

    /// Pin the submission to a specific synchronizer.
    #[must_use]
    pub fn with_synchronizer_id(mut self, synchronizer_id: impl Into<String>) -> Self {
        self.synchronizer_id = Some(synchronizer_id.into());
        self
    }

    /// Add a `CreateCommand` for `template_id` (`"<pkg>:<Module>:<Entity>"`) with
    /// `create_arguments` in Daml-LF JSON (a record is an object keyed by field).
    #[must_use]
    pub fn add_create(mut self, template_id: impl Into<String>, create_arguments: Value) -> Self {
        // Build the object directly (rather than `json!`) so `create_arguments`
        // is moved in, not cloned.
        let mut create = serde_json::Map::new();
        create.insert("templateId".to_string(), Value::String(template_id.into()));
        create.insert("createArguments".to_string(), create_arguments);
        let mut command = serde_json::Map::new();
        command.insert("CreateCommand".to_string(), Value::Object(create));
        self.commands.push(Value::Object(command));
        self
    }

    /// Add a raw command value (e.g. an `ExerciseCommand`), for shapes the
    /// convenience builders don't cover.
    #[must_use]
    pub fn add_command(mut self, command: Value) -> Self {
        self.commands.push(command);
        self
    }

    /// Set an explicit submission id, to correlate this particular submission
    /// attempt in completions. Defaults to participant-generated.
    #[must_use]
    pub fn with_submission_id(mut self, submission_id: impl Into<String>) -> Self {
        self.submission_id = Some(submission_id.into());
        self
    }

    /// Attach a disclosed contract (raw JSON: `{"templateId": …,
    /// "contractId": …, "createdEventBlob": …, "synchronizerId": …}`, with the
    /// blob obtained from a read with created-event blobs enabled). May be
    /// called repeatedly.
    #[must_use]
    pub fn add_disclosed_contract(mut self, contract: Value) -> Self {
        self.disclosed_contracts.push(contract);
        self
    }

    /// Restrict package selection for interpretation to these package ids
    /// (at most one preference per package name) — the SCU upgrade pin.
    #[must_use]
    pub fn with_package_id_selection_preference(mut self, package_ids: Vec<String>) -> Self {
        self.package_id_selection_preference = package_ids;
        self
    }

    /// Set the de-duplication period (raw JSON, e.g.
    /// `{"DeduplicationDuration": {"value": {"duration": "5s"}}}`), matching
    /// the JSON API's `deduplicationPeriod` encoding.
    #[must_use]
    pub fn with_deduplication_period(mut self, period: Value) -> Self {
        self.deduplication_period = Some(period);
        self
    }

    /// Set the absolute lower bound for the ledger-effective time (raw JSON,
    /// an ISO-8601 timestamp string). Mutually exclusive with
    /// [`Self::with_min_ledger_time_rel`].
    #[must_use]
    pub fn with_min_ledger_time_abs(mut self, time: Value) -> Self {
        self.min_ledger_time_abs = Some(time);
        self
    }

    /// Set the relative lower bound for the ledger-effective time (raw JSON,
    /// a proto duration like `"5s"`). Mutually exclusive with
    /// [`Self::with_min_ledger_time_abs`].
    #[must_use]
    pub fn with_min_ledger_time_rel(mut self, duration: Value) -> Self {
        self.min_ledger_time_rel = Some(duration);
        self
    }
}

/// The response to a successful `submit-and-wait` — the lighter of the two
/// waiting submissions, which reports where the command landed without
/// returning the transaction itself.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct JsonSubmitAndWaitResponse {
    /// The id of the transaction the command produced.
    pub update_id: String,
    /// The offset of the completion.
    pub completion_offset: i64,
}

/// The response to a successful `submit-and-wait-for-transaction`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct JsonSubmitResponse {
    /// The committed transaction.
    pub transaction: JsonTransaction,
}

/// A committed transaction from the JSON transport. Top-level fields are typed;
/// `events` stay as raw JSON (the M1 dynamic path).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct JsonTransaction {
    /// The update id (globally unique).
    pub update_id: String,
    /// The submitter-provided command id (empty if not echoed).
    #[serde(default)]
    pub command_id: String,
    /// The workflow id (empty if unset).
    #[serde(default)]
    pub workflow_id: String,
    /// The ledger offset at which this transaction was committed.
    pub offset: i64,
    /// The synchronizer that sequenced the transaction.
    #[serde(default)]
    pub synchronizer_id: String,
    /// Ledger-effective time (ISO-8601).
    #[serde(default)]
    pub effective_at: String,
    /// Record time (ISO-8601).
    #[serde(default)]
    pub record_time: String,
    /// The events, each a tagged object (`{"CreatedEvent": …}` / `{"ArchivedEvent": …}`).
    #[serde(default)]
    pub events: Vec<Value>,
}

/// The request body for an ACS snapshot at `active_at_offset` (POST and WS).
/// Built through [`crate::request::ActiveContractsRequest`], so the plain and
/// builder-driven methods share one body producer.
fn active_contracts_request(parties: &[String], active_at_offset: i64) -> Value {
    crate::request::ActiveContractsRequest::new(parties.to_vec(), active_at_offset).json_body()
}

/// The request body for updates over `(begin_exclusive, end_inclusive]` (POST
/// and WS); omit `end_inclusive` for an unbounded tail. Built through
/// [`crate::request::UpdatesRequest`] — `LEDGER_EFFECTS`, wildcard filters,
/// reassignments included — the same defaults as the gRPC lane, so both
/// transports yield the same event set for the same query.
fn updates_request(parties: &[String], begin_exclusive: i64, end_inclusive: Option<i64>) -> Value {
    let mut request = crate::request::UpdatesRequest::new(parties.to_vec(), begin_exclusive);
    if let Some(end) = end_inclusive {
        request = request.until(end);
    }
    request.json_body()
}

/// The request body for command completions from `begin_exclusive` (WS).
#[cfg(feature = "ws")]
fn completions_request(parties: &[String], begin_exclusive: i64) -> Value {
    crate::request::CompletionsRequest::new(parties.to_vec(), begin_exclusive).json_body()
}

/// Whether a failed submission is the participant refusing a command it already
/// has: the error id `DUPLICATE_COMMAND`, or the gRPC code `ALREADY_EXISTS`
/// that Canton assigns it (`grpcCodeValue` in a JSON body).
///
/// The HTTP status alone does not say: Canton's JSON lane maps `ALREADY_EXISTS`
/// *and* `ABORTED` to 409, and `PARTICIPANT_BACKPRESSURE` is the latter, so a
/// bare 409 on a retry could be a node that never accepted anything. Nor does
/// the text: a body that merely mentions `DUPLICATE_COMMAND` in a cause string
/// is not the error itself. Anything that is not the duplicate goes back to
/// the retry loop to be classified.
fn is_duplicate_submission(error: &Error) -> bool {
    error
        .error_info()
        .is_some_and(|info| info.reason == "DUPLICATE_COMMAND")
        || error.code() == Some(tonic::Code::AlreadyExists)
}

/// The HTTP client every JSON lane starts from. Redirects are not followed:
/// the requests carry a bearer token and, on a submission, a command body,
/// and a 3xx from the participant's address would have `reqwest` replay both
/// wherever the redirect points. A participant does not redirect; anything
/// that does is answered as the status it sent, which is not retried.
fn http_client_builder() -> reqwest::ClientBuilder {
    reqwest::Client::builder().redirect(reqwest::redirect::Policy::none())
}

/// Add W3C trace-context headers to an outgoing request (a no-op without the
/// `otel` feature, or when no OpenTelemetry context is active).
/// Percent-encode `value` as one path segment or one query value: everything
/// outside RFC 3986's unreserved set is encoded, so a page token carrying `&`
/// or a party id carrying `::` arrives as one value rather than as syntax.
fn encode(value: &str) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(char::from(byte));
            }
            _ => {
                // Writing to a String cannot fail.
                let _ = write!(out, "%{byte:02X}");
            }
        }
    }
    out
}

/// A caller-supplied identifier as a path segment. Empty, or carrying
/// whitespace, is a caller mistake rather than something to encode and send:
/// the participant would answer about a party that does not exist, and the
/// caller would learn only that.
fn segment(kind: &str, value: &str) -> Result<String> {
    if value.is_empty() || value.chars().any(char::is_whitespace) {
        return Err(Error::InvalidRequest(format!(
            "{kind} {value:?} cannot form a path segment"
        )));
    }
    Ok(encode(value))
}

fn with_trace_context(request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
    #[cfg(feature = "otel")]
    {
        let mut headers = reqwest::header::HeaderMap::new();
        canton_core::telemetry::otel::inject_trace_context(&mut headers);
        if !headers.is_empty() {
            return request.headers(headers);
        }
    }
    request
}

/// How much of an error body is kept. The status is the verdict; the body is
/// context for a log line, and a participant (or whatever answers in its
/// place) does not get to size the error the caller stores and prints.
const ERROR_BODY_CAP: usize = 64 * 1024;

/// Validate an HTTP response and deserialize its JSON body, reading at most
/// `cap` bytes of it: the JSON lane's counterpart to the gRPC decoding limit,
/// so a hostile or broken node cannot make the client allocate without bound.
async fn read_json<T: for<'de> Deserialize<'de>>(
    response: reqwest::Response,
    path: &str,
    cap: usize,
) -> Result<T> {
    // Non-2xx carries its status (e.g. `413` past the node's list cap, `401`
    // for a bad token), so callers can branch and retry 5xx/429.
    if !response.status().is_success() {
        let status = response.status().as_u16();
        let body = read_body(response, ERROR_BODY_CAP, path)
            .await
            .unwrap_or_else(|e| format!("<body not read: {e}>"));
        return Err(Error::http_at(status, body, path));
    }
    let body = read_body(response, cap, path).await?;
    // A malformed body is a deserialization error (Error::Json), not a bad request.
    serde_json::from_str::<T>(&body).map_err(Error::from)
}

/// Read a response body, refusing one that declares or grows past `cap`.
/// `reqwest`'s own `text()` reads to the end whatever the size; this reads
/// chunk by chunk and stops at the cap, so the bound holds for a chunked
/// stream with no `Content-Length` as much as for a declared one.
async fn read_body(mut response: reqwest::Response, cap: usize, path: &str) -> Result<String> {
    if let Some(declared) = response
        .content_length()
        .filter(|declared| usize::try_from(*declared).map_or(true, |n| n > cap))
    {
        {
            return Err(Error::UnexpectedResponse(format!(
                "{path} answered with a {declared}-byte body, above the {cap}-byte limit \
                 (raise it with `with_max_decoding_message_size` if it is expected)"
            )));
        }
    }
    let mut buffer: Vec<u8> = Vec::new();
    while let Some(chunk) = response
        .chunk()
        .await
        .map_err(|e| Error::Connection(format!("reading json body from {path} failed: {e}")))?
    {
        if buffer.len() + chunk.len() > cap {
            return Err(Error::UnexpectedResponse(format!(
                "{path} answered with a body above the {cap}-byte limit \
                 (raise it with `with_max_decoding_message_size` if it is expected)"
            )));
        }
        buffer.extend_from_slice(&chunk);
    }
    String::from_utf8(buffer).map_err(|e| {
        Error::UnexpectedResponse(format!(
            "{path} answered with a body that is not UTF-8: {e}"
        ))
    })
}

/// Upgrade an `http://` base URL to `https://` when TLS is configured.
///
/// Both JSON lanes select TLS by URL scheme: `reqwest` for HTTP, and
/// [`ws_url`](crate::ws) (`http`→`ws`, `https`→`wss`) for WebSocket. So a
/// `JsonClient` given an `http://` base URL together with `with_tls` would send
/// plaintext HTTP with the certificates unused and open a `ws://` socket. This
/// normalises the scheme so TLS is actually applied, matching the gRPC channel
/// builder. Detection is case-insensitive; anything not `http://` (already
/// `https://`, or another scheme) is left unchanged.
fn upgrade_base_url_for_tls(base_url: &str) -> String {
    if base_url
        .get(..7)
        .is_some_and(|s| s.eq_ignore_ascii_case("http://"))
    {
        format!("https://{}", &base_url[7..])
    } else {
        base_url.to_string()
    }
}

impl JsonClient {
    /// Create a JSON client for `base_url` (e.g. `http://localhost:3975`), with
    /// no authentication. A trailing slash on `base_url` is tolerated.
    #[must_use]
    pub fn new(base_url: impl Into<String>) -> Self {
        let mut base_url = base_url.into();
        while base_url.ends_with('/') {
            base_url.pop();
        }
        Self {
            base_url,
            http: http_client_builder()
                .build()
                .unwrap_or_else(|_| reqwest::Client::new()),
            auth: Auth::None,
            tls: None,
            retry: None,
            max_decoding_message_size: canton_core::DEFAULT_MAX_DECODING_MESSAGE_SIZE,
            timeout: DEFAULT_TIMEOUT,
        }
    }

    /// Build a client from a local development network exported into the
    /// environment — the JSON counterpart to [`Config::from_env`].
    ///
    /// ```text
    /// eval "$(canton-devkit localnet env demo)"
    /// ```
    ///
    /// reads `CANTON_JSON_LEDGER_API_URL` and the default participant's JWT.
    /// See [`canton_core::localnet`] for the full contract.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] when no JSON endpoint is exported,
    /// naming the variable and the command that produces it. A missing token is
    /// not an error: an unauthenticated LocalNet is a normal target.
    ///
    /// [`Config::from_env`]: canton_core::Config::from_env
    pub fn from_env() -> Result<Self> {
        Self::for_role(None)
    }

    /// The same, for a participant other than the default: `"app-user"`,
    /// `"sv"`, or any role the exporter knows.
    ///
    /// # Errors
    /// As [`Self::from_env`], naming that role's variable.
    pub fn from_env_for(role: &str) -> Result<Self> {
        Self::for_role(Some(role))
    }

    fn for_role(role: Option<&str>) -> Result<Self> {
        use canton_core::localnet;

        let base_url = localnet::json_endpoint(role).ok_or_else(|| {
            let variable = match role {
                None => "CANTON_JSON_LEDGER_API_URL".to_string(),
                Some(role) => format!(
                    "CANTON_{}_JSON_LEDGER_API_URL",
                    role.to_uppercase().replace('-', "_")
                ),
            };
            Error::InvalidRequest(format!(
                "no JSON ledger endpoint in the environment: set {variable}. \
                 A local network exports it with `canton-devkit localnet env <instance>`; \
                 run that through `eval` first."
            ))
        })?;
        let client = Self::new(base_url);
        Ok(match localnet::token(role) {
            Some(token) => client.with_token(token),
            None => client,
        })
    }

    /// How long one HTTP attempt may take (default 30s), the JSON lane's
    /// counterpart to [`Config::with_timeout`].
    ///
    /// `reqwest` imposes no timeout of its own, so without this a request to a
    /// participant that accepts the connection and then goes quiet never
    /// returns. Applied per attempt: under [`Self::with_retry`] each try gets
    /// the full budget, matching how the gRPC channel's timeout composes with
    /// its retries.
    ///
    /// The clock covers the whole exchange — connecting, sending, and reading
    /// the response body — so it is a real bound rather than a bound on the
    /// first byte.
    ///
    /// [`Config::with_timeout`]: canton_core::Config::with_timeout
    #[must_use]
    pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// The largest WebSocket message this client will accept, in bytes —
    /// the JSON lane's counterpart to [`Config::with_max_decoding_message_size`],
    /// and the same default.
    ///
    /// A WS stream carries the same payloads the gRPC one does, so it needs the
    /// same ceiling. Left alone, `tungstenite` applies its own: 64 MiB per
    /// message and **16 MiB per frame**, the second of which is the one a large
    /// update meets first. Both are set from this value, so a frame is capped
    /// only by what the caller asked for.
    ///
    /// Does not affect the HTTP (`POST`) lane, which has no ceiling to raise.
    ///
    /// [`Config::with_max_decoding_message_size`]: canton_core::Config::with_max_decoding_message_size
    #[must_use]
    pub fn with_max_decoding_message_size(mut self, bytes: usize) -> Self {
        self.max_decoding_message_size = bytes;
        self
    }

    /// Retry requests on retriable errors (category-first classification of
    /// the participant's error body, transient HTTP statuses, connection
    /// failures) with exponential backoff, honouring a server-recommended
    /// retry delay — the same policy as the gRPC client's unary retries.
    /// Off by default. Safe for command submission too: the command id in
    /// the body stays fixed across attempts, so the participant de-duplicates.
    /// Streaming (the WS lane) resumes via its own reconnect policy instead.
    #[must_use]
    pub fn with_retry(mut self, retry: canton_core::RetryConfig) -> Self {
        self.retry = Some(retry);
        self
    }

    /// Use TLS for the HTTP connection: a custom CA (server-side TLS against a
    /// private/self-signed server) and/or a client identity (mutual TLS). This
    /// is a terminal builder step — call it last, after [`Self::with_token`] /
    /// [`Self::with_oidc`].
    ///
    /// An `http://` base URL is normalised to `https://` so TLS is never
    /// silently downgraded: `reqwest` selects TLS from the URL scheme (not from
    /// the configured certificates), and the WebSocket lane maps `http`→`ws` /
    /// `https`→`wss` the same way, so an `http://` base URL with `with_tls`
    /// would otherwise send plaintext HTTP and open a `ws://` socket with the
    /// certificates unused. Detection is case-insensitive, mirroring the gRPC
    /// channel builder (`canton-core`'s `resolve_endpoint`).
    ///
    /// `TlsConfig::domain_name` is not applied here: `reqwest` derives SNI
    /// from the request URL (it is a gRPC/`tonic` knob).
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] if a certificate/identity PEM is
    /// invalid or the HTTPS client cannot be built.
    pub fn with_tls(mut self, tls: &canton_core::TlsConfig) -> Result<Self> {
        let mut builder = http_client_builder();
        if let Some(ca) = &tls.ca_certificate_pem {
            let cert = reqwest::Certificate::from_pem(ca)
                .map_err(|e| Error::InvalidRequest(format!("invalid CA certificate: {e}")))?;
            builder = builder.add_root_certificate(cert);
        }
        if let Some((cert, key)) = &tls.client_identity_pem {
            // reqwest/rustls expects one PEM blob: certificate chain then key.
            let mut pem = cert.clone();
            pem.push(b'\n');
            pem.extend_from_slice(key);
            let identity = reqwest::Identity::from_pem(&pem)
                .map_err(|e| Error::InvalidRequest(format!("invalid client identity: {e}")))?;
            builder = builder.identity(identity);
        }
        self.http = builder
            .build()
            .map_err(|e| Error::InvalidRequest(format!("building the HTTPS client failed: {e}")))?;
        self.base_url = upgrade_base_url_for_tls(&self.base_url);
        self.tls = Some(tls.clone());
        Ok(self)
    }

    /// Authenticate with a fixed bearer token.
    #[must_use]
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.auth = Auth::Static(token.into());
        self
    }

    /// Authenticate with an OIDC token provider (client-credentials, auto-refresh).
    #[must_use]
    pub fn with_oidc(mut self, provider: TokenProvider) -> Self {
        self.auth = Auth::Dynamic(Arc::new(provider));
        self
    }

    /// The WS lane's view of this client. One place, so a setting added to the
    /// transport reaches every subscription rather than the ones someone
    /// remembered.
    #[cfg(feature = "ws")]
    fn ws_transport(&self) -> crate::ws::WsTransport<'_> {
        crate::ws::WsTransport {
            base_url: &self.base_url,
            auth: &self.auth,
            tls: self.tls.as_ref(),
            max_decoding_message_size: self.max_decoding_message_size,
            timeout: self.timeout,
        }
    }

    async fn get<T: for<'de> Deserialize<'de>>(&self, path: &str) -> Result<T> {
        canton_core::retry::run_with_retry(self.retry.as_ref(), || async {
            let mut request = self
                .http
                .get(format!("{}{path}", self.base_url))
                .timeout(self.timeout);
            if let Some(token) = self.auth.bearer().await? {
                request = request.bearer_auth(token);
            }
            request = with_trace_context(request);
            let response = request
                .send()
                .await
                .map_err(|e| transport_error(path, &e))?;
            read_json(response, path, self.max_decoding_message_size).await
        })
        .await
    }

    async fn post<B: Serialize, T: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        canton_core::retry::run_with_retry(self.retry.as_ref(), || self.post_once(path, body)).await
    }

    /// One POST, no retry. The retrying wrappers are built on this so that a
    /// submission can tell its own retries apart from its first attempt.
    async fn post_once<B: Serialize, T: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let mut request = self
            .http
            .post(format!("{}{path}", self.base_url))
            .timeout(self.timeout)
            .json(body);
        if let Some(token) = self.auth.bearer().await? {
            request = request.bearer_auth(token);
        }
        request = with_trace_context(request);
        // main's structure (one-shot core under the retrying wrapper) with this
        // branch's transport classification instead of a blanket Connection.
        let response = request
            .send()
            .await
            .map_err(|e| transport_error(path, &e))?;
        read_json(response, path, self.max_decoding_message_size).await
    }

    /// One PATCH, no retry: the callers are mutations whose lost response the
    /// caller resolves by reading back, not by sending again.
    async fn patch_once<B: Serialize, T: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let mut request = self
            .http
            .patch(format!("{}{path}", self.base_url))
            .timeout(self.timeout)
            .json(body);
        if let Some(token) = self.auth.bearer().await? {
            request = request.bearer_auth(token);
        }
        request = with_trace_context(request);
        let response = request
            .send()
            .await
            .map_err(|e| transport_error(path, &e))?;
        read_json(response, path, self.max_decoding_message_size).await
    }

    /// The participant's Ledger API version (`GET /v2/version`, unauthenticated).
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails or the response is malformed.
    pub async fn version(&self) -> Result<String> {
        telemetry::instrument("version", TRANSPORT_JSON, async {
            Ok(self.get::<VersionResponse>("/v2/version").await?.version)
        })
        .await
    }

    /// The current ledger end offset (`GET /v2/state/ledger-end`, authenticated).
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails.
    pub async fn ledger_end(&self) -> Result<i64> {
        telemetry::instrument("ledger_end", TRANSPORT_JSON, async {
            Ok(self
                .get::<LedgerEndResponse>("/v2/state/ledger-end")
                .await?
                .offset)
        })
        .await
    }

    /// The ids of every package the participant knows (`GET /v2/packages`).
    ///
    /// The JSON twin of `canton-admin`'s `AdminClient::list_packages`,
    /// for a deployment that exposes only the JSON Ledger API. What a package
    /// *is* to the ledger — uploaded, vetted, both — is answered by
    /// [`package_status`](Self::package_status), not by presence in this list.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails.
    pub async fn list_packages(&self) -> Result<Vec<String>> {
        telemetry::instrument("list_packages", TRANSPORT_JSON, async {
            Ok(self
                .get::<PackagesResponse>("/v2/packages")
                .await?
                .package_ids)
        })
        .await
    }

    /// Whether the participant has a package registered
    /// (`GET /v2/packages/{package-id}/status`).
    ///
    /// Answers with the same [`PackageStatus`](canton_proto::com::daml::ledger::api::v2::PackageStatus)
    /// the gRPC path returns, so a caller can switch transports without
    /// re-learning the vocabulary. A status this build does not know is an
    /// [`Error::UnexpectedResponse`] rather than a silent
    /// `PACKAGE_STATUS_UNSPECIFIED`: the participant said something definite,
    /// and guessing would hide it.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] if `package_id` is empty or could not
    /// form a path segment, and an [`Error`] if authentication or the request
    /// fails or the status is not one this build knows.
    pub async fn package_status(
        &self,
        package_id: &str,
    ) -> Result<canton_proto::com::daml::ledger::api::v2::PackageStatus> {
        use canton_proto::com::daml::ledger::api::v2::PackageStatus;

        // The id becomes a path segment. A package id is a hex hash, so
        // anything that would change the path's shape is a caller mistake,
        // not something to escape and send.
        if package_id.is_empty()
            || package_id
                .chars()
                .any(|c| matches!(c, '/' | '?' | '#' | '%') || c.is_whitespace())
        {
            return Err(Error::InvalidRequest(format!(
                "package id {package_id:?} cannot form a path segment"
            )));
        }
        let path = format!("/v2/packages/{package_id}/status");
        telemetry::instrument("package_status", TRANSPORT_JSON, async {
            let status = self
                .get::<PackageStatusResponse>(&path)
                .await?
                .package_status;
            PackageStatus::from_str_name(&status).ok_or_else(|| {
                Error::UnexpectedResponse(format!(
                    "package status {status:?} is not one this build knows"
                ))
            })
        })
        .await
    }

    /// The participant's own identifier (`GET /v2/parties/participant-id`).
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails.
    pub async fn participant_id(&self) -> Result<String> {
        telemetry::instrument("participant_id", TRANSPORT_JSON, async {
            Ok(self
                .get::<ParticipantIdResponse>("/v2/parties/participant-id")
                .await?
                .participant_id)
        })
        .await
    }

    /// One page of the parties the participant knows (`GET /v2/parties`).
    /// Pass the returned token to fetch the next page; `page_size` `0` uses
    /// the server default.
    ///
    /// Answers with the same [`PartyDetails`](admin::PartyDetails) the gRPC
    /// path returns. Requires `ParticipantAdmin` or an identity-provider
    /// admin, as the gRPC call does; a plain user is refused.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails.
    pub async fn list_known_parties_page(
        &self,
        page_size: i32,
        page_token: Option<String>,
    ) -> Result<(Vec<admin::PartyDetails>, Option<String>)> {
        use std::fmt::Write as _;
        let mut path = String::from("/v2/parties");
        let mut separator = '?';
        if page_size > 0 {
            // Writing to a String cannot fail.
            let _ = write!(path, "{separator}pageSize={page_size}");
            separator = '&';
        }
        if let Some(token) = page_token.as_deref().filter(|t| !t.is_empty()) {
            let _ = write!(path, "{separator}pageToken={}", encode(token));
        }
        telemetry::instrument("list_known_parties_page", TRANSPORT_JSON, async {
            let response = self.get::<ListKnownPartiesResponse>(&path).await?;
            let next = (!response.next_page_token.is_empty()).then_some(response.next_page_token);
            Ok((
                response.party_details.into_iter().map(Into::into).collect(),
                next,
            ))
        })
        .await
    }

    /// Every party the participant knows, following pagination internally
    /// (`GET /v2/parties`).
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or any page request fails, and
    /// [`Error::UnexpectedResponse`] if the participant repeats a page token —
    /// the list would be a prefix that looks complete, so it fails instead.
    pub async fn list_known_parties(&self) -> Result<Vec<admin::PartyDetails>> {
        telemetry::instrument("list_known_parties", TRANSPORT_JSON, async {
            let mut all = Vec::new();
            let mut page_token: Option<String> = None;
            let mut seen = std::collections::HashSet::new();
            for page in 1.. {
                let (parties, next) = self.list_known_parties_page(0, page_token.clone()).await?;
                all.extend(parties);
                let Some(next) = next else {
                    break;
                };
                // A server that never advances the token, cycles between a
                // few, or mints a fresh one forever would have this loop run
                // until memory ran out. Stopping quietly is no better: the
                // caller would receive a prefix of the party list with nothing
                // to say it is a prefix, and "which parties exist" is a
                // question whose wrong answer looks exactly like a right one.
                // So a token seen before, or more pages than any participant
                // has, fails.
                if !seen.insert(next.clone()) {
                    return Err(Error::UnexpectedResponse(format!(
                        "the participant repeated a page token after {} parties; \
                         the list is incomplete and cannot be continued",
                        all.len()
                    )));
                }
                if page >= canton_core::MAX_LIST_PAGES {
                    return Err(Error::UnexpectedResponse(format!(
                        "the party listing did not end after {} pages and {} parties; \
                         the list is incomplete and cannot be continued",
                        canton_core::MAX_LIST_PAGES,
                        all.len()
                    )));
                }
                page_token = Some(next);
            }
            Ok(all)
        })
        .await
    }

    /// Details for specific parties (`GET /v2/parties/{party}`, the rest as
    /// `?parties=`). Unknown parties are omitted from the result rather than
    /// erroring, as over gRPC. A plain user may only ask about parties it can
    /// act or read as; anything else is refused by the participant.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] if `parties` is empty or one of them
    /// cannot form a path segment, and an [`Error`] if authentication or the
    /// request fails.
    pub async fn get_parties(&self, parties: Vec<String>) -> Result<Vec<admin::PartyDetails>> {
        use std::fmt::Write as _;
        let Some((first, rest)) = parties.split_first() else {
            return Err(Error::InvalidRequest(
                "get_parties needs at least one party".to_string(),
            ));
        };
        let mut path = format!("/v2/parties/{}", segment("party", first)?);
        for (i, party) in rest.iter().enumerate() {
            let separator = if i == 0 { '?' } else { '&' };
            // Writing to a String cannot fail.
            let _ = write!(path, "{separator}parties={}", segment("party", party)?);
        }
        telemetry::instrument("get_parties", TRANSPORT_JSON, async {
            Ok(self
                .get::<PartiesResponse>(&path)
                .await?
                .party_details
                .into_iter()
                .map(Into::into)
                .collect())
        })
        .await
    }

    /// Allocate a party (`POST /v2/parties`). `party_id_hint` suggests the
    /// local part of the id; the participant returns the actual
    /// [`PartyDetails`](admin::PartyDetails) (`party = "<hint>::<fingerprint>"`).
    ///
    /// The same call as `canton-admin`'s `allocate_party`, over JSON. For the
    /// rest of the request — synchronizer, user, annotations — see
    /// [`allocate_party_with`](Self::allocate_party_with).
    ///
    /// Requires the `ParticipantAdmin` right. Not retried: allocation is a
    /// non-idempotent topology mutation, so a transient failure surfaces to
    /// the caller rather than risking two parties.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or authorization fails, or the
    /// request fails.
    pub async fn allocate_party(&self, party_id_hint: Option<&str>) -> Result<admin::PartyDetails> {
        let mut request = AllocateParty::new();
        if let Some(hint) = party_id_hint {
            request = request.with_hint(hint);
        }
        self.allocate_party_with(&request).await
    }

    /// Allocate a party with the full request (`POST /v2/parties`).
    ///
    /// # Errors
    /// As [`allocate_party`](Self::allocate_party).
    pub async fn allocate_party_with(
        &self,
        request: &AllocateParty,
    ) -> Result<admin::PartyDetails> {
        telemetry::instrument("allocate_party", TRANSPORT_JSON, async {
            Ok(self
                .post_once::<_, PartyDetailsResponse>("/v2/parties", &request.wire())
                .await?
                .party_details
                .into())
        })
        .await
    }

    /// Update the participant-local details of a party
    /// (`PATCH /v2/parties/{party}`).
    ///
    /// `update_paths` is the field mask — which of `details` to apply, in the
    /// gRPC message's spelling: `local_metadata.annotations`, or
    /// `local_metadata` for all of it. To remove an annotation, send its key
    /// with an empty value. Carrying `resource_version` from a read makes the
    /// update conditional on nobody having changed the party since: a stale
    /// version is refused with a 409 (`CONCURRENT_PARTY_DETAILS_UPDATE_DETECTED`)
    /// the participant classifies as contention, so [`Error::is_retriable`]
    /// is true and the right move is to read again and update again.
    ///
    /// Not retried, for the reason [`allocate_party`](Self::allocate_party)
    /// gives: a lost response is resolved by reading the party back.
    ///
    /// # Errors
    /// Returns [`Error::InvalidRequest`] if `update_paths` is empty — the
    /// participant refuses an empty mask, and this says so before the trip —
    /// or the party cannot form a path segment; an [`Error`] if authentication
    /// or authorization fails, the request fails, or the participant reports a
    /// concurrent change.
    pub async fn update_party_details(
        &self,
        details: &admin::PartyDetails,
        update_paths: &[&str],
    ) -> Result<admin::PartyDetails> {
        if update_paths.is_empty() {
            return Err(Error::InvalidRequest(
                "update_party_details needs at least one update path".to_string(),
            ));
        }
        let path = format!("/v2/parties/{}", segment("party", &details.party)?);
        let body = UpdatePartyDetailsWire {
            party_details: details.into(),
            update_mask: FieldMaskWire {
                paths: update_paths.iter().map(|p| (*p).to_string()).collect(),
            },
        };
        telemetry::instrument("update_party_details", TRANSPORT_JSON, async {
            Ok(self
                .patch_once::<_, PartyDetailsResponse>(&path, &body)
                .await?
                .party_details
                .into())
        })
        .await
    }

    /// Submit commands and wait for the resulting transaction
    /// (`POST /v2/commands/submit-and-wait-for-transaction`).
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication fails, the command is rejected
    /// (surfaced as [`Error::Http`] carrying the participant's error body), or
    /// the response is malformed.
    pub async fn submit_and_wait_for_transaction(
        &self,
        commands: &JsonCommands,
    ) -> Result<JsonSubmitResponse> {
        telemetry::instrument("submit_and_wait_for_transaction", TRANSPORT_JSON, async {
            let body = json!({ "commands": commands });
            self.post("/v2/commands/submit-and-wait-for-transaction", &body)
                .await
        })
        .await
    }

    /// Submit **without waiting** (`POST /v2/commands/async/submit`): the
    /// participant accepts the command and the outcome arrives on the
    /// completion stream.
    ///
    /// The gRPC lane has had this since M1. Note what a failure here means: the
    /// command may still have committed, so reach for
    /// [`Self::submission`] rather than this method when losing the outcome is
    /// not acceptable.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication fails or the participant rejects
    /// the submission ([`Error::Http`] with its error body).
    pub async fn submit(&self, commands: &JsonCommands) -> Result<()> {
        telemetry::instrument("submit", TRANSPORT_JSON, async {
            // These two endpoints take the command set *itself* as the body,
            // where `submit-and-wait-for-transaction` takes a request object
            // wrapping it. The participant rejects the wrong one with a 400
            // naming the fields it could not find.
            // The response body is an empty object; accepting it is the answer.
            self.post_submission("/v2/commands/async/submit", commands)
                .await
        })
        .await
    }

    /// `post`, with the one rule a submission needs that a read does not: a
    /// retry the participant refuses as a duplicate means our *own* earlier
    /// attempt was accepted and its response was lost, so the command
    /// succeeded. Reporting the rejection would tell the caller their command
    /// failed when it did the opposite — which is the failure this change ID
    /// exists to prevent, and it is not the JSON lane's to have differently
    /// from gRPC.
    async fn post_submission<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
        let attempt = std::sync::atomic::AtomicU32::new(0);
        canton_core::retry::run_with_retry(self.retry.as_ref(), || async {
            let retry = attempt.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 0;
            match self.post_once::<B, serde_json::Value>(path, body).await {
                Ok(_) => Ok(()),
                Err(error) if retry && is_duplicate_submission(&error) => {
                    tracing::debug!(
                        "submission retry was de-duplicated; the earlier attempt is the one that landed"
                    );
                    Ok(())
                }
                Err(error) => Err(error),
            }
        })
        .await
    }

    /// Submit and wait for the completion (`POST /v2/commands/submit-and-wait`)
    /// without fetching the transaction — the update id and completion offset.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication fails or the command is rejected.
    pub async fn submit_and_wait(
        &self,
        commands: &JsonCommands,
    ) -> Result<JsonSubmitAndWaitResponse> {
        telemetry::instrument("submit_and_wait", TRANSPORT_JSON, async {
            self.post("/v2/commands/submit-and-wait", commands).await
        })
        .await
    }

    /// The create and consuming-exercise events of one contract
    /// (`POST /v2/events/events-by-contract-id`), as seen by `parties`.
    ///
    /// Returns the raw response object; a contract that has been pruned or is
    /// invisible to `parties` comes back as a `CONTRACT_EVENTS_NOT_FOUND`
    /// error rather than an empty result.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails, or the
    /// contract has no events visible to `parties`.
    pub async fn events_by_contract_id(
        &self,
        contract_id: impl Into<String>,
        parties: Vec<String>,
    ) -> Result<Value> {
        telemetry::instrument("events_by_contract_id", TRANSPORT_JSON, async {
            let request = crate::request::ActiveContractsRequest::new(parties, 0);
            let body = json!({
                "contractId": contract_id.into(),
                "eventFormat": request.json_body()["eventFormat"],
            });
            self.post("/v2/events/events-by-contract-id", &body).await
        })
        .await
    }

    /// Fix a submission's identity **before** sending it, returning a
    /// [`JsonSubmission`](crate::JsonSubmission) that carries its
    /// [`ChangeId`](crate::ChangeId) — the JSON lane's
    /// [`CantonClient::submission`](crate::CantonClient::submission).
    #[must_use]
    pub fn submission(&self, commands: JsonCommands) -> crate::submission::JsonSubmission {
        crate::submission::JsonSubmission::new(self.clone(), commands)
    }

    /// The active contract set snapshot at `active_at_offset`, wildcard-filtered
    /// to `parties` (`POST /v2/state/active-contracts`).
    ///
    /// This is a **bounded** read: the node caps results at
    /// `http-list-max-elements-limit` and returns [`Error::Http`] `413` past it,
    /// so pass a `limit` for large sets (or use the streaming transport).
    /// Each element is raw JSON (`{"workflowId": …, "contractEntry": …}`).
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails, or the
    /// result set exceeds the node limit (`413`).
    pub async fn active_contracts(
        &self,
        parties: Vec<String>,
        active_at_offset: i64,
        limit: Option<i64>,
    ) -> Result<Vec<Value>> {
        telemetry::instrument("active_contracts", TRANSPORT_JSON, async {
            let body = active_contracts_request(&parties, active_at_offset);
            let path = with_limit("/v2/state/active-contracts", limit);
            self.post(&path, &body).await
        })
        .await
    }

    /// Like [`Self::active_contracts`], with the full request surface of an
    /// [`ActiveContractsRequest`](crate::request::ActiveContractsRequest)
    /// (template/interface filters, created-event blobs, non-verbose records)
    /// — the same builder the gRPC lane takes.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails, or the
    /// result set exceeds the node limit (`413`).
    pub async fn active_contracts_with(
        &self,
        request: &crate::request::ActiveContractsRequest,
        limit: Option<i64>,
    ) -> Result<Vec<Value>> {
        telemetry::instrument("active_contracts", TRANSPORT_JSON, async {
            let path = with_limit("/v2/state/active-contracts", limit);
            self.post(&path, &request.json_body()).await
        })
        .await
    }

    /// Updates (transactions/reassignments) for `parties` in the offset range
    /// `(begin_exclusive, end_inclusive]` (`POST /v2/updates`).
    ///
    /// A **bounded** read like [`Self::active_contracts`]: bound it with
    /// `end_inclusive` and/or `limit`, or the node returns [`Error::Http`]
    /// `413`. Each element is raw JSON (`{"update": …}`), including
    /// `OffsetCheckpoint` heartbeats.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails, or the
    /// result set exceeds the node limit (`413`).
    pub async fn updates(
        &self,
        parties: Vec<String>,
        begin_exclusive: i64,
        end_inclusive: Option<i64>,
        limit: Option<i64>,
    ) -> Result<Vec<Value>> {
        telemetry::instrument("updates", TRANSPORT_JSON, async {
            let body = updates_request(&parties, begin_exclusive, end_inclusive);
            let path = with_limit("/v2/updates", limit);
            self.post(&path, &body).await
        })
        .await
    }

    /// Like [`Self::updates`], with the full request surface of an
    /// [`UpdatesRequest`](crate::request::UpdatesRequest) (bounds, template/
    /// interface filters, transaction shape, created-event blobs, topology
    /// events, non-verbose records) — the same builder the gRPC lane takes.
    ///
    /// # Errors
    /// Returns an [`Error`] if authentication or the request fails, or the
    /// result set exceeds the node limit (`413`).
    pub async fn updates_with(
        &self,
        request: &crate::request::UpdatesRequest,
        limit: Option<i64>,
    ) -> Result<Vec<Value>> {
        telemetry::instrument("updates", TRANSPORT_JSON, async {
            let path = with_limit("/v2/updates", limit);
            self.post(&path, &request.json_body()).await
        })
        .await
    }
}

/// Append a `?limit=<n>` query when a limit is set.
fn with_limit(path: &str, limit: Option<i64>) -> String {
    match limit {
        Some(limit) => format!("{path}?limit={limit}"),
        None => path.to_string(),
    }
}

#[cfg(feature = "ws")]
use futures_util::StreamExt as _;

#[cfg(feature = "ws")]
impl JsonClient {
    /// Stream updates over WebSocket (feature `ws`) for `parties`, starting after
    /// `begin_exclusive`. With `end_inclusive` the stream is bounded and closes
    /// once the range is exhausted; without it the stream tails live. Each item
    /// is a raw JSON update (`{"update": …}`); `OffsetCheckpoint` heartbeats are
    /// filtered out (as in the gRPC [`CantonClient::updates`]).
    ///
    /// Unlike [`Self::updates`], this is not capped by the node's list limit. For
    /// automatic reconnection use [`Self::ws_updates_resumable`].
    ///
    /// [`CantonClient::updates`]: crate::CantonClient::updates
    ///
    /// # Errors
    /// Returns an [`Error`] if the handshake fails; the stream yields `Err` on a
    /// participant error frame or a transport failure.
    #[allow(clippy::large_futures)] // the WS handshake state is inherently large; awaited once.
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub async fn ws_updates(
        &self,
        parties: Vec<String>,
        begin_exclusive: i64,
        end_inclusive: Option<i64>,
    ) -> Result<impl futures_core::Stream<Item = Result<Value>> + Send + use<>> {
        telemetry::instrument("ws_updates", TRANSPORT_JSON, async move {
            let request = updates_request(&parties, begin_exclusive, end_inclusive);
            let inner = crate::ws::subscribe(&self.ws_transport(), "/v2/updates", request).await?;
            Ok(telemetry::instrument_stream(
                "ws_updates",
                TRANSPORT_JSON,
                crate::ws::filter_checkpoints(inner),
            ))
        })
        .await
    }

    /// Like [`Self::ws_updates`], with the full request surface of an
    /// [`UpdatesRequest`](crate::request::UpdatesRequest) — the same builder
    /// the gRPC lane takes (bounds, filters, shape, blobs, topology events,
    /// non-verbose records).
    ///
    /// # Errors
    /// Returns an [`Error`] if the handshake fails; the stream yields `Err` on
    /// a participant error frame or a transport failure.
    #[allow(clippy::large_futures)] // the WS handshake state is inherently large; awaited once.
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub async fn ws_updates_with(
        &self,
        request: &crate::request::UpdatesRequest,
    ) -> Result<impl futures_core::Stream<Item = Result<Value>> + Send + use<>> {
        telemetry::instrument("ws_updates", TRANSPORT_JSON, async move {
            let inner =
                crate::ws::subscribe(&self.ws_transport(), "/v2/updates", request.json_body())
                    .await?;
            Ok(telemetry::instrument_stream(
                "ws_updates",
                TRANSPORT_JSON,
                crate::ws::filter_checkpoints(inner),
            ))
        })
        .await
    }

    /// Stream the active contract set snapshot at `active_at_offset` over
    /// WebSocket (feature `ws`), wildcard-filtered to `parties`. The stream
    /// closes when the snapshot is fully delivered. Each item is raw JSON
    /// (`{"workflowId": …, "contractEntry": …}`).
    ///
    /// Unlike [`Self::active_contracts`], this is not capped by the node's list
    /// limit.
    ///
    /// # Errors
    /// Returns an [`Error`] if the handshake fails; the stream yields `Err` on a
    /// participant error frame or a transport failure.
    #[allow(clippy::large_futures)] // the WS handshake state is inherently large; awaited once.
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub async fn ws_active_contracts(
        &self,
        parties: Vec<String>,
        active_at_offset: i64,
    ) -> Result<impl futures_core::Stream<Item = Result<Value>> + Send + use<>> {
        telemetry::instrument("ws_active_contracts", TRANSPORT_JSON, async move {
            let request = active_contracts_request(&parties, active_at_offset);
            let inner =
                crate::ws::subscribe(&self.ws_transport(), "/v2/state/active-contracts", request)
                    .await?;
            Ok(telemetry::instrument_stream(
                "ws_active_contracts",
                TRANSPORT_JSON,
                inner,
            ))
        })
        .await
    }

    /// Like [`Self::ws_active_contracts`], with the full request surface of an
    /// [`ActiveContractsRequest`](crate::request::ActiveContractsRequest) —
    /// the same builder the gRPC lane takes.
    ///
    /// # Errors
    /// Returns an [`Error`] if the handshake fails; the stream yields `Err` on
    /// a participant error frame or a transport failure.
    #[allow(clippy::large_futures)] // the WS handshake state is inherently large; awaited once.
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub async fn ws_active_contracts_with(
        &self,
        request: &crate::request::ActiveContractsRequest,
    ) -> Result<impl futures_core::Stream<Item = Result<Value>> + Send + use<>> {
        telemetry::instrument("ws_active_contracts", TRANSPORT_JSON, async move {
            let inner = crate::ws::subscribe(
                &self.ws_transport(),
                "/v2/state/active-contracts",
                request.json_body(),
            )
            .await?;
            Ok(telemetry::instrument_stream(
                "ws_active_contracts",
                TRANSPORT_JSON,
                inner,
            ))
        })
        .await
    }

    /// Stream command completions over WebSocket (feature `ws`) for `parties`,
    /// starting after `begin_exclusive`. Each item is a raw JSON completion;
    /// `OffsetCheckpoint` heartbeats are filtered out.
    ///
    /// # Errors
    /// Returns an [`Error`] if the handshake fails; the stream yields `Err` on a
    /// participant error frame or a transport failure.
    #[allow(clippy::large_futures)] // the WS handshake state is inherently large; awaited once.
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub async fn ws_completions(
        &self,
        parties: Vec<String>,
        begin_exclusive: i64,
    ) -> Result<impl futures_core::Stream<Item = Result<Value>> + Send + use<>> {
        telemetry::instrument("ws_completions", TRANSPORT_JSON, async move {
            let request = completions_request(&parties, begin_exclusive);
            let inner = crate::ws::subscribe(
                &self.ws_transport(),
                "/v2/commands/command-completions",
                request,
            )
            .await?;
            Ok(telemetry::instrument_stream(
                "ws_completions",
                TRANSPORT_JSON,
                crate::ws::filter_checkpoints(inner),
            ))
        })
        .await
    }

    /// Like [`Self::ws_completions`], with the full request surface of a
    /// [`CompletionsRequest`](crate::request::CompletionsRequest) — including
    /// the submitting `user_id` to scope the stream to (the same builder the
    /// gRPC lane takes).
    ///
    /// # Errors
    /// Returns an [`Error`] if the handshake fails; the stream yields `Err` on
    /// a participant error frame or a transport failure.
    #[allow(clippy::large_futures)] // the WS handshake state is inherently large; awaited once.
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub async fn ws_completions_with(
        &self,
        request: &crate::request::CompletionsRequest,
    ) -> Result<impl futures_core::Stream<Item = Result<Value>> + Send + use<>> {
        telemetry::instrument("ws_completions", TRANSPORT_JSON, async move {
            let inner = crate::ws::subscribe(
                &self.ws_transport(),
                "/v2/commands/command-completions",
                request.json_body(),
            )
            .await?;
            Ok(telemetry::instrument_stream(
                "ws_completions",
                TRANSPORT_JSON,
                crate::ws::filter_checkpoints(inner),
            ))
        })
        .await
    }

    /// The reconnect policy for the WebSocket streams: `(max_reconnects,
    /// backoff_unit)`, taken from this client's
    /// [`RetryConfig`](canton_core::RetryConfig) when one is configured — the
    /// same derivation the gRPC client makes, so configuring retries once
    /// governs both lanes rather than only the unary one.
    #[cfg(feature = "ws")]
    fn reconnect_policy(&self) -> (u32, std::time::Duration) {
        match &self.retry {
            Some(retry) => (retry.max_attempts, retry.initial_backoff),
            None => (5, std::time::Duration::from_millis(250)),
        }
    }

    /// Like [`Self::ws_active_contracts`], but **resumable**: on a retriable
    /// disconnect it resubscribes from the last continuation token the
    /// participant sent, rather than starting the snapshot again.
    ///
    /// An ACS snapshot has no offsets to resume from — it is a position in a
    /// stream of entries, which is what `streamContinuationToken` names. The
    /// gRPC lane has had a resumable ACS read since M1; this is its counterpart,
    /// and without it a WebSocket consumer of a large snapshot had to start over
    /// on any blip.
    ///
    /// The token is only valid against the same participant, the same
    /// `active_at_offset` and the same filters — all of which are fixed for the
    /// life of this stream — and while the snapshot's offset has not been
    /// pruned.
    #[cfg(feature = "ws")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub fn ws_active_contracts_resumable(
        &self,
        parties: Vec<String>,
        active_at_offset: i64,
    ) -> impl futures_core::Stream<Item = Result<Value>> + Send + use<> {
        let (max_reconnects, backoff_unit) = self.reconnect_policy();
        let base_url = self.base_url.clone();
        let auth = self.auth.clone();
        let tls = self.tls.clone();
        let max_decoding_message_size = self.max_decoding_message_size;
        let timeout = self.timeout;
        async_stream::stream! {
            let mut token: Option<String> = None;
            let mut reconnects = 0u32;
            loop {
                let mut request = active_contracts_request(&parties, active_at_offset);
                if let Some(token) = &token {
                    request["streamContinuationToken"] = Value::String(token.clone());
                }
                let transport = crate::ws::WsTransport {
                    base_url: &base_url,
                    auth: &auth,
                    tls: tls.as_ref(),
                    max_decoding_message_size,
                    timeout,
                };
                // What made this reconnect necessary, carried out of the inner
                // loop for the reason the gRPC streams carry it: giving up must
                // report the participant's own failure, not an error of ours.
                let cause = match crate::ws::subscribe(&transport, "/v2/state/active-contracts", request).await {
                    Ok(inner) => {
                        // Each connection is instrumented for its own life, so a
                        // subscription that dies mid-snapshot is counted rather
                        // than disappearing into the reconnect loop.
                        let inner = telemetry::instrument_stream(
                            "ws_active_contracts",
                            TRANSPORT_JSON,
                            inner,
                        );
                        tokio::pin!(inner);
                        loop {
                            match inner.next().await {
                                Some(Ok(frame)) => {
                                    if let Some(next) = frame
                                        .get("streamContinuationToken")
                                        .and_then(Value::as_str)
                                        .filter(|next| !next.is_empty())
                                    {
                                        token = Some(next.to_string());
                                    }
                                    reconnects = 0;
                                    yield Ok(frame);
                                }
                                Some(Err(err)) if err.is_retriable() => break err,
                                Some(Err(err)) => {
                                    yield Err(err);
                                    return;
                                }
                                // A bounded read: the participant closes the
                                // socket when the snapshot is delivered, and
                                // there is no token left to resume from.
                                None => return,
                            }
                        }
                    }
                    Err(err) if err.is_retriable() => err,
                    Err(err) => {
                        yield Err(err);
                        return;
                    }
                };

                reconnects += 1;
                if reconnects > max_reconnects {
                    tracing::warn!(
                        max_reconnects,
                        "ws acs stream gave up resuming; reporting the failure that caused it"
                    );
                    yield Err(cause);
                    return;
                }
                tokio::time::sleep(backoff_unit * reconnects).await;
            }
        }
    }

    /// Like [`Self::ws_updates`] (unbounded tail), but **resumable**: on a
    /// retriable disconnect it reconnects from the last offset it observed
    /// (tracked via `OffsetCheckpoint` heartbeats and update offsets), with a
    /// short backoff and a bounded number of consecutive reconnects. Mirrors the
    /// gRPC [`CantonClient::updates_resumable`]. Checkpoints are consumed for
    /// position tracking and not yielded.
    ///
    /// [`CantonClient::updates_resumable`]: crate::CantonClient::updates_resumable
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub fn ws_updates_resumable(
        &self,
        parties: Vec<String>,
        begin_exclusive: i64,
    ) -> impl futures_core::Stream<Item = Result<Value>> + Send + use<> {
        let (max_reconnects, backoff_unit) = self.reconnect_policy();
        let base_url = self.base_url.clone();
        let auth = self.auth.clone();
        let tls = self.tls.clone();
        let max_decoding_message_size = self.max_decoding_message_size;
        let timeout = self.timeout;
        async_stream::stream! {
            let mut offset = begin_exclusive;
            let mut reconnects = 0u32;
            loop {
                // Unbounded tail (no end): a close means the connection dropped.
                let request = updates_request(&parties, offset, None);
                let transport = crate::ws::WsTransport {
                    base_url: &base_url,
                    auth: &auth,
                    tls: tls.as_ref(),
                    max_decoding_message_size,
                    timeout,
                };
                // `Option`, unlike the other resumable streams: here a clean
                // WS close is also a reason to reconnect, and it carries no
                // failure to report. Everything else does.
                let cause = match crate::ws::subscribe(&transport, "/v2/updates", request).await {
                    Ok(inner) => {
                        let inner =
                            telemetry::instrument_stream("ws_updates", TRANSPORT_JSON, inner);
                        tokio::pin!(inner);
                        loop {
                            match inner.next().await {
                                Some(Ok(frame)) => {
                                    if let Some(o) = crate::ws::update_offset(&frame) {
                                        offset = o;
                                    }
                                    reconnects = 0;
                                    if !crate::ws::is_offset_checkpoint(&frame) {
                                        yield Ok(frame);
                                    }
                                }
                                Some(Err(err)) if err.is_retriable() => break Some(err),
                                Some(Err(err)) => {
                                    yield Err(err);
                                    return;
                                }
                                None => break None, // WS closed → reconnect from `offset`
                            }
                        }
                    }
                    Err(err) if err.is_retriable() => Some(err),
                    Err(err) => {
                        yield Err(err);
                        return;
                    }
                };

                reconnects += 1;
                if reconnects > max_reconnects {
                    tracing::warn!(
                        max_reconnects,
                        offset,
                        "ws update stream gave up resuming; reporting the failure that caused it"
                    );
                    // No cause means the participant kept closing the socket
                    // cleanly and the stream never got anywhere — which is not
                    // a participant error, so it is described as what it is.
                    yield Err(cause.unwrap_or_else(|| Error::UnexpectedResponse(format!(
                        "ws update stream was closed and reopened {max_reconnects} times \
                         without delivering an update"
                    ))));
                    return;
                }
                tokio::time::sleep(backoff_unit * reconnects).await;
            }
        }
    }
}

/// Classify a failure to *send* a JSON request.
///
/// This sits inside [`canton_core::retry::run_with_retry`], which loops while
/// `is_retriable()` — and `Error::Connection` always is. Reporting every
/// transport failure that way meant an unverifiable certificate, a malformed
/// URL and a redirect loop each ran the full retry schedule and then reported
/// `error sending request for url (…)`, with the word *certificate* left in the
/// source chain nobody read.
fn transport_error(path: &str, e: &reqwest::Error) -> Error {
    let detail = canton_core::chain(e);
    if e.is_timeout() {
        return Error::Timeout;
    }
    if e.is_builder() || e.is_redirect() {
        return Error::InvalidRequest(format!("the request to {path} could not be made: {detail}"));
    }
    if e.is_decode() {
        return Error::UnexpectedResponse(format!(
            "{path} returned a body this cannot read: {detail}"
        ));
    }
    // A TLS failure arrives as a connect error, indistinguishable by type from
    // a refused connection — reqwest exposes no typed TLS error — so the chain
    // is the only place it shows. Permanent, so not retriable.
    if detail.to_ascii_lowercase().contains("certificate") {
        return Error::InvalidRequest(format!(
            "the certificate presented for {path} could not be verified: {detail}"
        ));
    }
    Error::Connection(format!("json request to {path} failed: {detail}"))
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn updates_request_matches_grpc_and_includes_reassignments() {
        let parties = vec!["alice::1".to_string()];
        let body = updates_request(&parties, 10, Some(20));
        assert_eq!(body["beginExclusive"], 10);
        assert_eq!(body["endInclusive"], 20);
        let fmt = &body["updateFormat"];
        // Both sub-formats present — same event set as the gRPC lane, which sets
        // include_transactions AND include_reassignments.
        assert!(fmt["includeTransactions"].is_object(), "{body}");
        assert!(
            fmt["includeReassignments"].is_object(),
            "reassignments must be requested, or the JSON lane drops them: {body}"
        );
        assert_eq!(
            fmt["includeTransactions"]["transactionShape"],
            "TRANSACTION_SHAPE_LEDGER_EFFECTS"
        );
    }

    #[test]
    fn commands_serialize_to_the_json_api_shape() {
        let commands = JsonCommands::new(vec!["alice::1".to_string()])
            .with_command_id("cmd-1")
            .add_create("pkg:Mod:Ent", json!({ "owner": "alice::1" }));
        let value = serde_json::to_value(&commands).unwrap();

        assert_eq!(value["commandId"], "cmd-1");
        assert_eq!(value["actAs"][0], "alice::1");
        // Tagged CreateCommand with a Daml-LF-JSON record argument.
        assert_eq!(
            value["commands"][0]["CreateCommand"]["templateId"],
            "pkg:Mod:Ent"
        );
        assert_eq!(
            value["commands"][0]["CreateCommand"]["createArguments"]["owner"],
            "alice::1"
        );
        // Optional fields are omitted, not null.
        assert!(value.get("userId").is_none());
        assert!(value.get("readAs").is_none());
    }

    #[test]
    fn all_command_options_serialize_to_camel_case() {
        let commands = JsonCommands::new(vec!["alice::1".to_string()])
            .with_command_id("cmd-1")
            .with_user_id("user-1")
            .with_read_as(vec!["bob::2".to_string()])
            .with_workflow_id("wf-1")
            .with_synchronizer_id("sync-1")
            .with_submission_id("sub-1")
            .add_disclosed_contract(json!({ "contractId": "c9", "createdEventBlob": "AQI=" }))
            .with_package_id_selection_preference(vec!["pkg-9".to_string()])
            .with_deduplication_period(
                json!({ "DeduplicationDuration": { "value": { "duration": "30s" } } }),
            )
            .with_min_ledger_time_rel(json!("5s"))
            .add_create("pkg:Mod:Ent", json!({ "owner": "alice::1" }))
            .add_command(json!({ "ExerciseCommand": { "contractId": "c1" } }));
        let value = serde_json::to_value(&commands).unwrap();

        assert_eq!(value["userId"], "user-1");
        assert_eq!(value["readAs"][0], "bob::2");
        assert_eq!(value["workflowId"], "wf-1");
        assert_eq!(value["synchronizerId"], "sync-1");
        assert_eq!(value["submissionId"], "sub-1");
        assert_eq!(value["disclosedContracts"][0]["contractId"], "c9");
        assert_eq!(value["packageIdSelectionPreference"][0], "pkg-9");
        assert_eq!(
            value["deduplicationPeriod"]["DeduplicationDuration"]["value"]["duration"],
            "30s"
        );
        assert_eq!(value["minLedgerTimeRel"], "5s");
        assert!(value.get("minLedgerTimeAbs").is_none());
        // Both the convenience create and the raw command are present, in order.
        assert!(value["commands"][0]["CreateCommand"].is_object());
        assert_eq!(value["commands"][1]["ExerciseCommand"]["contractId"], "c1");
    }

    #[test]
    fn wildcard_event_format_filters_each_party() {
        let format = &active_contracts_request(&["alice::1".to_string(), "bob::2".to_string()], 0)
            ["eventFormat"];
        assert_eq!(format["verbose"], true);
        assert!(format["filtersByParty"]["alice::1"]["cumulative"][0]["identifierFilter"]
            ["WildcardFilter"]
            .is_object());
        assert!(format["filtersByParty"]["bob::2"].is_object());
    }

    #[test]
    fn with_limit_appends_only_when_set() {
        assert_eq!(with_limit("/v2/updates", None), "/v2/updates");
        assert_eq!(with_limit("/v2/updates", Some(5)), "/v2/updates?limit=5");
    }

    /// A participant that accepts the connection and then says nothing is the
    /// case no status code covers, and `reqwest` waits for it forever unless
    /// told not to. The gRPC lane has bounded this at 30s since M1; this one
    /// had no bound and no knob.
    ///
    /// The listener here accepts and never answers, which is the only way to
    /// tell a timeout that works from a request that happened to be fast.
    #[tokio::test]
    async fn a_request_to_a_silent_participant_gives_up_instead_of_hanging() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        // Hold every accepted connection open, answering nothing.
        tokio::spawn(async move {
            let mut held = Vec::new();
            while let Ok((socket, _)) = listener.accept().await {
                held.push(socket);
            }
        });

        let client = JsonClient::new(format!("http://{addr}"))
            .with_timeout(std::time::Duration::from_millis(250));

        // The outer bound is what makes this a test rather than a hang: with no
        // per-request timeout the call never returns at all, and a CI job that
        // stops responding says less than one that fails.
        let outcome =
            tokio::time::timeout(std::time::Duration::from_secs(5), client.version()).await;
        let Ok(result) = outcome else {
            panic!("the request never returned — the per-request timeout is not being applied");
        };

        let error = result.unwrap_err();
        assert!(
            error.is_retriable(),
            "a timeout is transient and should be retriable: {error}"
        );

        // And the default is a real bound, not `None` dressed up as one.
        assert_eq!(
            JsonClient::new("http://localhost:3975").timeout,
            DEFAULT_TIMEOUT
        );
    }

    /// A client is the thing a caller is most likely to put in a `tracing`
    /// field or a `{:?}`, and its base URL is the one place a credential can
    /// hide in plain sight. `Config` has redacted its endpoint since the
    /// mutual-TLS fix; this type held the same secret behind a derived `Debug`.
    #[test]
    fn debug_does_not_print_credentials_carried_in_the_base_url() {
        let secret = "s3cr3t-p@ssw0rd";
        let client = JsonClient::new(format!("https://svc-account:{secret}@ledger.example:3975"))
            .with_token("eyJhbGciOiJSUzI1NiJ9.PAYLOAD.SIG");
        let rendered = format!("{client:?}");

        assert!(
            !rendered.contains(secret),
            "leaked the password: {rendered}"
        );
        assert!(
            !rendered.contains("svc-account"),
            "leaked the user: {rendered}"
        );
        assert!(
            !rendered.contains("PAYLOAD"),
            "leaked the token: {rendered}"
        );
        // Still useful: the host has to survive, or the output tells a reader
        // nothing about which participant this client talks to.
        assert!(
            rendered.contains("ledger.example:3975"),
            "should keep the host: {rendered}"
        );
    }

    /// The WS lane must not silently inherit `tungstenite`'s ceiling: 64 MiB
    /// per message and 16 MiB per *frame*, neither of them anything the caller
    /// asked for. A JSON client carries the same limit the gRPC one does, and
    /// raising it is the caller's to do.
    #[test]
    fn the_ws_lane_starts_at_the_sdk_size_limit_not_tungstenites() {
        let client = JsonClient::new("http://localhost:3975");
        assert_eq!(
            client.max_decoding_message_size,
            canton_core::DEFAULT_MAX_DECODING_MESSAGE_SIZE,
        );
        // Well clear of both tungstenite defaults, which is the whole point.
        assert!(client.max_decoding_message_size > 64 << 20);

        let raised = client.with_max_decoding_message_size(256 << 20);
        assert_eq!(raised.max_decoding_message_size, 256 << 20);
    }

    #[test]
    fn command_id_defaults_to_a_generated_uuid() {
        let commands = JsonCommands::new(vec!["alice::1".to_string()]);
        let value = serde_json::to_value(&commands).unwrap();
        let id = value["commandId"].as_str().unwrap();
        assert!(id.starts_with("sdk-"), "got {id}");
        assert!(id.len() > 10, "expected a uuid suffix, got {id}");
    }

    #[test]
    fn with_tls_threads_a_ca_and_client_identity() {
        let ck = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
        let cert_pem = ck.cert.pem().into_bytes();
        let key_pem = ck.key_pair.serialize_pem().into_bytes();

        // A valid CA + client identity (mTLS) builds an HTTPS client.
        let tls = canton_core::TlsConfig::new()
            .with_ca_certificate(cert_pem.clone())
            .with_client_identity(cert_pem, key_pem);
        assert!(
            JsonClient::new("https://localhost:3975")
                .with_token("t")
                .with_tls(&tls)
                .is_ok()
        );

        // A malformed client-identity PEM is rejected as an InvalidRequest.
        let bad = canton_core::TlsConfig::new()
            .with_client_identity(b"not a pem".to_vec(), b"nor this".to_vec());
        assert!(matches!(
            JsonClient::new("https://localhost:3975").with_tls(&bad),
            Err(Error::InvalidRequest(_))
        ));
    }

    #[test]
    fn with_tls_upgrades_an_http_base_url_to_https() {
        // The security bug: `with_tls` on an http:// base URL would otherwise
        // send plaintext HTTP (certs unused) and open a ws:// socket. The scheme
        // must become https so both the reqwest and WebSocket lanes use TLS.
        let client = JsonClient::new("http://localhost:3975")
            .with_tls(&canton_core::TlsConfig::new())
            .unwrap();
        assert_eq!(client.base_url, "https://localhost:3975");

        // Already-https is left untouched, and the check is case-insensitive.
        assert_eq!(
            upgrade_base_url_for_tls("https://host:443"),
            "https://host:443"
        );
        assert_eq!(
            upgrade_base_url_for_tls("HTTP://host:80"),
            "https://host:80"
        );
        // Without TLS, plain http is preserved (no normalisation on `new`).
        assert_eq!(
            JsonClient::new("http://localhost:3975").base_url,
            "http://localhost:3975"
        );
    }
}