Skip to main content

nautilus_polymarket/http/
query.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 query and response model types for the Polymarket CLOB API.
17
18use std::collections::{HashMap, HashSet};
19
20use ahash::{AHashMap, AHashSet};
21use alloy_primitives::Address;
22use derive_builder::Builder;
23use jiff::{Timestamp, civil::Date, tz::Offset};
24use rust_decimal::Decimal;
25use serde::{
26    Deserialize, Deserializer, Serialize,
27    de::{Error, IgnoredAny, MapAccess, Visitor},
28};
29
30use crate::{
31    common::{
32        enums::{PolymarketOrderType, PolymarketSignatureType},
33        parse::{deserialize_decimal_from_str, deserialize_optional_decimal_from_str},
34    },
35    http::models::PolymarketOrder,
36};
37
38/// Query parameters for `GET /data/orders`.
39#[derive(Clone, Debug, Default, Serialize, Builder)]
40#[builder(setter(into, strip_option), default)]
41pub struct GetOrdersParams {
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub id: Option<String>,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub market: Option<String>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub asset_id: Option<String>,
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub next_cursor: Option<String>,
50}
51
52/// Query parameters for `GET /data/trades`.
53#[derive(Clone, Debug, Default, Serialize, Builder)]
54#[builder(setter(into, strip_option), default)]
55pub struct GetTradesParams {
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub id: Option<String>,
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub maker_address: Option<String>,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub market: Option<String>,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub asset_id: Option<String>,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub before: Option<u64>,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub after: Option<u64>,
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub next_cursor: Option<String>,
70}
71
72/// Query parameters for `GET /balance-allowance` and `GET /balance-allowance/update`.
73#[derive(Clone, Debug, Default, Serialize, Builder)]
74#[builder(setter(into, strip_option), default)]
75pub struct GetBalanceAllowanceParams {
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub asset_type: Option<AssetType>,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub token_id: Option<String>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub signature_type: Option<PolymarketSignatureType>,
82}
83
84/// Body parameters for `DELETE /cancel-market-orders`.
85#[derive(Clone, Debug, Default, Serialize, Builder)]
86#[builder(setter(into, strip_option), default)]
87pub struct CancelMarketOrdersParams {
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub market: Option<String>,
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub asset_id: Option<String>,
92}
93
94/// Asset type for balance and allowance requests.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
97pub enum AssetType {
98    Collateral,
99    Conditional,
100    #[serde(rename = "CONDITIONAL-V2")]
101    ConditionalV2,
102}
103
104/// Strict balance and allowance response for callers that require allowance evidence from
105/// `GET /balance-allowance`.
106///
107/// The plural [`Self::allowances`] map is the sole allowance authority. The legacy singular
108/// [`Self::allowance`] field remains public for source compatibility, but non-null wire values are
109/// rejected. Internal adapter balance-only consumers do not use this type.
110#[derive(Clone, Debug, Deserialize)]
111pub struct BalanceAllowance {
112    #[serde(deserialize_with = "deserialize_decimal_from_str")]
113    pub balance: Decimal,
114    /// Legacy singular field retained for Rust source compatibility.
115    ///
116    /// Deserialization accepts only an absent or null value; use [`Self::allowances`] for evidence.
117    #[serde(default, deserialize_with = "deserialize_rejected_legacy_allowance")]
118    pub allowance: Option<Decimal>,
119    #[serde(deserialize_with = "deserialize_spender_allowances")]
120    pub allowances: HashMap<String, String>,
121}
122
123fn deserialize_rejected_legacy_allowance<'de, D>(
124    deserializer: D,
125) -> Result<Option<Decimal>, D::Error>
126where
127    D: Deserializer<'de>,
128{
129    match Option::<IgnoredAny>::deserialize(deserializer)? {
130        None => Ok(None),
131        Some(_) => Err(D::Error::custom(
132            "legacy singular `allowance` is not accepted; use plural `allowances` evidence",
133        )),
134    }
135}
136
137struct CanonicalSpenderKey {
138    raw: String,
139    address: Address,
140}
141
142impl<'de> Deserialize<'de> for CanonicalSpenderKey {
143    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
144    where
145        D: Deserializer<'de>,
146    {
147        let raw = String::deserialize(deserializer)?;
148        let invalid_spender = format!("invalid spender `{raw}` in allowance evidence");
149        let address = raw
150            .parse::<Address>()
151            .map_err(|_| D::Error::custom(&invalid_spender))?;
152        let is_canonical = [format!("{address:#x}"), address.to_checksum(None)]
153            .into_iter()
154            .any(|candidate| candidate == raw);
155
156        is_canonical
157            .then_some(Self { raw, address })
158            .ok_or_else(|| D::Error::custom(invalid_spender))
159    }
160}
161
162fn deserialize_spender_allowances<'de, D>(
163    deserializer: D,
164) -> Result<HashMap<String, String>, D::Error>
165where
166    D: Deserializer<'de>,
167{
168    struct SpenderAllowancesVisitor;
169
170    impl<'de> Visitor<'de> for SpenderAllowancesVisitor {
171        type Value = HashMap<String, String>;
172
173        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174            formatter.write_str("a spender-to-allowance map without duplicate spenders")
175        }
176
177        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
178        where
179            A: MapAccess<'de>,
180        {
181            let mut allowances = HashMap::new();
182            let mut seen_spenders = HashSet::new();
183            while let Some(spender) = map.next_key::<CanonicalSpenderKey>()? {
184                if !seen_spenders.insert(spender.address) {
185                    return Err(A::Error::custom(format!(
186                        "duplicate spender `{}` in allowance evidence",
187                        spender.raw,
188                    )));
189                }
190                let allowance = map.next_value::<String>()?;
191                allowances.insert(spender.raw, allowance);
192            }
193            Ok(allowances)
194        }
195    }
196
197    deserializer.deserialize_map(SpenderAllowancesVisitor)
198}
199
200/// CLOB service version response from `GET /version`.
201#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
202pub struct ClobVersionResponse {
203    pub version: u8,
204}
205
206/// Status returned after an order submission is processed.
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub enum OrderResponseStatus {
209    Live,
210    Matched,
211    Delayed,
212    Unmatched,
213}
214
215/// Order submission response from `POST /order` and `POST /orders`.
216#[derive(Clone, Debug, Deserialize)]
217pub struct OrderResponse {
218    pub success: bool,
219    #[serde(rename = "orderID")]
220    pub order_id: Option<String>,
221    #[serde(
222        default,
223        deserialize_with = "deserialize_optional_order_response_status"
224    )]
225    pub status: Option<OrderResponseStatus>,
226    #[serde(
227        default,
228        rename = "makingAmount",
229        deserialize_with = "deserialize_optional_decimal_from_str"
230    )]
231    pub making_amount: Option<Decimal>,
232    #[serde(
233        default,
234        rename = "takingAmount",
235        deserialize_with = "deserialize_optional_decimal_from_str"
236    )]
237    pub taking_amount: Option<Decimal>,
238    #[serde(rename = "transactionsHashes")]
239    pub transaction_hashes: Option<Vec<String>>,
240    #[serde(rename = "tradeIDs")]
241    pub trade_ids: Option<Vec<String>>,
242    #[serde(rename = "errorMsg")]
243    pub error_msg: Option<String>,
244}
245
246fn deserialize_optional_order_response_status<'de, D>(
247    deserializer: D,
248) -> Result<Option<OrderResponseStatus>, D::Error>
249where
250    D: Deserializer<'de>,
251{
252    match Option::<String>::deserialize(deserializer)?.as_deref() {
253        None | Some("") => Ok(None),
254        Some("live") => Ok(Some(OrderResponseStatus::Live)),
255        Some("matched") => Ok(Some(OrderResponseStatus::Matched)),
256        Some("delayed") => Ok(Some(OrderResponseStatus::Delayed)),
257        Some("unmatched") => Ok(Some(OrderResponseStatus::Unmatched)),
258        Some(value) => Err(D::Error::unknown_variant(
259            value,
260            &["live", "matched", "delayed", "unmatched"],
261        )),
262    }
263}
264
265/// Cancel response from all cancel endpoints (`DELETE /order`, `/orders`,
266/// `/cancel-all`, `/cancel-market-orders`).
267///
268/// All endpoints return the same format:
269/// `{ "canceled": ["0x..."], "not_canceled": {"0x...": "reason"} }`
270#[derive(Clone, Debug, Default, Deserialize)]
271pub struct CancelResponse {
272    #[serde(default)]
273    pub canceled: Vec<String>,
274    #[serde(default)]
275    pub not_canceled: AHashMap<String, Option<String>>,
276}
277
278impl CancelResponse {
279    pub(crate) fn merge(&mut self, mut response: Self) {
280        self.canceled.append(&mut response.canceled);
281        self.not_canceled.extend(response.not_canceled);
282    }
283}
284
285/// Type alias for backwards compatibility.
286pub type BatchCancelResponse = CancelResponse;
287
288/// Parameters for `POST /order`.
289#[derive(Clone, Debug, Serialize)]
290#[serde(rename_all = "camelCase")]
291pub struct PostOrderParams {
292    pub order_type: PolymarketOrderType,
293    #[serde(skip_serializing_if = "std::ops::Not::not")]
294    pub post_only: bool,
295}
296
297/// One order entry for `POST /orders`.
298#[derive(Clone, Debug, Serialize)]
299#[serde(rename_all = "camelCase")]
300pub struct OrderSubmission {
301    pub order: PolymarketOrder,
302    pub order_type: PolymarketOrderType,
303    #[serde(skip_serializing_if = "std::ops::Not::not")]
304    pub post_only: bool,
305}
306
307/// Query parameters for Gamma API `GET /markets/keyset`.
308#[derive(Clone, Debug, Default, Serialize, Builder)]
309#[builder(setter(into, strip_option), default)]
310pub struct GetGammaMarketsParams {
311    /// Compatibility filter retained from the legacy Gamma market query.
312    #[serde(skip_serializing_if = "Option::is_none")]
313    pub active: Option<bool>,
314    #[serde(skip_serializing_if = "Option::is_none")]
315    pub closed: Option<bool>,
316    /// Compatibility filter retained from the legacy Gamma market query.
317    #[serde(skip_serializing_if = "Option::is_none")]
318    pub archived: Option<bool>,
319    #[serde(skip_serializing_if = "Option::is_none")]
320    pub id: Option<Vec<u64>>,
321    #[serde(skip_serializing_if = "Option::is_none")]
322    pub limit: Option<u32>,
323    /// Client-side initial offset. Keyset requests never send this field.
324    #[serde(skip_serializing_if = "Option::is_none")]
325    pub offset: Option<u32>,
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub order: Option<String>,
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub ascending: Option<bool>,
330    #[serde(skip_serializing_if = "Option::is_none")]
331    pub slug: Option<Vec<String>>,
332    #[serde(skip_serializing_if = "Option::is_none")]
333    pub clob_token_ids: Option<Vec<String>>,
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub condition_ids: Option<Vec<String>>,
336    #[serde(skip_serializing_if = "Option::is_none")]
337    pub question_ids: Option<Vec<String>>,
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub market_maker_address: Option<Vec<String>>,
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub liquidity_num_min: Option<Decimal>,
342    #[serde(skip_serializing_if = "Option::is_none")]
343    pub liquidity_num_max: Option<Decimal>,
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub volume_num_min: Option<Decimal>,
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub volume_num_max: Option<Decimal>,
348    /// ISO 8601 date or RFC 3339 date-time.
349    #[serde(skip_serializing_if = "Option::is_none")]
350    pub start_date_min: Option<String>,
351    /// ISO 8601 date or RFC 3339 date-time.
352    #[serde(skip_serializing_if = "Option::is_none")]
353    pub start_date_max: Option<String>,
354    /// ISO 8601 date or RFC 3339 date-time.
355    #[serde(skip_serializing_if = "Option::is_none")]
356    pub end_date_min: Option<String>,
357    /// ISO 8601 date or RFC 3339 date-time.
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub end_date_max: Option<String>,
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub tag_id: Option<Vec<u64>>,
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pub related_tags: Option<bool>,
364    #[serde(skip_serializing_if = "Option::is_none")]
365    pub tag_match: Option<String>,
366    #[serde(skip_serializing_if = "Option::is_none")]
367    pub decimalized: Option<bool>,
368    #[serde(skip_serializing_if = "Option::is_none")]
369    pub cyom: Option<bool>,
370    #[serde(skip_serializing_if = "Option::is_none")]
371    pub rfq_enabled: Option<bool>,
372    #[serde(skip_serializing_if = "Option::is_none")]
373    pub uma_resolution_status: Option<String>,
374    #[serde(skip_serializing_if = "Option::is_none")]
375    pub game_id: Option<String>,
376    #[serde(skip_serializing_if = "Option::is_none")]
377    pub sports_market_types: Option<Vec<String>>,
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub include_tag: Option<bool>,
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub locale: Option<String>,
382    /// Client-side cap on total markets to fetch across all pages.
383    /// Not sent to the API, only used by the paginator to stop early.
384    /// Each market produces 2 instruments (Yes/No outcomes).
385    #[serde(skip)]
386    pub max_markets: Option<u32>,
387}
388
389/// Query parameters for Gamma API `GET /events/keyset`.
390#[derive(Clone, Debug, Default, Serialize, Builder)]
391#[builder(setter(into, strip_option), default)]
392pub struct GetGammaEventsParams {
393    /// Compatibility filter retained from the legacy Gamma event query.
394    #[serde(skip_serializing_if = "Option::is_none")]
395    pub active: Option<bool>,
396    #[serde(skip_serializing_if = "Option::is_none")]
397    pub closed: Option<bool>,
398    /// Compatibility filter retained from the legacy Gamma event query.
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub archived: Option<bool>,
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub id: Option<Vec<u64>>,
403    #[serde(skip_serializing_if = "Option::is_none")]
404    pub slug: Option<Vec<String>>,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub live: Option<bool>,
407    #[serde(skip_serializing_if = "Option::is_none")]
408    pub featured: Option<bool>,
409    #[serde(skip_serializing_if = "Option::is_none")]
410    pub cyom: Option<bool>,
411    #[serde(skip_serializing_if = "Option::is_none")]
412    pub title_search: Option<String>,
413    #[serde(skip_serializing_if = "Option::is_none")]
414    pub liquidity_min: Option<Decimal>,
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub liquidity_max: Option<Decimal>,
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub volume_min: Option<Decimal>,
419    #[serde(skip_serializing_if = "Option::is_none")]
420    pub volume_max: Option<Decimal>,
421    /// ISO 8601 date or RFC 3339 date-time.
422    #[serde(skip_serializing_if = "Option::is_none")]
423    pub start_date_min: Option<String>,
424    /// ISO 8601 date or RFC 3339 date-time.
425    #[serde(skip_serializing_if = "Option::is_none")]
426    pub start_date_max: Option<String>,
427    /// ISO 8601 date or RFC 3339 date-time.
428    #[serde(skip_serializing_if = "Option::is_none")]
429    pub end_date_min: Option<String>,
430    /// ISO 8601 date or RFC 3339 date-time.
431    #[serde(skip_serializing_if = "Option::is_none")]
432    pub end_date_max: Option<String>,
433    /// ISO 8601 date or RFC 3339 date-time.
434    #[serde(skip_serializing_if = "Option::is_none")]
435    pub start_time_min: Option<String>,
436    /// ISO 8601 date or RFC 3339 date-time.
437    #[serde(skip_serializing_if = "Option::is_none")]
438    pub start_time_max: Option<String>,
439    #[serde(skip_serializing_if = "Option::is_none")]
440    pub tag_id: Option<Vec<u64>>,
441    #[serde(skip_serializing_if = "Option::is_none")]
442    pub tag_slug: Option<String>,
443    #[serde(skip_serializing_if = "Option::is_none")]
444    pub exclude_tag_id: Option<Vec<u64>>,
445    #[serde(skip_serializing_if = "Option::is_none")]
446    pub related_tags: Option<bool>,
447    #[serde(skip_serializing_if = "Option::is_none")]
448    pub tag_match: Option<String>,
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub series_id: Option<Vec<u64>>,
451    #[serde(skip_serializing_if = "Option::is_none")]
452    pub game_id: Option<Vec<u64>>,
453    /// ISO 8601 date or RFC 3339 date-time.
454    #[serde(skip_serializing_if = "Option::is_none")]
455    pub event_date: Option<String>,
456    #[serde(skip_serializing_if = "Option::is_none")]
457    pub event_week: Option<u32>,
458    #[serde(skip_serializing_if = "Option::is_none")]
459    pub featured_order: Option<bool>,
460    #[serde(skip_serializing_if = "Option::is_none")]
461    pub recurrence: Option<String>,
462    #[serde(skip_serializing_if = "Option::is_none")]
463    pub created_by: Option<Vec<String>>,
464    #[serde(skip_serializing_if = "Option::is_none")]
465    pub parent_event_id: Option<u64>,
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub include_children: Option<bool>,
468    #[serde(skip_serializing_if = "Option::is_none")]
469    pub partner_slug: Option<String>,
470    #[serde(skip_serializing_if = "Option::is_none")]
471    pub include_chat: Option<bool>,
472    #[serde(skip_serializing_if = "Option::is_none")]
473    pub include_template: Option<bool>,
474    #[serde(skip_serializing_if = "Option::is_none")]
475    pub include_best_lines: Option<bool>,
476    #[serde(skip_serializing_if = "Option::is_none")]
477    pub locale: Option<String>,
478    #[serde(skip_serializing_if = "Option::is_none")]
479    pub order: Option<String>,
480    #[serde(skip_serializing_if = "Option::is_none")]
481    pub ascending: Option<bool>,
482    #[serde(skip_serializing_if = "Option::is_none")]
483    pub limit: Option<u32>,
484    /// Client-side initial offset. Keyset requests never send this field.
485    #[serde(skip_serializing_if = "Option::is_none")]
486    pub offset: Option<u32>,
487    /// Client-side cap on total events to fetch across all pages.
488    #[serde(skip)]
489    pub max_events: Option<u32>,
490}
491
492impl GetGammaMarketsParams {
493    /// Validates values and combinations used by the Gamma market keyset endpoint.
494    pub fn validate_keyset(&self) -> Result<(), String> {
495        validate_limit(self.limit, 100, "market")?;
496        validate_non_empty_values(self.id.as_deref(), "id")?;
497        validate_non_empty_list(self.slug.as_deref(), "slug")?;
498        validate_non_empty_list(self.clob_token_ids.as_deref(), "clob_token_ids")?;
499        validate_non_empty_list(self.condition_ids.as_deref(), "condition_ids")?;
500        validate_non_empty_list(self.question_ids.as_deref(), "question_ids")?;
501        validate_non_empty_list(self.market_maker_address.as_deref(), "market_maker_address")?;
502        validate_non_empty_values(self.tag_id.as_deref(), "tag_id")?;
503        validate_non_empty_list(self.sports_market_types.as_deref(), "sports_market_types")?;
504
505        if self
506            .condition_ids
507            .as_ref()
508            .is_some_and(|ids| ids.len() > 100)
509        {
510            return Err("condition_ids accepts at most 100 values".to_string());
511        }
512
513        validate_decimal_bounds(
514            self.liquidity_num_min,
515            self.liquidity_num_max,
516            "liquidity_num",
517        )?;
518        validate_decimal_bounds(self.volume_num_min, self.volume_num_max, "volume_num")?;
519        validate_date_bounds(
520            self.start_date_min.as_deref(),
521            self.start_date_max.as_deref(),
522            "start_date",
523        )?;
524        validate_date_bounds(
525            self.end_date_min.as_deref(),
526            self.end_date_max.as_deref(),
527            "end_date",
528        )?;
529        validate_non_empty_string(self.order.as_deref(), "order")?;
530        validate_non_empty_string(self.tag_match.as_deref(), "tag_match")?;
531        validate_non_empty_string(
532            self.uma_resolution_status.as_deref(),
533            "uma_resolution_status",
534        )?;
535        validate_non_empty_string(self.game_id.as_deref(), "game_id")?;
536        validate_non_empty_string(self.locale.as_deref(), "locale")
537    }
538}
539
540impl GetGammaEventsParams {
541    /// Validates values and combinations used by the Gamma event keyset endpoint.
542    pub fn validate_keyset(&self) -> Result<(), String> {
543        validate_limit(self.limit, 500, "event")?;
544        validate_non_empty_values(self.id.as_deref(), "id")?;
545        validate_non_empty_list(self.slug.as_deref(), "slug")?;
546        validate_non_empty_values(self.tag_id.as_deref(), "tag_id")?;
547        validate_non_empty_values(self.exclude_tag_id.as_deref(), "exclude_tag_id")?;
548        validate_non_empty_values(self.series_id.as_deref(), "series_id")?;
549        validate_non_empty_values(self.game_id.as_deref(), "game_id")?;
550        validate_non_empty_list(self.created_by.as_deref(), "created_by")?;
551
552        if let (Some(tag_ids), Some(excluded_ids)) = (&self.tag_id, &self.exclude_tag_id) {
553            let tag_ids: AHashSet<u64> = tag_ids.iter().copied().collect();
554            if excluded_ids.iter().any(|id| tag_ids.contains(id)) {
555                return Err("tag_id and exclude_tag_id cannot overlap".to_string());
556            }
557        }
558
559        validate_decimal_bounds(self.liquidity_min, self.liquidity_max, "liquidity")?;
560        validate_decimal_bounds(self.volume_min, self.volume_max, "volume")?;
561        validate_date_bounds(
562            self.start_date_min.as_deref(),
563            self.start_date_max.as_deref(),
564            "start_date",
565        )?;
566        validate_date_bounds(
567            self.end_date_min.as_deref(),
568            self.end_date_max.as_deref(),
569            "end_date",
570        )?;
571        validate_date_bounds(
572            self.start_time_min.as_deref(),
573            self.start_time_max.as_deref(),
574            "start_time",
575        )?;
576        validate_date_value(self.event_date.as_deref(), "event_date")?;
577        validate_non_empty_string(self.order.as_deref(), "order")?;
578        validate_non_empty_string(self.title_search.as_deref(), "title_search")?;
579        validate_non_empty_string(self.tag_slug.as_deref(), "tag_slug")?;
580        validate_non_empty_string(self.tag_match.as_deref(), "tag_match")?;
581        validate_non_empty_string(self.recurrence.as_deref(), "recurrence")?;
582        validate_non_empty_string(self.partner_slug.as_deref(), "partner_slug")?;
583        validate_non_empty_string(self.locale.as_deref(), "locale")
584    }
585}
586
587fn validate_limit(limit: Option<u32>, ceiling: u32, endpoint: &str) -> Result<(), String> {
588    if let Some(limit) = limit
589        && !(1..=ceiling).contains(&limit)
590    {
591        return Err(format!(
592            "{endpoint} limit must be between 1 and {ceiling}, was {limit}"
593        ));
594    }
595    Ok(())
596}
597
598fn validate_non_empty_list(values: Option<&[String]>, name: &str) -> Result<(), String> {
599    if let Some(values) = values
600        && (values.is_empty() || values.iter().any(|value| value.trim().is_empty()))
601    {
602        return Err(format!("{name} must contain non-empty values"));
603    }
604    Ok(())
605}
606
607fn validate_non_empty_values<T>(values: Option<&[T]>, name: &str) -> Result<(), String> {
608    if values.is_some_and(<[T]>::is_empty) {
609        return Err(format!("{name} must contain at least one value"));
610    }
611    Ok(())
612}
613
614fn validate_decimal_bounds(
615    min: Option<Decimal>,
616    max: Option<Decimal>,
617    name: &str,
618) -> Result<(), String> {
619    if let (Some(min), Some(max)) = (min, max)
620        && min > max
621    {
622        return Err(format!("{name}_min cannot exceed {name}_max"));
623    }
624    Ok(())
625}
626
627fn validate_date_bounds(min: Option<&str>, max: Option<&str>, name: &str) -> Result<(), String> {
628    let min = parse_date_value(min, &format!("{name}_min"))?;
629    let max = parse_date_value(max, &format!("{name}_max"))?;
630    if let (Some(min), Some(max)) = (min, max)
631        && min > max
632    {
633        return Err(format!("{name}_min cannot exceed {name}_max"));
634    }
635    Ok(())
636}
637
638fn validate_date_value(value: Option<&str>, name: &str) -> Result<(), String> {
639    parse_date_value(value, name).map(|_| ())
640}
641
642fn parse_date_value(value: Option<&str>, name: &str) -> Result<Option<Timestamp>, String> {
643    value
644        .map(|value| {
645            if value.as_bytes().get(10) == Some(&b'T') {
646                return value
647                    .parse::<Timestamp>()
648                    .map_err(|_| format!("{name} must be an ISO 8601 date or RFC 3339 date-time"));
649            }
650
651            if value.len() == 10
652                && value.as_bytes().get(4) == Some(&b'-')
653                && value.as_bytes().get(7) == Some(&b'-')
654            {
655                return value
656                    .parse::<Date>()
657                    .and_then(|date| Offset::UTC.to_timestamp(date.at(0, 0, 0, 0)))
658                    .map_err(|_| format!("{name} must be an ISO 8601 date or RFC 3339 date-time"));
659            }
660
661            Err(format!(
662                "{name} must be an ISO 8601 date or RFC 3339 date-time"
663            ))
664        })
665        .transpose()
666}
667
668fn validate_non_empty_string(value: Option<&str>, name: &str) -> Result<(), String> {
669    if value.is_some_and(|value| value.trim().is_empty()) {
670        return Err(format!("{name} cannot be empty"));
671    }
672    Ok(())
673}
674
675/// Query parameters for Gamma API `GET /public-search`.
676#[derive(Clone, Debug, Default, Serialize, Builder)]
677#[builder(setter(into, strip_option), default)]
678pub struct GetSearchParams {
679    /// Free-text search query.
680    #[serde(skip_serializing_if = "Option::is_none")]
681    pub q: Option<String>,
682    /// Filter events by status ("active", "closed", etc.).
683    #[serde(skip_serializing_if = "Option::is_none")]
684    pub events_status: Option<String>,
685    /// Filter by event tag.
686    #[serde(skip_serializing_if = "Option::is_none")]
687    pub events_tag: Option<String>,
688    /// Sort field ("volume", "liquidity", etc.).
689    #[serde(skip_serializing_if = "Option::is_none")]
690    pub sort: Option<String>,
691    #[serde(skip_serializing_if = "Option::is_none")]
692    pub ascending: Option<bool>,
693    #[serde(skip_serializing_if = "Option::is_none")]
694    pub limit_per_type: Option<u32>,
695    #[serde(skip_serializing_if = "Option::is_none")]
696    pub page: Option<u32>,
697    #[serde(skip_serializing_if = "Option::is_none")]
698    pub keep_closed_markets: Option<bool>,
699}
700
701/// Paginated response wrapper for CLOB list endpoints.
702#[derive(Clone, Debug, Deserialize)]
703pub struct PaginatedResponse<T> {
704    pub data: Vec<T>,
705    pub next_cursor: Option<String>,
706}
707
708#[cfg(test)]
709mod tests {
710    use rstest::rstest;
711    use rust_decimal_macros::dec;
712    use serde::de::value::{Error as ValueError, MapDeserializer};
713
714    use super::*;
715    use crate::{
716        common::enums::{PolymarketOrderSide, PolymarketOrderType},
717        http::models::{PolymarketOpenOrder, PolymarketTradeReport},
718    };
719
720    const MAX_ALLOWANCE: &str =
721        "115792089237316195423570985008687907853269984665640564039457584007913129639935";
722
723    struct OversizedSizeHint<I>(I);
724
725    impl<I> Iterator for OversizedSizeHint<I>
726    where
727        I: Iterator,
728    {
729        type Item = I::Item;
730
731        fn next(&mut self) -> Option<Self::Item> {
732            self.0.next()
733        }
734
735        fn size_hint(&self) -> (usize, Option<usize>) {
736            (usize::MAX, Some(usize::MAX))
737        }
738    }
739
740    fn load<T: serde::de::DeserializeOwned>(filename: &str) -> T {
741        let path = format!("test_data/{filename}");
742        let content = std::fs::read_to_string(path).expect("Failed to read test data");
743        serde_json::from_str(&content).expect("Failed to parse test data")
744    }
745
746    #[rstest]
747    fn test_paginated_orders_page() {
748        let page: PaginatedResponse<PolymarketOpenOrder> = load("http_open_orders_page.json");
749
750        assert_eq!(page.data.len(), 2);
751        assert_eq!(page.next_cursor.as_deref(), Some("LTE="));
752        assert_eq!(page.data[0].side, PolymarketOrderSide::Buy);
753        assert_eq!(page.data[1].side, PolymarketOrderSide::Sell);
754    }
755
756    #[rstest]
757    fn test_paginated_trades_page() {
758        let page: PaginatedResponse<PolymarketTradeReport> = load("http_trades_page.json");
759
760        assert_eq!(page.data.len(), 1);
761        assert_eq!(page.next_cursor.as_deref(), Some("LTE="));
762        assert_eq!(page.data[0].id, "trade-0x001");
763    }
764
765    #[rstest]
766    fn test_balance_allowance_with_allowance() {
767        let ba: BalanceAllowance = load("http_balance_allowance_collateral.json");
768
769        assert_eq!(ba.balance, dec!(37_506_152));
770        assert!(ba.allowance.is_none());
771        assert_eq!(
772            ba.allowances,
773            std::collections::HashMap::from([
774                (
775                    "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
776                    MAX_ALLOWANCE.to_string(),
777                ),
778                (
779                    "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_string(),
780                    MAX_ALLOWANCE.to_string(),
781                ),
782                (
783                    "0xcccccccccccccccccccccccccccccccccccccccc".to_string(),
784                    MAX_ALLOWANCE.to_string(),
785                ),
786            ])
787        );
788    }
789
790    #[rstest]
791    fn test_balance_allowance_conditional() {
792        let ba: BalanceAllowance = load("http_balance_allowance_conditional.json");
793
794        assert_eq!(ba.balance, Decimal::ZERO);
795        assert!(ba.allowance.is_none());
796        assert_eq!(ba.allowances.len(), 3);
797        assert!(ba.allowances.values().all(|value| value == MAX_ALLOWANCE));
798    }
799
800    #[rstest]
801    fn test_balance_allowance_rejects_missing_allowances() {
802        let result = serde_json::from_str::<BalanceAllowance>(include_str!(concat!(
803            env!("CARGO_MANIFEST_DIR"),
804            "/test_data/http_balance_allowance_no_allowance.json"
805        )));
806
807        assert!(result.unwrap_err().to_string().contains("missing field"));
808    }
809
810    #[rstest]
811    fn test_balance_allowance_rejects_legacy_singular_without_allowances() {
812        let result =
813            serde_json::from_str::<BalanceAllowance>(r#"{"balance":"250.5","allowance":"1000"}"#);
814
815        assert!(
816            result
817                .unwrap_err()
818                .to_string()
819                .contains("legacy singular `allowance`")
820        );
821    }
822
823    #[rstest]
824    fn test_balance_allowance_rejects_conflicting_singular_and_plural_allowances() {
825        let result = serde_json::from_str::<BalanceAllowance>(
826            r#"{
827                "balance":"250.5",
828                "allowance":"0",
829                "allowances":{
830                    "0xe111180000d2663c0091e4f400237545b87b996b":"115792089237316195423570985008687907853269984665640564039457584007913129639935"
831                }
832            }"#,
833        );
834
835        assert!(
836            result
837                .unwrap_err()
838                .to_string()
839                .contains("legacy singular `allowance`")
840        );
841    }
842
843    #[rstest]
844    fn test_balance_allowance_accepts_null_legacy_marker() {
845        let result = serde_json::from_str::<BalanceAllowance>(
846            r#"{
847                "balance":"250.5",
848                "allowance":null,
849                "allowances":{
850                    "0xe111180000d2663c0091e4f400237545b87b996b":"1000"
851                }
852            }"#,
853        )
854        .unwrap();
855
856        assert!(result.allowance.is_none());
857        assert_eq!(result.allowances.len(), 1);
858    }
859
860    #[rstest]
861    fn test_balance_allowance_rejects_duplicate_spender() {
862        let duplicate = serde_json::from_str::<BalanceAllowance>(
863            r#"{
864                "balance":"250.5",
865                "allowances":{
866                    "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":"0",
867                    "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":"115792089237316195423570985008687907853269984665640564039457584007913129639935"
868                }
869            }"#,
870        )
871        .expect_err("duplicate spender evidence must be rejected before map construction");
872
873        assert!(duplicate.to_string().contains("duplicate spender"));
874    }
875
876    #[rstest]
877    fn test_balance_allowance_rejects_case_variant_spender_alias() {
878        let duplicate = serde_json::from_str::<BalanceAllowance>(
879            r#"{
880                "balance":"250.5",
881                "allowances":{
882                    "0xada2005600dec949baf300f4c6120000bdb6eaab":"0",
883                    "0xadA2005600Dec949baf300f4C6120000bDB6eAab":"115792089237316195423570985008687907853269984665640564039457584007913129639935"
884                }
885            }"#,
886        )
887        .expect_err("case variants of one EVM spender must be rejected as duplicates");
888
889        assert!(duplicate.to_string().contains("duplicate spender"));
890    }
891
892    #[rstest]
893    fn test_balance_allowance_rejects_malformed_spender() {
894        let malformed = serde_json::from_str::<BalanceAllowance>(
895            r#"{
896                "balance":"250.5",
897                "allowances":{
898                    "exchange":"1000"
899                }
900            }"#,
901        )
902        .expect_err("allowance spender must be an EVM address");
903
904        assert!(malformed.to_string().contains("invalid spender"));
905    }
906
907    #[rstest]
908    #[case::missing_prefix("ada2005600dec949baf300f4c6120000bdb6eaab")]
909    #[case::uppercase_prefix("0Xada2005600dec949baf300f4c6120000bdb6eaab")]
910    #[case::invalid_checksum("0xAdA2005600Dec949baf300f4C6120000bDB6eAab")]
911    fn test_balance_allowance_rejects_noncanonical_spender(#[case] spender: &str) {
912        let payload = format!(r#"{{"balance":"250.5","allowances":{{"{spender}":"1000"}}}}"#,);
913
914        let result = serde_json::from_str::<BalanceAllowance>(&payload);
915
916        assert!(result.unwrap_err().to_string().contains("invalid spender"));
917    }
918
919    #[rstest]
920    fn test_balance_allowance_preserves_checksummed_spender() {
921        let spender = "0xadA2005600Dec949baf300f4C6120000bDB6eAab";
922        let payload = format!(r#"{{"balance":"250.5","allowances":{{"{spender}":"1000"}}}}"#,);
923
924        let balance_allowance = serde_json::from_str::<BalanceAllowance>(&payload).unwrap();
925
926        assert_eq!(
927            balance_allowance.allowances.get(spender),
928            Some(&"1000".to_string())
929        );
930    }
931
932    #[rstest]
933    fn test_spender_allowances_ignores_untrusted_size_hint() {
934        let spender = "0xada2005600dec949baf300f4c6120000bdb6eaab";
935        let entries = [(spender, "1000")];
936        let deserializer =
937            MapDeserializer::<_, ValueError>::new(OversizedSizeHint(entries.into_iter()));
938
939        let allowances = deserialize_spender_allowances(deserializer).unwrap();
940
941        assert_eq!(allowances.get(spender).map(String::as_str), Some("1000"));
942    }
943
944    #[rstest]
945    fn test_order_response_success() {
946        let resp: OrderResponse = load("http_order_response_ok.json");
947
948        assert!(resp.success);
949        assert_eq!(
950            resp.order_id.as_deref(),
951            Some("0x1111111111111111111111111111111111111111111111111111111111111111")
952        );
953        assert_eq!(resp.status, Some(OrderResponseStatus::Delayed));
954        assert!(resp.making_amount.is_none());
955        assert!(resp.taking_amount.is_none());
956        assert!(resp.transaction_hashes.is_none());
957        assert!(resp.trade_ids.is_none());
958        assert_eq!(resp.error_msg.as_deref(), Some(""));
959    }
960
961    #[rstest]
962    fn test_order_response_failure() {
963        // Constructed compatibility case for a legacy failure response
964        let resp: OrderResponse = load("http_order_response_failed.json");
965
966        assert!(!resp.success);
967        assert!(resp.order_id.is_none());
968        assert!(resp.status.is_none());
969        assert!(resp.making_amount.is_none());
970        assert!(resp.taking_amount.is_none());
971        assert!(resp.transaction_hashes.is_none());
972        assert!(resp.trade_ids.is_none());
973        assert_eq!(resp.error_msg.as_deref(), Some("Insufficient balance"));
974    }
975
976    #[rstest]
977    fn test_order_response_empty_status() {
978        // Constructed from the documented post-only response, which uses empty strings
979        let json = r#"{
980            "success":true,
981            "orderID":"",
982            "status":"",
983            "makingAmount":"",
984            "takingAmount":"",
985            "errorMsg":"post-only mode"
986        }"#;
987        let resp: OrderResponse = serde_json::from_str(json).unwrap();
988
989        assert!(resp.success);
990        assert_eq!(resp.order_id.as_deref(), Some(""));
991        assert!(resp.status.is_none());
992        assert!(resp.making_amount.is_none());
993        assert!(resp.taking_amount.is_none());
994        assert!(resp.transaction_hashes.is_none());
995        assert!(resp.trade_ids.is_none());
996        assert_eq!(resp.error_msg.as_deref(), Some("post-only mode"));
997    }
998
999    #[rstest]
1000    fn test_order_response_unmatched_status() {
1001        // Constructed compatibility case for a failed delayed placement
1002        let json = r#"{
1003            "success":false,
1004            "orderID":"",
1005            "status":"unmatched",
1006            "makingAmount":"",
1007            "takingAmount":"",
1008            "errorMsg":"placement failed"
1009        }"#;
1010        let resp: OrderResponse = serde_json::from_str(json).unwrap();
1011
1012        assert!(!resp.success);
1013        assert_eq!(resp.order_id.as_deref(), Some(""));
1014        assert_eq!(resp.status, Some(OrderResponseStatus::Unmatched));
1015        assert!(resp.making_amount.is_none());
1016        assert!(resp.taking_amount.is_none());
1017        assert!(resp.transaction_hashes.is_none());
1018        assert!(resp.trade_ids.is_none());
1019        assert_eq!(resp.error_msg.as_deref(), Some("placement failed"));
1020    }
1021
1022    #[rstest]
1023    fn test_order_response_matched_fields() {
1024        // Constructed documented shape; commit 031318184d only established that these fields
1025        // were ignored without breaking decoding
1026        let resp: OrderResponse = load("http_order_response_async_exec.json");
1027
1028        assert!(resp.success);
1029        assert_eq!(
1030            resp.order_id.as_deref(),
1031            Some("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12")
1032        );
1033        assert_eq!(resp.status, Some(OrderResponseStatus::Matched));
1034        assert_eq!(resp.making_amount, Some(dec!(100_000_000)));
1035        assert_eq!(resp.taking_amount, Some(dec!(200_000_000)));
1036        assert_eq!(
1037            resp.transaction_hashes.as_deref(),
1038            Some(
1039                &[
1040                    "0xaaaa000000000000000000000000000000000000000000000000000000000000"
1041                        .to_string(),
1042                    "0xbbbb000000000000000000000000000000000000000000000000000000000000"
1043                        .to_string(),
1044                ][..]
1045            )
1046        );
1047        assert_eq!(
1048            resp.trade_ids.as_deref(),
1049            Some(&["trade-0x001".to_string(), "trade-0x002".to_string()][..])
1050        );
1051        assert!(resp.error_msg.is_none());
1052    }
1053
1054    #[rstest]
1055    fn test_order_response_trade_ids_without_transaction_hashes() {
1056        // Constructed compatibility case for a matched response without transaction hashes
1057        let resp: OrderResponse = load("http_order_response_trade_ids_only.json");
1058
1059        assert!(resp.success);
1060        assert_eq!(
1061            resp.order_id.as_deref(),
1062            Some("0xfedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fe")
1063        );
1064        assert_eq!(resp.status, Some(OrderResponseStatus::Matched));
1065        assert_eq!(resp.making_amount, Some(dec!(25_000_000)));
1066        assert_eq!(resp.taking_amount, Some(dec!(50_000_000)));
1067        assert!(resp.transaction_hashes.is_none());
1068        assert_eq!(
1069            resp.trade_ids.as_deref(),
1070            Some(&["trade-0x101".to_string(), "trade-0x102".to_string()][..])
1071        );
1072        assert!(resp.error_msg.is_none());
1073    }
1074
1075    #[rstest]
1076    fn test_batch_order_response_legs() {
1077        // Sanitized mainnet capture from `POST /orders`
1078        let resps: Vec<OrderResponse> = load("http_batch_order_response.json");
1079
1080        assert_eq!(resps.len(), 2);
1081
1082        for (index, resp) in resps.iter().enumerate() {
1083            assert!(resp.success);
1084            assert_eq!(
1085                resp.order_id.as_deref(),
1086                Some(if index == 0 {
1087                    "0x1111111111111111111111111111111111111111111111111111111111111111"
1088                } else {
1089                    "0x2222222222222222222222222222222222222222222222222222222222222222"
1090                })
1091            );
1092            assert_eq!(resp.status, Some(OrderResponseStatus::Delayed));
1093            assert!(resp.making_amount.is_none());
1094            assert!(resp.taking_amount.is_none());
1095            assert!(resp.transaction_hashes.is_none());
1096            assert!(resp.trade_ids.is_none());
1097            assert_eq!(resp.error_msg.as_deref(), Some(""));
1098        }
1099    }
1100
1101    #[rstest]
1102    fn test_cancel_response_ok() {
1103        let resp: CancelResponse = load("http_cancel_response_ok.json");
1104
1105        assert_eq!(resp.canceled.len(), 1);
1106        assert!(resp.not_canceled.is_empty());
1107    }
1108
1109    #[rstest]
1110    fn test_cancel_response_failed() {
1111        let resp: CancelResponse = load("http_cancel_response_failed.json");
1112
1113        assert!(resp.canceled.is_empty());
1114        assert_eq!(resp.not_canceled.len(), 1);
1115        let reason = resp.not_canceled.values().next().and_then(|v| v.as_deref());
1116        assert_eq!(reason, Some("already canceled or matched"));
1117    }
1118
1119    #[rstest]
1120    fn test_batch_cancel_response() {
1121        let resp: BatchCancelResponse = load("http_batch_cancel_response.json");
1122
1123        assert_eq!(resp.canceled.len(), 2);
1124        assert!(resp.canceled[0].contains("1111"));
1125        assert!(resp.canceled[1].contains("2222"));
1126        assert_eq!(resp.not_canceled.len(), 1);
1127        let reason = resp.not_canceled.values().next().and_then(|v| v.as_deref());
1128        assert_eq!(reason, Some("already canceled or matched"));
1129    }
1130
1131    #[rstest]
1132    fn test_cancel_response_merge_preserves_canceled_and_not_canceled_results() {
1133        let mut merged = CancelResponse {
1134            canceled: vec!["order-1".to_string()],
1135            not_canceled: AHashMap::from_iter([(
1136                "order-2".to_string(),
1137                Some("already canceled".to_string()),
1138            )]),
1139        };
1140        merged.merge(CancelResponse {
1141            canceled: vec!["order-3".to_string()],
1142            not_canceled: AHashMap::from_iter([(
1143                "order-4".to_string(),
1144                Some("order not found".to_string()),
1145            )]),
1146        });
1147
1148        assert_eq!(
1149            merged.canceled,
1150            vec!["order-1".to_string(), "order-3".to_string()]
1151        );
1152        assert_eq!(
1153            merged.not_canceled,
1154            AHashMap::from_iter([
1155                ("order-2".to_string(), Some("already canceled".to_string())),
1156                ("order-4".to_string(), Some("order not found".to_string())),
1157            ])
1158        );
1159    }
1160
1161    #[rstest]
1162    fn test_asset_type_serializes_screaming_snake() {
1163        assert_eq!(
1164            serde_json::to_string(&AssetType::Collateral).unwrap(),
1165            "\"COLLATERAL\""
1166        );
1167        assert_eq!(
1168            serde_json::to_string(&AssetType::Conditional).unwrap(),
1169            "\"CONDITIONAL\""
1170        );
1171        assert_eq!(
1172            serde_json::to_string(&AssetType::ConditionalV2).unwrap(),
1173            "\"CONDITIONAL-V2\""
1174        );
1175    }
1176
1177    #[rstest]
1178    fn test_asset_type_deserializes() {
1179        assert_eq!(
1180            serde_json::from_str::<AssetType>("\"COLLATERAL\"").unwrap(),
1181            AssetType::Collateral
1182        );
1183        assert_eq!(
1184            serde_json::from_str::<AssetType>("\"CONDITIONAL\"").unwrap(),
1185            AssetType::Conditional
1186        );
1187        assert_eq!(
1188            serde_json::from_str::<AssetType>("\"CONDITIONAL-V2\"").unwrap(),
1189            AssetType::ConditionalV2
1190        );
1191        assert!(serde_json::from_str::<AssetType>("\"CONDITIONAL_V2\"").is_err());
1192    }
1193
1194    #[rstest]
1195    fn test_get_orders_params_skips_none() {
1196        let params = GetOrdersParams::default();
1197        let json = serde_json::to_string(&params).unwrap();
1198        assert_eq!(json, "{}");
1199    }
1200
1201    #[rstest]
1202    fn test_get_orders_params_serializes_set_fields() {
1203        let params = GetOrdersParams {
1204            market: Some("0xmarket".to_string()),
1205            asset_id: None,
1206            next_cursor: Some("MA==".to_string()),
1207            ..Default::default()
1208        };
1209        let json = serde_json::to_string(&params).unwrap();
1210        assert!(json.contains("\"market\""));
1211        assert!(json.contains("\"next_cursor\""));
1212        assert!(!json.contains("\"asset_id\""));
1213    }
1214
1215    #[rstest]
1216    fn test_get_orders_params_id_filter() {
1217        let params = GetOrdersParams {
1218            id: Some("0xorder123".to_string()),
1219            ..Default::default()
1220        };
1221        let json = serde_json::to_string(&params).unwrap();
1222        assert!(json.contains("\"id\""));
1223        assert!(json.contains("0xorder123"));
1224    }
1225
1226    #[rstest]
1227    fn test_get_gamma_markets_params_slug() {
1228        let params = GetGammaMarketsParams {
1229            slug: Some(vec!["btc-updown-15m-1741500000".to_string()]),
1230            ..Default::default()
1231        };
1232        let json = serde_json::to_string(&params).unwrap();
1233        assert!(json.contains("\"slug\""));
1234        assert!(json.contains("btc-updown-15m-1741500000"));
1235        assert!(!json.contains("\"active\""));
1236    }
1237
1238    #[rstest]
1239    fn test_get_gamma_markets_params_skips_none_slug() {
1240        let params = GetGammaMarketsParams {
1241            active: Some(true),
1242            ..Default::default()
1243        };
1244        let json = serde_json::to_string(&params).unwrap();
1245        assert!(!json.contains("\"slug\""));
1246        assert!(json.contains("\"active\""));
1247    }
1248
1249    #[rstest]
1250    fn test_get_gamma_markets_params_new_filter_fields() {
1251        let params = GetGammaMarketsParams {
1252            volume_num_min: Some(dec!(1000.0)),
1253            tag_id: Some(vec![123]),
1254            end_date_min: Some("2025-06-01T00:00:00Z".to_string()),
1255            ..Default::default()
1256        };
1257        let json = serde_json::to_string(&params).unwrap();
1258        assert!(json.contains("\"volume_num_min\":\"1000.0\""));
1259        assert!(json.contains("\"tag_id\":[123]"));
1260        assert!(json.contains("\"end_date_min\":\"2025-06-01T00:00:00Z\""));
1261        assert!(!json.contains("\"active\""));
1262        assert!(!json.contains("\"archived\""));
1263    }
1264
1265    #[rstest]
1266    fn test_get_gamma_markets_params_condition_ids() {
1267        let params = GetGammaMarketsParams {
1268            condition_ids: Some(vec!["0xcond1".to_string(), "0xcond2".to_string()]),
1269            liquidity_num_min: Some(dec!(500.0)),
1270            ..Default::default()
1271        };
1272        let json = serde_json::to_string(&params).unwrap();
1273        assert!(json.contains("\"condition_ids\":[\"0xcond1\",\"0xcond2\"]"));
1274        assert!(json.contains("\"liquidity_num_min\":\"500.0\""));
1275    }
1276
1277    #[rstest]
1278    fn test_get_trades_params_skips_none() {
1279        let params = GetTradesParams::default();
1280        let json = serde_json::to_string(&params).unwrap();
1281        assert_eq!(json, "{}");
1282    }
1283
1284    #[rstest]
1285    fn test_post_order_params_skips_post_only_when_false() {
1286        let params = PostOrderParams {
1287            order_type: PolymarketOrderType::GTC,
1288            post_only: false,
1289        };
1290        let json = serde_json::to_string(&params).unwrap();
1291        assert!(!json.contains("post_only"));
1292        assert!(!json.contains("postOnly"));
1293    }
1294
1295    #[rstest]
1296    fn test_post_order_params_includes_post_only_when_true() {
1297        let params = PostOrderParams {
1298            order_type: PolymarketOrderType::GTC,
1299            post_only: true,
1300        };
1301        let json = serde_json::to_string(&params).unwrap();
1302        assert!(json.contains("postOnly"));
1303    }
1304}