-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlib.rs
More file actions
5801 lines (5321 loc) · 234 KB
/
Copy pathlib.rs
File metadata and controls
5801 lines (5321 loc) · 234 KB
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
// 2026 (c) Copyright Contributors to the GOSH DAO. All rights reserved.
//
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use async_trait::async_trait;
use dodex_domain::encode_order_flags;
use dodex_domain::is_multiple_of;
use dodex_domain::lift_decimal;
use dodex_domain::notional_meets_minimum;
use dodex_domain::precision_within;
use dodex_domain::DepthSnapshot;
use dodex_domain::DomainError;
use dodex_domain::MarketAddress;
use dodex_domain::MarketStatus;
use dodex_domain::MarketsPage;
use dodex_domain::Order;
use dodex_domain::OrderSide;
use dodex_domain::OrderStatus;
use dodex_domain::OrderType;
use dodex_domain::Outcome;
use dodex_domain::Permission;
use dodex_domain::SensitiveBytes;
use dodex_domain::Symbol;
use dodex_domain::TimeInForce;
use dodex_domain::PRICE_BPS_DECIMALS;
use num_bigint::BigUint;
use tracing::error;
use tracing::warn;
use uuid::Uuid;
/// Per-request authorization state assembled by the HMAC middleware and
/// consumed by handlers via the Salvo depot. Carries the resolved
/// account, its custodied trading PN (with decrypted signing key), and
/// the granted permissions. `pn_seckey` zeroes on drop.
#[derive(Debug, Clone)]
pub struct AuthContext {
pub account_id: Uuid,
pub api_key_id: i64,
pub trading_pn: TradingPn,
pub permissions: Vec<Permission>,
}
/// The custodied trading PN bound to an account. `pn_pubkey` and `pn_dih`
/// are decimal-encoded uint256 strings — the format the chain ABI accepts
/// for chain-side calls.
#[derive(Debug, Clone)]
pub struct TradingPn {
pub pn_address: String,
pub pn_pubkey: String,
pub pn_dih: String,
pub pn_seckey: SensitiveBytes,
}
impl AuthContext {
pub fn has_permission(&self, perm: Permission) -> bool {
self.permissions.contains(&perm)
}
/// Enforce a required permission. Returns `DomainError::AuthRequired`
/// when the key does not carry it; the api error layer maps that to
/// `-1002 / 401` per `docs/api-spec.md`.
pub fn require(&self, perm: Permission) -> Result<(), DomainError> {
if self.has_permission(perm) {
Ok(())
} else {
Err(DomainError::AuthRequired)
}
}
}
/// Inputs the HTTP layer hands to the authenticator. The service stays
/// thin: it extracts these fields out of the Salvo request and passes
/// them in unaltered. `raw_query_string` is canonicalized inside the
/// authenticator so the canonical/HMAC concern does not leak into the
/// service layer; `body` is the on-the-wire byte sequence (never
/// re-serialized JSON).
#[derive(Debug, Clone)]
pub struct AuthenticateRequest {
pub api_key: String,
pub timestamp_ms: i64,
pub recv_window_ms: Option<u64>,
pub signature_hex: String,
pub raw_query_string: String,
pub body: Vec<u8>,
pub now_ms: i64,
}
/// Verifies one HMAC-authenticated request and resolves it to the
/// account's [`AuthContext`]. Matches the verification pipeline in
/// `docs/tech-specs/auth.md §Authentication`. Implementations are
/// expected to be cheap to clone (e.g. wrap a connection pool in
/// `Arc`) so the trait object can sit in app state.
#[async_trait]
pub trait Authenticator: Send + Sync {
async fn authenticate(&self, request: AuthenticateRequest) -> Result<AuthContext, DomainError>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MarketsSort {
#[default]
ResultStartAsc,
CreatedAtDesc,
}
#[derive(Debug, Clone, Default)]
pub struct MarketsFilter {
pub statuses: Vec<MarketStatus>,
pub quote_asset: Option<String>,
pub oracle_name: Option<String>,
pub closing_before: Option<i64>,
}
#[derive(Debug, Clone)]
pub struct MarketsListing {
pub filter: MarketsFilter,
pub sort: MarketsSort,
pub cursor: Option<String>,
pub limit: u16,
pub now: i64,
}
#[derive(Debug, Clone)]
pub enum MarketsRequest {
One { market_address: MarketAddress, now: i64 },
Listing(MarketsListing),
}
/// Slim projection the `DELETE /api/v1/order` path needs. Built by a
/// single SELECT joining `live_orders ⋈ markets ⋈ market_outcomes` with
/// the ownership predicate `live_orders.owner_pn_address = :pn_address`
/// baked into the where-clause — a miss collapses to
/// `DomainError::UnknownOrder` regardless of whether the orderId does
/// not exist, belongs to another account, is no longer OPEN, or the
/// `(marketAddress, symbol)` does not match the order's actual market.
/// That ambiguity is intentional: differentiating those cases would
/// leak the existence of orders the caller does not own.
#[derive(Debug, Clone)]
pub struct OrderForCancel {
pub event_id: String,
pub oracle_list_hash: String,
/// Validated as non-negative at the repo boundary (the DB column is
/// `integer` but the chain ABI is `uint32`); callers can use it
/// directly as `u32` without a secondary cast.
pub token_type: u32,
pub market_status: MarketStatus,
/// `live_orders.client_order_id`. NULL in the DB surfaces as `None`
/// here; the handler renders it as the empty string per
/// api-spec §Cancel Order.
pub client_order_id: Option<String>,
}
/// Slim market+outcome projection the `POST /api/v1/order` path needs.
/// Built by a single SELECT joining `markets ⋈ market_outcomes`; the
/// oracle/event aggregation that `list_markets` performs is irrelevant
/// on the trading hot path. `status` is computed against the caller's
/// `now` so downstream validation can reject everything except
/// `MarketStatus::Trading` without a second round-trip.
#[derive(Debug, Clone)]
pub struct MarketForPlacement {
pub event_id: String,
pub oracle_list_hash: String,
/// Validated as non-negative at the repo boundary (the DB column is
/// `integer` but the chain ABI is `uint32`); callers can use it
/// directly as `u32` without a secondary cast.
pub token_type: u32,
pub status: MarketStatus,
pub outcome: Outcome,
/// Quote asset's on-chain `decimals` (from `ref_tokens`, keyed by
/// `token_type`). The order amount is lifted to token atoms with this —
/// not the coarser display `quantity_precision` — to match the OrderBook
/// contract's lot lattice.
pub decimals: u8,
}
/// Slim market projection the `POST /api/v1/buyFullSet` path needs.
/// No `market_outcomes` join — splitFullSet is a market-level operation
/// (the chain produces one outcome token of every outcome from the
/// `collateral`), so no symbol resolution is involved. `status` is
/// computed against the caller's `now` so downstream validation can
/// gate on `AWAITING_FREEZE | TRADING` without a second round-trip per
/// [api-spec §Buy Full Set](../../docs/api-spec.md#buy-full-set).
#[derive(Debug, Clone)]
pub struct MarketForBuyFullSet {
pub event_id: String,
pub oracle_list_hash: String,
/// Validated as non-negative at the repo boundary (the DB column is
/// `integer` but the chain ABI is `uint32`); callers can use it
/// directly as `u32` without a secondary cast. Doubles as the
/// `tokenType` slot of `ParamsOfSplitFullSet` and as the lookup key
/// for the quote asset's on-chain `decimals` via
/// [`ReferenceRepository::lookup_ref_token`].
pub token_type: u32,
pub status: MarketStatus,
}
/// Per-outcome metadata needed to render a market-balances row.
#[derive(Debug, Clone)]
pub struct BalanceOutcome {
pub outcome_id: u32,
pub symbol: Symbol,
pub quantity_precision: u8,
}
/// Result of resolving `marketAddress` for a balances request. Contains
/// every chain-side field (`event_id`, `oracle_list_hash`, `token_type`)
/// needed to compute `stake_hash` plus the outcome list used to render
/// the response.
#[derive(Debug, Clone)]
pub struct MarketBalancesResolution {
pub event_id: String,
pub oracle_list_hash: String,
/// Already validated as non-negative at the repo boundary
/// (`try_into().map_err(MarketInconsistent)`); callers can use it
/// directly as `u32` without a secondary cast.
pub token_type: u32,
pub orderbook_address: String,
/// Quote-asset on-chain `decimals` (from `ref_tokens` by `token_type`).
/// Outcome `_stakes` amounts are in atoms at this scale, so display
/// scales by the full `decimals` (like `GetAccountUseCase` / `/account`),
/// NOT by `quantity_precision`, which would over-report by
/// 10^(decimals - quantity_precision).
pub decimals: u8,
/// Number of outcomes for this market. `u32` because outcome counts
/// are non-negative; the Postgres `integer` column is cast at the
/// repo boundary (negative DB values → `MarketInconsistent`).
pub num_outcomes: u32,
pub outcomes: Vec<BalanceOutcome>,
}
#[async_trait]
pub trait MarketReadRepository: Send + Sync {
async fn list_markets(&self, request: &MarketsRequest) -> Result<MarketsPage, anyhow::Error>;
async fn get_depth(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
limit: u16,
) -> Result<DepthSnapshot, anyhow::Error>;
/// Resolve the `(marketAddress, symbol)` pair the trading path needs
/// in a single SELECT — no oracle/event aggregation, no second
/// outcome fetch. `now` lets the implementation compute the
/// `MarketStatus` so the use case can fail closed without a separate
/// `list_markets` call. Misses collapse to
/// `DomainError::InvalidMarketOrSymbol`.
async fn resolve_for_new_order(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
now: i64,
) -> Result<MarketForPlacement, anyhow::Error>;
/// Resolve one open order owned by `owner_pn_address` together with
/// the chain-side market fields needed for `PrivateNote.cancelOrder`,
/// in a single SELECT. The ownership predicate is part of the
/// where-clause: any miss (unknown id, wrong owner, wrong market,
/// already closed) collapses to `DomainError::UnknownOrder` so error
/// codes do not leak ownership.
async fn resolve_for_cancel(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
order_id: u64,
owner_pn_address: &str,
now: i64,
) -> Result<OrderForCancel, anyhow::Error>;
/// Resolve multiple open orders owned by `owner_pn_address` on a
/// single `(market_address, symbol)`. Returns matched rows in a
/// `HashMap<u64, OrderForCancelBatch>` keyed by chain `order_id`.
///
/// **Trait contract — every impl owes:** every key in
/// `orders` is an element of the caller's `order_ids[]` slice.
/// The Postgres impl enforces this with
/// `WHERE lo.order_id = ANY($3)`; the natural HashMap uniqueness
/// plus the `(orderbook_address, order_id)` primary key
/// guarantees no key collisions.
///
/// **Result shape:**
/// - `Ok(None)` — zero matches. Use case maps to `UnknownOrder`.
/// - `Ok(Some(r))` with `r.orders.len() == order_ids.len()` —
/// full match (by contract every key is in input; pigeonhole
/// gives an exact set match).
/// - `Ok(Some(r))` with `r.orders.len() < order_ids.len()` —
/// partial shortfall (one or more input ids did not match).
/// Use case maps to `UnknownOrder`.
/// - `Err(_)` — non-domain SELECT failure via `anyhow`.
///
/// **Wrapping fields:** `event_id`, `oracle_list_hash`,
/// `token_type`, and `market_status` are projected from the
/// JOINed `markets` row onto `CancelBatchResolution`, evaluated
/// at the caller-provided `now`. All four are constant by SELECT
/// construction (filter pins one `(pmp_address, symbol)`). The
/// use case re-checks `market_status == Trading` post-SELECT to
/// close the race between `resolve_for_new_order`'s earlier
/// snapshot and this bulk one — a reconciler commit between the
/// two MVCC snapshots rejects with `OrderValidationFailed`
/// before chain dispatch.
async fn resolve_for_cancel_batch(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
order_ids: &[u64],
owner_pn_address: &str,
now: i64,
) -> Result<Option<CancelBatchResolution>, anyhow::Error>;
async fn list_orders(&self, query: &OrdersQuery) -> Result<OrdersPage, anyhow::Error>;
/// Resolve a market for the balances path: returns chain-side
/// fields needed to compute `stake_hash` plus the outcome list
/// used to render the response. Gated by
/// `last_reconciled_at IS NOT NULL`. Misses collapse to
/// `DomainError::InvalidMarketOrSymbol`.
async fn resolve_market_for_balances(
&self,
market_address: &MarketAddress,
) -> Result<MarketBalancesResolution, anyhow::Error>;
/// Resolve `marketAddress` for `POST /api/v1/buyFullSet`. Returns
/// chain identity (`event_id`, `oracle_list_hash`, `token_type`)
/// plus the `MarketStatus` derived against `now`. Gated by
/// `last_reconciled_at IS NOT NULL`; misses collapse to
/// `DomainError::InvalidMarketOrSymbol`. No outcome join — the
/// splitFullSet ABI operates at the market level.
async fn resolve_for_buy_full_set(
&self,
market_address: &MarketAddress,
now: i64,
) -> Result<MarketForBuyFullSet, anyhow::Error>;
/// Sum `amount_remaining` over OPEN SELL rows owned by `owner_pn`
/// on `orderbook_address`, grouped by `outcome_id`. Returns a map
/// keyed by `outcome_id` with raw uint128 values as decimal strings
/// (scaled by the API). Missing outcomes default to "0" on the
/// caller side.
async fn sum_open_sell_remaining(
&self,
orderbook_address: &str,
owner_pn_address: &str,
) -> Result<std::collections::HashMap<u32, String>, anyhow::Error>;
}
#[async_trait]
impl<T: ?Sized + MarketReadRepository> MarketReadRepository for Arc<T> {
async fn list_markets(&self, request: &MarketsRequest) -> Result<MarketsPage, anyhow::Error> {
(**self).list_markets(request).await
}
async fn get_depth(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
limit: u16,
) -> Result<DepthSnapshot, anyhow::Error> {
(**self).get_depth(market_address, symbol, limit).await
}
async fn resolve_for_new_order(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
now: i64,
) -> Result<MarketForPlacement, anyhow::Error> {
(**self).resolve_for_new_order(market_address, symbol, now).await
}
async fn resolve_for_cancel(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
order_id: u64,
owner_pn_address: &str,
now: i64,
) -> Result<OrderForCancel, anyhow::Error> {
(**self).resolve_for_cancel(market_address, symbol, order_id, owner_pn_address, now).await
}
async fn resolve_for_cancel_batch(
&self,
market_address: &MarketAddress,
symbol: &Symbol,
order_ids: &[u64],
owner_pn_address: &str,
now: i64,
) -> Result<Option<CancelBatchResolution>, anyhow::Error> {
(**self)
.resolve_for_cancel_batch(market_address, symbol, order_ids, owner_pn_address, now)
.await
}
async fn list_orders(&self, query: &OrdersQuery) -> Result<OrdersPage, anyhow::Error> {
(**self).list_orders(query).await
}
async fn resolve_market_for_balances(
&self,
market_address: &MarketAddress,
) -> Result<MarketBalancesResolution, anyhow::Error> {
(**self).resolve_market_for_balances(market_address).await
}
async fn resolve_for_buy_full_set(
&self,
market_address: &MarketAddress,
now: i64,
) -> Result<MarketForBuyFullSet, anyhow::Error> {
(**self).resolve_for_buy_full_set(market_address, now).await
}
async fn sum_open_sell_remaining(
&self,
orderbook_address: &str,
owner_pn_address: &str,
) -> Result<std::collections::HashMap<u32, String>, anyhow::Error> {
(**self).sum_open_sell_remaining(orderbook_address, owner_pn_address).await
}
}
#[derive(Debug, Clone)]
pub struct GetDepthQuery {
pub market_address: MarketAddress,
pub symbol: Symbol,
pub limit: u16,
}
pub const ORDERS_DEFAULT_LIMIT: u16 = 100;
pub const ORDERS_MAX_LIMIT: u16 = 500;
/// Order statuses queryable through `GET /api/v1/orders`. This deliberately
/// excludes write-side synthetic states (`PENDING_NEW`, `PENDING_CANCEL`) so
/// SQL predicate construction cannot accidentally admit them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum QueryableOrderStatus {
New,
PartiallyFilled,
Filled,
Canceled,
Rejected,
}
impl QueryableOrderStatus {
pub fn as_public_status(self) -> OrderStatus {
match self {
Self::New => OrderStatus::New,
Self::PartiallyFilled => OrderStatus::PartiallyFilled,
Self::Filled => OrderStatus::Filled,
Self::Canceled => OrderStatus::Canceled,
Self::Rejected => OrderStatus::Rejected,
}
}
}
/// Non-empty subset of read-queryable statuses. The constructor is
/// crate-private and `from_csv` is the only way to build one from
/// outside, so `OrderStatusFilter::Only(_)` is non-empty by
/// construction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NonEmptyStatusSet(std::collections::BTreeSet<QueryableOrderStatus>);
impl NonEmptyStatusSet {
fn new(set: std::collections::BTreeSet<QueryableOrderStatus>) -> Option<Self> {
if set.is_empty() {
None
} else {
Some(Self(set))
}
}
pub fn iter(&self) -> impl Iterator<Item = &QueryableOrderStatus> + '_ {
self.0.iter()
}
}
/// Caller-supplied filter on order status. Either matches every row
/// (no `status` parameter on the request) or narrows to a non-empty
/// set of queryable tokens. Callers pattern-match on the variant
/// directly — `All` is plainly visible at the type level rather than
/// hidden behind an `is_all()` predicate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OrderStatusFilter {
/// No filter — every row passes.
All,
/// Filter to the listed statuses. The inner type's constructor is
/// crate-private, so this variant is always non-empty.
Only(NonEmptyStatusSet),
}
impl OrderStatusFilter {
/// Parse the request `status` parameter. `None` or all-whitespace
/// returns `All`; anything else is split on `,`, trimmed,
/// de-duplicated, and matched against the allow-list. An unknown
/// token (or `PENDING_NEW` / `PENDING_CANCEL`, which are write-side
/// only) returns [`DomainError::InvalidParameter`].
///
/// Whitespace-only input is treated as `All` by design. This is
/// asymmetric with the `cursor` parameter — a whitespace-only
/// `cursor` is rejected as `MissingParameter` — because the two
/// parameters express different intents: `status` is an optional
/// narrowing filter whose absence (any falsy form) trivially means
/// "no filter applied", while `cursor` is an opaque server-issued
/// token whose syntactic emptiness is always a client-side bug.
/// See docs/api-spec.md#orders (Behavior section) for the public
/// contract. Do not collapse the two parsers into a shared
/// "blank-is-empty" helper.
pub fn from_csv(raw: Option<&str>) -> Result<Self, DomainError> {
let Some(value) = raw else {
return Ok(Self::All);
};
let mut set = std::collections::BTreeSet::new();
for token in value.split(',') {
let trimmed = token.trim();
if trimmed.is_empty() {
continue;
}
let status = match trimmed {
"NEW" => QueryableOrderStatus::New,
"PARTIALLY_FILLED" => QueryableOrderStatus::PartiallyFilled,
"FILLED" => QueryableOrderStatus::Filled,
"CANCELED" => QueryableOrderStatus::Canceled,
"REJECTED" => QueryableOrderStatus::Rejected,
_ => return Err(DomainError::InvalidParameter),
};
set.insert(status);
}
match NonEmptyStatusSet::new(set) {
Some(non_empty) => Ok(Self::Only(non_empty)),
None => Ok(Self::All),
}
}
}
/// Opaque pagination cursor for `/api/v1/orders`. The inner string is
/// the `placed_chain_order` of the last row returned by a previous
/// page; the server reads it as a lexicographic token via the strict
/// `<` predicate in [`PostgresReadModelRepository::list_orders`].
///
/// Both [`OrdersCursor::new`] (client input) and
/// [`OrdersCursor::from_db_token`] (storage token) trim surrounding
/// whitespace, reject blank values, and reject lengths above
/// [`MAX_CURSOR_LEN`]. They differ only in the error variant: a
/// blank or oversized client value surfaces as `MissingParameter`
/// (blank) or `InvalidParameter` (oversized); a corrupt stored
/// value surfaces as `Unexpected`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OrdersCursor(String);
/// Hard cap on the length of a cursor token after trimming. The
/// gateway-issued `msg_chain_order` is ~32-50 chars in practice; 128
/// keeps generous headroom while making a hostile 10 MB
/// `?cursor=AAA...` request fail before reaching the SQL layer (the
/// cursor binds as `$4::text` and Postgres performs the comparison
/// per scanned index entry).
pub const MAX_CURSOR_LEN: usize = 128;
impl OrdersCursor {
/// Validating constructor for client input. Trims whitespace and
/// rejects blank as [`DomainError::MissingParameter`]; rejects
/// lengths above [`MAX_CURSOR_LEN`] as
/// [`DomainError::InvalidParameter`] (the value is present, just
/// malformed). Both maps surface to the documented `/api/v1/orders`
/// error codes — see read-api.md §error mapping.
pub fn new(raw: String) -> Result<Self, DomainError> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(DomainError::MissingParameter);
}
if trimmed.len() > MAX_CURSOR_LEN {
return Err(DomainError::InvalidParameter);
}
Ok(Self(trimmed.to_string()))
}
pub fn from_db_token(raw: String) -> Result<Self, DomainError> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(DomainError::Unexpected);
}
// Symmetric with `new`: a corrupt storage row with an
// unbounded `placed_chain_order` would otherwise resurface on
// the next page as a hostile-shaped cursor.
if trimmed.len() > MAX_CURSOR_LEN {
return Err(DomainError::Unexpected);
}
Ok(Self(trimmed.to_string()))
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
pub fn into_string(self) -> String {
self.0
}
}
/// Page-size cap for `/api/v1/orders`. The constructor enforces
/// `1..=ORDERS_MAX_LIMIT`, lifting the "must be at least 1" invariant
/// into the type so the Postgres cursor builder's
/// `last() == Some` after `truncate(limit)` holds by construction
/// rather than by a runtime `expect`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OrdersLimit(u16);
impl OrdersLimit {
/// Default page size when `limit` is absent on the request.
/// Routes through `from_const` so the validating `assert!` runs at
/// compile time — a future bump of `ORDERS_DEFAULT_LIMIT` above
/// `ORDERS_MAX_LIMIT` would fail to build rather than producing an
/// out-of-range default that bypasses the runtime guard in `new`.
pub const DEFAULT: Self = Self::from_const(ORDERS_DEFAULT_LIMIT);
/// Validating constructor for runtime input. Out-of-range values
/// surface as `MissingParameter` — matches the public `-1102` error
/// the HTTP handler emits.
pub fn new(value: u16) -> Result<Self, DomainError> {
if value == 0 || value > ORDERS_MAX_LIMIT {
return Err(DomainError::MissingParameter);
}
Ok(Self(value))
}
/// Const constructor for statically-known values (test fixtures,
/// derived defaults). The `assert!` is evaluated at compile time
/// only when the call site is itself in a const context (a const
/// item, another const fn, etc.); a non-const call site evaluates
/// the assert at runtime and panics on out-of-range input. Use
/// `OrdersLimit::new` for runtime construction with a typed error.
pub const fn from_const(value: u16) -> Self {
assert!(
value >= 1 && value <= ORDERS_MAX_LIMIT,
"OrdersLimit must be within 1..=ORDERS_MAX_LIMIT",
);
Self(value)
}
pub fn get(self) -> u16 {
self.0
}
}
#[derive(Debug, Clone)]
pub struct OrdersQuery {
pub owner_pn_address: String,
pub market: Option<OrdersMarketFilter>,
pub status: OrderStatusFilter,
pub limit: OrdersLimit,
pub cursor: Option<OrdersCursor>,
}
#[derive(Debug, Clone)]
pub struct OrdersMarketFilter {
market_address: MarketAddress,
symbol: Symbol,
}
impl OrdersMarketFilter {
pub fn pair(
market_address: Option<MarketAddress>,
symbol: Option<Symbol>,
) -> Result<Option<Self>, DomainError> {
match (market_address, symbol) {
(None, None) => Ok(None),
(Some(market_address), Some(symbol)) => Ok(Some(Self { market_address, symbol })),
_ => Err(DomainError::MissingParameter),
}
}
pub fn market_address(&self) -> &MarketAddress {
&self.market_address
}
pub fn symbol(&self) -> &Symbol {
&self.symbol
}
}
/// Result of `MarketReadRepository::list_orders`. All four combinations
/// of `(orders, next_cursor)` are legal:
///
/// - `(non-empty, Some)`: typical page with more results.
/// - `(non-empty, None)`: last page in the scan.
/// - `(empty, None)`: end of results (no rows in scope, or the cursor
/// advanced past every row).
/// - `(empty, Some)`: a `has_more=true` page in which every retained
/// row was filtered out by `order_from_row` (entire window is
/// corrupt). The cursor is built from the last retained row
/// *before* the filter pass — see read-api.md §SQL — so the client
/// can paginate through the corrupt window using the cursor without
/// ever re-reading the dropped rows. Surfacing `Unexpected` here
/// instead would strand the client at 500 with no usable cursor.
#[derive(Debug, Clone)]
pub struct OrdersPage {
pub orders: Vec<Order>,
pub next_cursor: Option<OrdersCursor>,
}
pub struct GetMarketsUseCase<R> {
repo: R,
}
impl<R> GetMarketsUseCase<R> {
pub fn new(repo: R) -> Self {
Self { repo }
}
}
impl<R> GetMarketsUseCase<R>
where
R: MarketReadRepository,
{
pub async fn execute(&self, request: MarketsRequest) -> Result<MarketsPage, anyhow::Error> {
self.repo.list_markets(&request).await
}
}
pub struct GetDepthUseCase<R> {
repo: R,
}
impl<R> GetDepthUseCase<R> {
pub fn new(repo: R) -> Self {
Self { repo }
}
}
impl<R> GetDepthUseCase<R>
where
R: MarketReadRepository,
{
pub async fn execute(&self, query: GetDepthQuery) -> Result<DepthSnapshot, anyhow::Error> {
self.repo.get_depth(&query.market_address, &query.symbol, query.limit).await
}
}
/// Input for `GetAccountUseCase`. Built by the HTTP layer from the
/// resolved auth context plus the request-entry timestamp.
#[derive(Debug, Clone)]
pub struct GetAccountInput {
pub account_id: uuid::Uuid,
pub pn_address: String,
/// Unix milliseconds. Echoed as `updateTime` in the response.
pub now_ms: i64,
}
pub struct GetAccountUseCase<P, R> {
pn: P,
refs: R,
}
impl<P, R> GetAccountUseCase<P, R> {
pub fn new(pn: P, refs: R) -> Self {
Self { pn, refs }
}
}
impl<P, R> GetAccountUseCase<P, R>
where
P: PnStateReader,
R: ReferenceRepository,
{
pub async fn execute(
&self,
input: GetAccountInput,
) -> Result<dodex_domain::AccountBalances, anyhow::Error> {
let details = self.pn.get_details(&input.pn_address).await.map_err(|e| {
// Render the full `with_context` chain on one line so ops can
// distinguish gateway flap from ABI parse failure — Debug
// formatting (`?e`) folds the chain into a multi-line block
// that's awkward to grep in fmt layers. Preserve a typed
// `DomainError` from the reader (in particular
// `AccountNotDeployed`) so the API surfaces 404 rather than
// collapsing every read-side failure to 503.
warn!(
error = %format_args!("{e:#}"),
pn = %input.pn_address,
"get_details failed",
);
if let Some(domain) = e.downcast_ref::<dodex_domain::DomainError>() {
return anyhow::anyhow!(*domain);
}
anyhow::anyhow!(dodex_domain::DomainError::MarketInconsistent)
})?;
// Build the per-token_type aggregate from the union of `_balance`
// and `_lockedInOrders` keys. A token_type that appears only on the
// locked side — the textbook case is a LIMIT SELL that consumed the
// caller's entire free balance, leaving `_balance[X]` absent (or
// pruned to 0) while `_lockedInOrders[X] > 0` — must still surface
// in the response with `free = "0"`. Iterating `_balance` alone
// would silently drop it.
//
// Each map is keyed by token_type and must be unique; the chain
// emits `map(uint32 → uint128)` so a duplicate key is read-model
// corruption. `HashMap::insert` returning `Some` fails closed
// rather than silently letting the last write win.
let mut free_by_tt: std::collections::HashMap<u32, String> =
std::collections::HashMap::with_capacity(details.balance.len());
for (tt, raw_free) in &details.balance {
if free_by_tt.insert(*tt, raw_free.clone()).is_some() {
warn!(token_type = *tt, "duplicate token_type in PN _balance");
return Err(anyhow::Error::from(dodex_domain::DomainError::MarketInconsistent)
.context(format!("duplicate token_type {tt} in PN _balance")));
}
}
let mut locked_by_tt: std::collections::HashMap<u32, String> =
std::collections::HashMap::with_capacity(details.locked_in_orders.len());
for (tt, raw_locked) in &details.locked_in_orders {
if locked_by_tt.insert(*tt, raw_locked.clone()).is_some() {
warn!(token_type = *tt, "duplicate token_type in PN _lockedInOrders");
return Err(anyhow::Error::from(dodex_domain::DomainError::MarketInconsistent)
.context(format!("duplicate token_type {tt} in PN _lockedInOrders")));
}
}
let mut by_tt: std::collections::HashMap<u32, (String, String)> =
std::collections::HashMap::with_capacity(free_by_tt.len() + locked_by_tt.len());
for (tt, raw_free) in free_by_tt {
by_tt.entry(tt).or_insert_with(|| ("0".to_string(), "0".to_string())).0 = raw_free;
}
for (tt, raw_locked) in locked_by_tt {
by_tt.entry(tt).or_insert_with(|| ("0".to_string(), "0".to_string())).1 = raw_locked;
}
let mut rows: Vec<dodex_domain::AssetBalance> = Vec::with_capacity(by_tt.len());
for (tt, (raw_free, raw_locked)) in &by_tt {
let token = self.refs.lookup_ref_token(*tt).await?.ok_or_else(|| {
warn!(token_type = tt, "PN state carries unknown token_type");
anyhow::anyhow!(dodex_domain::DomainError::MarketInconsistent)
})?;
rows.push(dodex_domain::AssetBalance {
asset: token.token_code.clone(),
free: scale_decimal(raw_free, token.decimals)?,
locked: scale_decimal(raw_locked, token.decimals)?,
});
}
rows.sort_by(|a, b| a.asset.cmp(&b.asset));
Ok(dodex_domain::AccountBalances {
account_id: input.account_id,
update_time_ms: input.now_ms,
balances: rows,
})
}
}
/// Scale a non-negative integer-decimal string `raw` (the smallest-unit
/// uint representation) to a fixed-point decimal with `decimals` digits
/// to the right of the point.
///
/// All inputs — including `"0"` and the empty string — are padded to
/// exactly `decimals` fractional digits (e.g. `"10000000000"` with
/// `decimals=9` → `"10.000000000"`, `"1"` → `"0.000000001"`,
/// `"0"` → `"0.000000000"`). The empty string is normalised to `"0"`
/// before scaling. `decimals == 0` returns `raw` unchanged (or `"0"`
/// for an empty input).
///
/// `raw` is validated as a non-negative integer literal before any
/// byte-level slicing — non-digit or multibyte input would otherwise
/// either produce garbage output or panic at the UTF-8 split when
/// `raw.len() > decimals` and the split falls inside a multibyte char.
/// Invalid input surfaces as `DomainError::MarketInconsistent` (503).
/// Upper bound on `decimals` accepted by `scale_decimal`. Mirrors
/// `crates/infrastructure/src/postgres_repo.rs::MAX_DECIMAL_PRECISION`:
/// the SQL NUMERIC(38, …) cap, far beyond any real asset's precision.
/// `scale_decimal` allocates `O(decimals)` bytes via `"0".repeat(...)`,
/// so an unbounded value on a corrupt `ref_tokens` row would OOM the
/// API process on the first scaled balance.
const MAX_DECIMALS: u8 = 38;
fn scale_decimal(raw: &str, decimals: u8) -> Result<String, DomainError> {
use std::str::FromStr;
if decimals > MAX_DECIMALS {
tracing::warn!(
decimals,
max = MAX_DECIMALS,
"scale_decimal: decimals exceed MAX_DECIMALS — refusing to allocate",
);
return Err(DomainError::MarketInconsistent);
}
let raw = if raw.is_empty() { "0" } else { raw };
// Parse and re-emit so the slicing path below operates on a
// canonical decimal string. `BigUint::from_str` accepts leading
// zeros ("00012345"), so without canonicalisation a padded input
// would survive into the `>` branch and slice to "00012.345"
// instead of "12.345". Triggers: a future tvm_abi version that
// emits zero-padded uint128 literals, or a corrupt repo row.
let canonical = BigUint::from_str(raw)
.map_err(|err| {
tracing::warn!(raw, error = %err, "scale_decimal: input is not a non-negative integer");
DomainError::MarketInconsistent
})?
.to_string();
let raw = canonical.as_str();
let d = decimals as usize;
if d == 0 {
// Keep the response format invariant: every scaled value has a decimal
// point. A strict client parser (`^[0-9]+\.[0-9]+$`) would otherwise
// reject the bare integer. `decimals=0` is reachable today because the
// schema does not CHECK `> 0` on `ref_tokens.decimals` /
// `market_outcomes.quantity_precision`.
return Ok(format!("{raw}.0"));
}
if raw.len() <= d {
let padded = "0".repeat(d - raw.len()) + raw;
Ok(format!("0.{padded}"))
} else {
let split = raw.len() - d;
Ok(format!("{}.{}", &raw[..split], &raw[split..]))
}
}
/// Input for `GetMarketBalancesUseCase`. The HTTP layer assembles it
/// from the validated query plus the resolved auth context.
#[derive(Debug, Clone)]
pub struct GetMarketBalancesInput {
pub pn_address: String,
pub market_address: MarketAddress,
/// Unix milliseconds. Echoed as `updateTime` in the response.
pub now_ms: i64,
}
/// Signature for the off-chain hash function — the use case holds it
/// as a function pointer so unit tests can plug a stub hasher without
/// pulling in the real `tvm_abi` machinery. Returns
/// `Err(DomainError::MarketInconsistent)` on parse or hash failure so
/// read-model corruption surfaces as a 503 instead of silently
/// producing all-zero outcome balances.
///
/// `token_type` is `u32` because the repo boundary already validates
/// that the DB value is non-negative; callers never need to cast.
pub type StakeHasher =
fn(event_id: &str, oracle_list_hash: &str, token_type: u32) -> Result<String, DomainError>;
pub struct GetMarketBalancesUseCase<P, R> {
pn: P,
repo: R,
hasher: StakeHasher,
}
impl<P, R> GetMarketBalancesUseCase<P, R> {
pub fn new(pn: P, repo: R, hasher: StakeHasher) -> Self {
Self { pn, repo, hasher }
}
}
impl<P, R> GetMarketBalancesUseCase<P, R>
where
P: PnStateReader,
R: MarketReadRepository,
{
pub async fn execute(
&self,
input: GetMarketBalancesInput,
) -> Result<dodex_domain::MarketBalances, anyhow::Error> {
// Resolve the market. The repo lifts unknown / unreconciled
// pairs to InvalidMarketOrSymbol; pass that error through verbatim.
let res = self.repo.resolve_market_for_balances(&input.market_address).await?;
// Compute the stake hash off chain. The hasher returns Err on
// parse / hash failure (read-model corruption) — propagate as
// MarketInconsistent so the caller receives a 503.
// `res.token_type` is already `u32` (validated at the repo boundary).
let stake_hash = (self.hasher)(&res.event_id, &res.oracle_list_hash, res.token_type)
.map_err(|e| anyhow::anyhow!(e))?;
// Fan out: chain-side stake lookup + DB-side sell aggregation.
// The two are independent, so we issue them in parallel.
let pn_address = input.pn_address.clone();
let stake_fut = self.pn.get_stake(&pn_address, &stake_hash);
let sum_fut = self.repo.sum_open_sell_remaining(&res.orderbook_address, &input.pn_address);
let (stake_opt, sums) = tokio::try_join!(stake_fut, sum_fut).map_err(|e| {
// Preserve a typed `DomainError` from either branch (e.g. the
// repo lifts negative `outcome_id` to MarketInconsistent and
// the reader can produce `AccountNotDeployed`). Without this
// downcast, the outer wrap would replace the inner
// classification and the handler would see only the
// freshly-minted MarketInconsistent. Log either way so a
// second simultaneous failure isn't silently dropped by
// try_join!'s "first error wins" behaviour.
if let Some(domain) = e.downcast_ref::<dodex_domain::DomainError>() {
tracing::warn!(
?domain,
market_address = %input.market_address.0,
pn = %input.pn_address,
error = %format_args!("{e:#}"),
"balances fan-out failed (typed domain error)",
);
return anyhow::anyhow!(*domain);
}
tracing::warn!(error = %format_args!("{e:#}"), "balances fan-out failed");
anyhow::anyhow!(dodex_domain::DomainError::MarketInconsistent)
})?;
let n = res.num_outcomes as usize;
// Shape validation: arrays in PnStake must be either empty