Skip to main content

nautilus_polymarket/
config.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//! Configuration structures for the Polymarket adapter.
17
18use std::{
19    collections::HashMap,
20    fmt::Debug,
21    sync::Arc,
22    time::{Duration, SystemTime, UNIX_EPOCH},
23};
24
25use ahash::AHashSet;
26use nautilus_common::config::{ConfigError, ConfigResult, check_range, check_unique_values};
27use nautilus_core::{datetime::SECONDS_IN_MINUTE, string::secret::SecretString};
28use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
29use nautilus_model::identifiers::{AccountId, InstrumentId};
30use nautilus_network::{
31    transport::TransportError,
32    websocket::{TransportBackend, proxy::ProxyUrl},
33};
34use serde::{Deserialize, Serialize};
35
36use crate::{
37    common::{
38        credential::{Credential, credential_env_vars, validate_env_override},
39        enums::{PolymarketSignatureType, PolymarketSignerType},
40        retry::AUTO_LOAD_RETRY_JITTER_FRACTION,
41        urls,
42    },
43    filters::InstrumentFilter,
44    providers::{build_gamma_params_from_hashmap, validated_condition_id},
45};
46
47const DEFAULT_UPDOWN_INTERVAL_MINS: u64 = 5;
48const DEFAULT_UPDOWN_PERIODS: u64 = 3;
49
50fn validated_proxy_url(value: Option<&SecretString>) -> Result<Option<ProxyUrl>, TransportError> {
51    value
52        .map(|value| ProxyUrl::parse(value.expose_secret().to_owned()))
53        .transpose()
54}
55
56fn default_updown_assets() -> Vec<String> {
57    vec!["btc".to_string()]
58}
59
60/// Rust-backed event slug builder for Polymarket Up/Down markets.
61///
62/// Up/Down event slugs follow the pattern
63/// `{asset}-updown-{interval_mins}m-{unix_timestamp}`, where the timestamp is
64/// aligned to the start of the interval. The builder emits slugs for each
65/// configured asset and period.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
67#[serde(default, deny_unknown_fields)]
68#[cfg_attr(
69    feature = "python",
70    pyo3::pyclass(module = "nautilus_trader.adapters.polymarket", from_py_object)
71)]
72#[cfg_attr(
73    feature = "python",
74    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.polymarket")
75)]
76pub struct PolymarketUpDownEventSlugConfig {
77    /// Asset codes used in the slug prefix.
78    #[builder(default = default_updown_assets())]
79    pub assets: Vec<String>,
80    /// Up/Down interval in minutes.
81    #[builder(default = DEFAULT_UPDOWN_INTERVAL_MINS)]
82    pub interval_mins: u64,
83    /// Number of periods to generate.
84    #[builder(default = DEFAULT_UPDOWN_PERIODS)]
85    pub periods: u64,
86    /// Offset from the current aligned period.
87    #[builder(default)]
88    pub start_offset_periods: i64,
89}
90
91#[cfg(feature = "python")]
92nautilus_core::impl_pyo3_config_getters!(PolymarketUpDownEventSlugConfig {
93    assets: Vec<String>,
94    interval_mins: u64,
95    periods: u64,
96    start_offset_periods: i64,
97});
98
99impl Default for PolymarketUpDownEventSlugConfig {
100    fn default() -> Self {
101        Self::builder().build()
102    }
103}
104
105impl PolymarketUpDownEventSlugConfig {
106    /// Validates assets, interval, and period count.
107    ///
108    /// Exact duplicates include blank entries. Nonblank assets must also be distinct after
109    /// trimming and lowercasing. At least one nonblank asset is required.
110    ///
111    /// # Errors
112    ///
113    /// Returns an error if assets are empty or repeated, the interval or period count is zero,
114    /// or the interval overflows seconds.
115    pub fn validate(&self) -> ConfigResult<()> {
116        self.validated_assets().map(|_| ())
117    }
118
119    /// Builds event slugs using the current system time.
120    ///
121    /// # Errors
122    ///
123    /// Returns an error if configuration validation fails, the system clock precedes the Unix
124    /// epoch, or an offset resolves before the Unix epoch.
125    pub fn build_event_slugs(&self) -> anyhow::Result<Vec<String>> {
126        let now = SystemTime::now()
127            .duration_since(UNIX_EPOCH)
128            .map_err(|e| anyhow::anyhow!("system clock before Unix epoch: {e}"))?
129            .as_secs();
130        self.build_event_slugs_at_unix_secs(now)
131    }
132
133    fn build_event_slugs_at_unix_secs(&self, unix_secs: u64) -> anyhow::Result<Vec<String>> {
134        let assets = self.validated_assets()?;
135        let period_secs = self.interval_mins * SECONDS_IN_MINUTE;
136        let period_start = (unix_secs / period_secs) * period_secs;
137        let period_secs = i128::from(period_secs);
138        let period_start = i128::from(period_start);
139        let mut slugs = Vec::new();
140
141        for period in 0..self.periods {
142            let period_offset = i128::from(self.start_offset_periods) + i128::from(period);
143            let timestamp = period_start + period_offset * period_secs;
144            if timestamp < 0 {
145                anyhow::bail!("event_slug_builder offset resolves before the Unix epoch");
146            }
147
148            for asset in &assets {
149                slugs.push(format!(
150                    "{asset}-updown-{}m-{timestamp}",
151                    self.interval_mins
152                ));
153            }
154        }
155
156        Ok(slugs)
157    }
158
159    fn validated_assets(&self) -> ConfigResult<Vec<String>> {
160        check_range(
161            "event_slug_builder.interval_mins",
162            self.interval_mins > 0 && self.interval_mins <= u64::MAX / SECONDS_IN_MINUTE,
163            "must be positive and fit in seconds",
164        )?;
165        check_range(
166            "event_slug_builder.periods",
167            self.periods > 0,
168            "must be positive",
169        )?;
170
171        check_unique_values("event_slug_builder.assets", &self.assets)?;
172        let mut assets = Vec::new();
173
174        for asset in &self.assets {
175            let asset = asset.trim().to_ascii_lowercase();
176            if asset.is_empty() {
177                continue;
178            }
179            assets.push(asset);
180        }
181
182        check_unique_values("event_slug_builder.assets", &assets)?;
183        if assets.is_empty() {
184            return Err(ConfigError::empty_field("event_slug_builder.assets"));
185        }
186
187        Ok(assets)
188    }
189}
190
191/// Configuration for the Polymarket instrument provider.
192///
193/// This mirrors the Python adapter's `instrument_config` layering so scoped
194/// market bootstrap can migrate naturally to the Rust/pyO3 live path.
195#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
196#[serde(default, deny_unknown_fields)]
197#[cfg_attr(
198    feature = "python",
199    pyo3::pyclass(module = "nautilus_trader.adapters.polymarket", from_py_object)
200)]
201#[cfg_attr(
202    feature = "python",
203    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.polymarket")
204)]
205pub struct PolymarketInstrumentProviderConfig {
206    /// Whether all venue instruments should be loaded on startup.
207    #[builder(default)]
208    pub load_all: bool,
209    /// Optional instrument IDs to load on startup instead of a full bootstrap.
210    pub load_ids: Option<Vec<InstrumentId>>,
211    /// Optional Gamma-style query filters encoded as string key/value pairs.
212    pub filters: Option<HashMap<String, String>>,
213    /// Optional static event slugs to resolve to markets during bootstrap.
214    pub event_slugs: Option<Vec<String>>,
215    /// Optional static market slugs to load directly during bootstrap.
216    pub market_slugs: Option<Vec<String>>,
217    /// Optional Rust-backed Up/Down event slug builder.
218    pub event_slug_builder: Option<PolymarketUpDownEventSlugConfig>,
219    /// Optional Gamma series IDs whose active events resolve to markets during bootstrap.
220    pub series_ids: Option<Vec<u64>>,
221    /// Whether provider warnings should be logged.
222    #[builder(default = true)]
223    pub log_warnings: bool,
224    /// Compatibility field matching the Python adapter. The Rust provider
225    /// already uses the Gamma API for bootstrap, so this currently has no
226    /// behavioral effect beyond configuration parity.
227    #[builder(default)]
228    pub use_gamma_markets: bool,
229}
230
231#[cfg(feature = "python")]
232nautilus_core::impl_pyo3_config_getters!(PolymarketInstrumentProviderConfig {
233    load_all: bool,
234    load_ids: Option<Vec<InstrumentId>>,
235    filters: Option<HashMap<String, String>>,
236    event_slugs: Option<Vec<String>>,
237    market_slugs: Option<Vec<String>>,
238    event_slug_builder: Option<PolymarketUpDownEventSlugConfig>,
239    series_ids: Option<Vec<u64>>,
240    log_warnings: bool,
241    use_gamma_markets: bool,
242});
243
244impl Default for PolymarketInstrumentProviderConfig {
245    fn default() -> Self {
246        Self::builder().build()
247    }
248}
249
250impl PolymarketInstrumentProviderConfig {
251    #[must_use]
252    pub fn new() -> Self {
253        Self::default()
254    }
255
256    /// Validates instrument IDs, selections, and Gamma filters.
257    ///
258    /// # Errors
259    ///
260    /// Returns an error if instrument IDs are invalid, selections contain duplicates, or Gamma
261    /// filters are invalid.
262    pub fn validate(&self) -> anyhow::Result<()> {
263        if let Some(values) = &self.load_ids {
264            check_unique_values("load_ids", values)?;
265            for instrument_id in values {
266                validated_condition_id(instrument_id)?;
267            }
268        }
269
270        if let Some(values) = &self.event_slugs {
271            check_unique_values("event_slugs", values)?;
272        }
273
274        if let Some(values) = &self.market_slugs {
275            check_unique_values("market_slugs", values)?;
276        }
277
278        if let Some(values) = &self.series_ids {
279            check_unique_values("series_ids", values)?;
280        }
281
282        if let Some(builder) = &self.event_slug_builder {
283            builder.validate()?;
284        }
285
286        if let Some(filters) = &self.filters {
287            let params = build_gamma_params_from_hashmap(filters)?;
288            check_unique_values("filters.id", params.id.as_deref().unwrap_or_default())?;
289            check_unique_values(
290                "filters.tag_id",
291                params.tag_id.as_deref().unwrap_or_default(),
292            )?;
293
294            for (field, values) in [
295                ("filters.slug", params.slug.as_deref()),
296                ("filters.condition_ids", params.condition_ids.as_deref()),
297                ("filters.clob_token_ids", params.clob_token_ids.as_deref()),
298                ("filters.question_ids", params.question_ids.as_deref()),
299                (
300                    "filters.market_maker_address",
301                    params.market_maker_address.as_deref(),
302                ),
303                (
304                    "filters.sports_market_types",
305                    params.sports_market_types.as_deref(),
306                ),
307            ] {
308                check_unique_values(field, values.unwrap_or_default())?;
309            }
310        }
311
312        Ok(())
313    }
314
315    /// Returns whether any configured scope drives a bootstrap load.
316    #[must_use]
317    pub fn should_load_all(&self) -> bool {
318        self.load_all || self.has_explicit_scope() || self.has_nonempty_filters()
319    }
320
321    /// Returns whether any explicit bootstrap scope (slug, builder, or series) is configured.
322    #[must_use]
323    pub fn has_explicit_scope(&self) -> bool {
324        self.event_slug_builder.is_some()
325            || self.event_slugs.as_ref().is_some_and(|s| !s.is_empty())
326            || self.market_slugs.as_ref().is_some_and(|s| !s.is_empty())
327            || self.has_series_ids()
328    }
329
330    #[must_use]
331    pub fn has_series_ids(&self) -> bool {
332        self.series_ids.as_ref().is_some_and(|ids| !ids.is_empty())
333    }
334
335    #[must_use]
336    pub fn has_nonempty_filters(&self) -> bool {
337        self.filters.as_ref().is_some_and(|map| !map.is_empty())
338    }
339
340    #[must_use]
341    pub fn has_load_ids(&self) -> bool {
342        self.load_ids.as_ref().is_some_and(|ids| !ids.is_empty())
343    }
344
345    pub(crate) fn resolve_event_slugs(&self) -> anyhow::Result<Vec<String>> {
346        let mut slugs = self.event_slugs.clone().unwrap_or_default();
347        if let Some(builder) = &self.event_slug_builder {
348            slugs.extend(builder.build_event_slugs()?);
349        }
350
351        let mut seen = AHashSet::new();
352        slugs.retain(|slug| !slug.trim().is_empty() && seen.insert(slug.clone()));
353        Ok(slugs)
354    }
355}
356
357/// Configuration for the Polymarket data client.
358///
359/// `filters` and `new_market_filter` hold `Arc<dyn InstrumentFilter>` trait objects
360/// and are skipped during serialization; they default to empty/`None` and must be
361/// installed programmatically after deserialization.
362#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
363#[serde(default, deny_unknown_fields)]
364#[cfg_attr(
365    feature = "python",
366    pyo3::pyclass(module = "nautilus_trader.adapters.polymarket", from_py_object)
367)]
368#[cfg_attr(
369    feature = "python",
370    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.polymarket")
371)]
372pub struct PolymarketDataClientConfig {
373    pub instrument_config: Option<PolymarketInstrumentProviderConfig>,
374    /// Instrument filters applied to all instruments during loading and discovery.
375    #[builder(default)]
376    #[serde(skip)]
377    pub filters: Vec<Arc<dyn InstrumentFilter>>,
378    pub base_url_http: Option<String>,
379    pub base_url_ws: Option<String>,
380    pub base_url_reference_prices: Option<String>,
381    pub base_url_gamma: Option<String>,
382    /// CLOB API key for PolyBolt reference-price channels; falls back to `POLYMARKET_API_KEY`.
383    pub api_key: Option<SecretString>,
384    /// CLOB API secret for PolyBolt reference-price channels; falls back to
385    /// `POLYMARKET_API_SECRET`.
386    pub api_secret: Option<SecretString>,
387    /// CLOB API passphrase for PolyBolt reference-price channels; falls back to
388    /// `POLYMARKET_PASSPHRASE`.
389    pub passphrase: Option<SecretString>,
390    pub base_url_data_api: Option<String>,
391    /// Optional HTTP or HTTPS proxy URL for all HTTP and WebSocket transports.
392    pub proxy_url: Option<SecretString>,
393    /// HTTP timeout in seconds.
394    #[builder(default = 60)]
395    pub http_timeout_secs: u64,
396    /// Timeout in seconds per market and reference-price WebSocket connection attempt,
397    /// including reconnects, and for sends waiting for reconnection. Must be positive;
398    /// keep it above the 5-second maximum reconnect backoff.
399    #[builder(default = 30)]
400    pub ws_timeout_secs: u64,
401    #[builder(default = crate::common::consts::WS_DEFAULT_SUBSCRIPTIONS)]
402    pub ws_max_subscriptions: usize,
403    /// Instrument reload interval in minutes; `None` disables refresh.
404    #[builder(required, default = Some(60), into)]
405    pub update_instruments_interval_mins: Option<u64>,
406    /// Whether to subscribe to new-market discovery, resolution, and best-bid/ask events.
407    #[builder(default)]
408    pub subscribe_new_markets: bool,
409    /// Optional filter applied to newly discovered markets before instrument emission.
410    #[serde(skip)]
411    pub new_market_filter: Option<Arc<dyn InstrumentFilter>>,
412    /// Maximum concurrent instrument fetches spawned from `new_market` events.
413    ///
414    /// This bounds adapter-side fan-out during event bursts and prevents
415    /// request storms against Gamma.
416    #[builder(default = 8)]
417    pub new_market_fetch_max_concurrency: usize,
418    /// Whether to drop quote ticks when bid or ask prices are missing.
419    #[builder(default = true)]
420    pub drop_quotes_missing_side: bool,
421    /// Whether to emit only the net changes from book snapshots against the local
422    /// book, at an additional CPU and memory cost.
423    #[builder(default)]
424    pub compute_effective_deltas: bool,
425    /// Whether subscribe and request commands referencing an unknown instrument should
426    /// trigger an ad-hoc load via the instrument provider. Concurrent misses within
427    /// `auto_load_debounce_ms` are coalesced into a single batched request.
428    #[builder(default = true)]
429    pub auto_load_missing_instruments: bool,
430    /// The window (milliseconds) over which concurrent auto-load requests are batched.
431    #[builder(default = 100)]
432    pub auto_load_debounce_ms: u64,
433    /// Maximum retry attempts on transient auto-load failures (markets in the CLOB
434    /// hydration window that return empty protocol-selected outcome IDs from Gamma,
435    /// or that are absent from the bulk response). Set to `0` to disable retry.
436    #[builder(default = 12)]
437    pub auto_load_max_retries: u32,
438    /// Initial delay (seconds) between transient auto-load retries; backed off
439    /// exponentially with positive jitter up to `auto_load_retry_delay_max_secs`.
440    #[builder(default = 5.0)]
441    pub auto_load_retry_delay_initial_secs: f64,
442    /// Maximum delay (seconds) between transient auto-load retries.
443    #[builder(default = 15.0)]
444    pub auto_load_retry_delay_max_secs: f64,
445    /// Whether automatic resolve polling is enabled.
446    #[builder(default = true)]
447    pub resolve_poll_enabled: bool,
448    /// Fixed interval between resolve poll cycles in seconds.
449    #[builder(default = 30)]
450    pub resolve_poll_interval_secs: u64,
451    /// Grace period after expiration before a market becomes resolve poll eligible.
452    #[builder(default = 10)]
453    pub resolve_poll_grace_secs: u64,
454    /// Maximum number of seconds to keep auto-polling after expiration before pausing.
455    #[builder(default = 1800)]
456    pub resolve_poll_max_wait_secs: u64,
457    /// WebSocket transport backend (defaults to `Sockudo`).
458    #[builder(default)]
459    pub transport_backend: TransportBackend,
460    /// Maximum wait for an initial, post-reconnect, or recovery book snapshot, in seconds.
461    ///
462    /// Set to 0 to disable initial and reconnect monitors, and per-attempt snapshot deadlines
463    /// within the retry budget. Updates without a baseline can still request recovery.
464    /// During recovery, book output stays gated until a valid snapshot arrives.
465    /// Retry-budget and retry-ceiling limits still apply.
466    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
467    pub book_snapshot_timeout_secs: u64,
468    /// Interval for checking order book feed staleness in seconds.
469    #[builder(default = 5)]
470    pub book_stale_check_interval_secs: u64,
471    /// Maximum time without order book updates before emitting a stale signal in seconds.
472    ///
473    /// Set to 0 to disable. Prediction markets go quiet for long stretches.
474    #[builder(default)]
475    pub book_stale_threshold_secs: u64,
476}
477
478#[cfg(feature = "python")]
479nautilus_core::impl_pyo3_config_getters!(PolymarketDataClientConfig {
480    instrument_config: Option<PolymarketInstrumentProviderConfig>,
481    base_url_http: Option<String>,
482    base_url_ws: Option<String>,
483    base_url_gamma: Option<String>,
484    base_url_data_api: Option<String>,
485    http_timeout_secs: u64,
486    ws_timeout_secs: u64,
487    ws_max_subscriptions: usize,
488    update_instruments_interval_mins: Option<u64>,
489    subscribe_new_markets: bool,
490    auto_load_missing_instruments: bool,
491    auto_load_debounce_ms: u64,
492    auto_load_max_retries: u32,
493    auto_load_retry_delay_initial_secs: f64,
494    auto_load_retry_delay_max_secs: f64,
495    new_market_fetch_max_concurrency: usize,
496    resolve_poll_enabled: bool,
497    resolve_poll_interval_secs: u64,
498    resolve_poll_grace_secs: u64,
499    resolve_poll_max_wait_secs: u64,
500    base_url_reference_prices: Option<String>,
501    transport_backend: TransportBackend,
502    drop_quotes_missing_side: bool,
503    compute_effective_deltas: bool,
504    book_snapshot_timeout_secs: u64,
505    book_stale_check_interval_secs: u64,
506    book_stale_threshold_secs: u64,
507});
508
509impl Default for PolymarketDataClientConfig {
510    fn default() -> Self {
511        Self::builder().build()
512    }
513}
514
515impl PolymarketDataClientConfig {
516    #[must_use]
517    pub fn new() -> Self {
518        Self::default()
519    }
520
521    /// Validates credential overrides, the WebSocket timeout, retry delays, and instrument selections.
522    ///
523    /// # Errors
524    ///
525    /// Returns an error if credential overrides are blank, retry delays are invalid, the WebSocket
526    /// timeout is zero, or nested instrument configuration is invalid.
527    pub fn validate(&self) -> anyhow::Result<()> {
528        validate_clob_overrides(&self.api_key, &self.api_secret, &self.passphrase)?;
529        check_range(
530            "ws_timeout_secs",
531            self.ws_timeout_secs > 0,
532            "must be positive",
533        )?;
534
535        for (field, seconds) in [
536            (
537                "auto_load_retry_delay_initial_secs",
538                self.auto_load_retry_delay_initial_secs,
539            ),
540            (
541                "auto_load_retry_delay_max_secs",
542                self.auto_load_retry_delay_max_secs,
543            ),
544        ] {
545            check_range(
546                field,
547                seconds.is_finite()
548                    && seconds >= 0.0
549                    && Duration::try_from_secs_f64(
550                        seconds + seconds * AUTO_LOAD_RETRY_JITTER_FRACTION,
551                    )
552                    .is_ok(),
553                "must be finite, nonnegative, and fit in a duration including 25% jitter",
554            )?;
555        }
556
557        check_range(
558            "auto_load_retry_delay_max_secs",
559            self.auto_load_retry_delay_max_secs >= self.auto_load_retry_delay_initial_secs,
560            "must be at least auto_load_retry_delay_initial_secs",
561        )?;
562
563        if let Some(config) = &self.instrument_config {
564            config.validate()?;
565        }
566
567        Ok(())
568    }
569
570    /// Returns the validated proxy URL, if configured.
571    ///
572    /// # Errors
573    ///
574    /// Returns an error if the URL is malformed, has no host, or does not use HTTP or HTTPS.
575    pub fn validated_proxy_url(&self) -> Result<Option<ProxyUrl>, TransportError> {
576        validated_proxy_url(self.proxy_url.as_ref())
577    }
578
579    #[must_use]
580    pub const fn has_proxy_url(&self) -> bool {
581        self.proxy_url.is_some()
582    }
583
584    #[must_use]
585    pub fn http_url(&self) -> String {
586        self.base_url_http
587            .clone()
588            .unwrap_or_else(|| urls::clob_http_url().to_string())
589    }
590
591    #[must_use]
592    pub fn ws_url(&self) -> String {
593        self.base_url_ws
594            .clone()
595            .unwrap_or_else(|| urls::clob_ws_url().to_string())
596    }
597
598    #[must_use]
599    pub fn reference_prices_url(&self) -> String {
600        self.base_url_reference_prices
601            .clone()
602            .unwrap_or_else(|| urls::polybolt_ws_url().to_string())
603    }
604
605    /// Resolves the CLOB API credential used for PolyBolt reference-price channels.
606    ///
607    /// Explicit `api_key`, `api_secret`, or `passphrase` fields are validated strictly.
608    /// Otherwise the `POLYMARKET_*` environment variables are used only when all three are
609    /// set and non-empty; a partial set is ignored with a warning so a data client that never
610    /// subscribes to reference prices still starts. Returns `None` when no credential applies.
611    ///
612    /// # Errors
613    ///
614    /// Returns an error if an explicitly configured credential is incomplete or malformed,
615    /// or if a complete environment credential is malformed.
616    pub fn polybolt_credential(&self) -> anyhow::Result<Option<Credential>> {
617        validate_clob_overrides(&self.api_key, &self.api_secret, &self.passphrase)?;
618        let explicit =
619            self.api_key.is_some() || self.api_secret.is_some() || self.passphrase.is_some();
620
621        if !explicit {
622            let (api_key_var, api_secret_var, passphrase_var, _, _) = credential_env_vars();
623            let present: Vec<&str> = [api_key_var, api_secret_var, passphrase_var]
624                .into_iter()
625                .filter(|var| std::env::var(var).is_ok_and(|value| !value.trim().is_empty()))
626                .collect();
627
628            if present.is_empty() {
629                return Ok(None);
630            }
631
632            if present.len() < 3 {
633                log::warn!(
634                    "Ignoring partial Polymarket CLOB credentials in the environment \
635                     (set: {present:?}); PolyBolt price subscriptions will be rejected"
636                );
637                return Ok(None);
638            }
639        }
640
641        Credential::resolve(
642            self.api_key.clone(),
643            self.api_secret.clone(),
644            self.passphrase.clone(),
645        )
646        .map(Some)
647        .map_err(|e| anyhow::anyhow!("Invalid Polymarket CLOB credentials for PolyBolt: {e}"))
648    }
649
650    #[must_use]
651    pub fn gamma_url(&self) -> String {
652        self.base_url_gamma
653            .clone()
654            .unwrap_or_else(|| urls::gamma_api_url().to_string())
655    }
656
657    #[must_use]
658    pub fn data_api_url(&self) -> String {
659        self.base_url_data_api
660            .clone()
661            .unwrap_or_else(|| urls::data_api_url().to_string())
662    }
663}
664
665/// Configuration for the Polymarket execution client.
666#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
667#[serde(default, deny_unknown_fields)]
668#[cfg_attr(
669    feature = "python",
670    pyo3::pyclass(module = "nautilus_trader.adapters.polymarket", from_py_object)
671)]
672#[cfg_attr(
673    feature = "python",
674    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.polymarket")
675)]
676pub struct PolymarketExecutionClientConfig {
677    #[builder(default = AccountId::from("POLYMARKET-001"))]
678    pub account_id: AccountId,
679    /// Falls back to `POLYMARKET_PK` env var.
680    pub private_key: Option<SecretString>,
681    /// Falls back to `POLYMARKET_API_KEY` env var.
682    pub api_key: Option<SecretString>,
683    /// Falls back to `POLYMARKET_API_SECRET` env var.
684    pub api_secret: Option<SecretString>,
685    /// Falls back to `POLYMARKET_PASSPHRASE` env var.
686    pub passphrase: Option<SecretString>,
687    /// Falls back to `POLYMARKET_FUNDER` env var.
688    pub funder: Option<String>,
689    #[builder(default = PolymarketSignatureType::Eoa)]
690    pub signature_type: PolymarketSignatureType,
691    /// Selects owner or delegated session signing.
692    #[builder(default)]
693    pub signer_type: PolymarketSignerType,
694    pub base_url_http: Option<String>,
695    pub base_url_ws: Option<String>,
696    pub base_url_data_api: Option<String>,
697    /// Optional HTTP or HTTPS proxy URL for all HTTP and WebSocket transports.
698    pub proxy_url: Option<SecretString>,
699    #[builder(default = 60)]
700    pub http_timeout_secs: u64,
701    #[builder(default = 3)]
702    pub max_retries: u32,
703    #[builder(default = 1000)]
704    pub retry_delay_initial_ms: u64,
705    #[builder(default = 10000)]
706    pub retry_delay_max_ms: u64,
707    /// Enables authenticated order-safety heartbeats.
708    #[builder(default)]
709    pub heartbeat_enabled: bool,
710    /// WebSocket transport backend (defaults to `Sockudo`).
711    #[builder(default)]
712    pub transport_backend: TransportBackend,
713    /// Same instrument provider configuration used by the data client.
714    ///
715    /// Reconciliation classifies unmapped records from `load_ids` on this
716    /// config. When that set is non-empty, venue records for other instruments
717    /// are out of scope. When this field is unset, or `load_ids` is unset or
718    /// empty, every record is in scope.
719    pub instrument_config: Option<PolymarketInstrumentProviderConfig>,
720}
721
722#[cfg(feature = "python")]
723nautilus_core::impl_pyo3_config_getters!(PolymarketExecutionClientConfig {
724    account_id: AccountId,
725    funder: Option<String>,
726    signature_type: PolymarketSignatureType,
727    signer_type: PolymarketSignerType,
728    base_url_http: Option<String>,
729    base_url_ws: Option<String>,
730    base_url_data_api: Option<String>,
731    http_timeout_secs: u64,
732    max_retries: u32,
733    retry_delay_initial_ms: u64,
734    retry_delay_max_ms: u64,
735    heartbeat_enabled: bool,
736    transport_backend: TransportBackend,
737    instrument_config: Option<PolymarketInstrumentProviderConfig>,
738});
739
740impl Default for PolymarketExecutionClientConfig {
741    fn default() -> Self {
742        Self::builder().build()
743    }
744}
745
746impl PolymarketExecutionClientConfig {
747    #[must_use]
748    pub fn new() -> Self {
749        Self::default()
750    }
751
752    /// Validates credential overrides and instrument selections.
753    ///
754    /// # Errors
755    ///
756    /// Returns an error if credential overrides are blank or nested instrument configuration
757    /// is invalid.
758    pub fn validate(&self) -> anyhow::Result<()> {
759        let (_, _, _, private_key_var, funder_var) = credential_env_vars();
760        validate_clob_overrides(&self.api_key, &self.api_secret, &self.passphrase)?;
761        validate_env_override(
762            self.private_key.as_ref().map(SecretString::expose_secret),
763            "private_key",
764            private_key_var,
765        )?;
766        validate_env_override(self.funder.as_deref(), "funder", funder_var)?;
767
768        if let Some(config) = &self.instrument_config {
769            config.validate()?;
770        }
771
772        Ok(())
773    }
774
775    pub(crate) fn validate_signer(&self) -> anyhow::Result<()> {
776        if self.signer_type == PolymarketSignerType::Session {
777            anyhow::ensure!(
778                self.signature_type == PolymarketSignatureType::Poly1271,
779                "Session signers require POLY_1271"
780            );
781
782            for (name, value) in [
783                ("private_key", self.private_key.as_ref()),
784                ("api_key", self.api_key.as_ref()),
785                ("api_secret", self.api_secret.as_ref()),
786                ("passphrase", self.passphrase.as_ref()),
787            ] {
788                anyhow::ensure!(
789                    value.is_some_and(|value| !value.expose_secret().trim().is_empty()),
790                    "Session signers require explicit {name}; environment fallback is disabled"
791                );
792            }
793
794            anyhow::ensure!(
795                self.funder
796                    .as_ref()
797                    .is_some_and(|value| !value.trim().is_empty()),
798                "Session signers require an explicit Deposit Wallet funder"
799            );
800        }
801
802        Ok(())
803    }
804
805    /// Returns the validated proxy URL, if configured.
806    ///
807    /// # Errors
808    ///
809    /// Returns an error if the URL is malformed, has no host, or does not use HTTP or HTTPS.
810    pub fn validated_proxy_url(&self) -> Result<Option<ProxyUrl>, TransportError> {
811        validated_proxy_url(self.proxy_url.as_ref())
812    }
813
814    #[must_use]
815    pub const fn has_proxy_url(&self) -> bool {
816        self.proxy_url.is_some()
817    }
818
819    #[must_use]
820    pub fn has_credentials(&self) -> bool {
821        self.private_key
822            .as_ref()
823            .map(SecretString::expose_secret)
824            .is_some_and(|s| !s.trim().is_empty())
825            || self
826                .api_key
827                .as_ref()
828                .map(SecretString::expose_secret)
829                .is_some_and(|s| !s.trim().is_empty())
830    }
831
832    /// Returns provider `load_ids` used to classify unmapped reconciliation records.
833    #[must_use]
834    pub fn reconciliation_load_ids(&self) -> Option<&[InstrumentId]> {
835        self.instrument_config
836            .as_ref()
837            .and_then(|config| config.load_ids.as_deref())
838    }
839
840    #[must_use]
841    pub fn http_url(&self) -> String {
842        self.base_url_http
843            .clone()
844            .unwrap_or_else(|| urls::clob_http_url().to_string())
845    }
846
847    #[must_use]
848    pub fn ws_url(&self) -> String {
849        self.base_url_ws
850            .clone()
851            .unwrap_or_else(|| urls::clob_ws_url().to_string())
852    }
853
854    #[must_use]
855    pub fn data_api_url(&self) -> String {
856        self.base_url_data_api
857            .clone()
858            .unwrap_or_else(|| urls::data_api_url().to_string())
859    }
860}
861
862fn validate_clob_overrides(
863    api_key: &Option<SecretString>,
864    api_secret: &Option<SecretString>,
865    passphrase: &Option<SecretString>,
866) -> anyhow::Result<()> {
867    let (key_var, secret_var, passphrase_var, _, _) = credential_env_vars();
868
869    for (field, value, env_var) in [
870        ("api_key", api_key, key_var),
871        ("api_secret", api_secret, secret_var),
872        ("passphrase", passphrase, passphrase_var),
873    ] {
874        validate_env_override(
875            value.as_ref().map(SecretString::expose_secret),
876            field,
877            env_var,
878        )?;
879    }
880
881    Ok(())
882}
883
884#[cfg(test)]
885mod tests {
886    use nautilus_common::config::ConfigError;
887    use rstest::rstest;
888
889    use super::*;
890
891    #[rstest]
892    fn updown_event_slug_config_builds_aligned_slugs() {
893        let config = PolymarketUpDownEventSlugConfig {
894            assets: vec!["BTC".to_string(), " eth ".to_string(), String::new()],
895            interval_mins: 5,
896            periods: 2,
897            start_offset_periods: -1,
898        };
899
900        let slugs = config
901            .build_event_slugs_at_unix_secs(1_700_000_123)
902            .expect("event slugs should build");
903
904        assert_eq!(
905            slugs,
906            [
907                "btc-updown-5m-1699999800",
908                "eth-updown-5m-1699999800",
909                "btc-updown-5m-1700000100",
910                "eth-updown-5m-1700000100",
911            ]
912        );
913    }
914
915    #[rstest]
916    fn updown_event_slug_config_rejects_zero_interval() {
917        let config = PolymarketUpDownEventSlugConfig {
918            interval_mins: 0,
919            ..PolymarketUpDownEventSlugConfig::default()
920        };
921
922        let err = config
923            .build_event_slugs_at_unix_secs(1_700_000_123)
924            .expect_err("zero interval should fail");
925
926        assert_eq!(
927            err.downcast_ref::<ConfigError>(),
928            Some(&ConfigError::range(
929                "event_slug_builder.interval_mins",
930                "must be positive and fit in seconds"
931            )),
932        );
933    }
934
935    #[rstest]
936    fn provider_config_series_ids_trigger_load_all() {
937        let config = PolymarketInstrumentProviderConfig {
938            series_ids: Some(vec![10684]),
939            ..PolymarketInstrumentProviderConfig::default()
940        };
941
942        assert!(config.has_series_ids());
943        assert!(config.should_load_all());
944    }
945
946    #[rstest]
947    fn provider_config_empty_series_ids_do_not_trigger_load_all() {
948        let config = PolymarketInstrumentProviderConfig {
949            series_ids: Some(Vec::new()),
950            ..PolymarketInstrumentProviderConfig::default()
951        };
952
953        assert!(!config.has_series_ids());
954        assert!(!config.should_load_all());
955    }
956
957    #[rstest]
958    fn provider_config_filters_trigger_load_all() {
959        let config = PolymarketInstrumentProviderConfig {
960            filters: Some(HashMap::from([("tag_id".to_string(), "84".to_string())])),
961            ..PolymarketInstrumentProviderConfig::default()
962        };
963
964        assert!(config.has_nonempty_filters());
965        assert!(!config.has_explicit_scope());
966        assert!(config.should_load_all());
967    }
968
969    #[rstest]
970    fn data_config_book_sync_defaults_match_documented_values() {
971        let config = PolymarketDataClientConfig::default();
972
973        assert_eq!(config.book_snapshot_timeout_secs, 10);
974        assert_eq!(config.book_stale_check_interval_secs, 5);
975        assert_eq!(
976            config.book_stale_threshold_secs, 0,
977            "stale monitor must stay disabled by default"
978        );
979    }
980
981    #[rstest]
982    fn provider_config_empty_filters_do_not_trigger_load_all() {
983        let config = PolymarketInstrumentProviderConfig {
984            filters: Some(HashMap::new()),
985            ..PolymarketInstrumentProviderConfig::default()
986        };
987
988        assert!(!config.has_nonempty_filters());
989        assert!(!config.should_load_all());
990    }
991
992    #[rstest]
993    fn test_data_config_toml_minimal() {
994        let config: PolymarketDataClientConfig = toml::from_str(
995            "
996http_timeout_secs = 30
997ws_max_subscriptions = 50
998update_instruments_interval_mins = 5
999subscribe_new_markets = true
1000new_market_fetch_max_concurrency = 16
1001auto_load_debounce_ms = 250
1002resolve_poll_enabled = true
1003resolve_poll_interval_secs = 30
1004resolve_poll_grace_secs = 10
1005resolve_poll_max_wait_secs = 1800
1006",
1007        )
1008        .unwrap();
1009
1010        assert!(config.instrument_config.is_none());
1011        assert!(config.filters.is_empty());
1012        assert_eq!(config.http_timeout_secs, 30);
1013        assert_eq!(config.ws_max_subscriptions, 50);
1014        assert_eq!(config.update_instruments_interval_mins, Some(5));
1015        assert!(config.subscribe_new_markets);
1016        assert!(config.new_market_filter.is_none());
1017        assert_eq!(config.new_market_fetch_max_concurrency, 16);
1018        assert_eq!(config.auto_load_debounce_ms, 250);
1019        assert!(config.resolve_poll_enabled);
1020        assert_eq!(config.resolve_poll_interval_secs, 30);
1021        assert_eq!(config.resolve_poll_grace_secs, 10);
1022        assert_eq!(config.resolve_poll_max_wait_secs, 1800);
1023        assert!(config.drop_quotes_missing_side);
1024        assert!(!config.compute_effective_deltas);
1025    }
1026
1027    #[rstest]
1028    fn test_data_config_toml_sets_compute_effective_deltas() {
1029        let config: PolymarketDataClientConfig =
1030            toml::from_str("compute_effective_deltas = true").unwrap();
1031
1032        assert!(config.compute_effective_deltas);
1033    }
1034
1035    #[rstest]
1036    fn test_data_config_toml_sets_drop_quotes_missing_side_false() {
1037        let config: PolymarketDataClientConfig =
1038            toml::from_str("drop_quotes_missing_side = false").unwrap();
1039
1040        assert!(!config.drop_quotes_missing_side);
1041    }
1042
1043    #[rstest]
1044    fn test_data_config_toml_with_instrument_config() {
1045        let config: PolymarketDataClientConfig = toml::from_str(
1046            r#"
1047[instrument_config]
1048load_all = true
1049event_slugs = ["btc-updown-5m-123", "eth-updown-15m-456"]
1050log_warnings = false
1051"#,
1052        )
1053        .unwrap();
1054
1055        let instrument_config = config.instrument_config.expect("instrument_config");
1056        assert!(instrument_config.load_all);
1057        assert_eq!(
1058            instrument_config.event_slugs,
1059            Some(vec![
1060                "btc-updown-5m-123".to_string(),
1061                "eth-updown-15m-456".to_string(),
1062            ]),
1063        );
1064        assert!(!instrument_config.log_warnings);
1065    }
1066
1067    #[rstest]
1068    fn test_exec_config_toml_empty_uses_defaults() {
1069        let config: PolymarketExecutionClientConfig = toml::from_str("").unwrap();
1070        let expected = PolymarketExecutionClientConfig::default();
1071        assert_eq!(config.account_id, expected.account_id);
1072        assert_eq!(config.signature_type, expected.signature_type);
1073        assert_eq!(config.http_timeout_secs, expected.http_timeout_secs);
1074        assert_eq!(config.max_retries, expected.max_retries);
1075        assert!(!config.heartbeat_enabled);
1076        assert_eq!(config.transport_backend, expected.transport_backend);
1077        assert!(config.instrument_config.is_none());
1078        assert!(config.reconciliation_load_ids().is_none());
1079    }
1080
1081    #[rstest]
1082    fn test_exec_config_reconciliation_load_ids_come_from_instrument_config() {
1083        let scoped = InstrumentId::from("0xabc-123.POLYMARKET");
1084        let config: PolymarketExecutionClientConfig = toml::from_str(
1085            r#"
1086[instrument_config]
1087load_ids = ["0xabc-123.POLYMARKET"]
1088"#,
1089        )
1090        .unwrap();
1091
1092        assert_eq!(config.reconciliation_load_ids(), Some([scoped].as_slice()));
1093    }
1094
1095    #[rstest]
1096    fn test_data_config_proxy_url_validates_and_redacts_debug() {
1097        const SECRET: &str = "data-proxy-secret";
1098        let proxy_url = format!("http://data-user:{SECRET}@127.0.0.1:18081");
1099        let config: PolymarketDataClientConfig =
1100            toml::from_str(&format!("proxy_url = \"{proxy_url}\""))
1101                .expect("deserialize data config");
1102        let validated = config
1103            .validated_proxy_url()
1104            .expect("validate data proxy")
1105            .expect("data proxy configured");
1106        let debug = format!("{config:?}");
1107
1108        assert_eq!(validated.expose(), proxy_url);
1109        assert!(config.has_proxy_url());
1110        assert!(debug.contains("proxy_url: Some(<redacted>)"));
1111        assert!(!debug.contains(SECRET));
1112    }
1113
1114    #[rstest]
1115    fn test_exec_config_proxy_url_validates_and_redacts_debug() {
1116        const SECRET: &str = "exec-proxy-secret";
1117        let proxy_url = format!("https://exec-user:{SECRET}@127.0.0.1:18082");
1118        let config: PolymarketExecutionClientConfig =
1119            toml::from_str(&format!("proxy_url = \"{proxy_url}\""))
1120                .expect("deserialize execution config");
1121        let validated = config
1122            .validated_proxy_url()
1123            .expect("validate execution proxy")
1124            .expect("execution proxy configured");
1125        let debug = format!("{config:?}");
1126
1127        assert_eq!(validated.expose(), proxy_url);
1128        assert!(config.has_proxy_url());
1129        assert!(debug.contains("proxy_url: Some(<redacted>)"));
1130        assert!(!debug.contains(SECRET));
1131    }
1132
1133    #[rstest]
1134    fn test_proxy_url_unset_preserves_direct_configuration() {
1135        let data_config = PolymarketDataClientConfig::default();
1136        let exec_config = PolymarketExecutionClientConfig::default();
1137
1138        assert_eq!(data_config.proxy_url, None);
1139        assert_eq!(exec_config.proxy_url, None);
1140        assert_eq!(data_config.validated_proxy_url().unwrap(), None);
1141        assert_eq!(exec_config.validated_proxy_url().unwrap(), None);
1142        assert!(!data_config.has_proxy_url());
1143        assert!(!exec_config.has_proxy_url());
1144    }
1145
1146    #[rstest]
1147    fn test_invalid_proxy_url_error_redacts_credentials() {
1148        const SECRET: &str = "invalid-proxy-secret";
1149        let config = PolymarketDataClientConfig {
1150            proxy_url: Some(format!("http://proxy-user:{SECRET}@[::1").into()),
1151            ..PolymarketDataClientConfig::default()
1152        };
1153        let error = config
1154            .validated_proxy_url()
1155            .expect_err("malformed proxy URL should fail");
1156
1157        assert!(!error.to_string().contains(SECRET));
1158    }
1159
1160    #[rstest]
1161    fn test_socks_proxy_url_is_rejected_for_consistent_routing() {
1162        let config = PolymarketExecutionClientConfig {
1163            proxy_url: Some("socks5://127.0.0.1:1080".into()),
1164            ..PolymarketExecutionClientConfig::default()
1165        };
1166        let error = config
1167            .validated_proxy_url()
1168            .expect_err("SOCKS proxy should fail validation");
1169
1170        assert_eq!(
1171            error.to_string(),
1172            "invalid URL: SOCKS proxy scheme 'socks5' is not yet supported for WebSocket connections; use an http:// or https:// proxy"
1173        );
1174    }
1175
1176    #[rstest]
1177    #[case("private_key")]
1178    #[case("api_key")]
1179    #[case("api_secret")]
1180    #[case("passphrase")]
1181    #[case("funder")]
1182    fn test_session_requires_explicit_credentials(#[case] missing: &str) {
1183        let mut config = PolymarketExecutionClientConfig {
1184            signer_type: PolymarketSignerType::Session,
1185            signature_type: PolymarketSignatureType::Poly1271,
1186            private_key: Some("key".into()),
1187            api_key: Some("api".into()),
1188            api_secret: Some("secret".into()),
1189            passphrase: Some("pass".into()),
1190            funder: Some("wallet".into()),
1191            ..Default::default()
1192        };
1193
1194        assert!(config.validate_signer().is_ok());
1195
1196        match missing {
1197            "private_key" => config.private_key = None,
1198            "api_key" => config.api_key = None,
1199            "api_secret" => config.api_secret = None,
1200            "passphrase" => config.passphrase = Some(" ".into()),
1201            "funder" => config.funder = Some(" ".into()),
1202            _ => unreachable!(),
1203        }
1204
1205        assert!(config.validate_signer().is_err());
1206    }
1207
1208    #[rstest]
1209    #[case(PolymarketSignatureType::Eoa)]
1210    #[case(PolymarketSignatureType::PolyProxy)]
1211    #[case(PolymarketSignatureType::PolyGnosisSafe)]
1212    fn test_session_rejects_other_signature_types(#[case] signature_type: PolymarketSignatureType) {
1213        let config = PolymarketExecutionClientConfig {
1214            signer_type: PolymarketSignerType::Session,
1215            signature_type,
1216            ..Default::default()
1217        };
1218
1219        assert_eq!(
1220            config.validate_signer().unwrap_err().to_string(),
1221            "Session signers require POLY_1271"
1222        );
1223    }
1224
1225    #[rstest]
1226    fn polybolt_credential_resolves_explicit_fields() {
1227        let config = PolymarketDataClientConfig {
1228            api_key: Some(SecretString::from("fixture-key")),
1229            api_secret: Some(SecretString::from("Zml4dHVyZS1zZWNyZXQ=")),
1230            passphrase: Some(SecretString::from("fixture-passphrase")),
1231            ..PolymarketDataClientConfig::default()
1232        };
1233
1234        let credential = config
1235            .polybolt_credential()
1236            .expect("explicit credentials resolve")
1237            .expect("credential present");
1238
1239        assert_eq!(credential.api_key_str(), "fixture-key");
1240    }
1241
1242    #[rstest]
1243    fn polybolt_credential_rejects_malformed_explicit_secret() {
1244        let config = PolymarketDataClientConfig {
1245            api_key: Some(SecretString::from("fixture-key")),
1246            api_secret: Some(SecretString::from("not base64!")),
1247            passphrase: Some(SecretString::from("fixture-passphrase")),
1248            ..PolymarketDataClientConfig::default()
1249        };
1250
1251        let error = config.polybolt_credential().unwrap_err().to_string();
1252
1253        assert!(
1254            error.starts_with("Invalid Polymarket CLOB credentials for PolyBolt"),
1255            "{error}"
1256        );
1257    }
1258
1259    #[rstest]
1260    #[case("load_ids", serde_json::json!([format!("0x{}-1.POLYMARKET", "a".repeat(64)), format!("0x{}-2.POLYMARKET", "b".repeat(64))]))]
1261    #[case("event_slugs", serde_json::json!(["event-one", "event-two"]))]
1262    #[case("market_slugs", serde_json::json!(["market-one", "market-two"]))]
1263    #[case("series_ids", serde_json::json!([1, 2]))]
1264    fn test_instrument_provider_selection_uniqueness(
1265        #[case] field: &str,
1266        #[case] mut values: serde_json::Value,
1267        #[values(false, true)] duplicate: bool,
1268    ) {
1269        if duplicate {
1270            let entries = values.as_array_mut().unwrap();
1271            entries.push(entries[0].clone());
1272        }
1273
1274        let mut input =
1275            serde_json::to_value(PolymarketInstrumentProviderConfig::default()).unwrap();
1276        input[field] = values;
1277        let config: PolymarketInstrumentProviderConfig = serde_json::from_value(input).unwrap();
1278        let original = serde_json::to_value(&config).unwrap();
1279
1280        let expected = if duplicate {
1281            Err(ConfigError::duplicate(field, None))
1282        } else {
1283            Ok(())
1284        };
1285
1286        let result = config
1287            .validate()
1288            .map_err(|e| e.downcast::<ConfigError>().unwrap());
1289
1290        assert_eq!(result, expected);
1291        assert_eq!(serde_json::to_value(&config).unwrap(), original);
1292    }
1293
1294    #[rstest]
1295    #[case::exact(vec!["btc".to_string(), "btc".to_string()])]
1296    #[case::normalized(vec!["BTC".to_string(), " btc ".to_string()])]
1297    fn test_slug_assets_reject_duplicates(#[case] assets: Vec<String>) {
1298        let config = PolymarketUpDownEventSlugConfig {
1299            assets,
1300            ..Default::default()
1301        };
1302
1303        let error = config
1304            .build_event_slugs_at_unix_secs(1_700_000_123)
1305            .unwrap_err();
1306
1307        assert_eq!(
1308            error.downcast_ref::<ConfigError>(),
1309            Some(&ConfigError::duplicate("event_slug_builder.assets", None))
1310        );
1311    }
1312
1313    #[rstest]
1314    #[case("slug", "market-a, market-b,market-a")]
1315    #[case("slug", " market-a,market-a ")]
1316    #[case("condition_ids", "condition-a,condition-b,condition-a")]
1317    #[case("clob_token_ids", "token-a,token-b,token-a")]
1318    #[case("question_ids", "question-a,question-b,question-a")]
1319    #[case("market_maker_address", "address-a,address-b,address-a")]
1320    #[case("sports_market_types", "type-a,type-b,type-a")]
1321    #[case("tag_id", "1,01")]
1322    #[case("id", "1,2,1")]
1323    #[case("id", "1,01")]
1324    fn test_gamma_filter_selection_duplicates(#[case] key: &str, #[case] values: &str) {
1325        let config = PolymarketInstrumentProviderConfig {
1326            filters: Some(std::collections::HashMap::from([(
1327                key.to_string(),
1328                values.to_string(),
1329            )])),
1330            ..Default::default()
1331        };
1332
1333        let error = config.validate().unwrap_err();
1334        assert_eq!(
1335            error.downcast_ref::<ConfigError>(),
1336            Some(&ConfigError::duplicate(format!("filters.{key}"), None))
1337        );
1338    }
1339
1340    #[rstest]
1341    fn test_execution_config_rejects_duplicate_provider_selections() {
1342        let config = PolymarketExecutionClientConfig {
1343            instrument_config: Some(PolymarketInstrumentProviderConfig {
1344                load_ids: Some(vec![
1345                    InstrumentId::from("one.POLYMARKET"),
1346                    InstrumentId::from("one.POLYMARKET"),
1347                ]),
1348                ..Default::default()
1349            }),
1350            ..Default::default()
1351        };
1352
1353        let error = config.validate().unwrap_err();
1354        assert_eq!(
1355            error.downcast_ref::<ConfigError>(),
1356            Some(&ConfigError::duplicate("load_ids", None))
1357        );
1358    }
1359
1360    #[rstest]
1361    #[case::interval_zero(0, 1, vec!["btc".to_string()], Err(ConfigError::range("event_slug_builder.interval_mins", "must be positive and fit in seconds")))]
1362    #[case::interval_overflow(u64::MAX, 1, vec!["btc".to_string()], Err(ConfigError::range("event_slug_builder.interval_mins", "must be positive and fit in seconds")))]
1363    #[case::periods_zero(5, 0, vec!["btc".to_string()], Err(ConfigError::range("event_slug_builder.periods", "must be positive")))]
1364    #[case::assets_empty(5, 1, vec![], Err(ConfigError::empty_field("event_slug_builder.assets")))]
1365    #[case::assets_blank(5, 1, vec![" ".to_string()], Err(ConfigError::empty_field("event_slug_builder.assets")))]
1366    #[case::interval_max(u64::MAX / SECONDS_IN_MINUTE, 1, vec!["btc".to_string()], Ok(()))]
1367    fn test_slug_builder_config_static_validation(
1368        #[case] interval_mins: u64,
1369        #[case] periods: u64,
1370        #[case] assets: Vec<String>,
1371        #[case] expected: ConfigResult<()>,
1372    ) {
1373        let config = PolymarketUpDownEventSlugConfig {
1374            assets,
1375            interval_mins,
1376            periods,
1377            ..Default::default()
1378        };
1379
1380        assert_eq!(config.validate(), expected);
1381    }
1382
1383    #[rstest]
1384    fn data_config_refresh_defaults_match() {
1385        let from_json: PolymarketDataClientConfig = serde_json::from_str("{}").unwrap();
1386        let from_toml: PolymarketDataClientConfig = toml::from_str("").unwrap();
1387
1388        for config in [
1389            PolymarketDataClientConfig::default(),
1390            PolymarketDataClientConfig::builder().build(),
1391            from_json,
1392            from_toml,
1393        ] {
1394            assert_eq!(config.update_instruments_interval_mins, Some(60));
1395        }
1396
1397        let disabled = PolymarketDataClientConfig::builder()
1398            .update_instruments_interval_mins(None)
1399            .build();
1400        assert_eq!(disabled.update_instruments_interval_mins, None);
1401        let explicit = PolymarketDataClientConfig::builder()
1402            .update_instruments_interval_mins(7)
1403            .build();
1404        assert_eq!(explicit.update_instruments_interval_mins, Some(7));
1405    }
1406
1407    #[rstest]
1408    #[case(f64::NAN, 15.0)]
1409    #[case(f64::INFINITY, 15.0)]
1410    #[case(5.0, f64::INFINITY)]
1411    #[case(-1.0, 15.0)]
1412    #[case(5.0, -1.0)]
1413    #[case(20.0, 15.0)]
1414    #[case(1e30, 1e30)]
1415    fn data_config_rejects_invalid_retry_delays(#[case] initial: f64, #[case] maximum: f64) {
1416        let config = PolymarketDataClientConfig {
1417            auto_load_retry_delay_initial_secs: initial,
1418            auto_load_retry_delay_max_secs: maximum,
1419            ..Default::default()
1420        };
1421
1422        let error = config.validate().unwrap_err();
1423        assert!(error.to_string().contains("auto_load_retry_delay_"));
1424    }
1425
1426    #[rstest]
1427    #[case(0.0, 0.0)]
1428    #[case(5.0, 15.0)]
1429    fn data_config_accepts_valid_retry_delays(#[case] initial: f64, #[case] maximum: f64) {
1430        let config = PolymarketDataClientConfig {
1431            auto_load_retry_delay_initial_secs: initial,
1432            auto_load_retry_delay_max_secs: maximum,
1433            ..Default::default()
1434        };
1435
1436        assert!(config.validate().is_ok());
1437    }
1438
1439    #[rstest]
1440    #[case("12345.POLYMARKET")]
1441    #[case("0xabc-123.POLYMARKET")]
1442    #[case("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-x.POLYMARKET")]
1443    #[case("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-1.OTHER")]
1444    fn provider_config_rejects_invalid_load_ids(#[case] value: &str) {
1445        let config = PolymarketInstrumentProviderConfig {
1446            load_ids: Some(vec![InstrumentId::from(value)]),
1447            ..Default::default()
1448        };
1449
1450        let error = config.validate().unwrap_err().to_string();
1451        assert!(error.contains(value));
1452        assert!(error.contains("expected <0x-prefixed 32-byte condition ID>"));
1453    }
1454
1455    #[rstest]
1456    fn provider_config_combines_event_slugs_and_builder() {
1457        let builder = PolymarketUpDownEventSlugConfig {
1458            periods: 1,
1459            ..Default::default()
1460        };
1461
1462        let config = PolymarketInstrumentProviderConfig {
1463            event_slugs: Some(vec!["explicit-event".to_string()]),
1464            event_slug_builder: Some(builder),
1465            ..Default::default()
1466        };
1467
1468        let slugs = config.resolve_event_slugs().unwrap();
1469        assert_eq!(slugs.len(), 2);
1470        assert_eq!(slugs[0], "explicit-event");
1471        assert!(slugs[1].starts_with("btc-updown-5m-"));
1472
1473        // Keep the generated period at the Unix epoch to avoid clock-boundary races
1474        let interval_mins = u64::MAX / SECONDS_IN_MINUTE;
1475        let shared_slug = format!("btc-updown-{interval_mins}m-0");
1476
1477        let overlapping = PolymarketInstrumentProviderConfig {
1478            event_slugs: Some(vec![shared_slug.clone()]),
1479            event_slug_builder: Some(PolymarketUpDownEventSlugConfig {
1480                interval_mins,
1481                periods: 1,
1482                ..Default::default()
1483            }),
1484            ..Default::default()
1485        };
1486
1487        overlapping.validate().unwrap();
1488        assert_eq!(
1489            overlapping.resolve_event_slugs().unwrap(),
1490            vec![shared_slug]
1491        );
1492    }
1493
1494    #[rstest]
1495    #[case("api_key")]
1496    #[case("api_secret")]
1497    #[case("passphrase")]
1498    #[case("private_key")]
1499    #[case("funder")]
1500    fn execution_config_rejects_blank_overrides(
1501        #[case] field: &str,
1502        #[values("", " \t")] blank: &str,
1503    ) {
1504        let mut config = PolymarketExecutionClientConfig::default();
1505        match field {
1506            "api_key" => config.api_key = Some(blank.into()),
1507            "api_secret" => config.api_secret = Some(blank.into()),
1508            "passphrase" => config.passphrase = Some(blank.into()),
1509            "private_key" => config.private_key = Some(blank.into()),
1510            "funder" => config.funder = Some(blank.to_string()),
1511            _ => unreachable!(),
1512        }
1513
1514        let error = config.validate().unwrap_err().to_string();
1515        assert!(error.starts_with(&format!("bad request: {field} must not be blank;")));
1516        assert!(error.contains("omit it or pass None"));
1517    }
1518}