Skip to main content

nautilus_lighter/
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 Lighter adapter.
17//!
18//! The default environment is mainnet. Deployment and environment select the credential namespace
19//! and protocol settings as well as endpoint defaults. URL overrides change only transport.
20//!
21//! Fields follow this order:
22//!
23//! - Environment
24//! - Deployment
25//! - Nautilus identity
26//! - Authentication
27//! - Connectivity
28//! - Operational behavior
29
30use nautilus_core::string::secret::SecretString;
31use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
32use nautilus_model::{
33    identifiers::{AccountId, Venue},
34    types::Currency,
35};
36use nautilus_network::websocket::{TransportBackend, proxy::ProxyUrl};
37use serde::{Deserialize, Deserializer, Serialize};
38
39use crate::common::{
40    consts::{
41        SCHEDULED_CANCEL_CLOCK_HEADROOM_SECS, SCHEDULED_CANCEL_MAX_DELAY_SECS,
42        SCHEDULED_CANCEL_MIN_DELAY_SECS, SCHEDULED_CANCEL_REQUEST_TIMEOUT,
43    },
44    credential::credential_env_vars_for_deployment,
45    deployment,
46    enums::{LighterDeployment, LighterEnvironment},
47};
48
49const WS_READONLY_QUERY_PARAM: &str = "readonly";
50
51/// Configuration for the Lighter data client.
52#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
53#[serde(default, deny_unknown_fields)]
54#[cfg_attr(
55    feature = "python",
56    pyo3::pyclass(module = "nautilus_trader.adapters.lighter", from_py_object,)
57)]
58#[cfg_attr(
59    feature = "python",
60    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.lighter")
61)]
62pub struct LighterDataClientConfig {
63    /// Target environment within the selected deployment.
64    #[builder(default)]
65    pub environment: LighterEnvironment,
66    /// Lighter protocol deployment, which controls endpoint defaults and protocol settings.
67    #[builder(default)]
68    pub deployment: LighterDeployment,
69    /// Optional Nautilus venue identifier override.
70    ///
71    /// This scopes instruments, cache entries, and message routing without changing the
72    /// deployment's signing or settlement settings.
73    pub venue: Option<Venue>,
74    /// Optional account index retained for config compatibility.
75    /// Public data requests do not use credentials.
76    pub account_index: Option<u64>,
77    /// Optional API key index retained for config compatibility.
78    /// Public data requests do not use credentials.
79    pub api_key_index: Option<u8>,
80    /// Optional private key retained for config compatibility.
81    /// Public data requests do not use credentials.
82    pub private_key: Option<SecretString>,
83    /// Optional REST URL override.
84    pub base_url_http: Option<String>,
85    /// Optional WebSocket URL override. The client enforces `readonly=true`.
86    /// Different resolved data and execution URLs use separate control-message limiters.
87    pub base_url_ws: Option<String>,
88    /// Optional absolute HTTP or HTTPS proxy URL for both transports, including its scheme.
89    #[serde(deserialize_with = "deserialize_proxy_url")]
90    pub proxy_url: Option<SecretString>,
91    /// HTTP request timeout in seconds.
92    #[builder(default = 60)]
93    pub http_timeout_secs: u64,
94    /// WebSocket connection and reconnection timeout in seconds.
95    #[builder(default = 30)]
96    pub ws_timeout_secs: u64,
97    /// Refresh interval for instrument metadata in minutes. Set to 0 to disable refresh.
98    #[builder(default = 60)]
99    pub update_instruments_interval_mins: u64,
100    /// Maximum time to wait for an initial, post-reconnect, or recovery order book
101    /// snapshot in seconds.
102    ///
103    /// Set to 0 to disable snapshot deadlines.
104    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
105    pub book_snapshot_timeout_secs: u64,
106    /// Optional REST read-bucket quota in requests per minute. `None` or 0 uses 60.
107    /// Each client has its own limiter; budget combined data and execution traffic.
108    /// Raising the quota requires venue IP registration and does not authenticate public data.
109    pub rest_quota_per_min: Option<u32>,
110    /// WebSocket transport backend.
111    #[builder(default)]
112    pub transport_backend: TransportBackend,
113}
114
115#[cfg(feature = "python")]
116nautilus_core::impl_pyo3_config_getters!(LighterDataClientConfig {
117    environment: LighterEnvironment,
118    deployment: LighterDeployment,
119    venue: Option<Venue>,
120    account_index: Option<u64>,
121    api_key_index: Option<u8>,
122    base_url_http: Option<String>,
123    base_url_ws: Option<String>,
124    http_timeout_secs: u64,
125    ws_timeout_secs: u64,
126    update_instruments_interval_mins: u64,
127    book_snapshot_timeout_secs: u64,
128    rest_quota_per_min: Option<u32>,
129    transport_backend: TransportBackend,
130});
131
132impl Default for LighterDataClientConfig {
133    fn default() -> Self {
134        Self::builder().build()
135    }
136}
137
138impl LighterDataClientConfig {
139    /// Creates a new configuration with default settings.
140    #[must_use]
141    pub fn new() -> Self {
142        Self::default()
143    }
144
145    /// Returns the resolved REST base URL.
146    #[must_use]
147    pub fn http_url(&self) -> String {
148        self.base_url_http.clone().unwrap_or_else(|| {
149            deployment::http_base_url(self.deployment, self.environment).to_string()
150        })
151    }
152
153    /// Returns the resolved WebSocket URL.
154    #[must_use]
155    pub fn ws_url(&self) -> String {
156        let url = self
157            .base_url_ws
158            .clone()
159            .unwrap_or_else(|| deployment::ws_url(self.deployment, self.environment).to_string());
160
161        ensure_readonly_ws_url(url)
162    }
163
164    /// Returns the configured venue or the deployment default.
165    #[must_use]
166    pub fn resolved_venue(&self) -> Venue {
167        self.venue
168            .unwrap_or_else(|| deployment::venue(self.deployment))
169    }
170
171    /// Returns the deployment settlement currency.
172    #[must_use]
173    pub fn settlement_currency(&self) -> Currency {
174        deployment::settlement_currency(self.deployment)
175    }
176
177    /// Returns `true` when all credential fields are present in config or the selected environment.
178    ///
179    /// This checks presence without validating credentials. Public data requests do not use them.
180    #[must_use]
181    pub fn has_credentials(&self) -> bool {
182        credentials_available(
183            self.private_key.as_ref(),
184            self.account_index,
185            self.api_key_index,
186            self.deployment,
187            self.environment,
188        )
189    }
190}
191
192fn ensure_readonly_ws_url(url: String) -> String {
193    let Ok(mut parsed) = url::Url::parse(&url) else {
194        return url;
195    };
196
197    let pairs = parsed
198        .query_pairs()
199        .filter(|(key, _)| key != WS_READONLY_QUERY_PARAM)
200        .map(|(key, value)| (key.into_owned(), value.into_owned()))
201        .collect::<Vec<_>>();
202
203    parsed.set_query(None);
204    {
205        let mut query = parsed.query_pairs_mut();
206        for (key, value) in pairs {
207            query.append_pair(&key, &value);
208        }
209        query.append_pair(WS_READONLY_QUERY_PARAM, "true");
210    }
211
212    parsed.to_string()
213}
214
215/// Configuration for the Lighter execution client.
216#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
217#[serde(default, deny_unknown_fields)]
218#[cfg_attr(
219    feature = "python",
220    pyo3::pyclass(module = "nautilus_trader.adapters.lighter", from_py_object,)
221)]
222#[cfg_attr(
223    feature = "python",
224    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.lighter")
225)]
226pub struct LighterExecutionClientConfig {
227    /// Target environment within the selected deployment.
228    #[builder(default)]
229    pub environment: LighterEnvironment,
230    /// Lighter protocol deployment, which controls endpoint defaults and protocol settings.
231    #[builder(default)]
232    pub deployment: LighterDeployment,
233    /// Optional Nautilus venue identifier override.
234    ///
235    /// This scopes instruments, cache entries, and execution routing without changing the
236    /// deployment's signing, settlement, or protocol behavior.
237    /// Use underscores instead of hyphens so the account ID issuer can match.
238    #[serde(deserialize_with = "deserialize_execution_venue")]
239    pub venue: Option<Venue>,
240    /// Account identifier on the venue. Its issuer must match the resolved venue.
241    /// Rust defaults to `LIGHTER-001`; override it for Robinhood or a custom venue.
242    /// Python requires an explicit account ID.
243    #[builder(default = AccountId::from("LIGHTER-001"))]
244    pub account_id: AccountId,
245    /// Lighter account index (numeric, assigned at registration). Falls back
246    /// to the environment variable selected by `deployment` and `environment`.
247    pub account_index: Option<u64>,
248    /// API key index for a user-created Lighter key. Low indexes are reserved
249    /// for Lighter clients; 255 is the `apikeys` all-keys sentinel. Falls back
250    /// to the environment variable selected by `deployment` and `environment`.
251    pub api_key_index: Option<u8>,
252    /// Hex-encoded private key for the API key (Schnorr / ecgfp5). Falls back
253    /// to the environment variable selected by `deployment` and `environment`.
254    pub private_key: Option<SecretString>,
255    /// Optional REST URL override.
256    pub base_url_http: Option<String>,
257    /// Optional WebSocket URL override. URLs containing `readonly=true` are rejected because
258    /// the query parameter does not prevent authenticated trading.
259    #[serde(deserialize_with = "deserialize_execution_ws_url")]
260    pub base_url_ws: Option<String>,
261    /// Optional absolute HTTP or HTTPS proxy URL for both transports, including its scheme.
262    #[serde(deserialize_with = "deserialize_proxy_url")]
263    pub proxy_url: Option<SecretString>,
264    /// HTTP request timeout in seconds.
265    #[builder(default = 60)]
266    pub http_timeout_secs: u64,
267    /// WebSocket connection and reconnection timeout in seconds.
268    #[builder(default = 30)]
269    pub ws_timeout_secs: u64,
270    /// Slippage buffer in basis points for market-style orders, in `[0, 10_000)`.
271    /// Per-order `market_order_slippage_bps` overrides must be integers in the same range;
272    /// invalid values cause local denial before signing or dispatch.
273    #[builder(default = 50)]
274    #[serde(deserialize_with = "deserialize_market_order_slippage_bps")]
275    pub market_order_slippage_bps: u32,
276    /// Optional REST read-bucket quota in requests per minute. `None` or 0 uses 60.
277    /// Raising the quota requires venue IP registration. Each client has its own limiter;
278    /// Standard accounts must budget combined REST and transaction traffic.
279    pub rest_quota_per_min: Option<u32>,
280    /// Optional transaction quota (req/min), independent of `rest_quota_per_min`.
281    /// `None` or 0 uses 60. HTTP and WebSocket sends share this limiter, including trading,
282    /// startup integrator approval, and scheduled cancellation. Low quotas can delay arming
283    /// and renewal; Standard accounts must budget combined REST and transaction traffic.
284    pub sendtx_quota_per_min: Option<u32>,
285    /// WebSocket transport backend.
286    #[builder(default)]
287    pub transport_backend: TransportBackend,
288    /// Whether to use Lighter-native GTD orders.
289    ///
290    /// The current Lighter venue validation requires a `GoodTillTime` expiry of at least five
291    /// minutes, so a shorter strategy GTD lifetime cannot be represented as an explicit venue
292    /// expiry. Set to false only when the strategy manages GTD expiry locally. Lighter then uses
293    /// a 28-day fallback expiry and the strategy must enable `manage_gtd_expiry` so the local
294    /// expiry timer sends the cancel. Local strategy expiries beyond 28 days are denied because
295    /// the fallback would expire first; use native GTD for those orders.
296    #[builder(default = true)]
297    pub use_gtd: bool,
298    /// Arms and renews account-wide scheduled cancellation with this timeout in seconds.
299    ///
300    /// Valid values are `[420, 1_295_940]`. `None` leaves the venue schedule untouched.
301    /// Connection fails if arming does not execute within 30 seconds after account streams are ready.
302    /// Shutdown stops renewal and preserves the last deadline. Scheduled cancellation does not close positions.
303    #[serde(deserialize_with = "deserialize_scheduled_cancel_timeout")]
304    pub scheduled_cancel_timeout_secs: Option<u64>,
305}
306
307#[cfg(feature = "python")]
308nautilus_core::impl_pyo3_config_getters!(LighterExecutionClientConfig {
309    environment: LighterEnvironment,
310    deployment: LighterDeployment,
311    venue: Option<Venue>,
312    account_id: AccountId,
313    account_index: Option<u64>,
314    api_key_index: Option<u8>,
315    base_url_http: Option<String>,
316    base_url_ws: Option<String>,
317    http_timeout_secs: u64,
318    ws_timeout_secs: u64,
319    market_order_slippage_bps: u32,
320    rest_quota_per_min: Option<u32>,
321    sendtx_quota_per_min: Option<u32>,
322    transport_backend: TransportBackend,
323    use_gtd: bool,
324    scheduled_cancel_timeout_secs: Option<u64>,
325});
326
327impl Default for LighterExecutionClientConfig {
328    fn default() -> Self {
329        Self::builder().build()
330    }
331}
332
333impl LighterExecutionClientConfig {
334    /// Returns `true` when all credential fields are present in config or the selected environment.
335    ///
336    /// This checks presence without validating credentials. Client construction validates
337    /// the resolved account index, API key index, and private key.
338    #[must_use]
339    pub fn has_credentials(&self) -> bool {
340        credentials_available(
341            self.private_key.as_ref(),
342            self.account_index,
343            self.api_key_index,
344            self.deployment,
345            self.environment,
346        )
347    }
348
349    /// Returns the resolved REST base URL.
350    #[must_use]
351    pub fn http_url(&self) -> String {
352        self.base_url_http.clone().unwrap_or_else(|| {
353            deployment::http_base_url(self.deployment, self.environment).to_string()
354        })
355    }
356
357    /// Returns the resolved WebSocket URL.
358    #[must_use]
359    pub fn ws_url(&self) -> String {
360        self.base_url_ws
361            .clone()
362            .unwrap_or_else(|| deployment::ws_url(self.deployment, self.environment).to_string())
363    }
364
365    /// Returns the configured venue or the deployment default.
366    #[must_use]
367    pub fn resolved_venue(&self) -> Venue {
368        self.venue
369            .unwrap_or_else(|| deployment::venue(self.deployment))
370    }
371
372    /// Returns the deployment settlement currency.
373    #[must_use]
374    pub fn settlement_currency(&self) -> Currency {
375        deployment::settlement_currency(self.deployment)
376    }
377
378    /// Returns the L2 signing-domain chain ID for the deployment and environment.
379    #[must_use]
380    pub const fn chain_id(&self) -> u32 {
381        deployment::chain_id(self.deployment, self.environment)
382    }
383}
384
385fn credentials_available(
386    private_key: Option<&SecretString>,
387    account_index: Option<u64>,
388    api_key_index: Option<u8>,
389    deployment: LighterDeployment,
390    environment: LighterEnvironment,
391) -> bool {
392    let (key_var, secret_var, account_var) =
393        credential_env_vars_for_deployment(deployment, environment);
394    let has_key = api_key_index.is_some() || env_var_is_set(key_var);
395    let has_account = account_index.is_some() || env_var_is_set(account_var);
396    let has_secret = private_key
397        .map(SecretString::expose_secret)
398        .is_some_and(|s| !s.trim().is_empty())
399        || env_var_is_set(secret_var);
400
401    has_key && has_account && has_secret
402}
403
404fn env_var_is_set(name: &str) -> bool {
405    std::env::var(name).is_ok_and(|value| !value.trim().is_empty())
406}
407
408fn deserialize_proxy_url<'de, D: Deserializer<'de>>(
409    deserializer: D,
410) -> Result<Option<SecretString>, D::Error> {
411    let value = Option::<SecretString>::deserialize(deserializer)?;
412    validate_proxy_url(value.as_ref()).map_err(serde::de::Error::custom)?;
413    Ok(value)
414}
415
416pub(crate) fn validate_proxy_url(value: Option<&SecretString>) -> anyhow::Result<()> {
417    if let Some(value) = value {
418        ProxyUrl::parse(value.expose_secret()).map_err(|_| {
419            anyhow::anyhow!(
420                "Lighter proxy_url must be an absolute http:// or https:// URL with a host"
421            )
422        })?;
423    }
424
425    Ok(())
426}
427
428fn deserialize_execution_venue<'de, D: Deserializer<'de>>(
429    deserializer: D,
430) -> Result<Option<Venue>, D::Error> {
431    let value = Option::<Venue>::deserialize(deserializer)?;
432    validate_execution_venue(value).map_err(serde::de::Error::custom)?;
433    Ok(value)
434}
435
436pub(crate) fn validate_execution_venue(value: Option<Venue>) -> anyhow::Result<()> {
437    anyhow::ensure!(
438        value.is_none_or(|venue| !venue.as_str().contains('-')),
439        "Lighter execution venue must not contain '-'; use '_' so the account ID issuer can match"
440    );
441    Ok(())
442}
443
444fn deserialize_execution_ws_url<'de, D: Deserializer<'de>>(
445    deserializer: D,
446) -> Result<Option<String>, D::Error> {
447    let value = Option::<String>::deserialize(deserializer)?;
448    validate_execution_ws_url(value.as_deref()).map_err(serde::de::Error::custom)?;
449    Ok(value)
450}
451
452pub(crate) fn validate_execution_ws_url(value: Option<&str>) -> anyhow::Result<()> {
453    if let Some(value) = value.and_then(|value| url::Url::parse(value).ok()) {
454        anyhow::ensure!(
455            !value.query_pairs().any(|(key, value)| {
456                key.eq_ignore_ascii_case(WS_READONLY_QUERY_PARAM)
457                    && value.trim().eq_ignore_ascii_case("true")
458            }),
459            "Lighter execution WebSocket URL must not set readonly=true; it does not disable trading"
460        );
461    }
462
463    Ok(())
464}
465
466fn deserialize_market_order_slippage_bps<'de, D: Deserializer<'de>>(
467    deserializer: D,
468) -> Result<u32, D::Error> {
469    let value = u32::deserialize(deserializer)?;
470    validate_market_order_slippage_bps(value).map_err(serde::de::Error::custom)?;
471    Ok(value)
472}
473
474pub(crate) fn validate_market_order_slippage_bps(value: u32) -> anyhow::Result<()> {
475    anyhow::ensure!(
476        value < 10_000,
477        "Lighter market_order_slippage_bps must be in [0, 10000)"
478    );
479    Ok(())
480}
481
482fn deserialize_scheduled_cancel_timeout<'de, D: Deserializer<'de>>(
483    deserializer: D,
484) -> Result<Option<u64>, D::Error> {
485    let timeout = Option::<u64>::deserialize(deserializer)?;
486    validate_scheduled_cancel_timeout(timeout).map_err(serde::de::Error::custom)?;
487    Ok(timeout)
488}
489
490pub(crate) fn validate_scheduled_cancel_timeout(timeout_secs: Option<u64>) -> anyhow::Result<()> {
491    let min = SCHEDULED_CANCEL_MIN_DELAY_SECS
492        + SCHEDULED_CANCEL_CLOCK_HEADROOM_SECS
493        + 2 * SCHEDULED_CANCEL_REQUEST_TIMEOUT.as_secs();
494    let max = SCHEDULED_CANCEL_MAX_DELAY_SECS - SCHEDULED_CANCEL_CLOCK_HEADROOM_SECS;
495
496    if let Some(timeout_secs) = timeout_secs {
497        anyhow::ensure!(
498            (min..=max).contains(&timeout_secs),
499            "scheduled_cancel_timeout_secs must be in [{min}, {max}]"
500        );
501    }
502
503    Ok(())
504}
505
506#[cfg(test)]
507mod tests {
508    use nautilus_core::string::secret::REDACTED;
509    use rstest::rstest;
510
511    use super::*;
512
513    const PRIVATE_KEY_HEX: &str =
514        "0b8e0f63c24d8baacd9d29ad4e9a4b73c4a8d2bb8b16dc4fa9d7c2e1d3a8b1f0e8d3a4c5b6e7f001";
515
516    #[rstest]
517    #[case(None, true)]
518    #[case(Some("http://127.0.0.1:8080"), true)]
519    #[case(Some("https://fixture:proxy-secret@proxy.example:8443"), true)]
520    #[case(Some("127.0.0.1:8080"), false)]
521    #[case(Some("socks5://127.0.0.1:1080"), false)]
522    #[case(Some("http://fixture:proxy-secret@[::1"), false)]
523    fn test_proxy_url_requires_shared_transport_support(
524        #[case] value: Option<&str>,
525        #[case] valid: bool,
526    ) {
527        let json = serde_json::json!({"proxy_url": value});
528        let data = serde_json::from_value::<LighterDataClientConfig>(json.clone());
529        let execution = serde_json::from_value::<LighterExecutionClientConfig>(json);
530
531        if valid {
532            assert_eq!(
533                data.unwrap()
534                    .proxy_url
535                    .as_ref()
536                    .map(SecretString::expose_secret),
537                value
538            );
539            assert_eq!(
540                execution
541                    .unwrap()
542                    .proxy_url
543                    .as_ref()
544                    .map(SecretString::expose_secret),
545                value
546            );
547        } else {
548            let expected =
549                "Lighter proxy_url must be an absolute http:// or https:// URL with a host";
550            assert_eq!(data.unwrap_err().to_string(), expected);
551            assert_eq!(execution.unwrap_err().to_string(), expected);
552        }
553    }
554
555    #[rstest]
556    #[case(None, true)]
557    #[case(Some("LIGHTER_ALT"), true)]
558    #[case(Some("LIGHTER-ALT"), false)]
559    fn test_execution_venue_requires_representable_account_issuer(
560        #[case] value: Option<&str>,
561        #[case] valid: bool,
562    ) {
563        let json = serde_json::json!({"venue": value});
564        let data: LighterDataClientConfig = serde_json::from_value(json.clone()).unwrap();
565        let execution = serde_json::from_value::<LighterExecutionClientConfig>(json);
566        assert_eq!(
567            data.venue.map(|venue| venue.to_string()),
568            value.map(str::to_string)
569        );
570
571        if valid {
572            assert_eq!(execution.unwrap().venue, data.venue);
573        } else {
574            assert_eq!(
575                execution.unwrap_err().to_string(),
576                "Lighter execution venue must not contain '-'; use '_' so the account ID issuer can match"
577            );
578        }
579    }
580
581    #[rstest]
582    #[case(None, true)]
583    #[case(Some("wss://example.com/stream"), true)]
584    #[case(Some("wss://example.com/stream?readonly=false"), true)]
585    #[case(Some("wss://example.com/stream?readonly=true"), false)]
586    #[case(Some("wss://example.com/stream?readonly=false&readonly=true"), false)]
587    #[case(Some("wss://example.com/stream?read%6Fnly=tr%75e"), false)]
588    #[case(Some("wss://example.com/stream?ReadOnly=%20TRUE%20"), false)]
589    fn test_execution_ws_url_rejects_misleading_readonly_query(
590        #[case] value: Option<&str>,
591        #[case] valid: bool,
592    ) {
593        let json = serde_json::json!({"base_url_ws": value});
594        let data: LighterDataClientConfig = serde_json::from_value(json.clone()).unwrap();
595        let execution = serde_json::from_value::<LighterExecutionClientConfig>(json);
596        assert_eq!(data.base_url_ws.as_deref(), value);
597
598        if valid {
599            assert_eq!(execution.unwrap().base_url_ws.as_deref(), value);
600        } else {
601            assert_eq!(
602                execution.unwrap_err().to_string(),
603                "Lighter execution WebSocket URL must not set readonly=true; it does not disable trading"
604            );
605        }
606    }
607
608    #[rstest]
609    #[case(0, true)]
610    #[case(9_999, true)]
611    #[case(10_000, false)]
612    #[case(u32::MAX, false)]
613    fn test_market_order_slippage_bps(#[case] value: u32, #[case] valid: bool) {
614        let decoded = serde_json::from_value::<LighterExecutionClientConfig>(serde_json::json!({
615            "market_order_slippage_bps": value,
616        }));
617
618        if valid {
619            assert_eq!(decoded.unwrap().market_order_slippage_bps, value);
620        } else {
621            assert_eq!(
622                decoded.unwrap_err().to_string(),
623                "Lighter market_order_slippage_bps must be in [0, 10000)"
624            );
625        }
626    }
627
628    #[rstest]
629    #[case(None, true)]
630    #[case(Some(0), false)]
631    #[case(Some(15), false)]
632    #[case(Some(419), false)]
633    #[case(Some(420), true)]
634    #[case(Some(1_295_940), true)]
635    #[case(Some(1_295_941), false)]
636    #[case(Some(u64::MAX), false)]
637    fn test_scheduled_cancel_timeout(#[case] timeout: Option<u64>, #[case] valid: bool) {
638        let config = LighterExecutionClientConfig {
639            scheduled_cancel_timeout_secs: timeout,
640            ..Default::default()
641        };
642
643        let encoded = serde_json::to_value(&config).unwrap();
644        assert_eq!(
645            encoded["scheduled_cancel_timeout_secs"],
646            serde_json::json!(timeout)
647        );
648        let decoded = serde_json::from_value::<LighterExecutionClientConfig>(encoded);
649        assert_eq!(decoded.is_ok(), valid);
650
651        if valid {
652            assert_eq!(decoded.unwrap().scheduled_cancel_timeout_secs, timeout);
653        }
654    }
655
656    #[rstest]
657    fn test_scheduled_cancel_timeout_default() {
658        assert_eq!(
659            LighterExecutionClientConfig::default().scheduled_cancel_timeout_secs,
660            None
661        );
662        let decoded: LighterExecutionClientConfig =
663            serde_json::from_value(serde_json::json!({})).unwrap();
664        assert_eq!(decoded.scheduled_cancel_timeout_secs, None);
665    }
666
667    #[rstest]
668    fn data_config_has_credentials_when_all_fields_set() {
669        let config = LighterDataClientConfig {
670            api_key_index: Some(5),
671            account_index: Some(12_345),
672            private_key: Some(PRIVATE_KEY_HEX.into()),
673            ..Default::default()
674        };
675
676        assert!(config.has_credentials());
677    }
678
679    #[rstest]
680    fn data_config_debug_redacts_private_key() {
681        let config = LighterDataClientConfig {
682            api_key_index: Some(5),
683            account_index: Some(12_345),
684            private_key: Some(PRIVATE_KEY_HEX.into()),
685            ..Default::default()
686        };
687
688        let dbg_out = format!("{config:?}");
689
690        assert!(dbg_out.contains(REDACTED));
691        assert!(!dbg_out.contains(PRIVATE_KEY_HEX));
692    }
693
694    #[rstest]
695    fn data_config_debug_omits_private_key_when_unset() {
696        let config = LighterDataClientConfig::default();
697
698        let dbg_out = format!("{config:?}");
699
700        assert!(dbg_out.contains("private_key: None"));
701    }
702
703    #[rstest]
704    fn data_config_ws_url_sets_readonly_query() {
705        let config = LighterDataClientConfig::default();
706
707        assert_eq!(
708            config.ws_url(),
709            "wss://mainnet.zklighter.elliot.ai/stream?readonly=true",
710        );
711    }
712
713    #[rstest]
714    fn data_config_ws_url_preserves_existing_query_params() {
715        let config = LighterDataClientConfig {
716            base_url_ws: Some("wss://mainnet.zklighter.elliot.ai/stream?foo=bar".to_string()),
717            ..Default::default()
718        };
719
720        assert_eq!(
721            config.ws_url(),
722            "wss://mainnet.zklighter.elliot.ai/stream?foo=bar&readonly=true",
723        );
724    }
725
726    #[rstest]
727    fn data_config_ws_url_overrides_readonly_query() {
728        let config = LighterDataClientConfig {
729            base_url_ws: Some(
730                "wss://mainnet.zklighter.elliot.ai/stream?readonly=false&foo=bar".to_string(),
731            ),
732            ..Default::default()
733        };
734
735        assert_eq!(
736            config.ws_url(),
737            "wss://mainnet.zklighter.elliot.ai/stream?foo=bar&readonly=true",
738        );
739    }
740
741    #[rstest]
742    fn data_config_book_snapshot_timeout_default_is_ten_seconds() {
743        let config = LighterDataClientConfig::default();
744
745        assert_eq!(config.book_snapshot_timeout_secs, 10);
746    }
747
748    #[derive(Debug)]
749    struct ExpectedDeploymentSettings {
750        http_url: &'static str,
751        data_ws_url: &'static str,
752        chain_id: u32,
753        venue: &'static str,
754        currency: &'static str,
755    }
756
757    #[rstest]
758    #[case::lighter_mainnet(
759        LighterDeployment::Lighter,
760        LighterEnvironment::Mainnet,
761        ExpectedDeploymentSettings {
762            http_url: "https://mainnet.zklighter.elliot.ai",
763            data_ws_url: "wss://mainnet.zklighter.elliot.ai/stream?readonly=true",
764            chain_id: 304,
765            venue: "LIGHTER",
766            currency: "USDC",
767        }
768    )]
769    #[case::lighter_testnet(
770        LighterDeployment::Lighter,
771        LighterEnvironment::Testnet,
772        ExpectedDeploymentSettings {
773            http_url: "https://testnet.zklighter.elliot.ai",
774            data_ws_url: "wss://testnet.zklighter.elliot.ai/stream?readonly=true",
775            chain_id: 300,
776            venue: "LIGHTER",
777            currency: "USDC",
778        }
779    )]
780    #[case::robinhood_mainnet(
781        LighterDeployment::Robinhood,
782        LighterEnvironment::Mainnet,
783        ExpectedDeploymentSettings {
784            http_url: "https://api.rh.lighter.xyz",
785            data_ws_url: "wss://api.rh.lighter.xyz/stream?readonly=true",
786            chain_id: 466_324,
787            venue: "LIGHTER_ROBINHOOD",
788            currency: "USDG",
789        }
790    )]
791    #[case::robinhood_testnet(
792        LighterDeployment::Robinhood,
793        LighterEnvironment::Testnet,
794        ExpectedDeploymentSettings {
795            http_url: "https://api.rh-testnet.lighter.xyz",
796            data_ws_url: "wss://api.rh-testnet.lighter.xyz/stream?readonly=true",
797            chain_id: 300,
798            venue: "LIGHTER_ROBINHOOD",
799            currency: "USDG",
800        }
801    )]
802    fn configs_resolve_deployment_settings(
803        #[case] deployment: LighterDeployment,
804        #[case] environment: LighterEnvironment,
805        #[case] expected: ExpectedDeploymentSettings,
806    ) {
807        let data = LighterDataClientConfig {
808            environment,
809            deployment,
810            ..Default::default()
811        };
812
813        let execution = LighterExecutionClientConfig {
814            environment,
815            deployment,
816            ..Default::default()
817        };
818
819        assert_eq!(data.http_url(), expected.http_url);
820        assert_eq!(data.ws_url(), expected.data_ws_url);
821        assert_eq!(data.resolved_venue().as_str(), expected.venue);
822        assert_eq!(data.settlement_currency().code, expected.currency);
823        assert_eq!(execution.http_url(), expected.http_url);
824        assert_eq!(
825            execution.ws_url(),
826            expected.data_ws_url.replace("?readonly=true", "")
827        );
828        assert_eq!(execution.resolved_venue().as_str(), expected.venue);
829        assert_eq!(execution.settlement_currency().code, expected.currency);
830        assert_eq!(execution.chain_id(), expected.chain_id);
831    }
832
833    #[rstest]
834    fn configs_preserve_custom_venue() {
835        let venue = Venue::from("LIGHTER_CUSTOM");
836        let data = LighterDataClientConfig {
837            deployment: LighterDeployment::Robinhood,
838            venue: Some(venue),
839            ..Default::default()
840        };
841
842        let execution = LighterExecutionClientConfig {
843            deployment: LighterDeployment::Robinhood,
844            venue: Some(venue),
845            ..Default::default()
846        };
847
848        assert_eq!(data.resolved_venue(), venue);
849        assert_eq!(execution.resolved_venue(), venue);
850        assert_eq!(execution.chain_id(), 466_324);
851    }
852
853    #[rstest]
854    fn exec_config_debug_redacts_private_key() {
855        let config = LighterExecutionClientConfig {
856            account_id: AccountId::from("LIGHTER-001"),
857            api_key_index: Some(5),
858            account_index: Some(12_345),
859            private_key: Some(PRIVATE_KEY_HEX.into()),
860            base_url_http: None,
861            base_url_ws: None,
862            proxy_url: None,
863            environment: LighterEnvironment::Mainnet,
864            deployment: LighterDeployment::Lighter,
865            venue: None,
866            http_timeout_secs: 60,
867            ws_timeout_secs: 30,
868            market_order_slippage_bps: 50,
869            rest_quota_per_min: None,
870            sendtx_quota_per_min: None,
871            transport_backend: TransportBackend::default(),
872            use_gtd: true,
873            scheduled_cancel_timeout_secs: None,
874        };
875
876        let dbg_out = format!("{config:?}");
877
878        assert!(dbg_out.contains(REDACTED));
879        assert!(!dbg_out.contains(PRIVATE_KEY_HEX));
880    }
881
882    #[rstest]
883    fn exec_config_use_gtd_defaults_to_true() {
884        // Backwards compatibility: the default preserves the native Lighter GTD
885        // behavior so existing configs are unchanged.
886        let config = LighterExecutionClientConfig::default();
887
888        assert!(config.use_gtd);
889    }
890
891    #[rstest]
892    fn exec_config_toml_use_gtd_override() {
893        let config: LighterExecutionClientConfig = toml::from_str("use_gtd = false").unwrap();
894
895        assert!(!config.use_gtd);
896    }
897
898    #[rstest]
899    fn exec_config_ws_url_keeps_regular_stream_url() {
900        let config = LighterExecutionClientConfig {
901            account_id: AccountId::from("LIGHTER-001"),
902            environment: LighterEnvironment::Mainnet,
903            ..Default::default()
904        };
905
906        assert_eq!(config.ws_url(), "wss://mainnet.zklighter.elliot.ai/stream");
907    }
908}