-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlib.rs
More file actions
1984 lines (1836 loc) · 76.5 KB
/
Copy pathlib.rs
File metadata and controls
1984 lines (1836 loc) · 76.5 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.
//
mod auth_hoop;
#[doc(hidden)]
pub mod testkit;
mod timeout_hoop;
use std::env;
use std::sync::Arc;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Context;
use dodex_application::AuthContext;
use dodex_application::Authenticator;
use dodex_application::BatchOrderInputItem;
use dodex_application::BuyFullSetInput;
use dodex_application::BuyFullSetUseCase;
use dodex_application::CancelBatchOrdersInput;
use dodex_application::CancelBatchOrdersUseCase;
use dodex_application::CancelOrderInput;
use dodex_application::CancelOrderUseCase;
use dodex_application::ChainOrderSender;
use dodex_application::CreateBatchOrdersInput;
use dodex_application::CreateBatchOrdersUseCase;
use dodex_application::CreateOrderUseCase;
use dodex_application::GetDepthQuery;
use dodex_application::GetDepthUseCase;
use dodex_application::GetMarketsUseCase;
use dodex_application::GetOrdersInput;
use dodex_application::GetOrdersUseCase;
use dodex_application::MarketReadRepository;
use dodex_application::MarketsFilter;
use dodex_application::MarketsListing;
use dodex_application::MarketsRequest;
use dodex_application::MarketsSort;
use dodex_application::NewOrderInput;
use dodex_application::OrdersCursor;
use dodex_application::OrdersMarketFilter;
use dodex_domain::DomainError;
use dodex_domain::Market;
use dodex_domain::MarketAddress;
use dodex_domain::MarketEvent;
use dodex_domain::MarketStatus;
use dodex_domain::Order;
use dodex_domain::OrderParts;
use dodex_domain::OrderSide;
use dodex_domain::OrderStatus;
use dodex_domain::OrderType;
use dodex_domain::Permission;
use dodex_domain::Symbol;
use dodex_domain::Terminal;
use dodex_domain::TerminalKind;
use dodex_domain::TimeInForce;
use dodex_domain::Timings;
use dodex_infrastructure::auth::PostgresAuthenticator;
use dodex_infrastructure::chain_sender::DexChainSender;
use dodex_infrastructure::config::ApiConfig;
use dodex_infrastructure::crypto::Kek;
use dodex_infrastructure::database;
use dodex_infrastructure::database::build_pool;
use dodex_infrastructure::postgres_repo::PostgresReadModelRepository;
use dodex_infrastructure::seed;
use salvo::http::StatusCode;
use salvo::prelude::*;
use salvo::writing::Json;
use salvo_extra::affix_state::inject;
use salvo_oapi::endpoint;
use salvo_oapi::security::ApiKey;
use salvo_oapi::security::ApiKeyValue;
use salvo_oapi::security::SecurityScheme;
use salvo_oapi::Components;
use salvo_oapi::EndpointOutRegister;
use salvo_oapi::Info;
use salvo_oapi::OpenApi;
use salvo_oapi::Operation;
use salvo_oapi::Response as OapiResponse;
use salvo_oapi::Server as OapiServer;
use salvo_oapi::ToSchema;
use serde::Deserialize;
use serde::Serialize;
use tracing::error;
use tracing::info;
use tracing::warn;
#[doc(hidden)]
pub type SharedRepo = Arc<dyn MarketReadRepository>;
#[doc(hidden)]
pub type SharedAuth = Arc<dyn Authenticator>;
#[doc(hidden)]
pub type SharedChainSender = Arc<dyn ChainOrderSender>;
#[doc(hidden)]
pub type SharedPnReader = Arc<dyn dodex_application::PnStateReader>;
#[doc(hidden)]
pub type SharedRefRepo = Arc<dyn dodex_application::ReferenceRepository>;
#[doc(hidden)]
#[derive(Clone)]
pub struct AppState {
pub(crate) repo: SharedRepo,
pub(crate) authenticator: SharedAuth,
pub(crate) chain_sender: SharedChainSender,
pub(crate) pn_reader: SharedPnReader,
pub(crate) ref_repo: SharedRefRepo,
/// Per-request wall-clock budget enforced by the `request_timeout`
/// hoop on every route. `Duration::ZERO` disables the hoop, which
/// is the implicit default `AppState::new` chooses so tests that
/// don't care about timeouts can ignore it.
pub(crate) request_timeout: Duration,
}
impl AppState {
/// Wire-up constructor. Re-exported through the `testkit` module
/// for integration tests; production code reaches it through `run`.
/// The request timeout defaults to `Duration::ZERO`, which keeps
/// the timeout hoop a no-op — tests that don't exercise it stay
/// terse. Production wires the configured value via
/// `with_request_timeout`.
#[doc(hidden)]
pub fn new(
repo: SharedRepo,
authenticator: SharedAuth,
chain_sender: SharedChainSender,
pn_reader: SharedPnReader,
ref_repo: SharedRefRepo,
) -> Self {
Self {
repo,
authenticator,
chain_sender,
pn_reader,
ref_repo,
request_timeout: Duration::ZERO,
}
}
#[doc(hidden)]
pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = timeout;
self
}
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct MarketsResponse {
server_time: i64,
next_cursor: Option<String>,
has_more: bool,
markets: Vec<MarketDto>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct MarketDto {
market_address: String,
order_book_address: String,
market_name: String,
status: &'static str,
quote_asset: String,
token_type: i32,
maker_commission: String,
taker_commission: String,
created_at: i64,
timings: Option<TimingsDto>,
event: EventDto,
terminal: Option<TerminalDto>,
outcomes: Vec<OutcomeDto>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct TimingsDto {
stake_start: i64,
stake_end: i64,
result_start: i64,
result_end: i64,
frozen_at: Option<i64>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct EventDto {
event_id: String,
event_name: Option<String>,
description: Option<String>,
oracles: Vec<OracleDto>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct OracleDto {
name: Option<String>,
address: Option<String>,
fee: Option<String>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct TerminalDto {
kind: &'static str,
at: i64,
resolved_outcome_id: Option<u32>,
cancel_reason: Option<&'static str>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct OutcomeDto {
outcome_id: u32,
outcome_name: String,
symbol: String,
price_precision: u8,
quantity_precision: u8,
tick_size: String,
step_size: String,
min_notional: String,
max_batch_size: u16,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct DepthResponse {
market_address: String,
symbol: String,
last_update_id: String,
bids: Vec<[String; 2]>,
asks: Vec<[String; 2]>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct OrderResponse {
market_address: String,
symbol: String,
order_id: String,
client_order_id: String,
price: String,
orig_qty: String,
executed_qty: String,
status: &'static str,
time_in_force: &'static str,
#[serde(rename = "type")]
order_type: &'static str,
side: &'static str,
time: i64,
update_time: i64,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct OrdersPageResponse {
orders: Vec<OrderResponse>,
next_cursor: Option<String>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct AccountResponse {
account_id: String,
update_time: i64,
balances: Vec<AccountBalanceItem>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct AccountBalanceItem {
asset: String,
free: String,
locked: String,
}
impl AccountResponse {
fn from_domain(d: dodex_domain::AccountBalances) -> Self {
Self {
account_id: d.account_id.to_string(),
update_time: d.update_time_ms,
balances: d
.balances
.into_iter()
.map(|b| AccountBalanceItem { asset: b.asset, free: b.free, locked: b.locked })
.collect(),
}
}
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct MarketBalancesResponse {
market_address: String,
update_time: i64,
balances: Vec<OutcomeBalanceItem>,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct OutcomeBalanceItem {
outcome_id: u32,
symbol: String,
free: String,
locked_in_orders: String,
}
impl MarketBalancesResponse {
fn from_domain(d: dodex_domain::MarketBalances) -> Self {
Self {
market_address: d.market_address.0,
update_time: d.update_time_ms,
balances: d
.balances
.into_iter()
.map(|b| OutcomeBalanceItem {
outcome_id: b.outcome_id,
symbol: b.symbol.0,
free: b.free,
locked_in_orders: b.locked_in_orders,
})
.collect(),
}
}
}
#[derive(Serialize, ToSchema)]
struct ErrorBody {
code: i32,
msg: &'static str,
}
#[derive(Debug)]
pub(crate) struct ApiError(DomainError);
impl ApiError {
pub(crate) fn status(&self) -> StatusCode {
// Matches are intentionally exhaustive (no `_`): when a new
// `DomainError` variant lands, the compiler forces an update
// here AND in `map_domain_or_unexpected` below — so the two
// sites cannot disagree about whether a new variant is 4xx
// or 5xx.
match self.0 {
DomainError::AuthRequired
| DomainError::AuthEnvelopeIncomplete
| DomainError::TimestampOutsideRecvWindow
| DomainError::InvalidSignature => StatusCode::UNAUTHORIZED,
DomainError::RequestTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
DomainError::UnknownOrder
| DomainError::InvalidMarketOrSymbol
| DomainError::AccountNotDeployed => StatusCode::NOT_FOUND,
// Transient indexer state — fail closed, client retries when
// the indexer catches up.
DomainError::MarketInconsistent => StatusCode::SERVICE_UNAVAILABLE,
// The request_timeout hoop tripped — emit 504 so clients can
// distinguish "our budget elapsed" from "upstream gateway
// failed" (502).
DomainError::RequestTimeout => StatusCode::GATEWAY_TIMEOUT,
// Per-PN serialisation is a chain invariant: only one
// chain operation per trading PN can be in flight at a
// time. 429 is the canonical "you sent too many to this
// PN; back off and retry" — distinct from a 401 (auth)
// or 400 (bad order).
DomainError::OrderPnBusy => StatusCode::TOO_MANY_REQUESTS,
DomainError::Unexpected => StatusCode::INTERNAL_SERVER_ERROR,
DomainError::MissingParameter
| DomainError::InvalidParameter
| DomainError::PrecisionExceeded
| DomainError::OrderValidationFailed => StatusCode::BAD_REQUEST,
}
}
}
impl From<DomainError> for ApiError {
fn from(value: DomainError) -> Self {
Self(value)
}
}
impl Scribe for ApiError {
fn render(self, res: &mut Response) {
res.status_code(self.status());
res.render(Json(ErrorBody { code: self.0.code(), msg: self.0.msg() }));
}
}
/// Map an `anyhow::Error` to `ApiError`: if the error is a typed `DomainError`,
/// return the matching `ApiError` and emit a `warn!` for non-client variants so
/// 5xx responses surface in ops dashboards. Unknown errors fall through to
/// `DomainError::Unexpected` with an `error!` log.
fn map_domain_or_unexpected(err: anyhow::Error, context: &str) -> ApiError {
if let Some(domain) = err.downcast_ref::<DomainError>() {
// Tap: log non-client domain errors at warn level. Match is
// exhaustive (no `_`) so a new variant lands in the classifier
// alongside the status-code site above.
match domain {
DomainError::MissingParameter
| DomainError::InvalidParameter
| DomainError::InvalidMarketOrSymbol
| DomainError::UnknownOrder
| DomainError::AccountNotDeployed
| DomainError::AuthRequired
| DomainError::AuthEnvelopeIncomplete
| DomainError::TimestampOutsideRecvWindow
| DomainError::InvalidSignature
| DomainError::RequestTooLarge
| DomainError::OrderValidationFailed
| DomainError::PrecisionExceeded
| DomainError::OrderPnBusy => {} // client error, no log
DomainError::MarketInconsistent
| DomainError::RequestTimeout
| DomainError::Unexpected => {
// Log the full anyhow chain (including any `.context()`
// breadcrumbs from the use case / repo) — `?domain` alone
// collapses to the variant name and drops upstream
// diagnostics that ops need to triage 5xx.
tracing::warn!(?err, ?domain, context, "handler surfacing 5xx domain error")
}
}
return ApiError::from(*domain);
}
error!(?err, context, "handler failed with non-domain error");
ApiError::from(DomainError::Unexpected)
}
// All error paths render an `ErrorBody` JSON. Status codes vary by `DomainError`
// variant — see `ApiError::status`. Spec-wise we collapse the matrix into a
// single `default` response so the OpenAPI consumer reads one error schema
// rather than 7 nearly-identical entries.
impl EndpointOutRegister for ApiError {
fn register(components: &mut Components, operation: &mut Operation) {
operation.responses.insert(
"default",
OapiResponse::new("Error response")
.add_content("application/json", <ErrorBody as ToSchema>::to_schema(components)),
);
}
}
/// Service readiness probe. Returns `ok` once the process is accepting traffic.
#[endpoint(tags("system"), summary = "Readiness probe", security(()))]
async fn readiness() -> &'static str {
"ok"
}
const DEFAULT_LIMIT: u16 = 50;
const MAX_LIMIT: u16 = 200;
/// List markets or look up a single market by `marketAddress`.
#[endpoint(
tags("market-data"),
summary = "List markets",
parameters(
("marketAddress" = Option<String>, Query, description = "Single-market lookup. Mutually exclusive with listing filters and pagination."),
("status" = Option<String>, Query, description = "Comma-separated MarketStatus filter."),
("quoteAsset" = Option<String>, Query, description = "Filter by quote asset symbol."),
("oracleName" = Option<String>, Query, description = "Filter by oracle name."),
("closingBefore" = Option<i64>, Query, description = "Upper bound on resultStart, unix seconds."),
("sort" = Option<String>, Query, description = "Sort order: resultStart (default) or createdAt."),
("cursor" = Option<String>, Query, description = "Opaque pagination cursor returned from a previous page."),
("limit" = Option<i64>, Query, description = "Page size. Default 50, max 200."),
),
security(()),
)]
async fn get_markets(
req: &mut Request,
depot: &mut Depot,
) -> Result<Json<MarketsResponse>, ApiError> {
let state = depot
.obtain::<AppState>()
.map_err(|err| {
error!(?err, "missing AppState in depot");
ApiError::from(DomainError::Unexpected)
})?
.clone();
let now = now_seconds();
let request = build_markets_request(req, now)?;
let use_case = GetMarketsUseCase::new(state.repo);
let page = use_case
.execute(request)
.await
.map_err(|err| map_domain_or_unexpected(err, "list_markets"))?;
let payload = MarketsResponse {
server_time: now,
next_cursor: page.next_cursor,
has_more: page.has_more,
markets: page.markets.into_iter().map(market_to_dto).collect(),
};
Ok(Json(payload))
}
fn build_markets_request(req: &mut Request, now: i64) -> Result<MarketsRequest, ApiError> {
let market_address = non_empty_query(req, "marketAddress");
let status = non_empty_query(req, "status");
let quote_asset = non_empty_query(req, "quoteAsset");
let oracle_name = non_empty_query(req, "oracleName");
let closing_before = optional_typed_query::<i64>(req, "closingBefore")?;
let sort_param = non_empty_query(req, "sort");
let cursor = non_empty_query(req, "cursor");
// Parse `limit` permissively as i64 so out-of-u16-range values (e.g.
// `limit=99999`) clamp to MAX_LIMIT instead of failing with 400. Only
// non-numeric input still returns InvalidParameter.
let limit_param = optional_typed_query::<i64>(req, "limit")?;
if let Some(addr) = market_address {
if status.is_some()
|| quote_asset.is_some()
|| oracle_name.is_some()
|| closing_before.is_some()
|| sort_param.is_some()
|| cursor.is_some()
|| limit_param.is_some()
{
return Err(ApiError::from(DomainError::MissingParameter));
}
return Ok(MarketsRequest::One { market_address: MarketAddress(addr), now });
}
let statuses = match status {
Some(s) => s
.split(',')
.map(|v| v.trim())
.filter(|v| !v.is_empty())
.map(|v| MarketStatus::parse(v).ok_or(ApiError::from(DomainError::InvalidParameter)))
.collect::<Result<Vec<_>, _>>()?,
None => Vec::new(),
};
let sort = match sort_param.as_deref() {
None | Some("resultStart") => MarketsSort::ResultStartAsc,
Some("createdAt") => MarketsSort::CreatedAtDesc,
Some(_) => return Err(ApiError::from(DomainError::InvalidParameter)),
};
let limit = limit_param.map(|v| v.clamp(1, MAX_LIMIT as i64) as u16).unwrap_or(DEFAULT_LIMIT);
Ok(MarketsRequest::Listing(MarketsListing {
filter: MarketsFilter { statuses, quote_asset, oracle_name, closing_before },
sort,
cursor,
limit,
now,
}))
}
fn market_to_dto(market: Market) -> MarketDto {
MarketDto {
market_address: market.market_address.0,
order_book_address: market.order_book_address,
market_name: market.market_name.0,
status: market.status.as_str(),
quote_asset: market.quote_asset,
token_type: market.token_type,
maker_commission: market.maker_commission,
taker_commission: market.taker_commission,
created_at: market.created_at,
timings: market.timings.map(timings_to_dto),
event: event_to_dto(market.event),
terminal: market.terminal.map(terminal_to_dto),
outcomes: market.outcomes.into_iter().map(outcome_to_dto).collect(),
}
}
fn timings_to_dto(t: Timings) -> TimingsDto {
TimingsDto {
stake_start: t.stake_start,
stake_end: t.stake_end,
result_start: t.result_start,
result_end: t.result_end,
frozen_at: t.frozen_at,
}
}
fn event_to_dto(e: MarketEvent) -> EventDto {
EventDto {
event_id: e.event_id,
event_name: e.event_name,
description: e.description,
oracles: e
.oracles
.into_iter()
.map(|o| OracleDto { name: o.name, address: o.address, fee: o.fee })
.collect(),
}
}
fn terminal_to_dto(t: Terminal) -> TerminalDto {
TerminalDto {
kind: match t.kind {
TerminalKind::Resolved => "RESOLVED",
TerminalKind::Cancelled => "CANCELLED",
TerminalKind::Expired => "EXPIRED",
},
at: t.at,
resolved_outcome_id: t.resolved_outcome_id,
cancel_reason: t.cancel_reason.map(|r| r.as_str()),
}
}
fn outcome_to_dto(o: dodex_domain::Outcome) -> OutcomeDto {
OutcomeDto {
outcome_id: o.outcome_id,
outcome_name: o.outcome_name,
symbol: o.symbol.0,
price_precision: o.price_precision,
quantity_precision: o.quantity_precision,
tick_size: o.tick_size,
step_size: o.step_size,
min_notional: o.min_notional,
max_batch_size: o.max_batch_size,
}
}
/// Order book depth snapshot for a (marketAddress, symbol).
#[endpoint(
tags("market-data"),
summary = "Order book depth",
parameters(
("marketAddress" = String, Query, description = "Market address."),
("symbol" = String, Query, description = "Outcome-token symbol."),
("limit" = Option<i64>, Query, description = "Levels per side. Default 100, max 1000."),
),
security(()),
)]
async fn get_depth(req: &mut Request, depot: &mut Depot) -> Result<Json<DepthResponse>, ApiError> {
let state = depot
.obtain::<AppState>()
.map_err(|err| {
error!(?err, "missing AppState in depot");
ApiError::from(DomainError::Unexpected)
})?
.clone();
let market_address = non_empty_query(req, "marketAddress")
.ok_or(ApiError::from(DomainError::MissingParameter))?;
let symbol =
non_empty_query(req, "symbol").ok_or(ApiError::from(DomainError::MissingParameter))?;
// Parse as i64 so values >u16::MAX clamp to 1000 rather than 400ing.
let limit =
optional_typed_query::<i64>(req, "limit")?.map(|v| v.clamp(1, 1000) as u16).unwrap_or(100);
let use_case = GetDepthUseCase::new(state.repo);
let snapshot = use_case
.execute(GetDepthQuery {
market_address: MarketAddress(market_address),
symbol: Symbol(symbol),
limit,
})
.await
.map_err(|err| map_domain_or_unexpected(err, "get_depth"))?;
Ok(Json(DepthResponse {
market_address: snapshot.market_address.0,
symbol: snapshot.symbol.0,
last_update_id: snapshot.last_update_id,
bids: snapshot.bids.into_iter().map(|level| [level.price, level.quantity]).collect(),
asks: snapshot.asks.into_iter().map(|level| [level.price, level.quantity]).collect(),
}))
}
/// List orders for the authenticated trading PN, with optional filters.
#[endpoint(
tags("trading"),
summary = "List orders",
parameters(
("X-DODEX-APIKEY" = String, Header, description = "API key issued by the Dodex backend."),
("timestamp" = i64, Query, description = "Unix milliseconds. Included in the signed payload."),
("recvWindow" = Option<i64>, Query, description = "Request validity window in milliseconds. Default 5000, max 60000."),
("signature" = String, Query, description = "Hex HMAC SHA-256 of canonicalQueryString + canonicalRequestBody."),
("marketAddress" = Option<String>, Query, description = "Market filter. Must pair with symbol when set."),
("symbol" = Option<String>, Query, description = "Symbol filter. Must pair with marketAddress."),
("status" = Option<String>, Query, description = "Comma-separated OrderStatus filter. Default: all statuses."),
("limit" = Option<i64>, Query, description = "Page size, 1..=500."),
("cursor" = Option<String>, Query, description = "Opaque pagination cursor."),
),
security(("apiKey" = [])),
)]
async fn get_orders(
req: &mut Request,
depot: &mut Depot,
) -> Result<Json<OrdersPageResponse>, ApiError> {
let ctx = require_auth(depot, Permission::UserData)?.clone();
let state = depot
.obtain::<AppState>()
.map_err(|err| {
error!(?err, "missing AppState in depot");
ApiError::from(DomainError::Unexpected)
})?
.clone();
let market_address = non_blank_query(req, "marketAddress")?.map(MarketAddress);
let symbol = non_blank_query(req, "symbol")?.map(Symbol);
let market_filter = OrdersMarketFilter::pair(market_address, symbol).map_err(ApiError::from)?;
// status: raw CSV, validated by OrderStatusFilter::from_csv inside the
// use case. Absent / blank → "all statuses".
let status = req.query::<String>("status");
// `optional_typed_query` returns `Err(InvalidParameter)` when the
// raw value is present but unparseable (e.g. `limit=abc`). That maps
// to -1130 ("Invalid value for a query or body parameter") per the
// api-spec.md error table, which is the precise diagnosis for a
// non-numeric `limit`. Out-of-range numeric inputs (e.g. `limit=501`
// or `limit=0`) still come back as -1102 because the use case applies
// the `[1, 500]` bound check after parsing succeeds; see
// `DomainError::MissingParameter` for the Binance-shaped wire message.
let limit = optional_typed_query::<i64>(req, "limit")?;
// cursor: raw string forwarded to `OrdersCursor::new` inside the
// use case, which trims and rejects blank as `MissingParameter`.
// The blank-rejects-loudly contract lives in the cursor type, not
// at this call site; `marketAddress` / `symbol` enforce the same
// contract one layer up via `non_blank_query` because the use
// case never sees their raw strings.
let cursor = req.query::<String>("cursor");
let use_case = GetOrdersUseCase::new(state.repo);
let page = use_case
.execute(GetOrdersInput {
owner_pn_address: ctx.trading_pn.pn_address.clone(),
market_filter,
status,
limit,
cursor,
})
.await
.map_err(|err| map_domain_or_unexpected(err, "get_orders"))?;
Ok(Json(OrdersPageResponse {
orders: page.orders.into_iter().map(order_to_dto).collect(),
next_cursor: page.next_cursor.map(OrdersCursor::into_string),
}))
}
fn order_to_dto(order: Order) -> OrderResponse {
let OrderParts {
market_address,
symbol,
order_id,
client_order_id,
price,
orig_qty,
executed_qty,
status,
time_in_force,
order_type,
side,
time,
update_time,
..
} = order.into_parts();
OrderResponse {
market_address: market_address.0,
symbol: symbol.0,
order_id,
client_order_id,
price,
orig_qty,
executed_qty,
status: status.as_str(),
time_in_force: time_in_force.as_str(),
order_type: order_type.as_str(),
side: side.as_str(),
time,
update_time,
}
}
fn non_empty_query(req: &mut Request, key: &str) -> Option<String> {
req.query::<String>(key).map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
}
/// Strict variant of [`non_empty_query`]: a present-but-blank value is
/// rejected as `MissingParameter` instead of being silently collapsed
/// to "absent". Mirrors `OrdersCursor::new`'s contract — a client that
/// sends `?marketAddress=&symbol=` is signalling a bug (an unbound
/// template variable), not "no filter". See read-api.md §error table.
fn non_blank_query(req: &mut Request, key: &str) -> Result<Option<String>, ApiError> {
let Some(raw) = req.query::<String>(key) else {
return Ok(None);
};
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(ApiError::from(DomainError::MissingParameter));
}
Ok(Some(trimmed.to_string()))
}
/// Parse an optional typed query parameter the strict way:
/// absent → `Ok(None)`, present-but-blank → `Ok(None)`, present-but-unparseable
/// → `Err(InvalidParameter)`. The default Salvo `req.query::<T>` swallows parse
/// failures and returns `None`, which is a footgun for a public API: callers
/// silently get the default value back instead of `400`.
fn optional_typed_query<T: std::str::FromStr>(
req: &mut Request,
key: &str,
) -> Result<Option<T>, ApiError> {
let Some(raw) = req.query::<String>(key) else {
return Ok(None);
};
let trimmed = raw.trim();
if trimmed.is_empty() {
return Ok(None);
}
trimmed.parse::<T>().map(Some).map_err(|_| ApiError::from(DomainError::InvalidParameter))
}
// Request body for `POST /api/v1/order`. Field names match
// docs/api-spec.md §New Order verbatim; `type` is the reserved keyword
// we rename for serde and rebind to `order_type` internally.
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct CreateOrderRequest {
market_address: Option<String>,
symbol: Option<String>,
new_order_client_id: Option<String>,
side: Option<String>,
quantity: Option<String>,
price: Option<String>,
#[serde(rename = "type")]
order_type: Option<String>,
time_in_force: Option<String>,
}
// Minimal by design — only facts the caller does not already have.
// `clientOrderId` may have been generated by the backend, `transactTime`
// is the moment we accepted, `status` is always `PENDING_NEW` because the
// order has only entered the chain queue at this point. The full order
// shape with chain-assigned `orderId` arrives later via `GET /api/v1/orders`
// once `OrderBook.OrderPlaced` projects.
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct CreateOrderResponse {
client_order_id: String,
transact_time: i64,
status: &'static str,
}
// Minimal by design, parallel to CreateOrderResponse. `clientOrderId` is
// the value recorded on placement, useful for correlating with the prior
// POST. Final state — CANCELED, or FILLED if matching raced the cancel —
// becomes visible later via `GET /api/v1/orders`.
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct CancelOrderResponse {
order_id: String,
client_order_id: String,
transact_time: i64,
status: &'static str,
}
// One market+symbol per request; every item is placed on that single
// book — matches the chain ABI's `PrivateNote.placeBatch(eventId,
// oracleListHash, tokenType, OrderBookOrder[])`. Per-item field names
// mirror `POST /api/v1/order` so a client can reuse the same type for
// both endpoints.
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct BatchOrdersRequest {
market_address: Option<String>,
symbol: Option<String>,
orders: Option<Vec<BatchOrdersRequestItem>>,
}
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct BatchOrdersRequestItem {
new_order_client_id: Option<String>,
side: Option<String>,
quantity: Option<String>,
price: Option<String>,
#[serde(rename = "type")]
order_type: Option<String>,
time_in_force: Option<String>,
}
// Same `PENDING_NEW` envelope as the single-order endpoint — see
// CreateOrderResponse for the rationale. Returned in request order;
// one element per accepted item.
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct BatchOrderResponseItem {
client_order_id: String,
transact_time: i64,
status: &'static str,
}
/// Request body for `DELETE /api/v1/batchOrders`. One market+symbol per
/// request, every id is cancelled on that single book — matches the
/// chain ABI's `PrivateNote.cancelBatch(eventId, oracleListHash,
/// tokenType, uint128[])`. `deny_unknown_fields` is strict on this
/// destructive write surface: a typo like `orderIDs` would otherwise
/// silently deserialise as `order_ids = None` and surface as
/// MissingParameter, masking the real bug — better to 400 with
/// `unknown field` and let the caller fix the key. `CreateOrderRequest`
/// and `BatchOrdersRequest` ship lenient by historical default;
/// flipping them strict is a repo-wide DTO policy change and is
/// tracked separately, not here.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CancelBatchOrdersRequest {
market_address: Option<String>,
symbol: Option<String>,
order_ids: Option<Vec<String>>,
}
// Manual `ToSchema` impl: `#[derive(ToSchema)]` is incompatible with
// `#[serde(deny_unknown_fields)]` in salvo-oapi-macros 0.74.3 — the
// macro emits `additional_properties(Some(...))` where the builder
// expects `Into<AdditionalProperties<Schema>>`, so the derive fails
// to compile. We keep `deny_unknown_fields` (a strict-input contract
// pinned by `unknown_field_in_body_returns_400_minus_1130`) and
// reproduce here what the derive would have generated: camelCase
// property names and an explicit `additionalProperties: false` so the
// OpenAPI consumer sees the same strict signal as the runtime. All
// three fields are marked required: the `Option<_>` only exists so a
// missing field surfaces as a typed `MissingParameter` via the
// `non_empty(...).ok_or(...)` chain in
// `build_cancel_batch_orders_input`, not because the contract treats
// any field as optional.
impl ToSchema for CancelBatchOrdersRequest {
fn to_schema(_components: &mut Components) -> salvo_oapi::RefOr<salvo_oapi::schema::Schema> {
use salvo_oapi::schema::AdditionalProperties;
use salvo_oapi::Array;
use salvo_oapi::BasicType;
use salvo_oapi::Object;
Object::new()
.property("marketAddress", Object::new().schema_type(BasicType::String))
.property("symbol", Object::new().schema_type(BasicType::String))
.property("orderIds", Array::new().items(Object::new().schema_type(BasicType::String)))
.required("marketAddress")
.required("symbol")
.required("orderIds")
.additional_properties(AdditionalProperties::FreeForm(false))
.into()
}
}
// Response item for `DELETE /api/v1/batchOrders`. Same `PENDING_CANCEL`
// envelope as the single-order DELETE — see `CancelOrderResponse`
// for the rationale. Returned in request order; the array has one
// element per accepted id.
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct CancelBatchOrderResponseItem {
order_id: String,
client_order_id: String,
transact_time: i64,
status: &'static str,
}
/// Request body for `POST /api/v1/buyFullSet`. Field names match
/// docs/api-spec.md §Buy Full Set verbatim. `deny_unknown_fields` is
/// strict on this destructive write surface — same rationale as
/// `CancelBatchOrdersRequest`: a typo like `marketAddres` would
/// otherwise silently deserialise as `market_address = None` and
/// surface as MissingParameter, masking the real bug; -1130 with
/// `unknown field` is the actionable signal.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct BuyFullSetRequest {
market_address: Option<String>,
collateral: Option<String>,
}
// Manual `ToSchema` impl: `#[derive(ToSchema)]` is incompatible with
// `#[serde(deny_unknown_fields)]` in salvo-oapi-macros 0.74.3 — same
// reason as `CancelBatchOrdersRequest` above.
//
// Both fields are marked required even though the Rust struct uses
// `Option<String>`: the `Option` only exists so a missing field
// surfaces as a typed `MissingParameter` (-1102) via the
// `non_empty(...).ok_or(...)` chain in the handler, not because the
// API contract treats either field as optional. The schema reflects
// the runtime contract so codegen'd clients get an actionable
// signal.
impl ToSchema for BuyFullSetRequest {
fn to_schema(_components: &mut Components) -> salvo_oapi::RefOr<salvo_oapi::schema::Schema> {
use salvo_oapi::schema::AdditionalProperties;
use salvo_oapi::BasicType;
use salvo_oapi::Object;
Object::new()
.property("marketAddress", Object::new().schema_type(BasicType::String))
.property("collateral", Object::new().schema_type(BasicType::String))
.required("marketAddress")
.required("collateral")
.additional_properties(AdditionalProperties::FreeForm(false))
.into()
}
}
// Minimal acceptance envelope per docs/api-spec.md §Buy Full Set: the
// resulting collateral debit and outcome-token credits become visible
// through `GET /api/v1/account` and `GET /api/v1/account/balances`
// once the chain confirms, so the synchronous response carries only
// the echoed identifier plus the moment we accepted.
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
struct BuyFullSetResponse {
market_address: String,
transact_time: i64,
}