Skip to main content

nautilus_derive/
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 Derive adapter.
17
18use nautilus_common::config::{ConfigError, ConfigResult, check_unique_values};
19use nautilus_core::string::secret::SecretString;
20use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
21use nautilus_model::identifiers::{AccountId, InstrumentId};
22use nautilus_network::websocket::TransportBackend;
23use rust_decimal::Decimal;
24use serde::{Deserialize, Serialize};
25
26use crate::{
27    common::{
28        consts::{
29            DERIVE_VENUE, HTTP_MAX_RETRIES, HTTP_RETRY_DELAY_INITIAL_MS, HTTP_RETRY_DELAY_MAX_MS,
30        },
31        enums::DeriveEnvironment,
32        urls,
33    },
34    providers::normalize_currency,
35};
36
37/// Configuration for the Derive data client.
38#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
39#[builder(on(SecretString, into))]
40#[serde(default, deny_unknown_fields)]
41#[cfg_attr(
42    feature = "python",
43    pyo3::pyclass(module = "nautilus_trader.adapters.derive", from_py_object)
44)]
45#[cfg_attr(
46    feature = "python",
47    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.derive")
48)]
49pub struct DeriveDataClientConfig {
50    /// The Derive environment to connect to.
51    #[builder(default)]
52    pub environment: DeriveEnvironment,
53    /// Override for the REST API base URL.
54    pub base_url_rest: Option<SecretString>,
55    /// Override for the WebSocket URL.
56    pub base_url_ws: Option<SecretString>,
57    /// Optional proxy URL for HTTP and WebSocket transports.
58    pub proxy_url: Option<SecretString>,
59    /// HTTP timeout in seconds.
60    #[builder(default = 10)]
61    pub http_timeout_secs: u64,
62    /// Optional per-operation WebSocket timeout in seconds (login, subscribe,
63    /// reads, writes). When unset, the low-level `WS_REQUEST_TIMEOUT` applies.
64    pub ws_timeout_secs: Option<u64>,
65    /// Maximum wait for an initial, post-reconnect, or recovery book snapshot, in seconds.
66    /// A zero value disables snapshot deadlines.
67    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
68    pub book_snapshot_timeout_secs: u64,
69    /// Maximum receive age of advancing book snapshots before recovery, in seconds.
70    /// Empty snapshots count as updates; a zero value disables stale book recovery.
71    #[builder(default = 120)]
72    pub book_stale_threshold_secs: u64,
73    /// Interval in minutes for refreshing instruments of configured currencies.
74    /// A zero value disables periodic refresh.
75    #[builder(default = 60)]
76    pub update_instruments_interval_mins: u64,
77    /// Underlying currencies to load on connect. Empty means lazy-load by
78    /// instrument ID when subscribing.
79    #[builder(default)]
80    pub currencies: Vec<String>,
81    /// Whether instrument loading includes expired instruments.
82    #[builder(default)]
83    pub include_expired: bool,
84    /// Whether subscriptions may fetch missing instruments before sending the
85    /// WebSocket request.
86    #[builder(default = true)]
87    pub auto_load_missing_instruments: bool,
88    /// WebSocket transport backend (defaults to `Sockudo`).
89    #[builder(default)]
90    pub transport_backend: TransportBackend,
91}
92
93#[cfg(feature = "python")]
94nautilus_core::impl_pyo3_config_getters!(DeriveDataClientConfig {
95    environment: DeriveEnvironment,
96    http_timeout_secs: u64,
97    ws_timeout_secs: Option<u64>,
98    book_snapshot_timeout_secs: u64,
99    book_stale_threshold_secs: u64,
100    update_instruments_interval_mins: u64,
101    currencies: Vec<String>,
102    include_expired: bool,
103    auto_load_missing_instruments: bool,
104    transport_backend: TransportBackend,
105});
106
107impl Default for DeriveDataClientConfig {
108    fn default() -> Self {
109        Self::builder().build()
110    }
111}
112
113impl DeriveDataClientConfig {
114    #[must_use]
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// Validates that configured currency entries contain no duplicates.
120    ///
121    /// Nonblank currencies must also be distinct after trimming.
122    ///
123    /// # Errors
124    ///
125    /// Returns an error if currency entries repeat or nonblank entries match after trimming.
126    pub fn validate(&self) -> ConfigResult<()> {
127        check_unique_values("currencies", &self.currencies)?;
128        let normalized: Vec<_> = self
129            .currencies
130            .iter()
131            .filter_map(|currency| normalize_currency(currency))
132            .collect();
133        check_unique_values("currencies", &normalized)
134    }
135
136    /// Returns the REST API base URL, respecting environment and overrides.
137    #[must_use]
138    pub fn rest_url(&self) -> String {
139        self.base_url_rest.as_ref().map_or_else(
140            || urls::rest_url(self.environment).to_string(),
141            |url| url.expose_secret().to_string(),
142        )
143    }
144
145    /// Returns the WebSocket URL, respecting environment and overrides.
146    #[must_use]
147    pub fn ws_url(&self) -> String {
148        self.base_url_ws.as_ref().map_or_else(
149            || urls::ws_url(self.environment).to_string(),
150            |url| url.expose_secret().to_string(),
151        )
152    }
153}
154
155/// Configuration for the Derive execution client.
156#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
157#[builder(on(SecretString, into))]
158#[serde(default, deny_unknown_fields)]
159#[cfg_attr(
160    feature = "python",
161    pyo3::pyclass(module = "nautilus_trader.adapters.derive", from_py_object)
162)]
163#[cfg_attr(
164    feature = "python",
165    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.derive")
166)]
167pub struct DeriveExecutionClientConfig {
168    /// Account identifier for the execution client.
169    #[builder(default = AccountId::from("DERIVE-001"))]
170    pub account_id: AccountId,
171    /// Owner's EOA or multisig address (`X-DeriveWallet`). Falls back
172    /// to `DERIVE_WALLET_ADDRESS` (or `DERIVE_TESTNET_WALLET_ADDRESS` on
173    /// testnet) when unset.
174    pub wallet_address: Option<String>,
175    /// secp256k1 session-key private key in hex (with or without `0x` prefix).
176    /// Falls back to `DERIVE_SESSION_PRIVATE_KEY` (or
177    /// `DERIVE_TESTNET_SESSION_PRIVATE_KEY` on testnet) when unset.
178    pub session_key: Option<SecretString>,
179    /// Subaccount identifier. Falls back to `DERIVE_SUBACCOUNT_ID` (or
180    /// `DERIVE_TESTNET_SUBACCOUNT_ID` on testnet) when unset.
181    pub subaccount_id: Option<u64>,
182    /// The Derive environment to connect to.
183    #[builder(default)]
184    pub environment: DeriveEnvironment,
185    /// Override for the REST API base URL.
186    pub base_url_rest: Option<SecretString>,
187    /// Override for the WebSocket URL.
188    pub base_url_ws: Option<SecretString>,
189    /// Optional proxy URL for HTTP and WebSocket transports.
190    pub proxy_url: Option<SecretString>,
191    /// HTTP timeout in seconds.
192    #[builder(default = 10)]
193    pub http_timeout_secs: u64,
194    /// Maximum number of retry attempts for HTTP requests.
195    #[builder(default = HTTP_MAX_RETRIES)]
196    pub max_retries: u32,
197    /// Initial retry delay in milliseconds.
198    #[builder(default = HTTP_RETRY_DELAY_INITIAL_MS)]
199    pub retry_delay_initial_ms: u64,
200    /// Maximum retry delay in milliseconds.
201    #[builder(default = HTTP_RETRY_DELAY_MAX_MS)]
202    pub retry_delay_max_ms: u64,
203    /// Optional per-operation WebSocket timeout in seconds (login, subscribe,
204    /// reads, writes). When unset, the low-level `WS_REQUEST_TIMEOUT` applies.
205    pub ws_timeout_secs: Option<u64>,
206    /// Per-contract USDC fee cap signed into every order. Required for
207    /// execution and must be greater than zero.
208    pub max_fee_per_contract: Option<Decimal>,
209    /// WebSocket transport backend (defaults to `Sockudo`).
210    #[builder(default)]
211    pub transport_backend: TransportBackend,
212    /// Override for the EIP-712 domain separator. Falls back to the shipped
213    /// v3 constant for the configured environment when unset.
214    pub domain_separator: Option<String>,
215    /// Override for the EIP-712 action typehash. Falls back to the shipped
216    /// [`crate::common::consts::ACTION_TYPEHASH`] when unset.
217    pub action_typehash: Option<String>,
218    /// Override for the Trade module contract address. Falls back to the
219    /// shipped per-environment constant when unset.
220    pub trade_module_address: Option<String>,
221    /// Signature expiry TTL in seconds for normal orders and replaces (added
222    /// to the wall clock before signing). Must be greater than the venue
223    /// minimum ([`crate::common::consts::MIN_SIGNATURE_TTL`], 10s) and at most 120 days.
224    #[builder(default = 600)]
225    pub signature_expiry_secs: u64,
226    /// Slippage bound applied to market orders when deriving a worst-acceptable
227    /// limit price from the cached top-of-book quote. Expressed in basis points
228    /// (1 bp = 0.01%). Defaults to 50 bp = 0.5%.
229    #[builder(default = 50)]
230    pub market_order_slippage_bps: u32,
231    /// Maximum wallet matching requests per second across HTTP, WebSocket,
232    /// session keys, and subaccounts on the same API host. Defaults to 1 when
233    /// unset. The first explicit setting for a wallet is shared by all clients;
234    /// the limiter ignores conflicting later settings. Verify deployed budgets with
235    /// `public/getRateLimits`. See <https://docs.derive.xyz/rate-limits>.
236    pub max_matching_requests_per_second: Option<u32>,
237    /// Per-wallet/instrument token refill rate for perpetuals, spot, and options.
238    /// Defaults to 1 token per second; capacity is five times the configured rate.
239    /// Clients for the same wallet on the same API host share the first explicit
240    /// setting, independently of the wallet matching allowance. Instrument budgets
241    /// are absent from `public/getRateLimits`.
242    /// See <https://docs.derive.xyz/rate-limits>.
243    pub max_per_instrument_matching_requests_per_second: Option<u32>,
244    /// Enables wallet-wide cancel-on-disconnect before accepting orders and tags resting limit orders
245    /// with `mmp: true`. Requires `Trade(All)` across all subaccounts and signature expiry at most
246    /// 15 minutes. False leaves the wallet setting unchanged. Shutdown never disables the setting.
247    #[builder(default)]
248    pub cancel_on_disconnect: bool,
249    /// Instruments included in reconciliation. `None` or empty includes every instrument.
250    /// Bulk-load their currencies through data-client `currencies` and set `reconciliation_instrument_ids`
251    /// to the same set so omitted positions are not treated as flat.
252    pub load_ids: Option<Vec<InstrumentId>>,
253}
254
255#[cfg(feature = "python")]
256nautilus_core::impl_pyo3_config_getters!(DeriveExecutionClientConfig {
257    account_id: AccountId,
258    wallet_address: Option<String>,
259    subaccount_id: Option<u64>,
260    environment: DeriveEnvironment,
261    http_timeout_secs: u64,
262    max_retries: u32,
263    retry_delay_initial_ms: u64,
264    retry_delay_max_ms: u64,
265    ws_timeout_secs: Option<u64>,
266    max_fee_per_contract: Option<Decimal>,
267    transport_backend: TransportBackend,
268    domain_separator: Option<String>,
269    action_typehash: Option<String>,
270    trade_module_address: Option<String>,
271    signature_expiry_secs: u64,
272    market_order_slippage_bps: u32,
273    max_matching_requests_per_second: Option<u32>,
274    max_per_instrument_matching_requests_per_second: Option<u32>,
275    cancel_on_disconnect: bool,
276    load_ids: Option<Vec<InstrumentId>>,
277});
278
279impl Default for DeriveExecutionClientConfig {
280    fn default() -> Self {
281        Self::builder().build()
282    }
283}
284
285impl DeriveExecutionClientConfig {
286    #[must_use]
287    pub fn new() -> Self {
288        Self::default()
289    }
290
291    /// Returns true when wallet, session-key, and subaccount are all populated
292    /// **in this config**. Environment-variable fallbacks documented on the
293    /// individual fields are resolved at factory-construction time, not here;
294    /// callers that need a "credentials available anywhere" check should
295    /// inspect both this method and the relevant env vars.
296    #[must_use]
297    pub fn has_credentials(&self) -> bool {
298        self.wallet_address
299            .as_deref()
300            .is_some_and(|s| !s.trim().is_empty())
301            && self
302                .session_key
303                .as_ref()
304                .map(SecretString::expose_secret)
305                .is_some_and(|s| !s.trim().is_empty())
306            && self.subaccount_id.is_some()
307    }
308
309    /// Validates execution configuration invariants.
310    ///
311    /// # Errors
312    ///
313    /// Returns an error if:
314    /// - `max_fee_per_contract` is missing or not greater than zero.
315    /// - Cancel-on-disconnect uses a signature expiry greater than 15 minutes.
316    /// - `load_ids` repeats an instrument or includes another venue.
317    pub fn validate(&self) -> anyhow::Result<()> {
318        self.validate_load_ids()?;
319
320        let Some(max_fee_per_contract) = self.max_fee_per_contract else {
321            anyhow::bail!("max_fee_per_contract is required");
322        };
323
324        if max_fee_per_contract <= Decimal::ZERO {
325            anyhow::bail!("max_fee_per_contract must be greater than zero");
326        }
327
328        if self.cancel_on_disconnect && self.signature_expiry_secs > 15 * 60 {
329            anyhow::bail!(
330                "cancel_on_disconnect requires signature_expiry_secs at most 900 seconds"
331            );
332        }
333
334        Ok(())
335    }
336
337    pub(crate) fn validate_load_ids(&self) -> ConfigResult<()> {
338        if let Some(ids) = &self.load_ids {
339            check_unique_values("load_ids", ids)?;
340            for id in ids {
341                if id.venue != *DERIVE_VENUE {
342                    return Err(ConfigError::invalid_value(
343                        "load_ids",
344                        format!("{id} is not a DERIVE instrument"),
345                    ));
346                }
347            }
348        }
349
350        Ok(())
351    }
352
353    /// Returns the REST API base URL, respecting environment and overrides.
354    #[must_use]
355    pub fn rest_url(&self) -> String {
356        self.base_url_rest.as_ref().map_or_else(
357            || urls::rest_url(self.environment).to_string(),
358            |url| url.expose_secret().to_string(),
359        )
360    }
361
362    /// Returns the WebSocket URL, respecting environment and overrides.
363    #[must_use]
364    pub fn ws_url(&self) -> String {
365        self.base_url_ws.as_ref().map_or_else(
366            || urls::ws_url(self.environment).to_string(),
367            |url| url.expose_secret().to_string(),
368        )
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use nautilus_common::config::ConfigError;
375    use nautilus_core::string::secret::REDACTED;
376    use rstest::rstest;
377
378    use super::*;
379
380    #[rstest]
381    #[case::unset(None)]
382    #[case::empty(Some(vec![]))]
383    #[case::explicit(Some(vec![InstrumentId::from("ETH-PERP.DERIVE"), InstrumentId::from("BTC-PERP.DERIVE")]))]
384    fn test_load_ids_configuration_roundtrip(#[case] load_ids: Option<Vec<InstrumentId>>) {
385        let config = DeriveExecutionClientConfig {
386            max_fee_per_contract: Some(Decimal::ONE),
387            load_ids: load_ids.clone(),
388            ..Default::default()
389        };
390
391        config.validate().unwrap();
392        let encoded = serde_json::to_string(&config).unwrap();
393        let decoded: DeriveExecutionClientConfig = serde_json::from_str(&encoded).unwrap();
394        assert_eq!(decoded.load_ids, load_ids);
395    }
396
397    #[rstest]
398    #[case::duplicate(vec![InstrumentId::from("ETH-PERP.DERIVE"), InstrumentId::from("ETH-PERP.DERIVE")], "duplicate load_ids")]
399    #[case::other_venue(vec![InstrumentId::from("ETH-PERP.BINANCE")], "invalid load_ids: ETH-PERP.BINANCE is not a DERIVE instrument")]
400    fn test_load_ids_reject_invalid_selection(
401        #[case] load_ids: Vec<InstrumentId>,
402        #[case] expected: &str,
403    ) {
404        let config = DeriveExecutionClientConfig {
405            max_fee_per_contract: Some(Decimal::ONE),
406            load_ids: Some(load_ids),
407            ..Default::default()
408        };
409
410        assert_eq!(config.validate().unwrap_err().to_string(), expected);
411    }
412
413    #[rstest]
414    fn test_config_builders_accept_plain_strings() {
415        let data = DeriveDataClientConfig::builder()
416            .base_url_rest("https://literal-rest.example/data")
417            .base_url_ws("wss://literal-ws.example/data")
418            .proxy_url("http://literal-proxy.example")
419            .build();
420
421        let execution = DeriveExecutionClientConfig::builder()
422            .base_url_rest("https://owned-rest.example/execution".to_string())
423            .base_url_ws("wss://owned-ws.example/execution".to_string())
424            .proxy_url("http://owned-proxy.example".to_string())
425            .session_key("SESSION_KEY_SENTINEL".to_string())
426            .build();
427
428        assert_eq!(data.rest_url(), "https://literal-rest.example/data");
429        assert_eq!(data.ws_url(), "wss://literal-ws.example/data");
430        assert_eq!(
431            data.proxy_url.as_ref().map(SecretString::expose_secret),
432            Some("http://literal-proxy.example")
433        );
434        assert_eq!(execution.rest_url(), "https://owned-rest.example/execution");
435        assert_eq!(execution.ws_url(), "wss://owned-ws.example/execution");
436        assert_eq!(
437            execution
438                .proxy_url
439                .as_ref()
440                .map(SecretString::expose_secret),
441            Some("http://owned-proxy.example")
442        );
443        assert_eq!(
444            execution
445                .session_key
446                .as_ref()
447                .map(SecretString::expose_secret),
448            Some("SESSION_KEY_SENTINEL")
449        );
450    }
451
452    #[rstest]
453    #[case::credentials(
454        "https://REST_USER:REST_PASSWORD@rest.example:8443/REST_PATH?token=REST_QUERY#REST_FRAGMENT",
455        "wss://WS_USER:WS_PASSWORD@stream.example:9443/WS_PATH?token=WS_QUERY#WS_FRAGMENT"
456    )]
457    #[case::invalid("REST_PATH", "WS_PATH")]
458    #[case::unsupported("file:///REST_PATH", "file:///WS_PATH")]
459    fn test_config_debug_redacts_endpoint_overrides(#[case] rest: &str, #[case] ws: &str) {
460        let proxy = "http://PROXY_USER:PROXY_PASSWORD@proxy.example:8080";
461        let session_key = "SESSION_KEY_SENTINEL";
462
463        let data = DeriveDataClientConfig {
464            base_url_rest: Some(rest.into()),
465            base_url_ws: Some(ws.into()),
466            proxy_url: Some(proxy.into()),
467            ..Default::default()
468        };
469
470        let execution = DeriveExecutionClientConfig {
471            base_url_rest: Some(rest.into()),
472            base_url_ws: Some(ws.into()),
473            proxy_url: Some(proxy.into()),
474            session_key: Some(session_key.into()),
475            ..Default::default()
476        };
477
478        let data_roundtrip: DeriveDataClientConfig =
479            serde_json::from_value(serde_json::to_value(&data).unwrap()).unwrap();
480        let execution_roundtrip: DeriveExecutionClientConfig =
481            serde_json::from_value(serde_json::to_value(&execution).unwrap()).unwrap();
482
483        assert_eq!(data.rest_url(), rest);
484        assert_eq!(data.ws_url(), ws);
485        assert_eq!(execution.rest_url(), rest);
486        assert_eq!(execution.ws_url(), ws);
487        assert_eq!(
488            data_roundtrip
489                .base_url_rest
490                .as_ref()
491                .map(SecretString::expose_secret),
492            Some(rest)
493        );
494        assert_eq!(
495            data_roundtrip
496                .base_url_ws
497                .as_ref()
498                .map(SecretString::expose_secret),
499            Some(ws)
500        );
501        assert_eq!(
502            execution_roundtrip
503                .base_url_rest
504                .as_ref()
505                .map(SecretString::expose_secret),
506            Some(rest)
507        );
508        assert_eq!(
509            execution_roundtrip
510                .base_url_ws
511                .as_ref()
512                .map(SecretString::expose_secret),
513            Some(ws)
514        );
515
516        for debug in [format!("{data:?}"), format!("{execution:?}")] {
517            assert!(debug.contains(&format!("base_url_rest: Some({REDACTED})")));
518            assert!(debug.contains(&format!("base_url_ws: Some({REDACTED})")));
519            assert!(debug.contains(&format!("proxy_url: Some({REDACTED})")));
520        }
521
522        for debug in [
523            format!("{data:?}"),
524            format!("{data:#?}"),
525            format!("{execution:?}"),
526            format!("{execution:#?}"),
527        ] {
528            for marker in [
529                "rest.example",
530                "stream.example",
531                "REST_USER",
532                "REST_PASSWORD",
533                "REST_PATH",
534                "REST_QUERY",
535                "REST_FRAGMENT",
536                "WS_USER",
537                "WS_PASSWORD",
538                "WS_PATH",
539                "WS_QUERY",
540                "WS_FRAGMENT",
541                "PROXY_USER",
542                "PROXY_PASSWORD",
543                "proxy.example",
544                session_key,
545            ] {
546                assert!(!debug.contains(marker), "Debug disclosed {marker}");
547            }
548        }
549    }
550
551    #[rstest]
552    #[case("currencies")]
553    fn test_data_config_rejects_duplicate_selections(#[case] field: &str) {
554        let mut input = serde_json::to_value(DeriveDataClientConfig::default()).unwrap();
555        input[field] = serde_json::json!(["first", "second", "first"]);
556        let config: DeriveDataClientConfig = serde_json::from_value(input).unwrap();
557        let original = serde_json::to_value(&config).unwrap();
558        let result = config.validate();
559
560        assert_eq!(result, Err(ConfigError::duplicate(field, None)));
561        assert_eq!(serde_json::to_value(&config).unwrap(), original);
562    }
563
564    #[rstest]
565    fn test_data_config_defaults() {
566        let config = DeriveDataClientConfig::default();
567        assert_eq!(config.environment, DeriveEnvironment::Mainnet);
568        assert_eq!(config.http_timeout_secs, 10);
569        assert_eq!(config.ws_timeout_secs, None);
570        assert_eq!(config.update_instruments_interval_mins, 60);
571        assert!(config.currencies.is_empty());
572        assert!(!config.include_expired);
573        assert!(config.auto_load_missing_instruments);
574    }
575
576    #[rstest]
577    fn test_data_config_urls_mainnet() {
578        let config = DeriveDataClientConfig::default();
579        assert_eq!(config.rest_url(), "https://api.derive.xyz/v3");
580        assert_eq!(config.ws_url(), "wss://api.derive.xyz/v3/ws");
581    }
582
583    #[rstest]
584    fn test_data_config_urls_testnet() {
585        let config = DeriveDataClientConfig {
586            environment: DeriveEnvironment::Testnet,
587            ..DeriveDataClientConfig::default()
588        };
589
590        assert_eq!(config.rest_url(), "https://testnet.api.derive.xyz/v3");
591        assert_eq!(config.ws_url(), "wss://testnet.api.derive.xyz/v3/ws");
592    }
593
594    #[rstest]
595    #[case(
596        DeriveEnvironment::Mainnet,
597        "https://api.derive.xyz/v3",
598        "wss://api.derive.xyz/v3/ws"
599    )]
600    #[case(
601        DeriveEnvironment::Testnet,
602        "https://testnet.api.derive.xyz/v3",
603        "wss://testnet.api.derive.xyz/v3/ws"
604    )]
605    fn test_exec_config_urls(
606        #[case] environment: DeriveEnvironment,
607        #[case] rest: &str,
608        #[case] ws: &str,
609    ) {
610        let config = DeriveExecutionClientConfig {
611            environment,
612            ..DeriveExecutionClientConfig::default()
613        };
614
615        assert_eq!(config.rest_url(), rest);
616        assert_eq!(config.ws_url(), ws);
617    }
618
619    #[rstest]
620    #[case(DeriveEnvironment::Mainnet)]
621    #[case(DeriveEnvironment::Testnet)]
622    fn test_config_url_overrides(#[case] environment: DeriveEnvironment) {
623        let rest = "https://dedicated.example.com";
624        let ws = "wss://dedicated.example.com/ws";
625
626        let data = DeriveDataClientConfig {
627            environment,
628            base_url_rest: Some(rest.into()),
629            base_url_ws: Some(ws.into()),
630            ..DeriveDataClientConfig::default()
631        };
632
633        let execution = DeriveExecutionClientConfig {
634            environment,
635            base_url_rest: Some(rest.into()),
636            base_url_ws: Some(ws.into()),
637            ..DeriveExecutionClientConfig::default()
638        };
639
640        assert_eq!(data.rest_url(), rest);
641        assert_eq!(data.ws_url(), ws);
642        assert_eq!(execution.rest_url(), rest);
643        assert_eq!(execution.ws_url(), ws);
644    }
645
646    #[rstest]
647    fn test_exec_config_defaults() {
648        let config = DeriveExecutionClientConfig::default();
649        assert!(!config.cancel_on_disconnect);
650        assert_eq!(config.environment, DeriveEnvironment::Mainnet);
651        assert_eq!(config.http_timeout_secs, 10);
652        assert_eq!(config.max_retries, 3);
653        assert!(config.max_matching_requests_per_second.is_none());
654        assert!(
655            config
656                .max_per_instrument_matching_requests_per_second
657                .is_none()
658        );
659        assert!(!config.has_credentials());
660    }
661
662    #[rstest]
663    #[case::enabled_maximum(true, 900, true)]
664    #[case::enabled_too_long(true, 901, false)]
665    #[case::disabled_long_expiry(false, 901, true)]
666    fn test_exec_config_cancel_on_disconnect_signature_expiry(
667        #[case] enabled: bool,
668        #[case] expiry_secs: u64,
669        #[case] valid: bool,
670    ) {
671        let config = DeriveExecutionClientConfig::builder()
672            .cancel_on_disconnect(enabled)
673            .signature_expiry_secs(expiry_secs)
674            .max_fee_per_contract(Decimal::ONE)
675            .build();
676        let result = config.validate();
677        let decoded: DeriveExecutionClientConfig =
678            serde_json::from_value(serde_json::to_value(&config).unwrap()).unwrap();
679
680        assert_eq!(decoded.cancel_on_disconnect, enabled);
681        assert_eq!(decoded.signature_expiry_secs, expiry_secs);
682        assert_eq!(result.is_ok(), valid);
683
684        if !valid {
685            assert_eq!(
686                result.unwrap_err().to_string(),
687                "cancel_on_disconnect requires signature_expiry_secs at most 900 seconds"
688            );
689        }
690    }
691
692    #[rstest]
693    fn test_exec_config_has_credentials_requires_all_three_fields() {
694        let mut config = DeriveExecutionClientConfig {
695            wallet_address: Some("0x1234".to_string()),
696            ..DeriveExecutionClientConfig::default()
697        };
698
699        assert!(!config.has_credentials());
700
701        config.session_key = Some("0xabcd".into());
702        assert!(!config.has_credentials());
703
704        config.subaccount_id = Some(1);
705        assert!(config.has_credentials());
706    }
707
708    #[rstest]
709    fn test_exec_config_has_credentials_rejects_blank_strings() {
710        let config = DeriveExecutionClientConfig {
711            wallet_address: Some("   ".to_string()),
712            session_key: Some("0xabcd".into()),
713            subaccount_id: Some(1),
714            ..DeriveExecutionClientConfig::default()
715        };
716
717        assert!(!config.has_credentials());
718    }
719
720    #[rstest]
721    fn test_exec_config_debug_redacts_session_key() {
722        // Use a low-entropy sentinel rather than a hex private key so the
723        // assertion exercises Debug-redaction without tripping the secrets
724        // scanner on a synthetic test value. The redaction logic is
725        // string-content-agnostic.
726        let session_key = "FAKE_SESSION_KEY_SENTINEL";
727
728        let config = DeriveExecutionClientConfig {
729            wallet_address: Some("0xWALLET".to_string()),
730            session_key: Some(session_key.into()),
731            subaccount_id: Some(42),
732            ..DeriveExecutionClientConfig::default()
733        };
734
735        let debug = format!("{config:?}");
736        assert!(debug.contains("redacted"));
737        assert!(!debug.contains(session_key));
738        assert!(debug.contains("0xWALLET"));
739        assert!(debug.contains("42"));
740    }
741
742    #[rstest]
743    fn test_exec_config_debug_omits_session_key_marker_when_unset() {
744        let config = DeriveExecutionClientConfig::default();
745        let debug = format!("{config:?}");
746        assert!(!debug.contains("redacted"));
747        assert!(debug.contains("session_key: None"));
748    }
749
750    #[rstest]
751    #[case::trimmed(vec!["BTC", "ETH", " BTC "], true)]
752    #[case::blank(vec!["", ""], true)]
753    #[case::distinct(vec![" ETH ", "BTC"], false)]
754    fn test_currencies_normalized_uniqueness(#[case] values: Vec<&str>, #[case] duplicate: bool) {
755        let currencies: Vec<_> = values.into_iter().map(str::to_string).collect();
756
757        let config = DeriveDataClientConfig {
758            currencies: currencies.clone(),
759            ..Default::default()
760        };
761
762        let expected = if duplicate {
763            Err(ConfigError::duplicate("currencies", None))
764        } else {
765            Ok(())
766        };
767
768        let result = config.validate();
769        assert_eq!(result, expected);
770        assert_eq!(config.currencies, currencies);
771    }
772}