strata-public-contract 0.1.7

Shared Rust types 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
//! Public SDK 2.0 request and response primitives.

use serde::{Deserialize, Serialize};

use crate::{CapabilityRisk, McpExposure};

pub const PLATFORM_SCHEMA_VERSION: u16 = 2;
pub const PLATFORM_CONTRACT_VERSION: &str = "2.0";
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_CAPABILITIES_FIXTURE: &str =
    include_str!("../fixtures/v2/platform-capabilities.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ASSETS_FIXTURE: &str = include_str!("../fixtures/v2/assets.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_MARKETS_FIXTURE: &str = include_str!("../fixtures/v2/markets.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_BOOK_FIXTURE: &str = include_str!("../fixtures/v2/book.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_BBO_FIXTURE: &str = include_str!("../fixtures/v2/bbo.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_FEES_FIXTURE: &str = include_str!("../fixtures/v2/fees.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_STATUS_FIXTURE: &str = include_str!("../fixtures/v2/status.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_TRADES_FIXTURE: &str = include_str!("../fixtures/v2/trades.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ACCOUNT_FIXTURE: &str = include_str!("../fixtures/v2/account.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_CHALLENGE_FIXTURE: &str =
    include_str!("../fixtures/v2/order-challenge.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_PREPARE_FIXTURE: &str = include_str!("../fixtures/v2/order-prepare.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_SUBMIT_FIXTURE: &str = include_str!("../fixtures/v2/order-submit.json");
#[cfg(any(test, feature = "fixtures"))]
#[doc(hidden)]
pub const PLATFORM_ORDER_STATUS_FIXTURE: &str = include_str!("../fixtures/v2/order-status.json");

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionSource {
    ExternalAgentOwner,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SigningLocation {
    External,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAuthority {
    pub permission_source: PermissionSource,
    pub signing_location: SigningLocation,
    pub accepts_private_keys: bool,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformTransport {
    Http,
    Websocket,
    Mcp,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMarketState {
    Active,
    ReadOnly,
    QuoteOnly,
    CancelOnly,
    Paused,
    Warming,
    Degraded,
    Unavailable,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderState {
    Created,
    Accepted,
    Open,
    PartiallyFilled,
    Filled,
    CancelPending,
    Cancelled,
    Expired,
    Rejected,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformSettlementState {
    NotApplicable,
    Pending,
    Confirmed,
    Failed,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformPublicErrorCode {
    InvalidRequest,
    UnsupportedCapability,
    MarketUnavailable,
    MarketWarming,
    QuoteUnavailable,
    QuoteExpired,
    PriceBoundFailed,
    InsufficientBalance,
    PolicyRejected,
    SessionExpired,
    SequenceConflict,
    DuplicateClientId,
    OrderRejected,
    OrderNotFound,
    CancelTooLate,
    RateLimited,
    TemporarilyUnavailable,
    SubmissionAmbiguous,
    SettlementPending,
    SettlementFailed,
}

/// Exact asset amount. Public money never crosses the contract as a float.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ExactAmount {
    pub asset_id: String,
    pub atoms: String,
}

/// Sequence metadata shared by all recoverable state streams.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SequenceEnvelope {
    pub stream_id: String,
    pub sequence: String,
    pub previous_sequence: Option<String>,
    pub server_time_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot_id: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PageRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PageInfo {
    pub next_cursor: Option<String>,
    pub has_more: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PublicOperationError {
    pub code: PlatformPublicErrorCode,
    pub message: String,
    pub retryable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_ms: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation_id: Option<String>,
}

/// One operation currently callable through the live v2 gateway.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LivePlatformCapability {
    pub id: String,
    pub risk: CapabilityRisk,
    pub required_scope: String,
    pub transports: Vec<PlatformTransport>,
    pub mcp_exposure: McpExposure,
}

/// Operations currently available to the client.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformDiscoveryResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub authority: PlatformAuthority,
    pub capabilities: Vec<LivePlatformCapability>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformNetwork {
    Solana,
}

/// Asset identity used by ordinary SDK operations.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAsset {
    pub asset_id: String,
    pub symbol: String,
    pub name: String,
    pub decimals: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo_url: Option<String>,
    pub network: PlatformNetwork,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAssetsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub assets: Vec<PlatformAsset>,
    pub page: PageInfo,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformMarketAction {
    Quote,
    ExecuteImmediate,
    PlaceOrder,
    ScheduleTwap,
}

/// Stable market metadata for public SDK operations.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMarket {
    pub market_id: String,
    pub label: String,
    pub base_asset_id: String,
    pub quote_asset_id: String,
    pub status: PlatformMarketState,
    pub available_actions: Vec<PlatformMarketAction>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMarketsResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub server_time_ms: u64,
    pub markets: Vec<PlatformMarket>,
    pub page: PageInfo,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBookLevel {
    /// Quote atoms per whole base unit, encoded as an unsigned decimal string.
    pub price_atoms: String,
    /// Available base quantity in base atoms, encoded as an unsigned decimal string.
    pub size_atoms: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformBookSide {
    Bid,
    Ask,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBookChange {
    pub side: PlatformBookSide,
    pub price_atoms: String,
    /// Zero removes the price level.
    pub size_atoms: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBookSnapshotResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub stream_id: String,
    pub sequence: String,
    pub server_time_ms: u64,
    pub snapshot_id: String,
    pub bids: Vec<PlatformBookLevel>,
    pub asks: Vec<PlatformBookLevel>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformBestBidAskResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub stream_id: String,
    pub sequence: String,
    pub server_time_ms: u64,
    pub best_bid: Option<PlatformBookLevel>,
    pub best_ask: Option<PlatformBookLevel>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformFeeScheduleResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub passive_maker_fee_bps: u16,
    pub maximum_immediate_execution_fee_bps: u16,
    pub book_prices_include_trading_fees: bool,
    pub exact_fee_returned_by_quote: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformMarketStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub status: PlatformMarketState,
    pub tick_size_atoms: String,
    pub minimum_order_size_atoms: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformTradeSide {
    Buy,
    Sell,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTrade {
    pub trade_id: String,
    pub side: PlatformTradeSide,
    pub price_atoms: String,
    pub size_atoms: String,
    pub executed_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformTradesResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub server_time_ms: u64,
    pub trades: Vec<PlatformTrade>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderType {
    GoodUntilCancelled,
    ImmediateOrCancel,
    FillOrKill,
    PostOnly,
}

/// Externally authorized resting-order operation. The public contract exposes
/// product intent only; private construction details never cross the SDK
/// boundary.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderAction {
    Place,
    Cancel,
    CancelAll,
    /// Atomically cancel one existing order and place its explicitly bound
    /// successor in the same transaction.
    Replace,
    /// Atomically execute a bounded heterogeneous set of place, cancel, and
    /// replace operations in one transaction.
    Batch,
}

/// One operation inside an atomic order-control batch. Owner and session
/// identity live on the enclosing challenge so no item can widen authority.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderBatchOperation {
    Place {
        account_sequence: String,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
    Cancel {
        order_id: String,
    },
    Replace {
        order_id: String,
        account_sequence: String,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
}

/// Request canonical bytes for one externally signed order-control operation.
/// Variant-specific fields are sealed so an authorization cannot be widened
/// between challenge and transaction preparation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformOrderChallengeRequest {
    Place {
        owner_wallet: String,
        session_public_key: String,
        account_sequence: String,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
    Cancel {
        owner_wallet: String,
        session_public_key: String,
        order_id: String,
    },
    CancelAll {
        owner_wallet: String,
        session_public_key: String,
    },
    Replace {
        owner_wallet: String,
        session_public_key: String,
        order_id: String,
        account_sequence: String,
        client_order_id: String,
        side: PlatformTradeSide,
        order_type: PlatformOrderType,
        limit_price_atoms: String,
        size_atoms: String,
    },
    Batch {
        owner_wallet: String,
        session_public_key: String,
        operations: Vec<PlatformOrderBatchOperation>,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderChallengeResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub challenge_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    /// Exact opaque order set bound by the authorization. Replace returns the
    /// old then new ID. Batch flattens item IDs in request order, with replace
    /// contributing old then new. A batch contains at most six operations.
    pub order_ids: Vec<String>,
    pub authorization_payload_base64: String,
    pub server_time_ms: u64,
    pub expires_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderPrepareRequest {
    pub challenge_id: String,
    /// Base58 Ed25519 signature over `authorization_payload_base64`.
    pub authorization_signature: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderPrepareResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub order_control_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    pub order_ids: Vec<String>,
    /// Backend-partially-signed Solana v0 transaction. The external session
    /// signer verifies and fills only its signature slot.
    pub transaction_base64: String,
    pub recent_blockhash: String,
    pub last_valid_block_height: u64,
    pub expires_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderSubmitRequest {
    pub order_control_id: String,
    pub signed_transaction_base64: String,
    pub idempotency_key: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderSubmissionStatus {
    Submitted,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderSubmitResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub order_control_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    pub order_ids: Vec<String>,
    pub signature: String,
    pub status: PlatformOrderSubmissionStatus,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderStatusRequest {
    pub order_control_id: String,
    pub idempotency_key: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformOrderControlStatus {
    Submitting,
    Submitted,
    Failed,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformOrderStatusResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub order_control_id: String,
    pub market_id: String,
    pub action: PlatformOrderAction,
    pub order_ids: Vec<String>,
    pub signature: String,
    pub status: PlatformOrderControlStatus,
    pub failure_code: Option<String>,
    pub updated_at_ms: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAccountOrder {
    pub order_id: String,
    pub side: PlatformTradeSide,
    pub order_type: PlatformOrderType,
    pub state: PlatformOrderState,
    pub limit_price_atoms: String,
    pub original_size_atoms: String,
    pub remaining_size_atoms: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAccountFill {
    pub fill_id: String,
    pub side: PlatformTradeSide,
    pub price_atoms: String,
    pub size_atoms: String,
    pub fee_quote_atoms: String,
    pub fee_is_final: bool,
    pub settlement: PlatformSettlementState,
    pub executed_at_ms: u64,
    pub confirmed_at_ms: Option<u64>,
    pub transaction_id: Option<String>,
    pub realized_pnl_quote_atoms: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformAccountSnapshotResponse {
    pub schema_version: u16,
    pub contract_version: String,
    pub market_id: String,
    pub wallet_address: String,
    pub server_time_ms: u64,
    pub orders: Vec<PlatformAccountOrder>,
    pub fills: Vec<PlatformAccountFill>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum PlatformAccountEvent {
    AuthChallenge {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        challenge: String,
        server_time_ms: u64,
        expires_at_ms: u64,
    },
    AccountSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        orders: Vec<PlatformAccountOrder>,
        fills: Vec<PlatformAccountFill>,
    },
    OrdersSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        orders: Vec<PlatformAccountOrder>,
    },
    Fill {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        fill: PlatformAccountFill,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        wallet_address: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PlatformMarketDataEvent {
    BookSnapshot {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        snapshot_id: String,
        bids: Vec<PlatformBookLevel>,
        asks: Vec<PlatformBookLevel>,
    },
    BookDelta {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        previous_sequence: String,
        server_time_ms: u64,
        changes: Vec<PlatformBookChange>,
    },
    BestBidAsk {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        stream_id: String,
        sequence: String,
        server_time_ms: u64,
        best_bid: Option<PlatformBookLevel>,
        best_ask: Option<PlatformBookLevel>,
    },
    Trade {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        server_time_ms: u64,
        trade: PlatformTrade,
    },
    MarketStatus {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        server_time_ms: u64,
        status: PlatformMarketState,
    },
    Heartbeat {
        schema_version: u16,
        contract_version: String,
        market_id: String,
        server_time_ms: u64,
    },
}

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

    #[test]
    fn public_platform_fixtures_decode_strictly() {
        let discovery: PlatformDiscoveryResponse =
            serde_json::from_str(PLATFORM_CAPABILITIES_FIXTURE).unwrap();
        let assets: PlatformAssetsResponse = serde_json::from_str(PLATFORM_ASSETS_FIXTURE).unwrap();
        let markets: PlatformMarketsResponse =
            serde_json::from_str(PLATFORM_MARKETS_FIXTURE).unwrap();
        let book: PlatformBookSnapshotResponse =
            serde_json::from_str(PLATFORM_BOOK_FIXTURE).unwrap();
        let bbo: PlatformBestBidAskResponse = serde_json::from_str(PLATFORM_BBO_FIXTURE).unwrap();
        let fees: PlatformFeeScheduleResponse =
            serde_json::from_str(PLATFORM_FEES_FIXTURE).unwrap();
        let status: PlatformMarketStatusResponse =
            serde_json::from_str(PLATFORM_STATUS_FIXTURE).unwrap();
        let trades: PlatformTradesResponse = serde_json::from_str(PLATFORM_TRADES_FIXTURE).unwrap();
        let account: PlatformAccountSnapshotResponse =
            serde_json::from_str(PLATFORM_ACCOUNT_FIXTURE).unwrap();
        let order_challenge: PlatformOrderChallengeResponse =
            serde_json::from_str(PLATFORM_ORDER_CHALLENGE_FIXTURE).unwrap();
        let order_prepare: PlatformOrderPrepareResponse =
            serde_json::from_str(PLATFORM_ORDER_PREPARE_FIXTURE).unwrap();
        let order_submit: PlatformOrderSubmitResponse =
            serde_json::from_str(PLATFORM_ORDER_SUBMIT_FIXTURE).unwrap();
        let order_status: PlatformOrderStatusResponse =
            serde_json::from_str(PLATFORM_ORDER_STATUS_FIXTURE).unwrap();

        assert_eq!(discovery.schema_version, PLATFORM_SCHEMA_VERSION);
        assert_eq!(discovery.capabilities.len(), 5);
        assert!(!discovery.authority.accepts_private_keys);
        assert_eq!(assets.assets.len(), 2);
        assert_eq!(markets.markets.len(), 1);
        assert_eq!(markets.markets[0].base_asset_id, assets.assets[0].asset_id);
        assert_eq!(markets.markets[0].quote_asset_id, assets.assets[1].asset_id);
        assert_eq!(book.sequence, "42");
        assert_eq!(bbo.best_bid.unwrap().price_atoms, "149990000");
        assert_eq!(fees.maximum_immediate_execution_fee_bps, 10);
        assert_eq!(status.status, PlatformMarketState::Active);
        assert_eq!(trades.trades.len(), 1);
        assert_eq!(account.orders.len(), 1);
        assert_eq!(account.fills.len(), 1);
        assert_eq!(order_challenge.action, PlatformOrderAction::Place);
        assert_eq!(order_prepare.order_ids, order_challenge.order_ids);
        assert_eq!(order_submit.order_ids, order_challenge.order_ids);
        assert_eq!(order_status.order_control_id, order_submit.order_control_id);
        assert_eq!(order_status.status, PlatformOrderControlStatus::Submitting);
    }

    #[test]
    fn public_platform_response_rejects_unreviewed_fields() {
        let mut value: serde_json::Value =
            serde_json::from_str(PLATFORM_CAPABILITIES_FIXTURE).unwrap();
        value
            .as_object_mut()
            .unwrap()
            .insert("unexpected_field".to_owned(), serde_json::Value::Bool(true));
        assert!(serde_json::from_value::<PlatformDiscoveryResponse>(value).is_err());

        let mut account_event: serde_json::Value =
            serde_json::from_str(PLATFORM_ACCOUNT_FIXTURE).unwrap();
        let event = account_event.as_object_mut().unwrap();
        event.insert("type".to_owned(), serde_json::json!("account_snapshot"));
        event.insert(
            "stream_id".to_owned(),
            serde_json::json!("account_stream_66666666666666666666666666666666"),
        );
        event.insert("sequence".to_owned(), serde_json::json!("1"));
        event.insert("unexpected_field".to_owned(), serde_json::json!(true));
        assert!(serde_json::from_value::<PlatformAccountEvent>(account_event).is_err());
    }

    #[test]
    fn atomic_order_batch_request_is_strict_and_typed() {
        let request: PlatformOrderChallengeRequest = serde_json::from_value(serde_json::json!({
            "action": "batch",
            "owner_wallet": "11111111111111111111111111111111",
            "session_public_key": "22222222222222222222222222222222",
            "operations": [
                {
                    "action": "cancel",
                    "order_id": "order_11111111111111111111111111111111"
                },
                {
                    "action": "replace",
                    "order_id": "order_22222222222222222222222222222222",
                    "account_sequence": "8",
                    "client_order_id": "replacement-8",
                    "side": "sell",
                    "order_type": "post_only",
                    "limit_price_atoms": "151000000",
                    "size_atoms": "2000000"
                }
            ]
        }))
        .unwrap();
        let PlatformOrderChallengeRequest::Batch { operations, .. } = request else {
            panic!("expected batch request");
        };
        assert_eq!(operations.len(), 2);
        assert!(matches!(
            operations[1],
            PlatformOrderBatchOperation::Replace { .. }
        ));

        assert!(
            serde_json::from_value::<PlatformOrderChallengeRequest>(serde_json::json!({
                "action": "batch",
                "owner_wallet": "11111111111111111111111111111111",
                "session_public_key": "22222222222222222222222222222222",
                "operations": [{
                    "action": "cancel",
                    "order_id": "order_11111111111111111111111111111111",
                    "implementation": "hidden"
                }]
            }))
            .is_err()
        );
    }
}