godark 0.2.0

Rust SDK for GoDark DEX — encrypted trading over WebSocket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
// Client configuration — builder pattern for GodarkClient

use std::collections::HashMap;
use std::env;
use std::time::Duration;

use uuid::Uuid;

use crate::error::GodarkError;

/// Default edge base URL (host only). The transport appends `/ws/v1` at
/// connect time.
///
/// Public mainnet is not currently exposed; testnet is the live network for
/// SDK users today and is the SDK default. For local development, override
/// to a localnet edge (`ws://127.0.0.1:13300`) via [`Environment::Localnet`],
/// the `base_url` builder, `GODARK_EDGE_URL`, or `GDX_EDGE_URL`. Either
/// `<host>` or `<host>/ws/v1` resolve to the same endpoint.
const DEFAULT_EDGE_BASE_URL: &str = "wss://api.godark-dex.com";
const DEVNET_EDGE_BASE_URL: &str = "wss://api.devnet.godark-dex.com";
const LOCALNET_EDGE_BASE_URL: &str = "ws://127.0.0.1:13300";

/// Sequencer HPKE static public key for public testnet (64 hex).
const TESTNET_HPKE_STATIC_PUBLIC_KEY_HEX: &str =
    "a9fdd7f26c0de36d82811e9fe1df2509960cd5b25eef037355e209b9222bea7d";

/// Sequencer HPKE static public key for public devnet (64 hex).
const DEVNET_HPKE_STATIC_PUBLIC_KEY_HEX: &str =
    "a6807e2f6cd04b54cc19be2fd4faea2a1239f1e2896912d91222678ab54cdd45";

const DEFAULT_SYMBOLS_JSON: &str = include_str!("../shared/symbols.json");

/// Named deployment target. Selects the default edge / REST URL and, when known,
/// a baked-in sequencer HPKE public key pin.
///
/// Explicit `.base_url(...)` / `.hpke_static_public_key_hex(...)` and env vars
/// still win over these presets. Localnet has no baked pin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Environment {
    /// Public testnet (`wss://api.godark-dex.com`).
    #[default]
    Testnet,
    /// Public devnet (`wss://api.devnet.godark-dex.com`).
    Devnet,
    /// Local `gdx up` edge (`ws://127.0.0.1:13300`).
    Localnet,
}

impl Environment {
    /// Default edge base URL for this environment (host only).
    #[must_use]
    pub const fn edge_base_url(self) -> &'static str {
        match self {
            Self::Testnet => DEFAULT_EDGE_BASE_URL,
            Self::Devnet => DEVNET_EDGE_BASE_URL,
            Self::Localnet => LOCALNET_EDGE_BASE_URL,
        }
    }

    /// Default REST base URL for this environment.
    #[must_use]
    pub const fn rest_base_url(self) -> &'static str {
        match self {
            Self::Testnet => "https://api.godark-dex.com",
            Self::Devnet => "https://api.devnet.godark-dex.com",
            Self::Localnet => "http://127.0.0.1:13300",
        }
    }

    /// Sequencer HPKE static public key (64 hex) when baked in for this environment.
    ///
    /// Testnet and Devnet return a pin; Localnet returns `None` (set via builder or env).
    #[must_use]
    pub const fn hpke_static_public_key_hex(self) -> Option<&'static str> {
        match self {
            Self::Testnet => Some(TESTNET_HPKE_STATIC_PUBLIC_KEY_HEX),
            Self::Devnet => Some(DEVNET_HPKE_STATIC_PUBLIC_KEY_HEX),
            Self::Localnet => None,
        }
    }
}

/// Tunable WebSocket transport (TLS verify, headers, timeouts).
#[derive(Debug, Clone)]
pub struct TransportConfig {
    /// When `true`, accept invalid TLS certificates (dev only; not for production).
    pub tls_skip_verify: bool,
    pub extra_headers: HashMap<String, String>,
    pub connect_timeout: Duration,
    pub command_timeout: Duration,
    /// No inbound message for this duration triggers disconnect (see transport heartbeat).
    pub stale_timeout: Duration,
    pub heartbeat_interval: Duration,
}

impl Default for TransportConfig {
    fn default() -> Self {
        Self {
            tls_skip_verify: false,
            extra_headers: HashMap::new(),
            connect_timeout: Duration::from_secs(30),
            command_timeout: Duration::from_secs(30),
            stale_timeout: Duration::from_secs(60),
            heartbeat_interval: Duration::from_secs(30),
        }
    }
}

/// Resolved configuration for a GodarkClient.
///
/// Construct via [`GodarkConfigBuilder`]. New fields are `pub(crate)` so
/// external struct-literal construction is not required to keep pace.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GodarkConfig {
    pub auth_token: String,
    pub base_url: String,
    pub auto_reconnect: bool,
    pub symbol_map: HashMap<String, u64>,
    pub transport: TransportConfig,
    /// Pre-configured user UUID. When the edge auth response does not include
    /// `user_uuid`, the SDK falls back to this value.  Resolved from
    /// `.user_uuid()` builder call or `GODARK_USER_UUID` / `GDX_USER_UUID`.
    pub user_uuid: Option<Uuid>,
    /// Pinned sequencer HPKE static X25519 public key (64 hex).
    /// From `.hpke_static_public_key_hex()`, `GDX_HPKE_STATIC_PUBLIC_KEY`, or Environment preset.
    pub hpke_static_public_key_hex: Option<String>,
    /// How long [`Confirmation::Book`](crate::types::Confirmation::Book)
    /// waits for an OPEN/reject/fill/cancel update after the fast ack.
    /// Always positive; use [`Confirmation::Ack`](crate::types::Confirmation::Ack)
    /// to skip waiting. Set via
    /// [`GodarkConfigBuilder::place_order_terminal_timeout`].
    pub(crate) place_order_terminal_timeout: Duration,
    /// When true, caller supplied custom symbols via builder; skip edge fetch.
    pub(crate) explicit_symbol_map: bool,
}

impl GodarkConfig {
    /// Timeout used when `place_order` confirmation is [`Confirmation::Book`](crate::types::Confirmation::Book).
    #[must_use]
    pub fn place_order_terminal_timeout(&self) -> Duration {
        self.place_order_terminal_timeout
    }
}

/// Builder for GodarkClient configuration.
pub struct GodarkConfigBuilder {
    api_key: Option<String>,
    api_key_id: Option<String>,
    api_secret: Option<String>,
    passphrase: Option<String>,
    base_url: Option<String>,
    environment: Environment,
    auto_reconnect: bool,
    symbol_map: HashMap<String, u64>,
    transport: TransportConfig,
    user_uuid: Option<Uuid>,
    hpke_static_public_key_hex: Option<String>,
    place_order_terminal_timeout: Option<Duration>,
    explicit_symbol_map: bool,
}

impl GodarkConfigBuilder {
    pub fn new() -> Self {
        let symbols: HashMap<String, u64> =
            serde_json::from_str(DEFAULT_SYMBOLS_JSON).expect("default symbols.json must be valid");

        Self {
            api_key: None,
            api_key_id: None,
            api_secret: None,
            passphrase: None,
            base_url: None,
            environment: Environment::Testnet,
            auto_reconnect: true,
            symbol_map: symbols,
            transport: TransportConfig::default(),
            user_uuid: None,
            hpke_static_public_key_hex: None,
            place_order_terminal_timeout: None,
            explicit_symbol_map: false,
        }
    }

    /// Select a named deployment. Defaults to [`Environment::Testnet`].
    pub fn environment(mut self, environment: Environment) -> Self {
        self.environment = environment;
        self
    }

    pub fn transport(mut self, transport: TransportConfig) -> Self {
        self.transport = transport;
        self
    }

    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    pub fn api_key_id(mut self, id: impl Into<String>) -> Self {
        self.api_key_id = Some(id.into());
        self
    }

    pub fn api_secret(mut self, secret: impl Into<String>) -> Self {
        self.api_secret = Some(secret.into());
        self
    }

    /// User-chosen API key passphrase (required with key pair; also reads
    /// `GODARK_PASSPHRASE` / `GDX_PASSPHRASE`).
    pub fn passphrase(mut self, pp: impl Into<String>) -> Self {
        self.passphrase = Some(pp.into());
        self
    }

    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    pub fn auto_reconnect(mut self, enabled: bool) -> Self {
        self.auto_reconnect = enabled;
        self
    }

    /// How long book confirmation waits after the fast ack (must be > 0).
    /// Defaults to the transport `command_timeout`.
    pub fn place_order_terminal_timeout(mut self, timeout: Duration) -> Self {
        self.place_order_terminal_timeout = Some(timeout);
        self
    }

    /// Set the user UUID explicitly. Required when the edge auth response does
    /// not return `user_uuid` (e.g. localnet / static-key auth). Falls back to
    /// `GODARK_USER_UUID` / `GDX_USER_UUID` environment variables at build time.
    pub fn user_uuid(mut self, uuid: impl Into<String>) -> Self {
        self.user_uuid = Uuid::parse_str(&uuid.into()).ok();
        self
    }

    /// Pin the sequencer HPKE static X25519 public key (64 hex characters).
    pub fn hpke_static_public_key_hex(mut self, key: impl Into<String>) -> Self {
        self.hpke_static_public_key_hex = Some(key.into());
        self
    }

    pub fn symbol(mut self, name: impl Into<String>, id: u64) -> Self {
        self.explicit_symbol_map = true;
        self.symbol_map.insert(name.into(), id);
        self
    }

    pub fn build(self) -> Result<GodarkConfig, GodarkError> {
        let auth_token = match (self.api_key_id, self.api_secret, self.api_key) {
            (Some(id), Some(secret), None) => {
                let pp = resolve_passphrase(self.passphrase.as_deref()).ok_or_else(|| {
                    GodarkError::Config(
                        "passphrase is required when using api_key_id and api_secret".into(),
                    )
                })?;
                format!("{id}:{secret}:{pp}")
            }
            (None, None, Some(key)) => {
                if self
                    .passphrase
                    .as_ref()
                    .is_some_and(|pp| !pp.trim().is_empty())
                {
                    return Err(GodarkError::Config(
                        "passphrase must not be set when using legacy api_key".into(),
                    ));
                }
                key
            }
            (Some(_), None, _) | (None, Some(_), _) => {
                return Err(GodarkError::Config(
                    "api_key_id and api_secret must be provided together".into(),
                ));
            }
            (Some(_), Some(_), Some(_)) => {
                return Err(GodarkError::Config(
                    "use either api_key or (api_key_id, api_secret), not both".into(),
                ));
            }
            (None, None, None) => {
                return Err(GodarkError::Config(
                    "provide api_key or both api_key_id and api_secret".into(),
                ));
            }
        };

        let base_url = resolve_edge_base_url_with_default(
            self.base_url.as_deref(),
            self.environment.edge_base_url(),
        );

        let user_uuid = self.user_uuid.or_else(resolve_user_uuid_env);
        let environment = self.environment;
        let pin_env = if self
            .base_url
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .is_some()
        {
            infer_environment_from_edge_url(&base_url)
        } else {
            environment
        };
        let hpke_static_public_key_hex = self
            .hpke_static_public_key_hex
            .or_else(resolve_hpke_static_public_key_env)
            .or_else(|| pin_env.hpke_static_public_key_hex().map(str::to_string));

        let place_order_terminal_timeout = self
            .place_order_terminal_timeout
            .unwrap_or(self.transport.command_timeout);
        if place_order_terminal_timeout.is_zero() {
            return Err(GodarkError::Config(
                "place_order_terminal_timeout must be greater than zero".into(),
            ));
        }
        Ok(GodarkConfig {
            auth_token,
            base_url,
            auto_reconnect: self.auto_reconnect,
            symbol_map: self.symbol_map,
            transport: self.transport,
            user_uuid,
            hpke_static_public_key_hex,
            place_order_terminal_timeout,
            explicit_symbol_map: self.explicit_symbol_map,
        })
    }
}

impl Default for GodarkConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

fn infer_environment_from_edge_url(base: &str) -> Environment {
    let mut host = base.trim().to_ascii_lowercase();
    for prefix in ["https://", "http://", "wss://", "ws://"] {
        if let Some(rest) = host.strip_prefix(prefix) {
            host = rest.to_string();
            break;
        }
    }
    if let Some(i) = host.find('/') {
        host.truncate(i);
    }
    if let Some(i) = host.find(':') {
        host.truncate(i);
    }
    if host == "127.0.0.1" || host == "localhost" || host.ends_with(".localhost") {
        return Environment::Localnet;
    }
    if host.contains("devnet") {
        return Environment::Devnet;
    }
    if host.contains("godark-dex.com") {
        return Environment::Testnet;
    }
    Environment::Testnet
}

/// Resolve passphrase: constructor arg wins, then env vars.
pub fn resolve_passphrase(explicit: Option<&str>) -> Option<String> {
    if let Some(v) = explicit {
        let trimmed = v.trim();
        if !trimmed.is_empty() {
            return Some(trimmed.to_string());
        }
    }
    for key in &["GODARK_PASSPHRASE", "GDX_PASSPHRASE"] {
        if let Ok(v) = env::var(key) {
            let trimmed = v.trim().to_string();
            if !trimmed.is_empty() {
                return Some(trimmed);
            }
        }
    }
    None
}

/// Resolve user UUID from `GODARK_USER_UUID` or `GDX_USER_UUID` environment variables.
fn resolve_user_uuid_env() -> Option<Uuid> {
    for key in &["GODARK_USER_UUID", "GDX_USER_UUID"] {
        if let Ok(v) = env::var(key) {
            if let Ok(u) = Uuid::parse_str(v.trim()) {
                return Some(u);
            }
        }
    }
    None
}

fn resolve_hpke_static_public_key_env() -> Option<String> {
    for key in &[
        "GDX_HPKE_STATIC_PUBLIC_KEY",
        "GDX_HPKE_STATIC_PUBKEY",
        "GODARK_HPKE_STATIC_PUBLIC_KEY",
        "VITE_GDX_HPKE_STATIC_PUBKEY",
    ] {
        if let Ok(value) = env::var(key) {
            let value = value.trim();
            if !value.is_empty() {
                return Some(value.to_string());
            }
        }
    }
    None
}

#[cfg(test)]
fn resolve_edge_base_url(explicit: Option<&str>) -> String {
    resolve_edge_base_url_with_default(explicit, DEFAULT_EDGE_BASE_URL)
}

/// Resolve edge base URL: explicit arg > env vars > `default`.
fn resolve_edge_base_url_with_default(explicit: Option<&str>, default: &str) -> String {
    if let Some(url) = explicit {
        let trimmed = url.trim();
        if !trimmed.is_empty() {
            return trimmed.to_string();
        }
    }
    for key in &["GODARK_EDGE_URL", "GDX_EDGE_URL"] {
        if let Ok(v) = env::var(key) {
            let trimmed = v.trim().to_string();
            if !trimmed.is_empty() {
                return trimmed;
            }
        }
    }
    default.to_string()
}

/// Resolve a base URL to the canonical edge WebSocket endpoint `<base>/ws/v1`.
///
/// Trailing slashes are stripped first, then:
/// - if the input already ends with `/ws/v1` it is returned unchanged;
/// - if the input ends with the legacy `/ws` suffix it is upgraded to `/ws/v1`;
/// - otherwise `/ws/v1` is appended.
pub(crate) fn ws_url(base_url: &str) -> String {
    let url = base_url.trim_end_matches('/');
    if url.ends_with("/ws/v1") {
        url.to_string()
    } else if let Some(stripped) = url.strip_suffix("/ws") {
        format!("{stripped}/ws/v1")
    } else {
        format!("{url}/ws/v1")
    }
}

/// Construct the GoMarket WebSocket URL from a base URL.
///
/// Strips a trailing `/ws/v1` or legacy `/ws` suffix from the base before
/// appending `/ws/gomarket`, so that any of `<host>`, `<host>/ws`, or
/// `<host>/ws/v1` resolve to `<host>/ws/gomarket`.
pub(crate) fn gomarket_url(base_url: &str) -> String {
    let mut url = base_url.trim_end_matches('/').to_string();
    if let Some(stripped) = url.strip_suffix("/ws/v1") {
        url = stripped.to_string();
    } else if let Some(stripped) = url.strip_suffix("/ws") {
        url = stripped.to_string();
    }
    format!("{url}/ws/gomarket")
}

/// True when the resolved URL is the public-docs `/ws/v1` path (ignores trailing slash / query).
pub fn is_docs_wire_url(url: &str) -> bool {
    let cut = url.split(['?', '#']).next().unwrap_or(url);
    cut.trim_end_matches('/').ends_with("/ws/v1")
}

fn env_first(keys: &[&str]) -> Option<String> {
    for key in keys {
        if let Ok(v) = env::var(key) {
            let trimmed = v.trim().to_string();
            if !trimmed.is_empty() {
                return Some(trimmed);
            }
        }
    }
    None
}

fn env_truthy(keys: &[&str]) -> bool {
    for key in keys {
        if let Ok(v) = env::var(key) {
            let raw = v.trim().to_lowercase();
            if matches!(raw.as_str(), "1" | "true" | "yes" | "on") {
                return true;
            }
        }
    }
    false
}

/// Resolve the market-data WebSocket URL.
///
/// Hosted edges default to `/ws/v1`. Override with `GODARK_MARKET_DATA_WS_URL`,
/// or set `GODARK_MARKET_DATA_USE_GOMARKET=1` for `/ws/gomarket`.
pub fn resolve_market_data_ws_url(base_url: &str) -> String {
    if let Some(override_url) = env_first(&["GODARK_MARKET_DATA_WS_URL", "GDX_MARKET_DATA_WS_URL"])
    {
        return override_url;
    }
    if env_truthy(&[
        "GODARK_MARKET_DATA_USE_GOMARKET",
        "GDX_MARKET_DATA_USE_GOMARKET",
    ]) {
        return gomarket_url(base_url.trim());
    }
    ws_url(base_url.trim())
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::Mutex;

    use super::{
        gomarket_url, resolve_edge_base_url, resolve_passphrase, ws_url, Environment,
        GodarkConfigBuilder, GodarkError,
    };

    /// Serialize tests that mutate process environment variables.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn test_builder_api_key_pair() {
        let cfg = GodarkConfigBuilder::new()
            .api_key_id("id")
            .api_secret("secret")
            .passphrase("pp")
            .build()
            .unwrap();
        assert_eq!(cfg.auth_token, "id:secret:pp");
    }

    #[test]
    fn test_builder_api_key_pair_requires_passphrase() {
        let _guard = ENV_LOCK.lock().unwrap();
        let old_g = std::env::var("GODARK_PASSPHRASE").ok();
        let old_x = std::env::var("GDX_PASSPHRASE").ok();
        std::env::remove_var("GODARK_PASSPHRASE");
        std::env::remove_var("GDX_PASSPHRASE");

        let err = GodarkConfigBuilder::new()
            .api_key_id("id")
            .api_secret("secret")
            .build()
            .unwrap_err();
        assert!(matches!(err, GodarkError::Config(ref msg) if msg.contains("passphrase")));

        if let Some(v) = old_g {
            std::env::set_var("GODARK_PASSPHRASE", v);
        } else {
            std::env::remove_var("GODARK_PASSPHRASE");
        }
        if let Some(v) = old_x {
            std::env::set_var("GDX_PASSPHRASE", v);
        } else {
            std::env::remove_var("GDX_PASSPHRASE");
        }
    }

    #[test]
    fn test_builder_legacy_rejects_passphrase() {
        let err = GodarkConfigBuilder::new()
            .api_key("k")
            .passphrase("pp")
            .build()
            .unwrap_err();
        assert!(matches!(err, GodarkError::Config(ref msg) if msg.contains("passphrase")));
    }

    #[test]
    fn test_builder_api_key_pair_passphrase_from_env() {
        let _guard = ENV_LOCK.lock().unwrap();
        let old_g = std::env::var("GODARK_PASSPHRASE").ok();
        let old_x = std::env::var("GDX_PASSPHRASE").ok();
        std::env::remove_var("GODARK_PASSPHRASE");
        std::env::set_var("GDX_PASSPHRASE", "env-pp");

        let cfg = GodarkConfigBuilder::new()
            .api_key_id("id")
            .api_secret("secret")
            .build()
            .unwrap();
        assert_eq!(cfg.auth_token, "id:secret:env-pp");

        if let Some(v) = old_g {
            std::env::set_var("GODARK_PASSPHRASE", v);
        } else {
            std::env::remove_var("GODARK_PASSPHRASE");
        }
        if let Some(v) = old_x {
            std::env::set_var("GDX_PASSPHRASE", v);
        } else {
            std::env::remove_var("GDX_PASSPHRASE");
        }
    }

    #[test]
    fn test_resolve_passphrase_prefers_constructor() {
        let _guard = ENV_LOCK.lock().unwrap();
        std::env::set_var("GDX_PASSPHRASE", "from-env");
        assert_eq!(
            resolve_passphrase(Some("explicit")),
            Some("explicit".into())
        );
        std::env::remove_var("GDX_PASSPHRASE");
    }

    #[test]
    fn test_resolve_passphrase_from_godark_env() {
        let _guard = ENV_LOCK.lock().unwrap();
        std::env::set_var("GODARK_PASSPHRASE", "godark-pw");
        std::env::set_var("GDX_PASSPHRASE", "gdx-pw");
        assert_eq!(resolve_passphrase(None), Some("godark-pw".into()));
        std::env::remove_var("GODARK_PASSPHRASE");
        std::env::remove_var("GDX_PASSPHRASE");
    }

    #[test]
    fn test_builder_place_order_terminal_timeout_default() {
        let cfg = GodarkConfigBuilder::new().api_key("k").build().unwrap();
        assert_eq!(
            cfg.place_order_terminal_timeout(),
            cfg.transport.command_timeout
        );
    }

    #[test]
    fn test_builder_place_order_terminal_timeout_custom() {
        use std::time::Duration;
        let cfg = GodarkConfigBuilder::new()
            .api_key("k")
            .place_order_terminal_timeout(Duration::from_secs(5))
            .build()
            .unwrap();
        assert_eq!(cfg.place_order_terminal_timeout(), Duration::from_secs(5));
    }

    #[test]
    fn test_builder_legacy_api_key() {
        let cfg = GodarkConfigBuilder::new().api_key("mykey").build().unwrap();
        assert_eq!(cfg.auth_token, "mykey");
    }

    #[test]
    fn test_builder_both_auth_modes_errors() {
        let err = GodarkConfigBuilder::new()
            .api_key("k")
            .api_key_id("id")
            .api_secret("secret")
            .build()
            .unwrap_err();
        assert!(matches!(err, GodarkError::Config(ref msg) if msg.contains("not both")));
    }

    #[test]
    fn test_builder_no_auth_errors() {
        let err = GodarkConfigBuilder::new().build().unwrap_err();
        assert!(matches!(err, GodarkError::Config(ref msg) if msg.contains("provide api_key")));
    }

    #[test]
    fn test_builder_incomplete_pair_errors() {
        let err = GodarkConfigBuilder::new()
            .api_key_id("id")
            .build()
            .unwrap_err();
        assert!(matches!(err, GodarkError::Config(ref msg) if msg.contains("together")));
    }

    #[test]
    fn test_builder_default_symbols() {
        let cfg = GodarkConfigBuilder::new().api_key("k").build().unwrap();
        assert_eq!(cfg.symbol_map.get("BTC-USDC-PERP"), Some(&1));
        assert_eq!(cfg.symbol_map.get("ETH-USDC-PERP"), Some(&2));
        // SOL is id 5 in prod (id 3 is BNB); see new-sdks parity audit.
        assert_eq!(cfg.symbol_map.get("SOL-USDC-PERP"), Some(&5));
    }

    #[test]
    fn test_default_symbols_from_shared_json() {
        let raw: HashMap<String, u64> =
            serde_json::from_str(super::DEFAULT_SYMBOLS_JSON).expect("parse");
        assert_eq!(raw.len(), 3);
    }

    #[test]
    fn test_builder_custom_symbol() {
        let cfg = GodarkConfigBuilder::new()
            .api_key("k")
            .symbol("DOGE-USDC-PERP", 8)
            .build()
            .unwrap();
        assert_eq!(cfg.symbol_map.get("DOGE-USDC-PERP"), Some(&8));
    }

    #[test]
    fn test_builder_auto_reconnect_default() {
        let cfg = GodarkConfigBuilder::new().api_key("k").build().unwrap();
        assert!(cfg.auto_reconnect);
    }

    #[test]
    fn test_builder_default_environment_uses_baked_hpke_pin() {
        let _guard = ENV_LOCK.lock().unwrap();
        for key in [
            "GDX_HPKE_STATIC_PUBLIC_KEY",
            "GDX_HPKE_STATIC_PUBKEY",
            "GODARK_HPKE_STATIC_PUBLIC_KEY",
            "VITE_GDX_HPKE_STATIC_PUBKEY",
            "GODARK_EDGE_URL",
            "GDX_EDGE_URL",
        ] {
            std::env::remove_var(key);
        }

        let cfg = GodarkConfigBuilder::new()
            .api_key_id("id")
            .api_secret("secret")
            .passphrase("pp")
            .build()
            .unwrap();
        assert_eq!(cfg.base_url, "wss://api.godark-dex.com");
        assert_eq!(
            cfg.hpke_static_public_key_hex.as_deref(),
            Some(super::TESTNET_HPKE_STATIC_PUBLIC_KEY_HEX)
        );
    }

    #[test]
    fn test_builder_devnet_url_and_baked_hpke_pin() {
        let _guard = ENV_LOCK.lock().unwrap();
        for key in [
            "GDX_HPKE_STATIC_PUBLIC_KEY",
            "GDX_HPKE_STATIC_PUBKEY",
            "GODARK_HPKE_STATIC_PUBLIC_KEY",
            "VITE_GDX_HPKE_STATIC_PUBKEY",
            "GODARK_EDGE_URL",
            "GDX_EDGE_URL",
        ] {
            std::env::remove_var(key);
        }

        let cfg = GodarkConfigBuilder::new()
            .environment(Environment::Devnet)
            .api_key_id("id")
            .api_secret("secret")
            .passphrase("pp")
            .build()
            .unwrap();
        assert_eq!(cfg.base_url, "wss://api.devnet.godark-dex.com");
        assert_eq!(
            cfg.hpke_static_public_key_hex.as_deref(),
            Some(super::DEVNET_HPKE_STATIC_PUBLIC_KEY_HEX)
        );
    }

    #[test]
    fn test_builder_localnet_has_no_baked_hpke_pin() {
        let _guard = ENV_LOCK.lock().unwrap();
        for key in [
            "GDX_HPKE_STATIC_PUBLIC_KEY",
            "GODARK_EDGE_URL",
            "GDX_EDGE_URL",
        ] {
            std::env::remove_var(key);
        }

        let cfg = GodarkConfigBuilder::new()
            .environment(Environment::Localnet)
            .api_key_id("id")
            .api_secret("secret")
            .passphrase("pp")
            .build()
            .unwrap();
        assert_eq!(cfg.base_url, "ws://127.0.0.1:13300");
        assert_eq!(cfg.hpke_static_public_key_hex, None);
    }

    #[test]
    fn test_builder_explicit_hpke_pin() {
        let cfg = GodarkConfigBuilder::new()
            .environment(Environment::Testnet)
            .hpke_static_public_key_hex("11".repeat(32))
            .api_key_id("id")
            .api_secret("secret")
            .passphrase("pp")
            .build()
            .unwrap();
        assert_eq!(
            cfg.hpke_static_public_key_hex.as_deref(),
            Some("1111111111111111111111111111111111111111111111111111111111111111")
        );
    }

    #[test]
    fn test_builder_env_hpke_overrides_environment_preset() {
        let _guard = ENV_LOCK.lock().unwrap();
        for key in [
            "GDX_HPKE_STATIC_PUBLIC_KEY",
            "GDX_HPKE_STATIC_PUBKEY",
            "GODARK_HPKE_STATIC_PUBLIC_KEY",
            "VITE_GDX_HPKE_STATIC_PUBKEY",
            "GODARK_EDGE_URL",
            "GDX_EDGE_URL",
        ] {
            std::env::remove_var(key);
        }
        let env_pin = "22".repeat(32);
        std::env::set_var("GDX_HPKE_STATIC_PUBLIC_KEY", &env_pin);

        let cfg = GodarkConfigBuilder::new()
            .environment(Environment::Testnet)
            .api_key_id("id")
            .api_secret("secret")
            .passphrase("pp")
            .build()
            .unwrap();
        assert_eq!(
            cfg.hpke_static_public_key_hex.as_deref(),
            Some(env_pin.as_str())
        );

        std::env::remove_var("GDX_HPKE_STATIC_PUBLIC_KEY");
    }

    #[test]
    fn test_resolve_edge_base_url_explicit() {
        assert_eq!(
            resolve_edge_base_url(Some("wss://custom.example")),
            "wss://custom.example"
        );
    }

    #[test]
    fn test_resolve_edge_base_url_default() {
        let _guard = ENV_LOCK.lock().unwrap();
        let old_godark = std::env::var("GODARK_EDGE_URL").ok();
        let old_gdx = std::env::var("GDX_EDGE_URL").ok();
        std::env::remove_var("GODARK_EDGE_URL");
        std::env::remove_var("GDX_EDGE_URL");

        assert_eq!(resolve_edge_base_url(None), "wss://api.godark-dex.com");

        if let Some(v) = old_godark {
            std::env::set_var("GODARK_EDGE_URL", v);
        }
        if let Some(v) = old_gdx {
            std::env::set_var("GDX_EDGE_URL", v);
        }
    }

    #[test]
    fn test_ws_url_appends_ws() {
        assert_eq!(ws_url("wss://example.com"), "wss://example.com/ws/v1");
    }

    #[test]
    fn test_ws_url_no_double_ws() {
        assert_eq!(ws_url("wss://example.com/ws"), "wss://example.com/ws/v1");
    }

    #[test]
    fn test_ws_url_idempotent_v1() {
        assert_eq!(ws_url("wss://x.com/ws/v1"), "wss://x.com/ws/v1");
    }

    #[test]
    fn test_ws_url_trailing_slash_v1() {
        assert_eq!(ws_url("wss://x.com/ws/v1/"), "wss://x.com/ws/v1");
    }

    #[test]
    fn test_gomarket_url_strips_ws() {
        assert_eq!(
            gomarket_url("wss://example.com/ws"),
            "wss://example.com/ws/gomarket"
        );
    }

    #[test]
    fn test_gomarket_url_strips_ws_v1() {
        assert_eq!(gomarket_url("wss://x.com/ws/v1"), "wss://x.com/ws/gomarket");
    }

    #[test]
    fn test_gomarket_url_plain() {
        assert_eq!(
            gomarket_url("wss://example.com"),
            "wss://example.com/ws/gomarket"
        );
    }
}