Skip to main content

nautilus_polymarket/http/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! HTTP REST model types for the Polymarket CLOB API.
17
18use std::sync::Arc;
19
20#[cfg(test)]
21use nautilus_core::string::secret::REDACTED;
22use nautilus_core::{
23    serialization::deserialize_empty_string_as_none, string::secret::SecretString,
24};
25use rust_decimal::Decimal;
26use serde::{Deserialize, Serialize};
27use ustr::Ustr;
28
29use crate::common::{
30    enums::{
31        PolymarketLiquiditySide, PolymarketOrderSide, PolymarketOrderStatus, PolymarketOrderType,
32        PolymarketOutcome, PolymarketSignatureType, PolymarketTradeStatus,
33    },
34    models::PolymarketMakerOrder,
35    parse::{
36        deserialize_decimal_from_json, deserialize_decimal_from_json_number,
37        deserialize_decimal_from_str, deserialize_optional_decimal_from_json,
38        deserialize_optional_decimal_from_json_number, deserialize_optional_polymarket_game_id,
39        serialize_decimal_as_json_number, serialize_decimal_as_str,
40        serialize_optional_decimal_as_json_number,
41    },
42};
43
44macro_rules! impl_gamma_response_serde {
45    ($record:ty) => {
46        impl<'de> Deserialize<'de> for $record {
47            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
48            where
49                D: serde::Deserializer<'de>,
50            {
51                let raw = Box::<serde_json::value::RawValue>::deserialize(deserializer)?;
52
53                // The remote derive parses typed fields; this impl also retains their source
54                let mut value =
55                    Self::deserialize(&mut serde_json::Deserializer::from_str(raw.get()))
56                        .map_err(serde::de::Error::custom)?;
57                value.raw = raw.get().to_owned();
58                Ok(value)
59            }
60        }
61
62        impl Serialize for $record {
63            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
64            where
65                S: serde::Serializer,
66            {
67                Self::serialize(self, serializer)
68            }
69        }
70    };
71}
72
73/// A signed limit order for submission to the CLOB V2 exchange.
74///
75/// References: <https://docs.polymarket.com/v2-migration>,
76/// <https://docs.polymarket.com/api-reference/trade/post-a-new-order>
77///
78/// `expiration` is part of the wire body but NOT part of the EIP-712 signed
79/// struct in V2 (the protocol enforces it server-side). `"0"` means no
80/// expiration. All other fields appear inside the signed struct.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "camelCase")]
83pub struct PolymarketOrder {
84    pub salt: u64,
85    pub maker: String,
86    pub signer: String,
87    pub token_id: Ustr,
88    #[serde(
89        serialize_with = "serialize_decimal_as_str",
90        deserialize_with = "deserialize_decimal_from_str"
91    )]
92    pub maker_amount: Decimal,
93    #[serde(
94        serialize_with = "serialize_decimal_as_str",
95        deserialize_with = "deserialize_decimal_from_str"
96    )]
97    pub taker_amount: Decimal,
98    pub side: PolymarketOrderSide,
99    pub signature_type: PolymarketSignatureType,
100    /// Unix seconds timestamp when a GTD order auto-expires. `"0"` for non-GTD.
101    /// Not included in the EIP-712 signed hash; protocol enforces this value.
102    pub expiration: String,
103    /// Order creation time in milliseconds. Replaces `nonce` from V1 for
104    /// per-address uniqueness (not an expiration).
105    pub timestamp: String,
106    /// Generic bytes32 metadata field. Zero bytes when unused.
107    pub metadata: String,
108    /// Builder code (`bytes32`). Zero bytes when unset.
109    pub builder: String,
110    pub signature: SecretString,
111}
112
113/// An active order returned by REST GET /orders.
114///
115/// References: <https://docs.polymarket.com/#get-orders>
116#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
117pub struct PolymarketOpenOrder {
118    pub associate_trades: Option<Vec<String>>,
119    pub id: String,
120    pub status: PolymarketOrderStatus,
121    pub market: Ustr,
122    #[serde(
123        serialize_with = "serialize_decimal_as_str",
124        deserialize_with = "deserialize_decimal_from_str"
125    )]
126    pub original_size: Decimal,
127    pub outcome: PolymarketOutcome,
128    pub maker_address: String,
129    pub owner: String,
130    #[serde(
131        serialize_with = "serialize_decimal_as_str",
132        deserialize_with = "deserialize_decimal_from_str"
133    )]
134    pub price: Decimal,
135    pub side: PolymarketOrderSide,
136    #[serde(
137        serialize_with = "serialize_decimal_as_str",
138        deserialize_with = "deserialize_decimal_from_str"
139    )]
140    pub size_matched: Decimal,
141    pub asset_id: Ustr,
142    pub expiration: Option<String>,
143    pub order_type: PolymarketOrderType,
144    pub created_at: u64,
145}
146
147/// A trade report returned by REST GET /trades.
148///
149/// Missing, null, and empty `transaction_hash` values deserialize as `None` and are
150/// omitted on serialization.
151///
152/// References: <https://docs.polymarket.com/#get-trades>
153#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
154pub struct PolymarketTradeReport {
155    pub id: String,
156    pub taker_order_id: String,
157    pub market: Ustr,
158    pub asset_id: Ustr,
159    pub side: PolymarketOrderSide,
160    #[serde(
161        serialize_with = "serialize_decimal_as_str",
162        deserialize_with = "deserialize_decimal_from_str"
163    )]
164    pub size: Decimal,
165    #[serde(
166        serialize_with = "serialize_decimal_as_str",
167        deserialize_with = "deserialize_decimal_from_str"
168    )]
169    pub fee_rate_bps: Decimal,
170    #[serde(
171        serialize_with = "serialize_decimal_as_str",
172        deserialize_with = "deserialize_decimal_from_str"
173    )]
174    pub price: Decimal,
175    pub status: PolymarketTradeStatus,
176    pub match_time: String,
177    pub last_update: String,
178    pub outcome: PolymarketOutcome,
179    pub bucket_index: u64,
180    pub owner: String,
181    pub maker_address: String,
182    #[serde(
183        default,
184        deserialize_with = "deserialize_empty_string_as_none",
185        skip_serializing_if = "Option::is_none"
186    )]
187    pub transaction_hash: Option<String>,
188    pub maker_orders: Vec<PolymarketMakerOrder>,
189    pub trader_side: PolymarketLiquiditySide,
190}
191
192/// A market response from the Gamma API `GET /markets`.
193///
194/// References: <https://docs.polymarket.com/developers/gamma-markets-api/get-markets>
195#[derive(Clone, Debug, Deserialize, Serialize)]
196#[serde(remote = "Self", rename_all = "camelCase")]
197pub struct GammaMarket {
198    /// Original Gamma response as a JSON string, before normalization or enrichment.
199    #[serde(skip)]
200    pub raw: String,
201    /// Internal Gamma market ID.
202    pub id: String,
203    /// On-chain condition ID for the market protocol.
204    pub condition_id: String,
205    /// Hash used for resolution.
206    #[serde(rename = "questionID")]
207    pub question_id: Option<String>,
208    /// JSON-encoded CTF outcome IDs, selected only for protocol `v1`.
209    #[serde(default)]
210    pub clob_token_ids: String,
211    /// Protocol V2 outcome position IDs in outcome order.
212    pub position_ids: Option<Vec<String>>,
213    /// Protocol V2 resolution state: inactive, active, or resolved.
214    pub resolution_status: Option<String>,
215    /// JSON-encoded outcome labels (e.g. `["Yes", "No"]`).
216    #[serde(default)]
217    pub outcomes: String,
218    /// Market question/title.
219    pub question: String,
220    /// Detailed description.
221    pub description: Option<String>,
222    /// Market start date (ISO 8601).
223    pub start_date: Option<String>,
224    /// Event window start time (ISO 8601).
225    pub event_start_time: Option<String>,
226    /// Market end date (ISO 8601).
227    pub end_date: Option<String>,
228    /// Whether market is active.
229    pub active: Option<bool>,
230    /// Whether market is closed.
231    pub closed: Option<bool>,
232    /// Time when the market closed.
233    pub closed_time: Option<String>,
234    /// UMA resolution state reported by Gamma.
235    pub uma_resolution_status: Option<String>,
236    /// JSON-encoded UMA resolution states reported by Gamma.
237    pub uma_resolution_statuses: Option<String>,
238    /// Source used to resolve the market.
239    pub resolution_source: Option<String>,
240    /// Crypto market resolution configuration.
241    pub crypto_market_config: Option<CryptoMarketConfig>,
242    /// Whether CLOB is accepting orders.
243    pub accepting_orders: Option<bool>,
244    /// Whether order book trading is enabled.
245    pub enable_order_book: Option<bool>,
246    /// Minimum price increment.
247    #[serde(
248        default,
249        deserialize_with = "deserialize_optional_decimal_from_json_number",
250        serialize_with = "serialize_optional_decimal_as_json_number"
251    )]
252    pub order_price_min_tick_size: Option<Decimal>,
253    /// Minimum order size.
254    #[serde(
255        default,
256        deserialize_with = "deserialize_optional_decimal_from_json_number",
257        serialize_with = "serialize_optional_decimal_as_json_number"
258    )]
259    pub order_min_size: Option<Decimal>,
260    /// Maker fee in basis points.
261    pub maker_base_fee: Option<i64>,
262    /// Taker fee in basis points.
263    pub taker_base_fee: Option<i64>,
264    /// URL slug.
265    #[serde(rename = "slug")]
266    pub market_slug: Option<String>,
267    /// Whether the market uses neg-risk CTF exchange.
268    #[serde(rename = "negRisk")]
269    pub neg_risk: Option<bool>,
270    /// Numeric liquidity value for sorting.
271    #[serde(
272        default,
273        deserialize_with = "deserialize_optional_decimal_from_json_number",
274        serialize_with = "serialize_optional_decimal_as_json_number"
275    )]
276    pub liquidity_num: Option<Decimal>,
277    /// Numeric volume value for sorting.
278    #[serde(
279        default,
280        deserialize_with = "deserialize_optional_decimal_from_json_number",
281        serialize_with = "serialize_optional_decimal_as_json_number"
282    )]
283    pub volume_num: Option<Decimal>,
284    /// 24-hour trading volume.
285    #[serde(rename = "volume24hr")]
286    #[serde(
287        default,
288        deserialize_with = "deserialize_optional_decimal_from_json_number",
289        serialize_with = "serialize_optional_decimal_as_json_number"
290    )]
291    pub volume_24hr: Option<Decimal>,
292    /// JSON-encoded outcome prices (e.g. `["0.60", "0.40"]`).
293    pub outcome_prices: Option<String>,
294    /// Best bid price.
295    #[serde(
296        default,
297        deserialize_with = "deserialize_optional_decimal_from_json_number",
298        serialize_with = "serialize_optional_decimal_as_json_number"
299    )]
300    pub best_bid: Option<Decimal>,
301    /// Best ask price.
302    #[serde(
303        default,
304        deserialize_with = "deserialize_optional_decimal_from_json_number",
305        serialize_with = "serialize_optional_decimal_as_json_number"
306    )]
307    pub best_ask: Option<Decimal>,
308    /// Bid-ask spread.
309    #[serde(
310        default,
311        deserialize_with = "deserialize_optional_decimal_from_json_number",
312        serialize_with = "serialize_optional_decimal_as_json_number"
313    )]
314    pub spread: Option<Decimal>,
315    /// Last trade price.
316    #[serde(
317        default,
318        deserialize_with = "deserialize_optional_decimal_from_json_number",
319        serialize_with = "serialize_optional_decimal_as_json_number"
320    )]
321    pub last_trade_price: Option<Decimal>,
322    /// 1-day price change.
323    #[serde(
324        default,
325        deserialize_with = "deserialize_optional_decimal_from_json_number",
326        serialize_with = "serialize_optional_decimal_as_json_number"
327    )]
328    pub one_day_price_change: Option<Decimal>,
329    /// 1-week price change.
330    #[serde(
331        default,
332        deserialize_with = "deserialize_optional_decimal_from_json_number",
333        serialize_with = "serialize_optional_decimal_as_json_number"
334    )]
335    pub one_week_price_change: Option<Decimal>,
336    /// 1-week volume.
337    #[serde(rename = "volume1wk")]
338    #[serde(
339        default,
340        deserialize_with = "deserialize_optional_decimal_from_json_number",
341        serialize_with = "serialize_optional_decimal_as_json_number"
342    )]
343    pub volume_1wk: Option<Decimal>,
344    /// 1-month volume.
345    #[serde(rename = "volume1mo")]
346    #[serde(
347        default,
348        deserialize_with = "deserialize_optional_decimal_from_json_number",
349        serialize_with = "serialize_optional_decimal_as_json_number"
350    )]
351    pub volume_1mo: Option<Decimal>,
352    /// 1-year volume.
353    #[serde(rename = "volume1yr")]
354    #[serde(
355        default,
356        deserialize_with = "deserialize_optional_decimal_from_json_number",
357        serialize_with = "serialize_optional_decimal_as_json_number"
358    )]
359    pub volume_1yr: Option<Decimal>,
360    /// Minimum size for rewards eligibility.
361    #[serde(
362        default,
363        deserialize_with = "deserialize_optional_decimal_from_json_number",
364        serialize_with = "serialize_optional_decimal_as_json_number"
365    )]
366    pub rewards_min_size: Option<Decimal>,
367    /// Maximum spread for rewards eligibility.
368    #[serde(
369        default,
370        deserialize_with = "deserialize_optional_decimal_from_json_number",
371        serialize_with = "serialize_optional_decimal_as_json_number"
372    )]
373    pub rewards_max_spread: Option<Decimal>,
374    /// Competitiveness score.
375    pub competitive: Option<f64>,
376    /// Market category.
377    pub category: Option<String>,
378    /// Neg-risk market ID for CTF exchange interaction.
379    #[serde(rename = "negRiskMarketID")]
380    pub neg_risk_market_id: Option<String>,
381    /// Fee schedule for this market.
382    pub fee_schedule: Option<FeeSchedule>,
383    /// Whether fees are enabled for this market.
384    pub fees_enabled: Option<bool>,
385    /// Fee type identifier (e.g. `crypto_fees`, `sports_fees_v2`).
386    pub fee_type: Option<String>,
387    /// Tags associated with this market.
388    pub tags: Option<Vec<GammaTag>>,
389    /// Sports market type (e.g. `moneyline`), present for sports markets.
390    pub sports_market_type: Option<String>,
391    /// Game ID for sport markets, kept verbatim because Gamma emits both
392    /// numeric and composite `<uuid>:<away>:<home>` forms. `null` and `-1`
393    /// both mean "no game" and surface as `None`. Reference shape:
394    /// <https://github.com/Polymarket/rs-clob-client/blob/main/src/gamma/types/response.rs>.
395    #[serde(default, deserialize_with = "deserialize_optional_polymarket_game_id")]
396    pub game_id: Option<String>,
397    /// Enclosing event supplied by event-based discovery, with its markets moved out.
398    /// The original event JSON, including those markets, remains in `raw`.
399    #[serde(skip)]
400    pub parent_event: Option<Arc<GammaEvent>>,
401    /// Events linked to this gamma market.
402    pub events: Option<Vec<GammaEvent>>,
403    /// Market protocol version, independent of the CLOB service version.
404    pub version: Option<String>,
405}
406
407impl_gamma_response_serde!(GammaMarket);
408
409#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
410#[serde(rename_all = "camelCase")]
411pub struct FeeSchedule {
412    #[serde(
413        serialize_with = "serialize_decimal_as_json_number",
414        deserialize_with = "deserialize_decimal_from_json"
415    )]
416    pub exponent: Decimal,
417    #[serde(
418        serialize_with = "serialize_decimal_as_json_number",
419        deserialize_with = "deserialize_decimal_from_json"
420    )]
421    pub rate: Decimal,
422    pub taker_only: bool,
423    #[serde(
424        serialize_with = "serialize_decimal_as_json_number",
425        deserialize_with = "deserialize_decimal_from_json"
426    )]
427    pub rebate_rate: Decimal,
428}
429
430impl FeeSchedule {
431    pub(crate) fn to_info(&self) -> serde_json::Value {
432        serde_json::json!({
433            "exponent": self.exponent.to_string(),
434            "rate": self.rate.to_string(),
435            "takerOnly": self.taker_only,
436            "rebateRate": self.rebate_rate.to_string(),
437        })
438    }
439}
440
441/// Crypto market resolution configuration returned by Gamma.
442#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
443#[serde(rename_all = "camelCase")]
444pub struct CryptoMarketConfig {
445    pub id: String,
446    pub asset: String,
447    pub duration: String,
448    pub twap_enabled: bool,
449    #[serde(
450        default,
451        skip_serializing_if = "Option::is_none",
452        deserialize_with = "deserialize_optional_non_null_i64"
453    )]
454    pub twap_lookback_seconds: Option<i64>,
455}
456
457fn deserialize_optional_non_null_i64<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
458where
459    D: serde::Deserializer<'de>,
460{
461    i64::deserialize(deserializer).map(Some)
462}
463
464/// An event response from the Gamma API `GET /events`.
465///
466/// Events are parent containers grouping related markets (e.g., an election
467/// event contains multiple outcome markets). Each event's `markets` array
468/// contains full [`GammaMarket`] objects.
469#[derive(Clone, Debug, Deserialize, Serialize)]
470#[serde(remote = "Self", rename_all = "camelCase")]
471pub struct GammaEvent {
472    /// Original Gamma response as a JSON string, before normalization or enrichment.
473    #[serde(skip)]
474    pub raw: String,
475    pub id: String,
476    pub slug: Option<String>,
477    pub title: Option<String>,
478    pub description: Option<String>,
479    pub start_date: Option<String>,
480    pub end_date: Option<String>,
481    pub active: Option<bool>,
482    pub closed: Option<bool>,
483    pub archived: Option<bool>,
484    #[serde(default)]
485    pub markets: Vec<GammaMarket>,
486    /// Event-level liquidity.
487    #[serde(
488        default,
489        deserialize_with = "deserialize_optional_decimal_from_json_number",
490        serialize_with = "serialize_optional_decimal_as_json_number"
491    )]
492    pub liquidity: Option<Decimal>,
493    /// Event-level volume.
494    #[serde(
495        default,
496        deserialize_with = "deserialize_optional_decimal_from_json_number",
497        serialize_with = "serialize_optional_decimal_as_json_number"
498    )]
499    pub volume: Option<Decimal>,
500    /// Event-level open interest.
501    #[serde(
502        default,
503        deserialize_with = "deserialize_optional_decimal_from_json_number",
504        serialize_with = "serialize_optional_decimal_as_json_number"
505    )]
506    pub open_interest: Option<Decimal>,
507    /// 24-hour event volume.
508    #[serde(rename = "volume24hr")]
509    #[serde(
510        default,
511        deserialize_with = "deserialize_optional_decimal_from_json_number",
512        serialize_with = "serialize_optional_decimal_as_json_number"
513    )]
514    pub volume_24hr: Option<Decimal>,
515    /// Event category.
516    pub category: Option<String>,
517    /// Tags associated with this event.
518    pub tags: Option<Vec<GammaTag>>,
519    /// Whether event uses neg-risk.
520    pub neg_risk: Option<bool>,
521    /// Neg-risk market ID.
522    #[serde(rename = "negRiskMarketID")]
523    pub neg_risk_market_id: Option<String>,
524    /// Whether event is featured.
525    pub featured: Option<bool>,
526    /// Game ID for sport markets, kept verbatim because Gamma emits both
527    /// numeric and composite `<uuid>:<away>:<home>` forms. `null` and `-1`
528    /// both mean "no game" and surface as `None`. Reference shape:
529    /// <https://github.com/Polymarket/rs-clob-client/blob/main/src/gamma/types/response.rs>.
530    #[serde(default, deserialize_with = "deserialize_optional_polymarket_game_id")]
531    pub game_id: Option<String>,
532}
533
534impl_gamma_response_serde!(GammaEvent);
535
536/// A tag from the Gamma API `GET /tags`.
537#[derive(Clone, Debug, Deserialize, Serialize)]
538pub struct GammaTag {
539    /// Tag identifier.
540    pub id: String,
541    /// Human-readable label.
542    pub label: Option<String>,
543    /// URL slug.
544    pub slug: Option<String>,
545}
546
547/// Response from the Gamma API `GET /public-search`.
548#[derive(Clone, Debug, Deserialize, Serialize)]
549pub struct SearchResponse {
550    /// Matching markets.
551    #[serde(default)]
552    pub markets: Option<Vec<GammaMarket>>,
553    /// Matching events.
554    #[serde(default)]
555    pub events: Option<Vec<GammaEvent>>,
556}
557
558/// Tick size response from CLOB `GET /tick-size`.
559///
560/// References: <https://docs.polymarket.com/api-reference/market-data/get-tick-size>
561#[derive(Clone, Debug, Deserialize)]
562pub struct TickSizeResponse {
563    /// Minimum tick size (price increment) for a token.
564    #[serde(deserialize_with = "deserialize_decimal_from_json_number")]
565    pub minimum_tick_size: Decimal,
566}
567
568/// Fee rate response from CLOB `GET /fee-rate`.
569///
570/// This legacy base fee is distinct from the effective `FeeSchedule::rate`.
571#[derive(Clone, Debug, Deserialize)]
572pub struct FeeRateResponse {
573    /// Base fee in basis points.
574    #[serde(deserialize_with = "deserialize_decimal_from_json")]
575    pub base_fee: Decimal,
576}
577
578/// A single price level from the CLOB order book.
579#[derive(Clone, Debug, Deserialize)]
580pub struct ClobBookLevel {
581    pub price: String,
582    pub size: String,
583}
584
585/// Response from the CLOB `GET /book` endpoint.
586///
587/// Extra fields (`market`, `asset_id`, `hash`, `timestamp`) are silently ignored.
588#[derive(Clone, Debug, Deserialize)]
589pub struct ClobBookResponse {
590    pub bids: Vec<ClobBookLevel>,
591    pub asks: Vec<ClobBookLevel>,
592}
593
594/// A single outcome token in a CLOB market response.
595#[derive(Clone, Debug, Deserialize, Serialize)]
596pub struct ClobMarketToken {
597    pub token_id: String,
598    pub outcome: String,
599    #[serde(
600        default,
601        deserialize_with = "deserialize_optional_decimal_from_json_number",
602        serialize_with = "serialize_optional_decimal_as_json_number"
603    )]
604    pub price: Option<Decimal>,
605    pub winner: bool,
606}
607
608/// A daily reward rate in a CLOB market response.
609#[derive(Clone, Debug, Deserialize, Serialize)]
610pub struct ClobMarketRewardRate {
611    pub asset_address: String,
612    #[serde(
613        deserialize_with = "deserialize_decimal_from_json_number",
614        serialize_with = "serialize_decimal_as_json_number"
615    )]
616    pub rewards_daily_rate: Decimal,
617}
618
619/// Reward configuration in a CLOB market response.
620#[derive(Clone, Debug, Deserialize, Serialize)]
621pub struct ClobMarketRewards {
622    pub rates: Option<Vec<ClobMarketRewardRate>>,
623    #[serde(
624        default,
625        deserialize_with = "deserialize_optional_decimal_from_json_number",
626        serialize_with = "serialize_optional_decimal_as_json_number"
627    )]
628    pub min_size: Option<Decimal>,
629    #[serde(
630        default,
631        deserialize_with = "deserialize_optional_decimal_from_json_number",
632        serialize_with = "serialize_optional_decimal_as_json_number"
633    )]
634    pub max_spread: Option<Decimal>,
635}
636
637/// Response from CLOB `GET /markets/{condition_id}`.
638#[derive(Clone, Debug, Deserialize, Serialize)]
639pub struct ClobMarketResponse {
640    pub enable_order_book: Option<bool>,
641    pub active: Option<bool>,
642    pub condition_id: String,
643    pub closed: bool,
644    pub archived: Option<bool>,
645    pub accepting_orders: Option<bool>,
646    pub accepting_order_timestamp: Option<String>,
647    #[serde(
648        default,
649        deserialize_with = "deserialize_optional_decimal_from_json_number",
650        serialize_with = "serialize_optional_decimal_as_json_number"
651    )]
652    pub minimum_order_size: Option<Decimal>,
653    #[serde(
654        default,
655        deserialize_with = "deserialize_optional_decimal_from_json_number",
656        serialize_with = "serialize_optional_decimal_as_json_number"
657    )]
658    pub minimum_tick_size: Option<Decimal>,
659    pub question_id: Option<String>,
660    pub question: Option<String>,
661    pub description: Option<String>,
662    pub market_slug: Option<String>,
663    pub end_date_iso: Option<String>,
664    pub game_start_time: Option<String>,
665    pub seconds_delay: Option<i64>,
666    pub fpmm: Option<String>,
667    pub maker_base_fee: Option<i64>,
668    pub taker_base_fee: Option<i64>,
669    pub notifications_enabled: Option<bool>,
670    pub neg_risk: Option<bool>,
671    pub neg_risk_market_id: Option<String>,
672    pub neg_risk_request_id: Option<String>,
673    pub icon: Option<String>,
674    pub image: Option<String>,
675    pub rewards: Option<ClobMarketRewards>,
676    pub is_50_50_outcome: Option<bool>,
677    pub tokens: Vec<ClobMarketToken>,
678    pub tags: Option<Vec<String>>,
679    pub version: Option<String>,
680}
681
682/// A position row from the Polymarket Data API v2 `GET /v2/positions` endpoint.
683///
684/// References: <https://docs.polymarket.com/api-reference/data-api/migrating-from-v1>
685#[derive(Clone, Debug, Deserialize)]
686pub struct DataApiPosition {
687    #[serde(rename = "token_id")]
688    pub asset: String,
689    pub condition_id: String,
690    #[serde(
691        rename = "current_size",
692        deserialize_with = "deserialize_decimal_from_json"
693    )]
694    pub size: Decimal,
695    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_json")]
696    pub avg_price: Option<Decimal>,
697    #[serde(default)]
698    pub redeemable: bool,
699}
700
701/// A trade row from the Polymarket Data API v2 `GET /v2/trades` endpoint.
702///
703/// References: <https://docs.polymarket.com/api-reference/data-api/migrating-from-v1>
704#[derive(Clone, Debug, Deserialize)]
705pub struct DataApiTrade {
706    pub proxy_wallet: Option<String>,
707    #[serde(rename = "token_id")]
708    pub asset: String,
709    pub condition_id: String,
710    pub side: PolymarketOrderSide,
711    #[serde(deserialize_with = "deserialize_decimal_from_json_number")]
712    pub price: Decimal,
713    #[serde(deserialize_with = "deserialize_decimal_from_json_number")]
714    pub size: Decimal,
715    pub timestamp: i64,
716    pub title: Option<String>,
717    pub slug: Option<String>,
718    pub icon: Option<String>,
719    pub event_slug: Option<String>,
720    pub outcome: Option<String>,
721    pub outcome_index: Option<i64>,
722    pub name: Option<String>,
723    pub pseudonym: Option<String>,
724    pub bio: Option<String>,
725    pub profile_image: Option<String>,
726    pub profile_image_optimized: Option<String>,
727    pub transaction_hash: String,
728}
729
730/// The `pagination` object shared by every paginated Data API v2 response.
731#[derive(Clone, Debug, Deserialize)]
732pub struct DataApiPagination {
733    /// Exact: `true` iff another page exists, never inferred from page fullness.
734    pub has_more: bool,
735    /// Opaque cursor for the next page; `null` on the last page.
736    pub next_cursor: Option<String>,
737}
738
739/// The `{ data, pagination }` envelope shared by every Data API v2 response.
740///
741/// A documented miss is `data: null` or an empty list, never an error.
742#[derive(Clone, Debug, Deserialize)]
743#[serde(bound = "T: Deserialize<'de>")]
744pub struct DataApiPage<T> {
745    #[serde(
746        default = "Vec::new",
747        deserialize_with = "deserialize_nullable_vec_as_empty"
748    )]
749    pub data: Vec<T>,
750    pub pagination: DataApiPagination,
751}
752
753fn deserialize_nullable_vec_as_empty<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
754where
755    D: serde::Deserializer<'de>,
756    T: Deserialize<'de>,
757{
758    Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
759}
760
761#[cfg(test)]
762mod tests {
763    use rstest::rstest;
764    use rust_decimal_macros::dec;
765
766    use super::*;
767    use crate::common::enums::{
768        PolymarketOrderStatus, PolymarketSignatureType, PolymarketTradeStatus,
769    };
770
771    fn load<T: serde::de::DeserializeOwned>(filename: &str) -> T {
772        let path = format!("test_data/{filename}");
773        let content = std::fs::read_to_string(path).expect("Failed to read test data");
774        serde_json::from_str(&content).expect("Failed to parse test data")
775    }
776
777    #[rstest]
778    #[case::market(include_str!("../../test_data/decimal_precision_market.json"), false)]
779    #[case::event(include_str!("../../test_data/decimal_precision_event.json"), true)]
780    fn test_gamma_financial_fields_round_trip_exactly(#[case] raw: &str, #[case] event: bool) {
781        let encoded = if event {
782            serde_json::to_string(&serde_json::from_str::<GammaEvent>(raw).unwrap()).unwrap()
783        } else {
784            serde_json::to_string(&serde_json::from_str::<GammaMarket>(raw).unwrap()).unwrap()
785        };
786        let expected: std::collections::BTreeMap<String, Box<serde_json::value::RawValue>> =
787            serde_json::from_str(raw).unwrap();
788        let actual: std::collections::BTreeMap<String, Box<serde_json::value::RawValue>> =
789            serde_json::from_str(&encoded).unwrap();
790
791        for (field, value) in expected {
792            if value.get().starts_with(|c: char| c.is_ascii_digit()) {
793                assert_eq!(actual[&field].get(), value.get(), "{field}");
794            }
795        }
796    }
797
798    #[rstest]
799    fn test_data_api_position_preserves_decimal_precision() {
800        let raw = include_str!("../../test_data/decimal_precision_position.json");
801        let position: DataApiPosition = serde_json::from_str(raw).unwrap();
802        assert_eq!(position.asset, "precision-asset");
803        assert_eq!(position.condition_id, "0xprecision");
804        assert_eq!(position.size, dec!(12345678901.123456));
805        assert_eq!(
806            position.avg_price,
807            Some(dec!(0.1234567890123456789012345678))
808        );
809        let strings = raw
810            .replace("12345678901.123456", "\"12345678901.123456\"")
811            .replace(
812                "0.1234567890123456789012345678",
813                "\"0.1234567890123456789012345678\"",
814            );
815        let string_position: DataApiPosition = serde_json::from_str(&strings).unwrap();
816        assert_eq!(string_position.size, position.size);
817        assert_eq!(string_position.avg_price, position.avg_price);
818    }
819
820    #[rstest]
821    fn test_gamma_financial_fields_and_fee_info_preserve_decimal_precision() {
822        let market: GammaMarket = serde_json::from_str(include_str!(
823            "../../test_data/decimal_precision_market.json"
824        ))
825        .unwrap();
826        assert_eq!(market.best_bid, Some(dec!(0.1234567890123456789012345678)));
827        assert_eq!(market.best_ask, Some(dec!(0.2345678901234567890123456789)));
828        assert_eq!(market.liquidity_num, Some(dec!(12345678901.123456)));
829        assert_eq!(market.volume_num, Some(dec!(12345678901.123457)));
830        let fee = market.fee_schedule.unwrap();
831        let info = fee.to_info();
832        assert_eq!(info["exponent"], "1.234567890123456789012345678");
833        assert_eq!(info["rate"], "0.1234567890123456789012345678");
834        assert_eq!(info["rebateRate"], "0.0234567890123456789012345678");
835        assert_eq!(info["takerOnly"], true);
836        let restored: FeeSchedule = serde_json::from_value(info).unwrap();
837        assert_eq!(restored.exponent, fee.exponent);
838        assert_eq!(restored.rate, fee.rate);
839        assert_eq!(restored.rebate_rate, fee.rebate_rate);
840        assert_eq!(restored.taker_only, fee.taker_only);
841    }
842
843    #[rstest]
844    fn test_open_order_live_buy_gtc() {
845        let order: PolymarketOpenOrder = load("http_open_order.json");
846
847        assert_eq!(
848            order.id,
849            "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12"
850        );
851        assert_eq!(order.status, PolymarketOrderStatus::Live);
852        assert_eq!(order.side, PolymarketOrderSide::Buy);
853        assert_eq!(order.order_type, PolymarketOrderType::GTC);
854        assert_eq!(order.outcome, PolymarketOutcome::yes());
855        assert_eq!(order.original_size, dec!(100.0000));
856        assert_eq!(order.price, dec!(0.5000));
857        assert_eq!(order.size_matched, dec!(25.0000));
858        assert_eq!(order.created_at, 1703875200);
859        assert!(order.expiration.is_none());
860        assert_eq!(order.associate_trades, Some(vec!["0xabc001".to_string()]));
861    }
862
863    #[rstest]
864    fn test_open_order_matched_sell_fok() {
865        let order: PolymarketOpenOrder = load("http_open_order_sell_fok.json");
866
867        assert_eq!(order.status, PolymarketOrderStatus::Matched);
868        assert_eq!(order.side, PolymarketOrderSide::Sell);
869        assert_eq!(order.order_type, PolymarketOrderType::FOK);
870        assert_eq!(order.outcome, PolymarketOutcome::no());
871        assert_eq!(order.size_matched, dec!(50.0000));
872        assert_eq!(order.expiration, Some("1735689600".to_string()));
873        assert!(order.associate_trades.is_none());
874    }
875
876    #[rstest]
877    fn test_open_order_roundtrip() {
878        let order: PolymarketOpenOrder = load("http_open_order.json");
879        let json = serde_json::to_string(&order).unwrap();
880        let order2: PolymarketOpenOrder = serde_json::from_str(&json).unwrap();
881        assert_eq!(order, order2);
882    }
883
884    #[rstest]
885    fn test_trade_report_fields() {
886        let trade: PolymarketTradeReport = load("http_trade_report.json");
887
888        assert_eq!(trade.id, "trade-0xabcdef1234");
889        assert_eq!(
890            trade.taker_order_id,
891            "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12"
892        );
893        assert_eq!(trade.side, PolymarketOrderSide::Buy);
894        assert_eq!(trade.size, dec!(25.0000));
895        assert_eq!(trade.fee_rate_bps, dec!(0));
896        assert_eq!(trade.price, dec!(0.5000));
897        assert_eq!(trade.status, PolymarketTradeStatus::Confirmed);
898        assert_eq!(trade.outcome, PolymarketOutcome::yes());
899        assert_eq!(trade.bucket_index, 0);
900        assert_eq!(trade.trader_side, PolymarketLiquiditySide::Taker);
901        assert_eq!(trade.maker_orders.len(), 2);
902        assert_eq!(
903            trade.transaction_hash.as_deref(),
904            Some("0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab")
905        );
906    }
907
908    #[rstest]
909    fn test_trade_report_maker_orders() {
910        let trade: PolymarketTradeReport = load("http_trade_report.json");
911
912        let first = &trade.maker_orders[0];
913        assert_eq!(first.matched_amount, dec!(20.0000));
914        assert_eq!(first.price, dec!(0.5000));
915        assert_eq!(first.outcome, PolymarketOutcome::yes());
916
917        let second = &trade.maker_orders[1];
918        assert_eq!(second.matched_amount, dec!(5.0000));
919    }
920
921    #[rstest]
922    fn test_trade_report_roundtrip() {
923        let trade: PolymarketTradeReport = load("http_trade_report.json");
924        let json = serde_json::to_string(&trade).unwrap();
925        let trade2: PolymarketTradeReport = serde_json::from_str(&json).unwrap();
926        assert_eq!(trade, trade2);
927    }
928
929    #[rstest]
930    #[case::failed_missing("FAILED", None)]
931    #[case::failed_null("FAILED", Some(serde_json::Value::Null))]
932    #[case::failed_empty("FAILED", Some(serde_json::json!("")))]
933    #[case::not_broadcast_missing("TRADE_STATUS_MATCHED_NOT_BROADCASTED", None)]
934    #[case::not_broadcast_null(
935        "TRADE_STATUS_MATCHED_NOT_BROADCASTED",
936        Some(serde_json::Value::Null)
937    )]
938    #[case::not_broadcast_empty("TRADE_STATUS_MATCHED_NOT_BROADCASTED", Some(serde_json::json!("")))]
939    fn test_trade_report_unavailable_transaction_hash(
940        #[case] status: &str,
941        #[case] hash: Option<serde_json::Value>,
942    ) {
943        let baseline: PolymarketTradeReport = load("http_trade_report.json");
944        let mut expected = serde_json::to_value(baseline).unwrap();
945        expected["status"] = serde_json::to_value(
946            serde_json::from_value::<PolymarketTradeStatus>(serde_json::json!(status)).unwrap(),
947        )
948        .unwrap();
949        expected.as_object_mut().unwrap().remove("transaction_hash");
950        let mut payload = expected.clone();
951        payload["status"] = serde_json::json!(status);
952        if let Some(hash) = hash {
953            payload["transaction_hash"] = hash;
954        }
955
956        let trade: PolymarketTradeReport = serde_json::from_value(payload).unwrap();
957
958        assert_eq!(serde_json::to_value(trade).unwrap(), expected);
959    }
960
961    #[rstest]
962    #[case::number(serde_json::json!(123))]
963    #[case::boolean(serde_json::json!(false))]
964    #[case::array(serde_json::json!([]))]
965    #[case::object(serde_json::json!({}))]
966    fn test_trade_report_rejects_invalid_transaction_hash(#[case] hash: serde_json::Value) {
967        let baseline: PolymarketTradeReport = load("http_trade_report.json");
968        let mut payload = serde_json::to_value(baseline).unwrap();
969        payload["transaction_hash"] = hash;
970
971        let error = serde_json::from_value::<PolymarketTradeReport>(payload).unwrap_err();
972
973        assert_eq!(error.classify(), serde_json::error::Category::Data);
974        assert!(error.to_string().contains("expected a string"));
975    }
976
977    #[rstest]
978    fn test_signed_order_camel_case_fields() {
979        let order: PolymarketOrder = load("http_signed_order.json");
980        let debug = format!("{order:?}");
981
982        assert_eq!(order.salt, 123456789);
983        assert_eq!(order.maker, "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
984        assert_eq!(order.maker_amount, dec!(100000000));
985        assert_eq!(order.taker_amount, dec!(50000000));
986        assert_eq!(order.expiration, "0");
987        assert_eq!(order.timestamp, "1713398400000");
988        assert_eq!(
989            order.metadata,
990            "0x0000000000000000000000000000000000000000000000000000000000000000"
991        );
992        assert_eq!(
993            order.builder,
994            "0x0000000000000000000000000000000000000000000000000000000000000000"
995        );
996        assert_eq!(order.side, PolymarketOrderSide::Buy);
997        assert_eq!(order.signature_type, PolymarketSignatureType::Eoa);
998        assert!(debug.contains(REDACTED));
999        assert!(!debug.contains(order.signature.expose_secret()));
1000    }
1001
1002    #[rstest]
1003    fn test_signed_order_roundtrip() {
1004        let order: PolymarketOrder = load("http_signed_order.json");
1005        let json = serde_json::to_string(&order).unwrap();
1006        let order2: PolymarketOrder = serde_json::from_str(&json).unwrap();
1007        assert_eq!(order, order2);
1008    }
1009
1010    #[rstest]
1011    fn test_signed_order_serializes_camel_case() {
1012        let order: PolymarketOrder = load("http_signed_order.json");
1013        let json = serde_json::to_string(&order).unwrap();
1014
1015        // Verify camelCase field names are present in serialized output
1016        assert!(json.contains("\"tokenId\""));
1017        assert!(json.contains("\"makerAmount\""));
1018        assert!(json.contains("\"takerAmount\""));
1019        assert!(json.contains("\"signatureType\""));
1020        assert!(json.contains("\"expiration\""));
1021        assert!(json.contains("\"timestamp\""));
1022        assert!(json.contains("\"metadata\""));
1023        assert!(json.contains("\"builder\""));
1024    }
1025
1026    #[rstest]
1027    fn test_signed_order_omits_v1_fields() {
1028        // V2 dropped `taker`, `nonce`, and `feeRateBps` from the order body.
1029        // A regression that re-introduces any of them would silently land V1
1030        // shape on a V2 endpoint, so we explicitly assert their absence.
1031        let order: PolymarketOrder = load("http_signed_order.json");
1032        let json = serde_json::to_string(&order).unwrap();
1033
1034        assert!(
1035            !json.contains("\"taker\""),
1036            "wire body must not include `taker`: {json}"
1037        );
1038        assert!(
1039            !json.contains("\"nonce\""),
1040            "wire body must not include `nonce`: {json}"
1041        );
1042        assert!(
1043            !json.contains("\"feeRateBps\""),
1044            "wire body must not include `feeRateBps`: {json}"
1045        );
1046    }
1047
1048    #[rstest]
1049    fn test_signed_order_v2_docs_example_roundtrips() {
1050        // POST /order body shape from <https://docs.polymarket.com/v2-migration>.
1051        // Round-tripping it ensures we accept the exact shape the docs publish.
1052        let docs_example = r#"{
1053            "salt": 12345,
1054            "maker": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
1055            "signer": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
1056            "tokenId": "102936",
1057            "makerAmount": "1000000",
1058            "takerAmount": "2000000",
1059            "side": "BUY",
1060            "signatureType": 1,
1061            "expiration": "0",
1062            "timestamp": "1713398400000",
1063            "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000",
1064            "builder": "0x0000000000000000000000000000000000000000000000000000000000000000",
1065            "signature": "0xdeadbeef"
1066        }"#;
1067
1068        let order: PolymarketOrder = serde_json::from_str(docs_example).unwrap();
1069        assert_eq!(order.salt, 12345);
1070        assert_eq!(order.token_id.as_str(), "102936");
1071        assert_eq!(order.maker_amount, dec!(1000000));
1072        assert_eq!(order.taker_amount, dec!(2000000));
1073        assert_eq!(order.side, PolymarketOrderSide::Buy);
1074        assert_eq!(order.signature_type, PolymarketSignatureType::PolyProxy);
1075        assert_eq!(order.expiration, "0");
1076        assert_eq!(order.timestamp, "1713398400000");
1077
1078        // Round-trip preserves field semantics.
1079        let json = serde_json::to_string(&order).unwrap();
1080        let order2: PolymarketOrder = serde_json::from_str(&json).unwrap();
1081        assert_eq!(order, order2);
1082    }
1083
1084    #[rstest]
1085    fn test_gamma_event_deserialization() {
1086        let events: Vec<GammaEvent> = load("gamma_event.json");
1087
1088        assert_eq!(events.len(), 1);
1089        let event = &events[0];
1090        assert_eq!(event.id, "30829");
1091        assert_eq!(
1092            event.slug.as_deref(),
1093            Some("democratic-presidential-nominee-2028")
1094        );
1095        assert_eq!(
1096            event.title.as_deref(),
1097            Some("Democratic Presidential Nominee 2028")
1098        );
1099        assert_eq!(event.active, Some(true));
1100        assert_eq!(event.closed, Some(false));
1101        assert_eq!(event.archived, Some(false));
1102        assert_eq!(event.markets.len(), 2);
1103        assert_eq!(
1104            event.markets[0].condition_id,
1105            "0xc8f1cf5d4f26e0fd9c8fe89f2a7b3263b902cf14fde7bfccef525753bb492e47"
1106        );
1107        assert_eq!(
1108            event.markets[1].condition_id,
1109            "0xe39adea057926dc197fe30a441f57a340b2a232d5a687010f78bba9b6e02620f"
1110        );
1111    }
1112
1113    #[rstest]
1114    fn test_gamma_event_empty_markets() {
1115        let json = r#"[{"id": "evt-002"}]"#;
1116        let events: Vec<GammaEvent> = serde_json::from_str(json).unwrap();
1117
1118        assert_eq!(events.len(), 1);
1119        assert_eq!(events[0].id, "evt-002");
1120        assert!(events[0].markets.is_empty());
1121        assert!(events[0].slug.is_none());
1122    }
1123
1124    #[rstest]
1125    fn test_sports_market_are_weird() {
1126        let money_line: GammaMarket = load("gamma_market_sports_market_money_line.json");
1127        let map_handicap: GammaMarket = load("gamma_market_sports_market_map_handicap.json");
1128
1129        // same event, same slug
1130        assert_eq!(
1131            money_line.events.as_ref().unwrap()[0].game_id,
1132            map_handicap.events.as_ref().unwrap()[0].game_id
1133        );
1134
1135        // one market has no game_id
1136        assert!(map_handicap.game_id.is_none());
1137        assert_eq!(money_line.game_id.as_deref(), Some("1427074"));
1138    }
1139
1140    #[rstest]
1141    fn test_gamma_event_composite_sports_game_id() {
1142        // Live Gamma record from issue #4771: the event carries a numeric
1143        // `gameId` while its first market carries a composite one.
1144        let events: Vec<GammaEvent> = load("gamma_event_sports_composite_game_id.json");
1145
1146        assert_eq!(events.len(), 1);
1147
1148        let event = &events[0];
1149
1150        assert_eq!(event.id, "835109");
1151        assert_eq!(event.game_id.as_deref(), Some("287011684"));
1152        assert_eq!(event.markets.len(), 2);
1153        assert_eq!(event.markets[0].id, "3524358");
1154        assert_eq!(
1155            event.markets[0].game_id.as_deref(),
1156            Some("dd80aae9-52f9-4c7b-a1cf-7b4ab63cd281:STL:TEX")
1157        );
1158        assert_eq!(event.markets[1].id, "3554041");
1159        assert_eq!(event.markets[1].game_id, None);
1160
1161        // Re-serialization feeds the Python loader, so the key stays a string
1162        // even where Gamma sent a number.
1163        let encoded = serde_json::to_value(event).unwrap();
1164
1165        assert_eq!(encoded["gameId"], serde_json::json!("287011684"));
1166        assert_eq!(
1167            encoded["markets"][0]["gameId"],
1168            serde_json::json!("dd80aae9-52f9-4c7b-a1cf-7b4ab63cd281:STL:TEX")
1169        );
1170    }
1171
1172    #[rstest]
1173    fn test_fee_schedule_decimal_fields() {
1174        let market: GammaMarket = load("gamma_market_sports_market_money_line.json");
1175        let schedule = market.fee_schedule.unwrap();
1176
1177        assert_eq!(schedule.exponent, Decimal::ONE);
1178        assert_eq!(schedule.rate, dec!(0.03));
1179        assert!(schedule.taker_only);
1180        assert_eq!(schedule.rebate_rate, dec!(0.25));
1181    }
1182
1183    #[rstest]
1184    fn test_gamma_market_crypto_market_config_fields() {
1185        let market: GammaMarket = load("gamma_market_crypto_twap.json");
1186        let config = market.crypto_market_config.as_ref().unwrap();
1187
1188        assert_eq!(config.id, "btc-5m-twap-60");
1189        assert_eq!(config.asset, "btc");
1190        assert_eq!(config.duration, "5m");
1191        assert!(config.twap_enabled);
1192        assert_eq!(config.twap_lookback_seconds, Some(60));
1193        assert_eq!(
1194            market.resolution_source.as_deref(),
1195            Some("https://data.chain.link/streams/btc-usd-twap-60s-streams")
1196        );
1197        assert_eq!(
1198            market.event_start_time.as_deref(),
1199            Some("2026-08-22T16:00:00Z")
1200        );
1201    }
1202
1203    #[rstest]
1204    fn test_crypto_market_config_absent_twap_lookback_serializes_omitted() {
1205        let crypto_market_config = serde_json::json!({
1206            "id": "btc-5m",
1207            "asset": "btc",
1208            "duration": "5m",
1209            "twapEnabled": false,
1210        });
1211
1212        let config: CryptoMarketConfig = serde_json::from_value(crypto_market_config).unwrap();
1213        let encoded = serde_json::to_value(config).unwrap();
1214
1215        assert!(encoded.get("twapLookbackSeconds").is_none());
1216    }
1217
1218    #[rstest]
1219    fn test_crypto_market_config_rejects_null_twap_lookback() {
1220        let crypto_market_config = serde_json::json!({
1221            "id": "btc-5m",
1222            "asset": "btc",
1223            "duration": "5m",
1224            "twapEnabled": false,
1225            "twapLookbackSeconds": null,
1226        });
1227
1228        let result = serde_json::from_value::<CryptoMarketConfig>(crypto_market_config);
1229
1230        assert!(result.is_err());
1231    }
1232
1233    #[rstest]
1234    #[case(serde_json::json!(-37))]
1235    #[case(serde_json::json!(i64::MIN))]
1236    #[case(serde_json::json!(i64::MAX))]
1237    fn test_crypto_market_config_signed_twap_lookback_roundtrip(
1238        #[case] twap_lookback_seconds: serde_json::Value,
1239    ) {
1240        let crypto_market_config = serde_json::json!({
1241            "id": "eth-15m",
1242            "asset": "eth",
1243            "duration": "15m",
1244            "twapEnabled": true,
1245            "twapLookbackSeconds": twap_lookback_seconds,
1246        });
1247
1248        let config: CryptoMarketConfig = serde_json::from_value(crypto_market_config).unwrap();
1249        let encoded = serde_json::to_value(config).unwrap();
1250
1251        assert_eq!(encoded["twapLookbackSeconds"], twap_lookback_seconds);
1252    }
1253
1254    #[rstest]
1255    fn test_crypto_market_config_rejects_twap_lookback_above_i64_max() {
1256        let crypto_market_config = serde_json::json!({
1257            "id": "eth-15m",
1258            "asset": "eth",
1259            "duration": "15m",
1260            "twapEnabled": true,
1261            "twapLookbackSeconds": 9_223_372_036_854_775_808u64,
1262        });
1263
1264        let result = serde_json::from_value::<CryptoMarketConfig>(crypto_market_config);
1265
1266        assert!(result.is_err());
1267    }
1268
1269    #[rstest]
1270    fn test_gamma_market_enriched_fields() {
1271        let market: GammaMarket = load("gamma_market.json");
1272
1273        assert_eq!(
1274            market.event_start_time.as_deref(),
1275            Some("2026-03-12T09:20:00Z")
1276        );
1277        assert_eq!(market.best_bid, Some(dec!(0.5)));
1278        assert_eq!(market.best_ask, Some(dec!(0.51)));
1279        assert_eq!(market.spread, Some(dec!(0.009)));
1280        assert_eq!(market.last_trade_price, Some(dec!(0.51)));
1281        assert!(market.one_day_price_change.is_none());
1282        assert!(market.one_week_price_change.is_none());
1283        assert_eq!(market.volume_1wk, Some(dec!(9.999997)));
1284        assert_eq!(market.volume_1mo, Some(dec!(9.999997)));
1285        assert_eq!(market.volume_1yr, Some(dec!(9.999997)));
1286        assert_eq!(market.rewards_min_size, Some(dec!(50.0)));
1287        assert_eq!(market.rewards_max_spread, Some(dec!(4.5)));
1288        assert_eq!(market.competitive, Some(0.9999750006249843));
1289        assert!(market.category.is_none());
1290        assert!(market.neg_risk_market_id.is_none());
1291        assert!(market.uma_resolution_status.is_none());
1292        assert_eq!(market.uma_resolution_statuses.as_deref(), Some("[]"));
1293        assert_eq!(
1294            market.outcome_prices.as_deref(),
1295            Some("[\"0.505\", \"0.495\"]")
1296        );
1297    }
1298
1299    #[rstest]
1300    fn test_gamma_market_uma_resolution_statuses() {
1301        let market: GammaMarket = load("gamma_market.json");
1302
1303        assert!(market.uma_resolution_status.is_none());
1304        assert_eq!(market.uma_resolution_statuses.as_deref(), Some("[]"));
1305    }
1306
1307    #[rstest]
1308    fn test_gamma_market_enriched_fields_default_to_none() {
1309        // Minimal market JSON: only required fields
1310        let json = r#"{"id": "m1", "conditionId": "0xcond", "clobTokenIds": "[]", "outcomes": "[]", "question": "Q?"}"#;
1311        let market: GammaMarket = serde_json::from_str(json).unwrap();
1312
1313        assert!(market.best_bid.is_none());
1314        assert!(market.spread.is_none());
1315        assert!(market.volume_1wk.is_none());
1316        assert!(market.rewards_min_size.is_none());
1317        assert!(market.competitive.is_none());
1318        assert!(market.category.is_none());
1319        assert!(market.neg_risk_market_id.is_none());
1320        assert!(market.crypto_market_config.is_none());
1321        assert!(market.event_start_time.is_none());
1322    }
1323
1324    #[rstest]
1325    fn test_gamma_event_enriched_fields() {
1326        let events: Vec<GammaEvent> = load("gamma_event.json");
1327        let event = &events[0];
1328
1329        assert_eq!(event.liquidity, Some(dec!(43042905.16152)));
1330        assert_eq!(event.volume, Some(dec!(799823812.487094)));
1331        assert_eq!(event.open_interest, Some(dec!(0.0)));
1332        assert_eq!(event.volume_24hr, Some(dec!(5669354.219446001)));
1333        assert!(event.category.is_none());
1334        assert_eq!(event.neg_risk, Some(true));
1335        assert_eq!(
1336            event.neg_risk_market_id.as_deref(),
1337            Some("0x2c3d7e0eee6f058be3006baabf0d54a07da254ba47fe6e3e095e7990c7814700")
1338        );
1339        assert_eq!(event.featured, Some(false));
1340    }
1341
1342    #[rstest]
1343    fn test_gamma_tag_deserialization() {
1344        let tags: Vec<GammaTag> = load("gamma_tags.json");
1345
1346        assert_eq!(tags.len(), 5);
1347        assert_eq!(tags[0].id, "101259");
1348        assert_eq!(tags[0].label.as_deref(), Some("Health and Human Services"));
1349        assert_eq!(tags[0].slug.as_deref(), Some("health-and-human-services"));
1350        assert_eq!(tags[2].slug.as_deref(), Some("attorney-general"));
1351    }
1352
1353    #[rstest]
1354    fn test_search_response_deserialization() {
1355        let response: SearchResponse = load("search_response.json");
1356
1357        // Real API returns no top-level "markets" key
1358        assert!(response.markets.is_none());
1359
1360        let events = response.events.as_ref().unwrap();
1361        assert_eq!(events.len(), 1);
1362        assert_eq!(events[0].slug.as_deref(), Some("bitcoin-above-on-march-11"));
1363        assert_eq!(events[0].markets.len(), 1);
1364    }
1365
1366    #[rstest]
1367    fn test_search_response_empty_fields() {
1368        let json = "{}";
1369        let response: SearchResponse = serde_json::from_str(json).unwrap();
1370        assert!(response.markets.is_none());
1371        assert!(response.events.is_none());
1372    }
1373
1374    #[rstest]
1375    fn test_clob_book_response_deserialization() {
1376        let response: ClobBookResponse = load("clob_book_response.json");
1377
1378        assert_eq!(response.bids.len(), 3);
1379        assert_eq!(response.asks.len(), 3);
1380
1381        assert_eq!(response.bids[0].price, "0.48");
1382        assert_eq!(response.bids[0].size, "100.00");
1383        assert_eq!(response.bids[2].price, "0.50");
1384        assert_eq!(response.bids[2].size, "150.00");
1385
1386        assert_eq!(response.asks[0].price, "0.51");
1387        assert_eq!(response.asks[0].size, "120.00");
1388        assert_eq!(response.asks[2].price, "0.53");
1389        assert_eq!(response.asks[2].size, "90.00");
1390    }
1391
1392    #[rstest]
1393    fn test_clob_book_response_ignores_extra_fields() {
1394        // Verify serde silently ignores fields from both V1 and V2 `/book`
1395        // responses. The live V2 endpoint adds `tick_size`, `min_order_size`,
1396        // `neg_risk`, and `last_trade_price` on top of the V1 fields; pinning
1397        // them here catches a future `#[serde(deny_unknown_fields)]` regression
1398        // before it breaks production parsing.
1399        let json = r#"{
1400            "market": "0xabc",
1401            "asset_id": "123",
1402            "hash": "0x1",
1403            "timestamp": "123",
1404            "bids": [],
1405            "asks": [],
1406            "tick_size": "0.01",
1407            "min_order_size": "5",
1408            "neg_risk": false,
1409            "last_trade_price": "0.55"
1410        }"#;
1411        let response: ClobBookResponse = serde_json::from_str(json).unwrap();
1412        assert!(response.bids.is_empty());
1413        assert!(response.asks.is_empty());
1414    }
1415
1416    #[rstest]
1417    fn test_clob_market_response_captured_fields() {
1418        let response: ClobMarketResponse = load("clob_market_response.json");
1419        let raw: serde_json::Value = load("clob_market_response.json");
1420
1421        assert_eq!(response.enable_order_book, Some(true));
1422        assert_eq!(response.active, Some(true));
1423        assert!(!response.closed);
1424        assert_eq!(response.archived, Some(false));
1425        assert_eq!(response.accepting_orders, Some(true));
1426        assert_eq!(
1427            response.accepting_order_timestamp.as_deref(),
1428            Some("2026-08-01T22:56:49Z")
1429        );
1430        assert_eq!(response.minimum_order_size, Some(dec!(5)));
1431        assert_eq!(response.minimum_tick_size, Some(dec!(0.01)));
1432        assert_eq!(
1433            response.condition_id,
1434            "0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
1435        );
1436        assert_eq!(
1437            response.question_id.as_deref(),
1438            Some("0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
1439        );
1440        assert_eq!(
1441            response.question.as_deref(),
1442            Some("LoL: T1 vs Hanwha Life Esports (BO3) - LCK Round 3-4 Legend Group")
1443        );
1444        assert_eq!(response.description.as_deref(), raw["description"].as_str());
1445        assert_eq!(
1446            response.market_slug.as_deref(),
1447            Some("sanitized-clob-market")
1448        );
1449        assert_eq!(
1450            response.end_date_iso.as_deref(),
1451            Some("2026-08-08T00:00:00Z")
1452        );
1453        assert_eq!(
1454            response.game_start_time.as_deref(),
1455            Some("2026-08-08T08:00:00Z")
1456        );
1457        assert_eq!(response.seconds_delay, Some(1));
1458        assert_eq!(response.fpmm.as_deref(), Some(""));
1459        assert_eq!(response.maker_base_fee, Some(1000));
1460        assert_eq!(response.taker_base_fee, Some(1000));
1461        assert_eq!(response.notifications_enabled, Some(true));
1462        assert_eq!(response.neg_risk, Some(false));
1463        assert_eq!(response.neg_risk_market_id.as_deref(), Some(""));
1464        assert_eq!(response.neg_risk_request_id.as_deref(), Some(""));
1465        assert_eq!(
1466            response.icon.as_deref(),
1467            Some("https://example.com/sanitized-market.png")
1468        );
1469        assert_eq!(
1470            response.image.as_deref(),
1471            Some("https://example.com/sanitized-market.png")
1472        );
1473        let rewards = response.rewards.as_ref().expect("captured rewards");
1474        assert!(rewards.rates.is_none());
1475        assert_eq!(rewards.min_size, Some(dec!(50)));
1476        assert_eq!(rewards.max_spread, Some(dec!(4.5)));
1477        assert_eq!(response.is_50_50_outcome, Some(false));
1478        assert_eq!(response.tokens.len(), 2);
1479        assert_eq!(
1480            response.tokens[0].token_id,
1481            "10000000000000000000000000000000000000000000000000000000000000000000000000001"
1482        );
1483        assert_eq!(response.tokens[0].outcome, "T1");
1484        assert_eq!(response.tokens[0].price, Some(dec!(0.715)));
1485        assert!(!response.tokens[0].winner);
1486        assert_eq!(
1487            response.tokens[1].token_id,
1488            "10000000000000000000000000000000000000000000000000000000000000000000000000002"
1489        );
1490        assert_eq!(response.tokens[1].outcome, "Hanwha Life Esports");
1491        assert_eq!(response.tokens[1].price, Some(dec!(0.285)));
1492        assert!(!response.tokens[1].winner);
1493        assert_eq!(
1494            response.tags.as_deref(),
1495            Some(
1496                &[
1497                    "Sports".to_string(),
1498                    "Esports".to_string(),
1499                    "league of legends".to_string(),
1500                    "Games".to_string(),
1501                ][..]
1502            )
1503        );
1504    }
1505
1506    #[rstest]
1507    fn test_clob_market_rewards_documented_rate_fields() {
1508        // Constructed from the documented Rewards schema because the capture has `rates: null`
1509        let json = r#"{
1510            "rates":[{"asset_address":"0x1111111111111111111111111111111111111111","rewards_daily_rate":12.5}],
1511            "min_size":25,
1512            "max_spread":3.5
1513        }"#;
1514        let rewards: ClobMarketRewards = serde_json::from_str(json).unwrap();
1515
1516        let rates = rewards.rates.as_deref().expect("documented reward rate");
1517        assert_eq!(rates.len(), 1);
1518        assert_eq!(
1519            rates[0].asset_address,
1520            "0x1111111111111111111111111111111111111111"
1521        );
1522        assert_eq!(rates[0].rewards_daily_rate, dec!(12.5));
1523        assert_eq!(rewards.min_size, Some(dec!(25)));
1524        assert_eq!(rewards.max_spread, Some(dec!(3.5)));
1525    }
1526
1527    #[rstest]
1528    fn test_clob_market_decimal_fields_preserve_precision() {
1529        let json = r#"{
1530            "condition_id":"0xcondition",
1531            "closed":false,
1532            "minimum_order_size":123456789.1234567890123456789,
1533            "minimum_tick_size":0.1234567890123456789012345678,
1534            "rewards":{
1535                "rates":[{
1536                    "asset_address":"0x1111111111111111111111111111111111111111",
1537                    "rewards_daily_rate":0.1234567890123456789012345678
1538                }],
1539                "min_size":123456789.1234567890123456789,
1540                "max_spread":0.1234567890123456789012345678
1541            },
1542            "tokens":[{
1543                "token_id":"token-1",
1544                "outcome":"Yes",
1545                "price":0.1234567890123456789012345678,
1546                "winner":false
1547            }]
1548        }"#;
1549        let market: ClobMarketResponse = serde_json::from_str(json).unwrap();
1550        let precise = Decimal::from_str_exact("0.1234567890123456789012345678").unwrap();
1551        let large = Decimal::from_str_exact("123456789.1234567890123456789").unwrap();
1552
1553        assert_eq!(market.minimum_order_size, Some(large));
1554        assert_eq!(market.minimum_tick_size, Some(precise));
1555        let rewards = market.rewards.as_ref().unwrap();
1556        assert_eq!(
1557            rewards.rates.as_ref().unwrap()[0].rewards_daily_rate,
1558            precise
1559        );
1560        assert_eq!(rewards.min_size, Some(large));
1561        assert_eq!(rewards.max_spread, Some(precise));
1562        assert_eq!(market.tokens[0].price, Some(precise));
1563        let serialized = serde_json::to_string(&market).unwrap();
1564        assert!(serialized.contains("\"minimum_order_size\":123456789.1234567890123456789"));
1565        assert!(serialized.contains("\"minimum_tick_size\":0.1234567890123456789012345678"));
1566        assert!(serialized.contains("\"rewards_daily_rate\":0.1234567890123456789012345678"));
1567        assert!(serialized.contains("\"min_size\":123456789.1234567890123456789"));
1568        assert!(serialized.contains("\"max_spread\":0.1234567890123456789012345678"));
1569        assert!(serialized.contains("\"price\":0.1234567890123456789012345678"));
1570    }
1571
1572    #[rstest]
1573    fn test_clob_market_response_deserialization_accepting_false() {
1574        let response: ClobMarketResponse = load("clob_market_closed_binary_accepting_false.json");
1575        assert_eq!(
1576            response.condition_id,
1577            "0x8ccc3f4951ff02c1d34b87988752b4444ad17228732780a6cf22afefe8478bb6"
1578        );
1579        assert!(response.closed);
1580        assert_eq!(response.tokens.len(), 2);
1581        assert_eq!(response.tokens[0].outcome, "Yes");
1582        assert!(!response.tokens[0].winner);
1583        assert_eq!(response.tokens[1].outcome, "No");
1584        assert!(response.tokens[1].winner);
1585    }
1586
1587    #[rstest]
1588    fn test_clob_market_response_deserialization_accepting_true() {
1589        let response: ClobMarketResponse = load("clob_market_closed_binary_accepting_true.json");
1590        assert_eq!(
1591            response.condition_id,
1592            "0xd57eed0d44f5b8ca54925d8d6ff440b146b3e6e071da18136ee3ee572d34479e"
1593        );
1594        assert!(response.closed);
1595        assert_eq!(response.tokens.len(), 2);
1596        assert_eq!(response.tokens[0].outcome, "Yes");
1597        assert!(response.tokens[0].winner);
1598        assert_eq!(response.tokens[1].outcome, "No");
1599        assert!(!response.tokens[1].winner);
1600    }
1601
1602    #[rstest]
1603    fn test_tick_size_response_preserves_json_number() {
1604        let response: TickSizeResponse =
1605            serde_json::from_str(r#"{"minimum_tick_size":0.1234567890123456789012345678}"#)
1606                .unwrap();
1607        let precise =
1608            rust_decimal::Decimal::from_str_exact("0.1234567890123456789012345678").unwrap();
1609
1610        assert_eq!(response.minimum_tick_size, precise);
1611    }
1612
1613    #[rstest]
1614    fn test_fee_rate_response_zero() {
1615        let response: FeeRateResponse = load("clob_fee_rate_response_zero.json");
1616        assert_eq!(response.base_fee, dec!(0));
1617    }
1618
1619    #[rstest]
1620    fn test_fee_rate_response_nonzero() {
1621        let response: FeeRateResponse = load("clob_fee_rate_response_nonzero.json");
1622        assert_eq!(response.base_fee, dec!(150));
1623    }
1624
1625    #[rstest]
1626    fn test_fee_rate_response_numeric() {
1627        let response: FeeRateResponse =
1628            serde_json::from_value(serde_json::json!({"base_fee": 1000})).unwrap();
1629
1630        assert_eq!(response.base_fee, dec!(1000));
1631    }
1632
1633    #[rstest]
1634    fn test_data_api_position_deserialization() {
1635        let positions: Vec<DataApiPosition> =
1636            load::<DataApiPage<DataApiPosition>>("data_api_positions_response.json").data;
1637
1638        assert_eq!(positions.len(), 4);
1639        assert_eq!(
1640            positions[0].asset,
1641            "71321045863084981365469005770620412523470745398083994982746259498689308907982"
1642        );
1643        assert_eq!(
1644            positions[0].condition_id,
1645            "0xc8f1cf5d4f26e0fd9c8fe89f2a7b3263b902cf14fde7bfccef525753bb492e47"
1646        );
1647        assert_eq!(positions[0].size, dec!(150.5));
1648        assert_eq!(positions[0].avg_price, Some(dec!(0.55)));
1649        assert!(!positions[0].redeemable);
1650
1651        // Zero-size position
1652        assert_eq!(positions[1].size, dec!(0));
1653        assert_eq!(positions[1].avg_price, Some(dec!(0.45)));
1654        assert!(!positions[1].redeemable);
1655
1656        // Third position
1657        assert_eq!(
1658            positions[2].condition_id,
1659            "0xabc123def456789012345678901234567890abcdef1234567890abcdef123456"
1660        );
1661        assert_eq!(positions[2].size, dec!(42));
1662        assert_eq!(positions[2].avg_price, Some(dec!(0.3)));
1663        assert!(positions[2].redeemable);
1664
1665        // Dust position (below DUST_POSITION_THRESHOLD)
1666        assert_eq!(positions[3].size, dec!(0.005));
1667        assert_eq!(positions[3].avg_price, Some(dec!(0.7)));
1668        assert!(!positions[3].redeemable);
1669    }
1670
1671    #[rstest]
1672    fn test_data_api_page_deserializes_null_and_missing_data_as_empty() {
1673        // A documented miss is `data: null` or an empty list, never an error.
1674        let null_data = r#"{
1675            "data": null,
1676            "pagination": {"limit": 500, "offset": 0, "has_more": false, "next_cursor": null}
1677        }"#;
1678        let page: DataApiPage<DataApiTrade> = serde_json::from_str(null_data).unwrap();
1679        assert!(page.data.is_empty());
1680        assert!(!page.pagination.has_more);
1681        assert!(page.pagination.next_cursor.is_none());
1682
1683        let missing_data = r#"{
1684            "pagination": {"limit": 500, "offset": 0, "has_more": false, "next_cursor": null}
1685        }"#;
1686        let page: DataApiPage<DataApiTrade> = serde_json::from_str(missing_data).unwrap();
1687        assert!(page.data.is_empty());
1688    }
1689
1690    #[rstest]
1691    fn test_data_api_trade_deserialization() {
1692        let trades: Vec<DataApiTrade> =
1693            load::<DataApiPage<DataApiTrade>>("data_api_trades_captured_response.json").data;
1694
1695        assert_eq!(trades.len(), 3);
1696        assert_eq!(
1697            trades[0].asset,
1698            "10000000000000000000000000000000000000000000000000000000000000000000000000001"
1699        );
1700        assert_eq!(
1701            trades[0].condition_id,
1702            "0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
1703        );
1704        assert_eq!(trades[0].side, PolymarketOrderSide::Sell);
1705        assert_eq!(trades[0].price, dec!(0.7));
1706        assert_eq!(trades[0].size, dec!(92.59));
1707        assert_eq!(trades[0].timestamp, 1786179735);
1708        assert_eq!(
1709            trades[0].transaction_hash,
1710            "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
1711        );
1712
1713        assert_eq!(trades[1].asset, trades[0].asset);
1714        assert_eq!(trades[1].condition_id, trades[0].condition_id);
1715        assert_eq!(trades[1].side, PolymarketOrderSide::Buy);
1716        assert_eq!(trades[1].price, dec!(0.709999959));
1717        assert_eq!(trades[1].size, dec!(1.464786));
1718        assert_eq!(trades[1].timestamp, 1786179730);
1719        assert_eq!(
1720            trades[1].transaction_hash,
1721            "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
1722        );
1723        assert_eq!(
1724            trades[2].asset,
1725            "10000000000000000000000000000000000000000000000000000000000000000000000000002"
1726        );
1727        assert_eq!(trades[2].condition_id, trades[0].condition_id);
1728        assert_eq!(trades[2].side, PolymarketOrderSide::Buy);
1729        assert_eq!(trades[2].price, dec!(0.2972581967));
1730        assert_eq!(trades[2].size, dec!(244));
1731        assert_eq!(trades[2].timestamp, 1786179726);
1732        assert_eq!(
1733            trades[2].transaction_hash,
1734            "0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
1735        );
1736
1737        for (trade, outcome, outcome_index) in [
1738            (&trades[0], "T1", 0),
1739            (&trades[1], "T1", 0),
1740            (&trades[2], "Hanwha Life Esports", 1),
1741        ] {
1742            assert_eq!(
1743                trade.proxy_wallet.as_deref(),
1744                Some("0x1111111111111111111111111111111111111111")
1745            );
1746            assert_eq!(
1747                trade.title.as_deref(),
1748                Some("LoL: T1 vs Hanwha Life Esports (BO3) - LCK Round 3-4 Legend Group")
1749            );
1750            assert_eq!(trade.slug.as_deref(), Some("sanitized-market"));
1751            assert_eq!(
1752                trade.icon.as_deref(),
1753                Some("https://example.com/sanitized-market.png")
1754            );
1755            assert_eq!(trade.event_slug.as_deref(), Some("sanitized-event"));
1756            assert_eq!(trade.outcome.as_deref(), Some(outcome));
1757            assert_eq!(trade.outcome_index, Some(outcome_index));
1758            assert_eq!(trade.name.as_deref(), Some("Sanitized trader"));
1759            assert_eq!(trade.pseudonym.as_deref(), Some("sanitized-trader"));
1760            assert_eq!(trade.bio.as_deref(), Some("Sanitized profile"));
1761            assert_eq!(
1762                trade.profile_image.as_deref(),
1763                Some("https://example.com/sanitized-profile.png")
1764            );
1765            assert_eq!(
1766                trade.profile_image_optimized.as_deref(),
1767                Some("https://example.com/sanitized-profile-optimized.png")
1768            );
1769        }
1770    }
1771
1772    #[rstest]
1773    fn test_data_api_trade_decimal_fields_preserve_precision() {
1774        let json = r#"{
1775            "token_id":"token-1",
1776            "condition_id":"0xcondition",
1777            "side":"BUY",
1778            "price":0.1234567890123456789012345678,
1779            "size":123456789.1234567890123456789,
1780            "timestamp":1786179735,
1781            "transaction_hash":"0xtransaction"
1782        }"#;
1783        let trade: DataApiTrade = serde_json::from_str(json).unwrap();
1784
1785        assert_eq!(
1786            trade.price,
1787            Decimal::from_str_exact("0.1234567890123456789012345678").unwrap()
1788        );
1789        assert_eq!(
1790            trade.size,
1791            Decimal::from_str_exact("123456789.1234567890123456789").unwrap()
1792        );
1793    }
1794
1795    #[rstest]
1796    fn test_gamma_market_fee_fields() {
1797        let market: GammaMarket = load("gamma_market.json");
1798
1799        assert_eq!(market.fees_enabled, Some(true));
1800        assert_eq!(market.fee_type.as_deref(), Some("crypto_fees"));
1801        assert!(market.tags.is_none());
1802        assert!(market.sports_market_type.is_none());
1803    }
1804
1805    #[rstest]
1806    fn test_gamma_market_sports_fee_fields() {
1807        let market: GammaMarket = load("gamma_market_sports_market_money_line.json");
1808
1809        assert_eq!(market.fees_enabled, Some(true));
1810        assert_eq!(market.fee_type.as_deref(), Some("sports_fees_v2"));
1811    }
1812
1813    #[rstest]
1814    fn test_gamma_event_tags() {
1815        let events: Vec<GammaEvent> = load("gamma_event_sports_composite_game_id.json");
1816        let tags = events[0].tags.as_ref().unwrap();
1817
1818        assert!(tags.iter().any(|tag| tag.slug.as_deref() == Some("sports")));
1819    }
1820}