strata-sdk 0.1.5

Official Rust SDK for Strata markets and Sonar quotes.
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
//! Official Rust client for Strata markets and Sonar quotes.
//!
//! It provides typed requests and responses and validates compatibility, quote
//! binding, and economic fields before returning data to the application.

use async_trait::async_trait;
use base64::Engine as _;
use reqwest::{StatusCode, Url};
use serde::de::DeserializeOwned;
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use strata_public_contract::{ErrorResponse, CONTRACT_MAJOR, CONTRACT_VERSION};
use thiserror::Error;

pub use strata_public_contract::platform::{
    PlatformOrderAction, PlatformOrderChallengeRequest, PlatformOrderChallengeResponse,
    PlatformOrderPrepareRequest, PlatformOrderPrepareResponse, PlatformOrderSubmissionStatus,
    PlatformOrderSubmitRequest, PlatformOrderSubmitResponse, PlatformOrderType, PlatformTradeSide,
};
pub use strata_public_contract::{
    ActionAuthorityModel, ActionEdge, ActionGraph, ActionNode, ActionNodeKind, ActionOperation,
    CapabilityCatalog, CapabilityDescriptor, CapabilityRisk, CapabilityStability,
    ExecutionChallengeRequest, ExecutionChallengeResponse, ExecutionPrepareRequest,
    ExecutionPrepareResponse, ExecutionStatus, ExecutionSubmitRequest, ExecutionSubmitResponse,
    Market, MarketsResponse, McpExposure, QuoteRequest, QuoteResponse, QuoteSide,
    DEFAULT_SLIPPAGE_BPS,
};

pub const DEFAULT_API_BASE: &str = "https://api.stratabook.app";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const PUBLIC_EXECUTION_AUTH_DOMAIN: &[u8] = b"strata-sonar-execution:v1\0";
const PUBLIC_ORDER_AUTH_DOMAIN: &[u8] = b"strata-platform-order-control:v1\0";

#[async_trait]
pub trait SessionSigner: Send + Sync {
    /// Canonical base58 Ed25519 public key registered as the Vault delegate.
    fn public_key(&self) -> &str;

    /// Sign the exact SDK-validated public operation authorization.
    async fn sign_message(&self, message: &[u8]) -> Result<Vec<u8>, String>;

    /// Add only the session signature to an already-verified transaction.
    async fn sign_transaction(&self, transaction_base64: &str) -> Result<String, String>;
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OrderExecuteOperation {
    Place {
        owner_wallet: String,
        account_sequence: String,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
    Cancel {
        owner_wallet: String,
        order_id: String,
    },
    CancelAll {
        owner_wallet: String,
    },
}

impl OrderExecuteOperation {
    fn challenge_request(&self, session_public_key: String) -> PlatformOrderChallengeRequest {
        match self {
            Self::Place {
                owner_wallet,
                account_sequence,
                client_order_id,
                side,
                order_type,
                limit_price_atoms,
                size_atoms,
            } => PlatformOrderChallengeRequest::Place {
                owner_wallet: owner_wallet.clone(),
                session_public_key,
                account_sequence: account_sequence.clone(),
                client_order_id: client_order_id.clone(),
                side: *side,
                order_type: *order_type,
                limit_price_atoms: limit_price_atoms.clone(),
                size_atoms: size_atoms.clone(),
            },
            Self::Cancel {
                owner_wallet,
                order_id,
            } => PlatformOrderChallengeRequest::Cancel {
                owner_wallet: owner_wallet.clone(),
                session_public_key,
                order_id: order_id.clone(),
            },
            Self::CancelAll { owner_wallet } => PlatformOrderChallengeRequest::CancelAll {
                owner_wallet: owner_wallet.clone(),
                session_public_key,
            },
        }
    }
}

#[derive(Debug)]
pub struct OrderVerificationContext<'a> {
    pub challenge: &'a PlatformOrderChallengeResponse,
    pub prepared: &'a PlatformOrderPrepareResponse,
    pub owner_wallet: &'a str,
    pub session_public_key: &'a str,
}

#[async_trait]
pub trait OrderVerifier: Send + Sync {
    /// Reject unless the prepared transaction implements the exact signed
    /// order operation for this Vault session.
    async fn verify(&self, context: &OrderVerificationContext<'_>) -> Result<(), String>;
}

#[derive(Debug)]
pub struct ExecutionVerificationContext<'a> {
    pub quote: &'a QuoteResponse,
    pub challenge: &'a ExecutionChallengeResponse,
    pub prepared: &'a ExecutionPrepareResponse,
    pub owner_wallet: &'a str,
    pub session_public_key: &'a str,
}

#[async_trait]
pub trait ExecutionVerifier: Send + Sync {
    /// Reject unless the prepared transaction is acceptable for this exact
    /// Vault session and public economic intent.
    async fn verify(&self, context: &ExecutionVerificationContext<'_>) -> Result<(), String>;
}

#[derive(Debug, Error)]
pub enum SdkError {
    #[error("invalid API base URL: {0}")]
    InvalidBaseUrl(String),
    #[error("invalid request: {0}")]
    InvalidRequest(String),
    #[error("market is not available: {0}")]
    MarketNotFound(String),
    #[error("operation is not available for market: {0}")]
    OperationUnavailable(String),
    #[error("Strata API error {status} ({code}): {message}")]
    Api {
        status: StatusCode,
        code: String,
        message: String,
        retryable: bool,
    },
    #[error("invalid public contract response: {0}")]
    InvalidResponse(String),
    #[error("session signer rejected the operation: {0}")]
    Signer(String),
    #[error("prepared transaction was rejected: {0}")]
    Verification(String),
    #[error(transparent)]
    Transport(#[from] reqwest::Error),
}

#[derive(Clone, Debug)]
pub struct StrataClient {
    base_url: Url,
    http: reqwest::Client,
}

impl StrataClient {
    pub fn production() -> Result<Self, SdkError> {
        Self::new(DEFAULT_API_BASE)
    }

    pub fn new(base_url: impl AsRef<str>) -> Result<Self, SdkError> {
        Self::with_timeout(base_url, DEFAULT_TIMEOUT)
    }

    pub fn with_timeout(base_url: impl AsRef<str>, timeout: Duration) -> Result<Self, SdkError> {
        if timeout.is_zero() {
            return Err(SdkError::InvalidRequest(
                "timeout must be greater than zero".to_owned(),
            ));
        }
        let base_url = normalize_base_url(base_url.as_ref())?;
        let http = reqwest::Client::builder().timeout(timeout).build()?;
        Ok(Self { base_url, http })
    }

    pub async fn capabilities(&self) -> Result<CapabilityCatalog, SdkError> {
        let catalog: CapabilityCatalog = self.get("sonar/capabilities", &[]).await?;
        validate_version(catalog.schema_version, &catalog.contract_version)?;

        let mut ids = HashSet::new();
        if catalog
            .capabilities
            .iter()
            .any(|capability| !ids.insert(capability.id.as_str()))
        {
            return Err(SdkError::InvalidResponse(
                "capability IDs must be unique".to_owned(),
            ));
        }
        Ok(catalog)
    }

    /// Return the live operation topology, including capability-gated nodes and
    /// the points where the agent owner's signer acts outside Strata.
    pub async fn action_graph(&self) -> Result<ActionGraph, SdkError> {
        let graph: ActionGraph = self.get("sonar/action-graph", &[]).await?;
        validate_action_graph(&graph)?;
        Ok(graph)
    }

    pub async fn markets(&self) -> Result<MarketsResponse, SdkError> {
        let markets: MarketsResponse = self.get("sonar/markets", &[]).await?;
        validate_version(markets.schema_version, &markets.contract_version)?;
        Ok(markets)
    }

    /// Request a short-lived Sonar quote by human market label or market ID.
    pub async fn quote(&self, request: QuoteRequest) -> Result<QuoteResponse, SdkError> {
        let amount_in = parse_atoms("amount_in_atoms", &request.amount_in_atoms)?;
        if amount_in == 0 {
            return Err(SdkError::InvalidRequest(
                "amount_in_atoms must be greater than zero".to_owned(),
            ));
        }
        if request.slippage_bps > 1_000 {
            return Err(SdkError::InvalidRequest(
                "slippage_bps must be between 0 and 1,000".to_owned(),
            ));
        }

        let markets = self.markets().await?;
        let market = markets
            .markets
            .iter()
            .find(|market| {
                market.label.eq_ignore_ascii_case(&request.market_id)
                    || market.market_pda.as_deref() == Some(request.market_id.as_str())
            })
            .ok_or_else(|| SdkError::MarketNotFound(request.market_id.clone()))?;
        if !market.ready {
            return Err(SdkError::OperationUnavailable(market.label.clone()));
        }
        let market_pda = market
            .market_pda
            .as_deref()
            .ok_or_else(|| SdkError::MarketNotFound(request.market_id.clone()))?;
        let quote_path = market
            .quote_path
            .as_deref()
            .filter(|path| valid_public_operation_path(path))
            .ok_or_else(|| SdkError::OperationUnavailable(market.label.clone()))?;
        let wire = QuoteRequest {
            market_id: market_pda.to_owned(),
            side: request.side,
            amount_in_atoms: request.amount_in_atoms.clone(),
            slippage_bps: request.slippage_bps,
        };
        let quote: QuoteResponse = self.post(quote_path, &wire).await?;
        validate_quote(&quote, market_pda, &request, amount_in)?;
        Ok(quote)
    }

    /// Request canonical authorization bytes for an external signer. This
    /// operation accepts public identity only; signing material stays external.
    pub async fn execution_challenge(
        &self,
        market: &str,
        request: ExecutionChallengeRequest,
    ) -> Result<ExecutionChallengeResponse, SdkError> {
        if !valid_handle(&request.quote_id, "sq_") {
            return Err(SdkError::InvalidRequest("quote_id is invalid".to_owned()));
        }
        let request = ExecutionChallengeRequest {
            quote_id: request.quote_id,
            owner_wallet: canonical_public_key(&request.owner_wallet, "owner_wallet")?,
            session_public_key: canonical_public_key(
                &request.session_public_key,
                "session_public_key",
            )?,
            account_sequence: parse_atoms("account_sequence", &request.account_sequence)?
                .to_string(),
        };
        let execution_path = self.execution_path(market).await?;
        let challenge: ExecutionChallengeResponse = self
            .post(&format!("{execution_path}/challenge"), &request)
            .await?;
        validate_version(challenge.schema_version, &challenge.contract_version)?;
        if !valid_handle(&challenge.challenge_id, "sc_") || challenge.quote_id != request.quote_id {
            return Err(SdkError::InvalidResponse(
                "execution challenge does not match the requested quote".to_owned(),
            ));
        }
        Ok(challenge)
    }

    /// Exchange an external authorization signature for a quote-bound,
    /// partially signed transaction.
    pub async fn execution_prepare(
        &self,
        market: &str,
        request: ExecutionPrepareRequest,
    ) -> Result<ExecutionPrepareResponse, SdkError> {
        if !valid_handle(&request.challenge_id, "sc_") {
            return Err(SdkError::InvalidRequest(
                "challenge_id is invalid".to_owned(),
            ));
        }
        let signature = bs58::decode(request.authorization_signature.trim())
            .into_vec()
            .map_err(|_| {
                SdkError::InvalidRequest("authorization_signature must be base58".to_owned())
            })?;
        if signature.len() != 64
            || bs58::encode(&signature).into_string() != request.authorization_signature.trim()
        {
            return Err(SdkError::InvalidRequest(
                "authorization_signature must be a canonical Ed25519 signature".to_owned(),
            ));
        }
        let request = ExecutionPrepareRequest {
            challenge_id: request.challenge_id,
            authorization_signature: bs58::encode(signature).into_string(),
        };
        let execution_path = self.execution_path(market).await?;
        let prepared: ExecutionPrepareResponse = self
            .post(&format!("{execution_path}/prepare"), &request)
            .await?;
        validate_version(prepared.schema_version, &prepared.contract_version)?;
        if !valid_handle(&prepared.execution_id, "se_") {
            return Err(SdkError::InvalidResponse(
                "prepared execution ID is invalid".to_owned(),
            ));
        }
        Ok(prepared)
    }

    /// Submit an externally signed transaction. Reusing the same idempotency
    /// key cannot create a second execution.
    pub async fn execution_submit(
        &self,
        market: &str,
        request: ExecutionSubmitRequest,
    ) -> Result<ExecutionSubmitResponse, SdkError> {
        if !valid_handle(&request.execution_id, "se_") {
            return Err(SdkError::InvalidRequest(
                "execution_id is invalid".to_owned(),
            ));
        }
        let transaction = request.signed_transaction_base64.trim();
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(transaction)
            .map_err(|_| {
                SdkError::InvalidRequest(
                    "signed_transaction_base64 must be canonical base64".to_owned(),
                )
            })?;
        if decoded.is_empty()
            || base64::engine::general_purpose::STANDARD.encode(&decoded) != transaction
        {
            return Err(SdkError::InvalidRequest(
                "signed_transaction_base64 must be canonical base64".to_owned(),
            ));
        }
        let request = ExecutionSubmitRequest {
            execution_id: request.execution_id,
            signed_transaction_base64: transaction.to_owned(),
            idempotency_key: normalize_idempotency_key(&request.idempotency_key)?,
        };
        let execution_path = self.execution_path(market).await?;
        let submitted: ExecutionSubmitResponse = self
            .post(&format!("{execution_path}/submit"), &request)
            .await?;
        validate_version(submitted.schema_version, &submitted.contract_version)?;
        if submitted.execution_id != request.execution_id
            || submitted.status != ExecutionStatus::Submitted
            || submitted.signature.trim().is_empty()
        {
            return Err(SdkError::InvalidResponse(
                "execution receipt does not match the submitted transaction".to_owned(),
            ));
        }
        Ok(submitted)
    }

    /// Request exact authorization bytes for one product-level resting-order
    /// operation. Private key material never enters this client or Strata.
    pub async fn order_challenge(
        &self,
        market_id: &str,
        request: PlatformOrderChallengeRequest,
    ) -> Result<PlatformOrderChallengeResponse, SdkError> {
        let market_id = validate_platform_market_id(market_id)?;
        let request = normalize_order_challenge_request(request)?;
        let expected_action = order_request_action(&request);
        let challenge: PlatformOrderChallengeResponse = self
            .post(
                &format!("v2/markets/{market_id}/orders/challenge"),
                &request,
            )
            .await?;
        validate_platform_version(challenge.schema_version, &challenge.contract_version)?;
        if challenge.market_id != market_id
            || challenge.action != expected_action
            || !valid_handle(&challenge.challenge_id, "oc_")
            || challenge.order_ids.is_empty()
            || challenge.order_ids.len() > 6
            || challenge.expires_at_ms <= challenge.server_time_ms
            || challenge
                .order_ids
                .iter()
                .any(|order_id| !valid_handle(order_id, "order_"))
        {
            return Err(SdkError::InvalidResponse(
                "order challenge bindings are invalid".to_owned(),
            ));
        }
        canonical_base64(
            &challenge.authorization_payload_base64,
            "authorization_payload_base64",
        )?;
        Ok(challenge)
    }

    /// Exchange a detached external authorization signature for a backend-
    /// partially-signed v0 transaction.
    pub async fn order_prepare(
        &self,
        market_id: &str,
        request: PlatformOrderPrepareRequest,
    ) -> Result<PlatformOrderPrepareResponse, SdkError> {
        let market_id = validate_platform_market_id(market_id)?;
        if !valid_handle(&request.challenge_id, "oc_") {
            return Err(SdkError::InvalidRequest(
                "order challenge_id is invalid".to_owned(),
            ));
        }
        let signature =
            canonical_signature(&request.authorization_signature, "authorization_signature")?;
        let prepared: PlatformOrderPrepareResponse = self
            .post(
                &format!("v2/markets/{market_id}/orders/prepare"),
                &PlatformOrderPrepareRequest {
                    challenge_id: request.challenge_id,
                    authorization_signature: signature,
                },
            )
            .await?;
        validate_platform_version(prepared.schema_version, &prepared.contract_version)?;
        if prepared.market_id != market_id
            || !valid_handle(&prepared.order_control_id, "or_")
            || prepared.order_ids.is_empty()
            || prepared.order_ids.len() > 6
            || prepared.transaction_base64.trim().is_empty()
            || prepared.expires_at_ms == 0
        {
            return Err(SdkError::InvalidResponse(
                "prepared order control is invalid".to_owned(),
            ));
        }
        canonical_base64(&prepared.transaction_base64, "transaction_base64")?;
        canonical_base58_32(&prepared.recent_blockhash, "recent_blockhash")?;
        Ok(prepared)
    }

    /// Submit an externally signed order-control transaction. The same
    /// control ID and idempotency key return the same receipt.
    pub async fn order_submit(
        &self,
        market_id: &str,
        request: PlatformOrderSubmitRequest,
    ) -> Result<PlatformOrderSubmitResponse, SdkError> {
        let market_id = validate_platform_market_id(market_id)?;
        if !valid_handle(&request.order_control_id, "or_") {
            return Err(SdkError::InvalidRequest(
                "order_control_id is invalid".to_owned(),
            ));
        }
        let transaction = canonical_base64(
            &request.signed_transaction_base64,
            "signed_transaction_base64",
        )?;
        let request = PlatformOrderSubmitRequest {
            order_control_id: request.order_control_id,
            signed_transaction_base64: transaction,
            idempotency_key: normalize_idempotency_key(&request.idempotency_key)?,
        };
        let submitted: PlatformOrderSubmitResponse = self
            .post(&format!("v2/markets/{market_id}/orders/submit"), &request)
            .await?;
        validate_platform_version(submitted.schema_version, &submitted.contract_version)?;
        if submitted.market_id != market_id
            || submitted.order_control_id != request.order_control_id
            || submitted.status != PlatformOrderSubmissionStatus::Submitted
            || submitted.signature.trim().is_empty()
        {
            return Err(SdkError::InvalidResponse(
                "order control receipt is invalid".to_owned(),
            ));
        }
        canonical_signature(&submitted.signature, "signature")?;
        Ok(submitted)
    }

    /// Execute one resting-order operation while all private keys and signing
    /// policy remain in the caller's signer adapter. Authorization bytes are
    /// parsed before message signing, and the mandatory verifier runs before
    /// the transaction signature is requested.
    pub async fn execute_order<S, V>(
        &self,
        market_id: &str,
        operation: &OrderExecuteOperation,
        signer: &S,
        verifier: &V,
        idempotency_key: Option<&str>,
    ) -> Result<PlatformOrderSubmitResponse, SdkError>
    where
        S: SessionSigner + ?Sized,
        V: OrderVerifier + ?Sized,
    {
        let market_id = validate_platform_market_id(market_id)?;
        let session_public_key = canonical_public_key(signer.public_key(), "session_public_key")?;
        let request = normalize_order_challenge_request(
            operation.challenge_request(session_public_key.clone()),
        )?;
        let owner_wallet = order_request_owner(&request).to_owned();
        if owner_wallet == session_public_key {
            return Err(SdkError::InvalidRequest(
                "session_public_key must be distinct from owner_wallet".to_owned(),
            ));
        }
        let challenge = self.order_challenge(&market_id, request.clone()).await?;
        if challenge.action != order_request_action(&request) {
            return Err(SdkError::InvalidResponse(
                "order challenge action changed".to_owned(),
            ));
        }
        let authorization = validate_order_authorization(&challenge, &request)?;
        let signature = signer
            .sign_message(&authorization.bytes)
            .await
            .map_err(SdkError::Signer)?;
        if signature.len() != 64 {
            return Err(SdkError::InvalidResponse(
                "order authorization signature must contain 64 bytes".to_owned(),
            ));
        }
        let prepared = self
            .order_prepare(
                &market_id,
                PlatformOrderPrepareRequest {
                    challenge_id: challenge.challenge_id.clone(),
                    authorization_signature: bs58::encode(signature).into_string(),
                },
            )
            .await?;
        validate_order_prepare_binding(&prepared, &challenge, &authorization)?;
        verifier
            .verify(&OrderVerificationContext {
                challenge: &challenge,
                prepared: &prepared,
                owner_wallet: &owner_wallet,
                session_public_key: &session_public_key,
            })
            .await
            .map_err(SdkError::Verification)?;
        let signed_transaction = signer
            .sign_transaction(&prepared.transaction_base64)
            .await
            .map_err(SdkError::Signer)?;
        let signed_transaction =
            canonical_base64(&signed_transaction, "signed_transaction_base64")?;
        self.order_submit(
            &market_id,
            PlatformOrderSubmitRequest {
                order_control_id: prepared.order_control_id.clone(),
                signed_transaction_base64: signed_transaction,
                idempotency_key: normalize_idempotency_key(
                    idempotency_key.unwrap_or(&prepared.order_control_id),
                )?,
            },
        )
        .await
    }

    /// Execute one short-lived Sonar quote without giving the SDK custody of a
    /// session private key. The transaction verifier always runs before the
    /// session adapter is allowed to sign.
    pub async fn execute_quote<S, V>(
        &self,
        quote: &QuoteResponse,
        owner_wallet: &str,
        account_sequence: u64,
        signer: &S,
        verifier: &V,
        idempotency_key: Option<&str>,
    ) -> Result<ExecutionSubmitResponse, SdkError>
    where
        S: SessionSigner + ?Sized,
        V: ExecutionVerifier + ?Sized,
    {
        validate_version(quote.schema_version, &quote.contract_version)?;
        let now_ms = unix_ms()?;
        if quote.expires_at_ms <= now_ms {
            return Err(SdkError::InvalidRequest("quote has expired".to_owned()));
        }
        let owner_wallet = canonical_public_key(owner_wallet, "owner_wallet")?;
        let session_public_key = canonical_public_key(signer.public_key(), "session_public_key")?;
        let markets = self.markets().await?;
        let market = markets
            .markets
            .iter()
            .find(|market| market.market_pda.as_deref() == Some(quote.market_id.as_str()))
            .ok_or_else(|| SdkError::MarketNotFound(quote.market_id.clone()))?;
        let quote_path = market
            .quote_path
            .as_deref()
            .filter(|path| valid_public_operation_path(path))
            .ok_or_else(|| SdkError::OperationUnavailable(market.label.clone()))?;
        let execution_path = format!(
            "{}/execution",
            quote_path
                .strip_suffix("/quote")
                .ok_or_else(|| SdkError::OperationUnavailable(market.label.clone()))?
        );
        let challenge: ExecutionChallengeResponse = self
            .post(
                &format!("{execution_path}/challenge"),
                &ExecutionChallengeRequest {
                    quote_id: quote.quote_id.clone(),
                    owner_wallet: owner_wallet.clone(),
                    session_public_key: session_public_key.clone(),
                    account_sequence: account_sequence.to_string(),
                },
            )
            .await?;
        validate_execution_challenge(&challenge, quote)?;
        let authorization = validate_execution_authorization(
            &challenge,
            quote,
            &owner_wallet,
            &session_public_key,
            account_sequence,
        )?;
        let signature = signer
            .sign_message(&authorization.bytes)
            .await
            .map_err(SdkError::Signer)?;
        if signature.len() != 64 {
            return Err(SdkError::InvalidResponse(
                "session authorization signature must contain 64 bytes".to_owned(),
            ));
        }
        let prepared: ExecutionPrepareResponse = self
            .post(
                &format!("{execution_path}/prepare"),
                &ExecutionPrepareRequest {
                    challenge_id: challenge.challenge_id.clone(),
                    authorization_signature: bs58::encode(signature).into_string(),
                },
            )
            .await?;
        validate_execution_prepare(&prepared, quote, &challenge, &authorization)?;
        verifier
            .verify(&ExecutionVerificationContext {
                quote,
                challenge: &challenge,
                prepared: &prepared,
                owner_wallet: &owner_wallet,
                session_public_key: &session_public_key,
            })
            .await
            .map_err(SdkError::Verification)?;
        let signed_transaction = signer
            .sign_transaction(&prepared.transaction_base64)
            .await
            .map_err(SdkError::Signer)?;
        base64::engine::general_purpose::STANDARD
            .decode(signed_transaction.trim())
            .map_err(|_| {
                SdkError::InvalidResponse(
                    "session signer returned an invalid base64 transaction".to_owned(),
                )
            })?;
        let idempotency_key =
            normalize_idempotency_key(idempotency_key.unwrap_or(&prepared.execution_id))?;
        let submitted: ExecutionSubmitResponse = self
            .post(
                &format!("{execution_path}/submit"),
                &ExecutionSubmitRequest {
                    execution_id: prepared.execution_id.clone(),
                    signed_transaction_base64: signed_transaction,
                    idempotency_key,
                },
            )
            .await?;
        validate_version(submitted.schema_version, &submitted.contract_version)?;
        if submitted.execution_id != prepared.execution_id
            || submitted.status != ExecutionStatus::Submitted
            || submitted.signature.trim().is_empty()
        {
            return Err(SdkError::InvalidResponse(
                "execution receipt does not match the prepared transaction".to_owned(),
            ));
        }
        Ok(submitted)
    }

    async fn get<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)],
    ) -> Result<T, SdkError> {
        let mut url = self.base_url.join(path).map_err(|error| {
            SdkError::InvalidBaseUrl(format!("could not join public operation: {error}"))
        })?;
        url.query_pairs_mut().extend_pairs(query.iter().copied());

        let response = self
            .http
            .get(url)
            .header(reqwest::header::ACCEPT, "application/json")
            .send()
            .await?;
        let status = response.status();
        let bytes = response.bytes().await?;
        if !status.is_success() {
            return match serde_json::from_slice::<ErrorResponse>(&bytes) {
                Ok(error) => Err(SdkError::Api {
                    status,
                    code: error.error.code,
                    message: error.error.message,
                    retryable: error.error.retryable,
                }),
                Err(_) => Err(SdkError::Api {
                    status,
                    code: "request_failed".to_owned(),
                    message: "Strata could not complete the request.".to_owned(),
                    retryable: status.is_server_error(),
                }),
            };
        }
        serde_json::from_slice(&bytes).map_err(|error| SdkError::InvalidResponse(error.to_string()))
    }

    async fn post<T: DeserializeOwned, B: serde::Serialize>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T, SdkError> {
        let url = self.base_url.join(path).map_err(|error| {
            SdkError::InvalidBaseUrl(format!("could not join public operation: {error}"))
        })?;
        let response = self
            .http
            .post(url)
            .header(reqwest::header::ACCEPT, "application/json")
            .json(body)
            .send()
            .await?;
        let status = response.status();
        let bytes = response.bytes().await?;
        if !status.is_success() {
            return match serde_json::from_slice::<ErrorResponse>(&bytes) {
                Ok(error) => Err(SdkError::Api {
                    status,
                    code: error.error.code,
                    message: error.error.message,
                    retryable: error.error.retryable,
                }),
                Err(_) => Err(SdkError::Api {
                    status,
                    code: "request_failed".to_owned(),
                    message: "Strata could not complete the request.".to_owned(),
                    retryable: status.is_server_error(),
                }),
            };
        }
        serde_json::from_slice(&bytes).map_err(|error| SdkError::InvalidResponse(error.to_string()))
    }

    async fn execution_path(&self, requested_market: &str) -> Result<String, SdkError> {
        let markets = self.markets().await?;
        let market = markets
            .markets
            .iter()
            .find(|market| {
                market.label.eq_ignore_ascii_case(requested_market.trim())
                    || market.market_pda.as_deref() == Some(requested_market.trim())
            })
            .ok_or_else(|| SdkError::MarketNotFound(requested_market.to_owned()))?;
        if !market.ready {
            return Err(SdkError::OperationUnavailable(market.label.clone()));
        }
        let quote_path = market
            .quote_path
            .as_deref()
            .filter(|path| valid_public_operation_path(path))
            .ok_or_else(|| SdkError::OperationUnavailable(market.label.clone()))?;
        Ok(format!(
            "{}/execution",
            quote_path
                .strip_suffix("/quote")
                .ok_or_else(|| SdkError::OperationUnavailable(market.label.clone()))?
        ))
    }
}

fn normalize_base_url(value: &str) -> Result<Url, SdkError> {
    let mut normalized = value.trim().to_owned();
    if !normalized.ends_with('/') {
        normalized.push('/');
    }
    let url =
        Url::parse(&normalized).map_err(|error| SdkError::InvalidBaseUrl(error.to_string()))?;
    if !matches!(url.scheme(), "http" | "https") || url.cannot_be_a_base() {
        return Err(SdkError::InvalidBaseUrl(
            "URL must use http or https and include a host".to_owned(),
        ));
    }
    Ok(url)
}

fn validate_action_graph(graph: &ActionGraph) -> Result<(), SdkError> {
    validate_version(graph.schema_version, &graph.contract_version)?;
    if graph.graph_version != "1.0"
        || graph.authority.permission_source != "external_agent_owner"
        || graph.authority.signing_location != "external"
        || graph.authority.accepts_private_keys
    {
        return Err(SdkError::InvalidResponse(
            "unsupported action graph authority model".to_owned(),
        ));
    }
    let ids = graph
        .nodes
        .iter()
        .map(|node| node.id.as_str())
        .collect::<HashSet<_>>();
    if ids.len() != graph.nodes.len() || !ids.contains(graph.entry_node.as_str()) {
        return Err(SdkError::InvalidResponse(
            "action graph node IDs are invalid".to_owned(),
        ));
    }
    if graph.edges.iter().any(|edge| {
        !ids.contains(edge.from.as_str())
            || !ids.contains(edge.to.as_str())
            || edge.condition.trim().is_empty()
    }) {
        return Err(SdkError::InvalidResponse(
            "action graph contains an invalid edge".to_owned(),
        ));
    }
    Ok(())
}

fn validate_version(schema_version: u16, contract_version: &str) -> Result<(), SdkError> {
    if schema_version != CONTRACT_MAJOR || contract_version != CONTRACT_VERSION {
        return Err(SdkError::InvalidResponse(format!(
            "unsupported contract {contract_version} (schema {schema_version})"
        )));
    }
    Ok(())
}

fn validate_platform_version(schema_version: u16, contract_version: &str) -> Result<(), SdkError> {
    if schema_version != strata_public_contract::platform::PLATFORM_SCHEMA_VERSION
        || contract_version != strata_public_contract::platform::PLATFORM_CONTRACT_VERSION
    {
        return Err(SdkError::InvalidResponse(format!(
            "unsupported platform contract {contract_version} (schema {schema_version})"
        )));
    }
    Ok(())
}

fn validate_platform_market_id(value: &str) -> Result<String, SdkError> {
    let value = value.trim();
    if !valid_handle(value, "market_") {
        return Err(SdkError::InvalidRequest(
            "market_id must be an opaque Strata market ID".to_owned(),
        ));
    }
    Ok(value.to_owned())
}

fn canonical_request_atoms(value: &str, field: &str, allow_zero: bool) -> Result<String, SdkError> {
    if value.is_empty()
        || !value.bytes().all(|byte| byte.is_ascii_digit())
        || (value.len() > 1 && value.starts_with('0'))
    {
        return Err(SdkError::InvalidRequest(format!(
            "{field} must be a canonical unsigned atomic decimal string"
        )));
    }
    let parsed = value
        .parse::<u64>()
        .map_err(|_| SdkError::InvalidRequest(format!("{field} exceeds u64")))?;
    if !allow_zero && parsed == 0 {
        return Err(SdkError::InvalidRequest(format!(
            "{field} must be greater than zero"
        )));
    }
    Ok(parsed.to_string())
}

fn canonical_signature(value: &str, field: &str) -> Result<String, SdkError> {
    let value = value.trim();
    let decoded = bs58::decode(value)
        .into_vec()
        .map_err(|_| SdkError::InvalidRequest(format!("{field} must be base58")))?;
    if decoded.len() != 64 || bs58::encode(&decoded).into_string() != value {
        return Err(SdkError::InvalidRequest(format!(
            "{field} must be a canonical Ed25519 signature"
        )));
    }
    Ok(value.to_owned())
}

fn canonical_base58_32(value: &str, field: &str) -> Result<String, SdkError> {
    let value = value.trim();
    let decoded = bs58::decode(value)
        .into_vec()
        .map_err(|_| SdkError::InvalidRequest(format!("{field} must be base58")))?;
    if decoded.len() != 32 || bs58::encode(&decoded).into_string() != value {
        return Err(SdkError::InvalidRequest(format!(
            "{field} must be a canonical 32-byte base58 value"
        )));
    }
    Ok(value.to_owned())
}

fn canonical_base64(value: &str, field: &str) -> Result<String, SdkError> {
    let value = value.trim();
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(value)
        .map_err(|_| SdkError::InvalidRequest(format!("{field} must be base64")))?;
    if decoded.is_empty() || base64::engine::general_purpose::STANDARD.encode(decoded) != value {
        return Err(SdkError::InvalidRequest(format!(
            "{field} must be canonical base64"
        )));
    }
    Ok(value.to_owned())
}

fn normalize_order_challenge_request(
    request: PlatformOrderChallengeRequest,
) -> Result<PlatformOrderChallengeRequest, SdkError> {
    let normalized = match request {
        PlatformOrderChallengeRequest::Place {
            owner_wallet,
            session_public_key,
            account_sequence,
            client_order_id,
            side,
            order_type,
            limit_price_atoms,
            size_atoms,
        } => {
            let client_order_id = client_order_id.trim().to_owned();
            if client_order_id.is_empty()
                || client_order_id.len() > 64
                || !client_order_id
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
                || !matches!(
                    order_type,
                    PlatformOrderType::GoodUntilCancelled | PlatformOrderType::PostOnly
                )
            {
                return Err(SdkError::InvalidRequest(
                    "resting order client ID or type is invalid".to_owned(),
                ));
            }
            PlatformOrderChallengeRequest::Place {
                owner_wallet: canonical_public_key(&owner_wallet, "owner_wallet")?,
                session_public_key: canonical_public_key(
                    &session_public_key,
                    "session_public_key",
                )?,
                account_sequence: canonical_request_atoms(
                    &account_sequence,
                    "account_sequence",
                    true,
                )?,
                client_order_id,
                side,
                order_type,
                limit_price_atoms: canonical_request_atoms(
                    &limit_price_atoms,
                    "limit_price_atoms",
                    false,
                )?,
                size_atoms: canonical_request_atoms(&size_atoms, "size_atoms", false)?,
            }
        }
        PlatformOrderChallengeRequest::Cancel {
            owner_wallet,
            session_public_key,
            order_id,
        } => {
            if !valid_handle(order_id.trim(), "order_") {
                return Err(SdkError::InvalidRequest("order_id is invalid".to_owned()));
            }
            PlatformOrderChallengeRequest::Cancel {
                owner_wallet: canonical_public_key(&owner_wallet, "owner_wallet")?,
                session_public_key: canonical_public_key(
                    &session_public_key,
                    "session_public_key",
                )?,
                order_id: order_id.trim().to_owned(),
            }
        }
        PlatformOrderChallengeRequest::CancelAll {
            owner_wallet,
            session_public_key,
        } => PlatformOrderChallengeRequest::CancelAll {
            owner_wallet: canonical_public_key(&owner_wallet, "owner_wallet")?,
            session_public_key: canonical_public_key(&session_public_key, "session_public_key")?,
        },
    };
    if order_request_owner(&normalized) == order_request_session(&normalized) {
        return Err(SdkError::InvalidRequest(
            "session_public_key must be distinct from owner_wallet".to_owned(),
        ));
    }
    Ok(normalized)
}

fn order_request_action(request: &PlatformOrderChallengeRequest) -> PlatformOrderAction {
    match request {
        PlatformOrderChallengeRequest::Place { .. } => PlatformOrderAction::Place,
        PlatformOrderChallengeRequest::Cancel { .. } => PlatformOrderAction::Cancel,
        PlatformOrderChallengeRequest::CancelAll { .. } => PlatformOrderAction::CancelAll,
    }
}

fn order_request_owner(request: &PlatformOrderChallengeRequest) -> &str {
    match request {
        PlatformOrderChallengeRequest::Place { owner_wallet, .. }
        | PlatformOrderChallengeRequest::Cancel { owner_wallet, .. }
        | PlatformOrderChallengeRequest::CancelAll { owner_wallet, .. } => owner_wallet,
    }
}

fn order_request_session(request: &PlatformOrderChallengeRequest) -> &str {
    match request {
        PlatformOrderChallengeRequest::Place {
            session_public_key, ..
        }
        | PlatformOrderChallengeRequest::Cancel {
            session_public_key, ..
        }
        | PlatformOrderChallengeRequest::CancelAll {
            session_public_key, ..
        } => session_public_key,
    }
}

struct OrderAuthorization {
    bytes: Vec<u8>,
    recent_blockhash: String,
    last_valid_block_height: u64,
}

fn validate_order_authorization(
    challenge: &PlatformOrderChallengeResponse,
    request: &PlatformOrderChallengeRequest,
) -> Result<OrderAuthorization, SdkError> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(challenge.authorization_payload_base64.trim())
        .map_err(|_| SdkError::InvalidResponse("order authorization is not base64".to_owned()))?;
    let owner = decode_public_key(order_request_owner(request), "owner_wallet")?;
    let session = decode_public_key(order_request_session(request), "session_public_key")?;
    let mut cursor = 0usize;
    take_expected(
        &bytes,
        &mut cursor,
        PUBLIC_ORDER_AUTH_DOMAIN,
        "order authorization domain",
    )?;
    let _market = take_bytes(&bytes, &mut cursor, 32, "order authorization market")?;
    take_expected(&bytes, &mut cursor, &owner, "order authorization owner")?;
    take_expected(&bytes, &mut cursor, &session, "order authorization session")?;
    let action = take_bytes(&bytes, &mut cursor, 1, "order authorization action")?[0];
    let expected_action = match order_request_action(request) {
        PlatformOrderAction::Place => 0,
        PlatformOrderAction::Cancel => 1,
        PlatformOrderAction::CancelAll => 2,
    };
    if action != expected_action || challenge.action != order_request_action(request) {
        return Err(SdkError::InvalidResponse(
            "order authorization action changed".to_owned(),
        ));
    }
    let mut derived_order_ids = Vec::new();
    match request {
        PlatformOrderChallengeRequest::Place {
            account_sequence,
            client_order_id,
            side,
            order_type,
            limit_price_atoms,
            size_atoms,
            ..
        } => {
            take_u64_eq(
                &bytes,
                &mut cursor,
                parse_request_u64(account_sequence, "account_sequence")?,
                "order account sequence",
            )?;
            let client_length = take_u16(&bytes, &mut cursor, "client order ID length")? as usize;
            if client_length != client_order_id.len() {
                return Err(SdkError::InvalidResponse(
                    "client order ID length changed".to_owned(),
                ));
            }
            take_expected(
                &bytes,
                &mut cursor,
                client_order_id.as_bytes(),
                "client order ID",
            )?;
            let actual_side = take_bytes(&bytes, &mut cursor, 1, "order side")?[0];
            let expected_side = if *side == PlatformTradeSide::Buy {
                0
            } else {
                1
            };
            if actual_side != expected_side {
                return Err(SdkError::InvalidResponse("order side changed".to_owned()));
            }
            let actual_type = take_bytes(&bytes, &mut cursor, 1, "order type")?[0];
            let expected_type = match order_type {
                PlatformOrderType::GoodUntilCancelled => 0,
                PlatformOrderType::PostOnly => 3,
                PlatformOrderType::ImmediateOrCancel | PlatformOrderType::FillOrKill => {
                    return Err(SdkError::InvalidRequest(
                        "order type is not a resting order".to_owned(),
                    ));
                }
            };
            if actual_type != expected_type {
                return Err(SdkError::InvalidResponse("order type changed".to_owned()));
            }
            take_u64_eq(
                &bytes,
                &mut cursor,
                parse_request_u64(limit_price_atoms, "limit_price_atoms")?,
                "order limit price",
            )?;
            take_u64_eq(
                &bytes,
                &mut cursor,
                parse_request_u64(size_atoms, "size_atoms")?,
                "order size",
            )?;
            let order = take_bytes(&bytes, &mut cursor, 32, "order identity")?;
            derived_order_ids.push(opaque_order_id(&challenge.market_id, order));
        }
        PlatformOrderChallengeRequest::Cancel { .. }
        | PlatformOrderChallengeRequest::CancelAll { .. } => {
            let count = usize::from(take_bytes(&bytes, &mut cursor, 1, "cancel order count")?[0]);
            if count == 0
                || count > 6
                || (matches!(request, PlatformOrderChallengeRequest::Cancel { .. }) && count != 1)
            {
                return Err(SdkError::InvalidResponse(
                    "cancel order count changed".to_owned(),
                ));
            }
            for index in 0..count {
                let order = take_bytes(&bytes, &mut cursor, 32, &format!("cancel order {index}"))?;
                let rent_source = take_bytes(
                    &bytes,
                    &mut cursor,
                    1,
                    &format!("cancel rent source {index}"),
                )?[0];
                if rent_source > 1 {
                    return Err(SdkError::InvalidResponse(
                        "cancel rent source is invalid".to_owned(),
                    ));
                }
                derived_order_ids.push(opaque_order_id(&challenge.market_id, order));
            }
            if let PlatformOrderChallengeRequest::Cancel { order_id, .. } = request {
                if derived_order_ids.first() != Some(order_id) {
                    return Err(SdkError::InvalidResponse(
                        "cancel order identity changed".to_owned(),
                    ));
                }
            }
        }
    }
    if derived_order_ids != challenge.order_ids {
        return Err(SdkError::InvalidResponse(
            "order authorization opaque identities changed".to_owned(),
        ));
    }
    let recent_blockhash = bs58::encode(take_bytes(
        &bytes,
        &mut cursor,
        32,
        "order authorization blockhash",
    )?)
    .into_string();
    let last_valid_block_height = take_u64(
        &bytes,
        &mut cursor,
        "order authorization last valid block height",
    )?;
    take_u64_eq(
        &bytes,
        &mut cursor,
        challenge.expires_at_ms,
        "order authorization expiry",
    )?;
    let nonce = take_bytes(&bytes, &mut cursor, 16, "order authorization nonce")?;
    if hex::encode(nonce) != challenge.challenge_id[3..] {
        return Err(SdkError::InvalidResponse(
            "order challenge nonce changed".to_owned(),
        ));
    }
    let _epoch = take_bytes(&bytes, &mut cursor, 16, "order authorization epoch")?;
    if cursor != bytes.len() {
        return Err(SdkError::InvalidResponse(
            "order authorization contains unrecognized fields".to_owned(),
        ));
    }
    Ok(OrderAuthorization {
        bytes,
        recent_blockhash,
        last_valid_block_height,
    })
}

fn validate_order_prepare_binding(
    prepared: &PlatformOrderPrepareResponse,
    challenge: &PlatformOrderChallengeResponse,
    authorization: &OrderAuthorization,
) -> Result<(), SdkError> {
    if prepared.market_id != challenge.market_id
        || prepared.action != challenge.action
        || prepared.order_ids != challenge.order_ids
        || prepared.recent_blockhash != authorization.recent_blockhash
        || prepared.last_valid_block_height != authorization.last_valid_block_height
        || prepared.expires_at_ms != challenge.expires_at_ms
    {
        return Err(SdkError::InvalidResponse(
            "prepared order control changed the signed bindings".to_owned(),
        ));
    }
    Ok(())
}

fn parse_request_u64(value: &str, field: &str) -> Result<u64, SdkError> {
    value
        .parse::<u64>()
        .map_err(|_| SdkError::InvalidRequest(format!("{field} exceeds u64")))
}

fn take_u16(source: &[u8], cursor: &mut usize, field: &str) -> Result<u16, SdkError> {
    let bytes: [u8; 2] = take_bytes(source, cursor, 2, field)?
        .try_into()
        .map_err(|_| SdkError::InvalidResponse(format!("{field} is invalid")))?;
    Ok(u16::from_le_bytes(bytes))
}

fn opaque_order_id(market_id: &str, order: &[u8]) -> String {
    let mut digest = Sha256::new();
    digest.update(b"strata-sdk-product:v1\0");
    digest.update(b"order");
    digest.update([0]);
    digest.update(market_id.as_bytes());
    digest.update(b":");
    digest.update(bs58::encode(order).into_string().as_bytes());
    format!("order_{}", hex::encode(&digest.finalize()[..16]))
}

fn parse_atoms(field: &str, value: &str) -> Result<u64, SdkError> {
    if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(SdkError::InvalidResponse(format!(
            "{field} must be an unsigned atomic decimal string"
        )));
    }
    value
        .parse::<u64>()
        .map_err(|_| SdkError::InvalidResponse(format!("{field} exceeds the supported range")))
}

fn valid_public_operation_path(path: &str) -> bool {
    let Some(market_id) = path
        .strip_prefix("/sonar/markets/")
        .and_then(|value| value.strip_suffix("/quote"))
    else {
        return false;
    };
    !market_id.is_empty()
        && !market_id.starts_with('-')
        && !market_id.ends_with('-')
        && market_id
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
}

fn validate_quote(
    quote: &QuoteResponse,
    market_id: &str,
    request: &QuoteRequest,
    requested_amount: u64,
) -> Result<(), SdkError> {
    validate_version(quote.schema_version, &quote.contract_version)?;
    if quote.provider != "Sonar"
        || quote.market_id != market_id
        || quote.side != request.side
        || quote.amount_in_atoms != request.amount_in_atoms
        || quote.quote_id.len() != 35
        || !quote.quote_id.starts_with("sq_")
        || !quote.quote_id[3..]
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        || quote.expires_at_ms <= quote.server_time_ms
    {
        return Err(SdkError::InvalidResponse(
            "quote binding or lifetime is invalid".to_owned(),
        ));
    }

    let consumed = parse_atoms("amount_in_consumed_atoms", &quote.amount_in_consumed_atoms)?;
    let output = parse_atoms("amount_out_atoms", &quote.amount_out_atoms)?;
    let minimum = parse_atoms("minimum_output_atoms", &quote.minimum_output_atoms)?;
    parse_atoms("input_fee_atoms", &quote.input_fee_atoms)?;
    parse_atoms("output_fee_atoms", &quote.output_fee_atoms)?;
    if consumed > requested_amount || minimum > output {
        return Err(SdkError::InvalidResponse(
            "quote economics are internally inconsistent".to_owned(),
        ));
    }
    quote
        .reference_price
        .parse::<f64>()
        .ok()
        .filter(|value| value.is_finite() && *value > 0.0)
        .ok_or_else(|| SdkError::InvalidResponse("reference_price is invalid".to_owned()))?;
    quote
        .price_impact_pct
        .parse::<f64>()
        .ok()
        .filter(|value| value.is_finite() && *value >= 0.0)
        .ok_or_else(|| SdkError::InvalidResponse("price_impact_pct is invalid".to_owned()))?;
    Ok(())
}

struct ExecutionAuthorization {
    bytes: Vec<u8>,
    recent_blockhash: String,
    last_valid_block_height: u64,
}

fn validate_execution_challenge(
    challenge: &ExecutionChallengeResponse,
    quote: &QuoteResponse,
) -> Result<(), SdkError> {
    validate_version(challenge.schema_version, &challenge.contract_version)?;
    validate_execution_binding(
        &challenge.quote_id,
        &challenge.market_id,
        challenge.side,
        &challenge.amount_in_atoms,
        &challenge.minimum_output_atoms,
        quote,
    )?;
    if !valid_handle(&challenge.challenge_id, "sc_")
        || challenge.expires_at_ms <= challenge.server_time_ms
        || challenge.expires_at_ms > quote.expires_at_ms
    {
        return Err(SdkError::InvalidResponse(
            "execution challenge binding or lifetime is invalid".to_owned(),
        ));
    }
    Ok(())
}

fn validate_execution_prepare(
    prepared: &ExecutionPrepareResponse,
    quote: &QuoteResponse,
    challenge: &ExecutionChallengeResponse,
    authorization: &ExecutionAuthorization,
) -> Result<(), SdkError> {
    validate_version(prepared.schema_version, &prepared.contract_version)?;
    validate_execution_binding(
        &prepared.quote_id,
        &prepared.market_id,
        prepared.side,
        &prepared.amount_in_atoms,
        &prepared.minimum_output_atoms,
        quote,
    )?;
    if !valid_handle(&prepared.execution_id, "se_")
        || prepared.recent_blockhash != authorization.recent_blockhash
        || prepared.last_valid_block_height != authorization.last_valid_block_height
        || prepared.expires_at_ms > challenge.expires_at_ms
        || prepared.transaction_base64.trim().is_empty()
        || base64::engine::general_purpose::STANDARD
            .decode(prepared.transaction_base64.trim())
            .is_err()
    {
        return Err(SdkError::InvalidResponse(
            "prepared execution changed the signed authorization".to_owned(),
        ));
    }
    Ok(())
}

fn validate_execution_binding(
    quote_id: &str,
    market_id: &str,
    side: QuoteSide,
    amount_in_atoms: &str,
    minimum_output_atoms: &str,
    quote: &QuoteResponse,
) -> Result<(), SdkError> {
    if quote_id != quote.quote_id
        || market_id != quote.market_id
        || side != quote.side
        || amount_in_atoms != quote.amount_in_atoms
        || minimum_output_atoms != quote.minimum_output_atoms
    {
        return Err(SdkError::InvalidResponse(
            "execution does not match the Sonar quote".to_owned(),
        ));
    }
    Ok(())
}

fn validate_execution_authorization(
    challenge: &ExecutionChallengeResponse,
    quote: &QuoteResponse,
    owner_wallet: &str,
    session_public_key: &str,
    account_sequence: u64,
) -> Result<ExecutionAuthorization, SdkError> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(challenge.authorization_payload_base64.trim())
        .map_err(|_| SdkError::InvalidResponse("authorization payload is not base64".to_owned()))?;
    let market = decode_public_key(&quote.market_id, "market_id")?;
    let owner = decode_public_key(owner_wallet, "owner_wallet")?;
    let session = decode_public_key(session_public_key, "session_public_key")?;
    let mut cursor = 0usize;
    take_expected(
        &bytes,
        &mut cursor,
        PUBLIC_EXECUTION_AUTH_DOMAIN,
        "authorization domain",
    )?;
    take_expected(&bytes, &mut cursor, &market, "authorization market")?;
    take_expected(
        &bytes,
        &mut cursor,
        quote.quote_id.as_bytes(),
        "authorization quote",
    )?;
    take_expected(&bytes, &mut cursor, &owner, "authorization owner")?;
    take_expected(&bytes, &mut cursor, &session, "authorization session")?;
    let side = take_bytes(&bytes, &mut cursor, 1, "authorization side")?[0];
    if side != if quote.side == QuoteSide::Buy { 0 } else { 1 } {
        return Err(SdkError::InvalidResponse(
            "authorization side changed".to_owned(),
        ));
    }
    take_u64_eq(
        &bytes,
        &mut cursor,
        parse_atoms("amount_in_atoms", &quote.amount_in_atoms)?,
        "authorization input",
    )?;
    take_u64_eq(
        &bytes,
        &mut cursor,
        parse_atoms("minimum_output_atoms", &quote.minimum_output_atoms)?,
        "authorization minimum output",
    )?;
    take_u64_eq(
        &bytes,
        &mut cursor,
        account_sequence,
        "authorization account sequence",
    )?;
    let _output_balance = take_u64(&bytes, &mut cursor, "authorization output balance")?;
    let recent_blockhash = bs58::encode(take_bytes(
        &bytes,
        &mut cursor,
        32,
        "authorization blockhash",
    )?)
    .into_string();
    let last_valid_block_height =
        take_u64(&bytes, &mut cursor, "authorization last valid block height")?;
    take_u64_eq(
        &bytes,
        &mut cursor,
        challenge.expires_at_ms,
        "authorization expiry",
    )?;
    let nonce = take_bytes(&bytes, &mut cursor, 16, "authorization nonce")?;
    if hex::encode(nonce) != challenge.challenge_id[3..] {
        return Err(SdkError::InvalidResponse(
            "authorization challenge nonce changed".to_owned(),
        ));
    }
    let _epoch = take_bytes(&bytes, &mut cursor, 16, "authorization epoch")?;
    if cursor != bytes.len() {
        return Err(SdkError::InvalidResponse(
            "authorization contains unrecognized fields".to_owned(),
        ));
    }
    Ok(ExecutionAuthorization {
        bytes,
        recent_blockhash,
        last_valid_block_height,
    })
}

fn take_expected(
    source: &[u8],
    cursor: &mut usize,
    expected: &[u8],
    field: &str,
) -> Result<(), SdkError> {
    if take_bytes(source, cursor, expected.len(), field)? != expected {
        return Err(SdkError::InvalidResponse(format!("{field} changed")));
    }
    Ok(())
}

fn take_bytes<'a>(
    source: &'a [u8],
    cursor: &mut usize,
    length: usize,
    field: &str,
) -> Result<&'a [u8], SdkError> {
    let end = cursor
        .checked_add(length)
        .filter(|end| *end <= source.len())
        .ok_or_else(|| SdkError::InvalidResponse(format!("{field} is missing")))?;
    let value = &source[*cursor..end];
    *cursor = end;
    Ok(value)
}

fn take_u64(source: &[u8], cursor: &mut usize, field: &str) -> Result<u64, SdkError> {
    let bytes: [u8; 8] = take_bytes(source, cursor, 8, field)?
        .try_into()
        .map_err(|_| SdkError::InvalidResponse(format!("{field} is invalid")))?;
    Ok(u64::from_le_bytes(bytes))
}

fn take_u64_eq(
    source: &[u8],
    cursor: &mut usize,
    expected: u64,
    field: &str,
) -> Result<(), SdkError> {
    if take_u64(source, cursor, field)? != expected {
        return Err(SdkError::InvalidResponse(format!("{field} changed")));
    }
    Ok(())
}

fn decode_public_key(value: &str, field: &str) -> Result<Vec<u8>, SdkError> {
    let bytes = bs58::decode(value.trim())
        .into_vec()
        .map_err(|_| SdkError::InvalidRequest(format!("{field} must be base58")))?;
    if bytes.len() != 32 || bs58::encode(&bytes).into_string() != value.trim() {
        return Err(SdkError::InvalidRequest(format!(
            "{field} must be a canonical 32-byte public key"
        )));
    }
    Ok(bytes)
}

fn canonical_public_key(value: &str, field: &str) -> Result<String, SdkError> {
    decode_public_key(value, field)?;
    Ok(value.trim().to_owned())
}

fn valid_handle(value: &str, prefix: &str) -> bool {
    value.len() == prefix.len() + 32
        && value.starts_with(prefix)
        && value[prefix.len()..]
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn normalize_idempotency_key(value: &str) -> Result<String, SdkError> {
    let value = value.trim();
    if value.is_empty()
        || value.len() > 64
        || !value.bytes().all(|byte| {
            byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_' || byte == b'.'
        })
    {
        return Err(SdkError::InvalidRequest(
            "idempotency key must contain 1-64 URL-safe characters".to_owned(),
        ));
    }
    Ok(value.to_owned())
}

fn unix_ms() -> Result<u64, SdkError> {
    let elapsed = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| SdkError::InvalidRequest("system clock is before Unix epoch".to_owned()))?;
    u64::try_from(elapsed.as_millis())
        .map_err(|_| SdkError::InvalidRequest("system clock exceeds supported range".to_owned()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{body_json, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn fixture(path: &str) -> serde_json::Value {
        let raw = match path {
            "action-graph" => strata_public_contract::contract_fixtures::ACTION_GRAPH,
            "markets" => strata_public_contract::contract_fixtures::MARKETS,
            "quote" => strata_public_contract::contract_fixtures::QUOTE,
            "capabilities" => strata_public_contract::contract_fixtures::CAPABILITIES,
            "order-challenge" => strata_public_contract::platform::PLATFORM_ORDER_CHALLENGE_FIXTURE,
            "order-prepare" => strata_public_contract::platform::PLATFORM_ORDER_PREPARE_FIXTURE,
            "order-submit" => strata_public_contract::platform::PLATFORM_ORDER_SUBMIT_FIXTURE,
            _ => unreachable!(),
        };
        serde_json::from_str(raw).unwrap()
    }

    #[tokio::test]
    async fn reads_capabilities_and_quotes_without_internal_metadata() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/sonar/capabilities"))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("capabilities")))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/sonar/markets"))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("markets")))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/sonar/action-graph"))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("action-graph")))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/sonar/markets/sol-usdc/quote"))
            .and(body_json(serde_json::json!({
                "market_id": "11111111111111111111111111111111",
                "side": "sell",
                "amount_in_atoms": "10000000",
                "slippage_bps": 50
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("quote")))
            .expect(1)
            .mount(&server)
            .await;

        let client = StrataClient::new(server.uri()).unwrap();
        let capabilities = client.capabilities().await.unwrap();
        assert!(capabilities
            .capabilities
            .iter()
            .any(|capability| capability.id == "quotes.read"));

        let graph = client.action_graph().await.unwrap();
        assert_eq!(graph.entry_node, "discover_capabilities");
        assert_eq!(graph.authority.permission_source, "external_agent_owner");

        let quote = client
            .quote(QuoteRequest {
                market_id: "SOL/USDC".to_owned(),
                side: QuoteSide::Sell,
                amount_in_atoms: "10000000".to_owned(),
                slippage_bps: 50,
            })
            .await
            .unwrap();
        let public = serde_json::to_value(quote).unwrap();
        assert!(public.get("quote_id").is_some());
        assert!(public.get("unexpected_field").is_none());
    }

    #[tokio::test]
    async fn resting_order_calls_use_only_product_paths_and_external_signatures() {
        let server = MockServer::start().await;
        let market_id = "market_22222222222222222222222222222222";
        let owner_wallet = bs58::encode([1u8; 32]).into_string();
        let session_public_key = bs58::encode([2u8; 32]).into_string();
        let authorization_signature = bs58::encode([3u8; 64]).into_string();
        Mock::given(method("POST"))
            .and(path(format!("/v2/markets/{market_id}/orders/challenge")))
            .and(body_json(serde_json::json!({
                "action": "place",
                "owner_wallet": owner_wallet,
                "session_public_key": session_public_key,
                "account_sequence": "7",
                "client_order_id": "agent-order-7",
                "side": "buy",
                "order_type": "post_only",
                "limit_price_atoms": "150000000",
                "size_atoms": "1000000"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("order-challenge")))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path(format!("/v2/markets/{market_id}/orders/prepare")))
            .and(body_json(serde_json::json!({
                "challenge_id": "oc_11111111111111111111111111111111",
                "authorization_signature": authorization_signature
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("order-prepare")))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path(format!("/v2/markets/{market_id}/orders/submit")))
            .and(body_json(serde_json::json!({
                "order_control_id": "or_44444444444444444444444444444444",
                "signed_transaction_base64": "AQIDBA==",
                "idempotency_key": "order-attempt-7"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(fixture("order-submit")))
            .expect(1)
            .mount(&server)
            .await;

        let client = StrataClient::new(server.uri()).unwrap();
        let challenge = client
            .order_challenge(
                market_id,
                PlatformOrderChallengeRequest::Place {
                    owner_wallet,
                    session_public_key,
                    account_sequence: "7".to_owned(),
                    client_order_id: "agent-order-7".to_owned(),
                    side: PlatformTradeSide::Buy,
                    order_type: PlatformOrderType::PostOnly,
                    limit_price_atoms: "150000000".to_owned(),
                    size_atoms: "1000000".to_owned(),
                },
            )
            .await
            .unwrap();
        let prepared = client
            .order_prepare(
                market_id,
                PlatformOrderPrepareRequest {
                    challenge_id: challenge.challenge_id,
                    authorization_signature,
                },
            )
            .await
            .unwrap();
        let receipt = client
            .order_submit(
                market_id,
                PlatformOrderSubmitRequest {
                    order_control_id: prepared.order_control_id,
                    signed_transaction_base64: "AQIDBA==".to_owned(),
                    idempotency_key: "order-attempt-7".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(receipt.status, PlatformOrderSubmissionStatus::Submitted);
    }

    #[test]
    fn order_authorization_parser_binds_every_public_place_field() {
        let owner = [1u8; 32];
        let session = [2u8; 32];
        let order = [3u8; 32];
        let nonce = [4u8; 16];
        let blockhash = [5u8; 32];
        let epoch = [6u8; 16];
        let market_id = "market_22222222222222222222222222222222";
        let expires_at_ms = 1_786_550_460_000u64;
        let request = PlatformOrderChallengeRequest::Place {
            owner_wallet: bs58::encode(owner).into_string(),
            session_public_key: bs58::encode(session).into_string(),
            account_sequence: "7".to_owned(),
            client_order_id: "agent-order-7".to_owned(),
            side: PlatformTradeSide::Buy,
            order_type: PlatformOrderType::PostOnly,
            limit_price_atoms: "150000000".to_owned(),
            size_atoms: "1000000".to_owned(),
        };
        let mut payload = Vec::new();
        payload.extend_from_slice(PUBLIC_ORDER_AUTH_DOMAIN);
        payload.extend_from_slice(&[9u8; 32]);
        payload.extend_from_slice(&owner);
        payload.extend_from_slice(&session);
        payload.push(0);
        payload.extend_from_slice(&7u64.to_le_bytes());
        payload.extend_from_slice(&("agent-order-7".len() as u16).to_le_bytes());
        payload.extend_from_slice(b"agent-order-7");
        payload.push(0);
        payload.push(3);
        payload.extend_from_slice(&150_000_000u64.to_le_bytes());
        payload.extend_from_slice(&1_000_000u64.to_le_bytes());
        payload.extend_from_slice(&order);
        payload.extend_from_slice(&blockhash);
        payload.extend_from_slice(&400_000_000u64.to_le_bytes());
        payload.extend_from_slice(&expires_at_ms.to_le_bytes());
        payload.extend_from_slice(&nonce);
        payload.extend_from_slice(&epoch);
        let challenge = PlatformOrderChallengeResponse {
            schema_version: 2,
            contract_version: "2.0".to_owned(),
            challenge_id: format!("oc_{}", hex::encode(nonce)),
            market_id: market_id.to_owned(),
            action: PlatformOrderAction::Place,
            order_ids: vec![opaque_order_id(market_id, &order)],
            authorization_payload_base64: base64::engine::general_purpose::STANDARD.encode(payload),
            server_time_ms: expires_at_ms - 60_000,
            expires_at_ms,
        };
        let authorization = validate_order_authorization(&challenge, &request).unwrap();
        assert_eq!(
            authorization.recent_blockhash,
            bs58::encode(blockhash).into_string()
        );
        assert_eq!(authorization.last_valid_block_height, 400_000_000);

        let mut changed = request;
        if let PlatformOrderChallengeRequest::Place { size_atoms, .. } = &mut changed {
            *size_atoms = "1000001".to_owned();
        }
        assert!(validate_order_authorization(&challenge, &changed).is_err());
    }

    #[test]
    fn rejects_non_http_base_urls() {
        assert!(matches!(
            StrataClient::new("file:///tmp/contract"),
            Err(SdkError::InvalidBaseUrl(_))
        ));
    }

    #[test]
    fn accepts_only_product_level_quote_operation_paths() {
        assert!(valid_public_operation_path("/sonar/markets/sol-usdc/quote"));
        for unsupported_or_ambiguous in [
            "/unsupported/build",
            "/unsupported/quote",
            "/sonar/markets/../quote",
            "/sonar/markets/SOL-USDC/quote",
        ] {
            assert!(!valid_public_operation_path(unsupported_or_ambiguous));
        }
    }
}