Skip to main content

nautilus_hyperliquid/websocket/
client.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
16use std::{
17    str::FromStr,
18    sync::{
19        Arc,
20        atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
21    },
22    time::Duration,
23};
24
25use ahash::{AHashMap, AHashSet};
26use anyhow::Context;
27use arc_swap::ArcSwap;
28use dashmap::DashMap;
29use nautilus_common::cache::{InstrumentLookupError, fifo::FifoCacheMap};
30#[cfg(test)]
31use nautilus_common::live::get_runtime;
32#[cfg(test)]
33use nautilus_core::string::secret::REDACTED;
34use nautilus_core::{AtomicMap, string::secret::SecretString};
35use nautilus_live::{
36    SocketControl,
37    book::snapshot::SnapshotGate,
38    task::{SharedTaskSlot, TaskGroupGuard, TaskJoinOutcome},
39};
40use nautilus_model::{
41    data::BarType,
42    enums::{OrderSide, OrderType, TimeInForce},
43    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
44    instruments::{Instrument, InstrumentAny},
45    orders::{Order, OrderAny},
46    reports::OrderStatusReport,
47    types::{Price, Quantity},
48};
49use nautilus_network::{
50    ConnectionUrl, SocketStateSink,
51    http::create_standard_nautilus_headers,
52    mode::ConnectionMode,
53    websocket::{
54        AuthTracker, SubscriptionState, TransportBackend, WebSocketClient, WebSocketConfig,
55        channel_message_handler,
56    },
57};
58use parking_lot::Mutex;
59use rust_decimal::Decimal;
60use serde::Deserialize;
61use tokio_util::sync::CancellationToken;
62use ustr::Ustr;
63
64use crate::{
65    common::{
66        consts::{HEARTBEAT_INTERVAL, HTTP_TIMEOUT, ws_url},
67        enums::{HyperliquidBarInterval, HyperliquidEnvironment},
68        parse::{
69            bar_type_to_interval, clamp_price_to_precision, derive_limit_from_trigger,
70            determine_order_list_grouping, extract_error_message, extract_inner_error,
71            extract_inner_errors, normalize_or_validate_wire_price,
72            order_to_hyperliquid_request_with_optional_decimals, round_to_sig_figs,
73            time_in_force_to_hyperliquid_tif,
74        },
75    },
76    http::{
77        client::HyperliquidHttpClient,
78        error::{Error as HyperliquidError, Result as HyperliquidResult},
79        models::{
80            HyperliquidExchangeAction, HyperliquidExchangeCancelByCloidRequest,
81            HyperliquidExchangeCancelOrderRequest, HyperliquidExchangeGrouping,
82            HyperliquidExchangeLimitParams, HyperliquidExchangeModifyOrderRequest,
83            HyperliquidExchangeModifyTarget, HyperliquidExchangeOrderKind,
84            HyperliquidExchangePlaceOrderRequest, HyperliquidExchangeResponse,
85            HyperliquidExchangeTif, HyperliquidExchangeTpSl, HyperliquidExchangeTriggerParams,
86            RESPONSE_STATUS_OK,
87        },
88        rate_limits::exec_action_weight,
89    },
90    websocket::{
91        book::{
92            BookStreamOptions, BookStreamRegistration, BookStreamRegistry, BookStreamRelease,
93            BookStreamUse,
94        },
95        enums::HyperliquidWsChannel,
96        error::HyperliquidWsError,
97        handler::{FeedHandler, HandlerCommand},
98        messages::{
99            NautilusWsMessage, PostRequest, PostResponse, PostResponsePayload, SubscriptionRequest,
100        },
101        post::{PostIds, PostRouter},
102        rate_limits::{WebSocketRateLimits, shared_websocket_limits},
103        trades::{TradeStreamRegistry, TradeStreamUse},
104    },
105};
106
107const RESPONSE_STATUS_ERR: &str = "err";
108
109static NEXT_WEBSOCKET_CLIENT_ID: AtomicU64 = AtomicU64::new(1);
110
111/// FIFO bound on the cloid -> `ClientOrderId` resolution cache so missed
112/// evictions self-recover (see GH-3972 cancel-replace drain path).
113pub(super) const CLOID_CACHE_CAPACITY: usize = 10_000;
114
115/// Shared cloid -> `ClientOrderId` cache used by the WS handler.
116pub(super) type CloidCache = Arc<Mutex<FifoCacheMap<Ustr, ClientOrderId, CLOID_CACHE_CAPACITY>>>;
117
118/// Represents the different data types available from asset context subscriptions.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub(super) enum AssetContextDataType {
121    MarkPrice,
122    IndexPrice,
123    FundingRate,
124    OpenInterest,
125}
126
127/// Hyperliquid WebSocket client.
128///
129/// Orchestrates WebSocket connection and subscriptions using a command-based architecture,
130/// where the inner FeedHandler owns the WebSocketClient and handles all I/O.
131#[derive(Debug)]
132pub struct HyperliquidWebSocketClient {
133    url: ConnectionUrl,
134    connection_mode: Arc<ArcSwap<AtomicU8>>,
135    signal: Arc<AtomicBool>,
136    cmd_tx: Arc<tokio::sync::RwLock<tokio::sync::mpsc::UnboundedSender<HandlerCommand>>>,
137    out_rx: Option<tokio::sync::mpsc::UnboundedReceiver<NautilusWsMessage>>,
138    auth_tracker: AuthTracker,
139    subscriptions: SubscriptionState,
140    book_streams: BookStreamRegistry,
141    trade_streams: TradeStreamRegistry,
142    trade_stream_lock: Arc<Mutex<()>>,
143    quote_streams: Arc<DashMap<Ustr, ()>>,
144    instruments: Arc<AtomicMap<Ustr, InstrumentAny>>,
145    cache_tx: Arc<Mutex<tokio::sync::mpsc::UnboundedSender<HandlerCommand>>>,
146    bar_types: Arc<AtomicMap<String, BarType>>,
147    asset_context_subs: Arc<DashMap<Ustr, AHashSet<AssetContextDataType>>>,
148    all_dex_asset_ctxs_instrument_ids: Arc<AtomicMap<Ustr, Vec<Option<InstrumentId>>>>,
149    cloid_cache: CloidCache,
150    post_router: Arc<PostRouter>,
151    post_ids: Arc<PostIds>,
152    rate_limits: Arc<WebSocketRateLimits>,
153    client_id: u64,
154    connection_permit: Arc<Mutex<Option<tokio::sync::OwnedSemaphorePermit>>>,
155    post_timeout: Duration,
156    task_handle: Arc<SharedTaskSlot<()>>,
157    connect_lock: Arc<tokio::sync::Mutex<()>>,
158    account_id: Option<AccountId>,
159    transport_backend: TransportBackend,
160    proxy_url: Option<SecretString>,
161    socket_sink: Option<SocketStateSink>,
162    socket_control: Option<SocketControl>,
163}
164
165impl Clone for HyperliquidWebSocketClient {
166    fn clone(&self) -> Self {
167        Self {
168            url: self.url.clone(),
169            connection_mode: Arc::clone(&self.connection_mode),
170            signal: Arc::clone(&self.signal),
171            cmd_tx: Arc::clone(&self.cmd_tx),
172            out_rx: None,
173            auth_tracker: self.auth_tracker.clone(),
174            subscriptions: self.subscriptions.clone(),
175            book_streams: self.book_streams.clone(),
176            trade_streams: self.trade_streams.clone(),
177            trade_stream_lock: Arc::clone(&self.trade_stream_lock),
178            quote_streams: Arc::clone(&self.quote_streams),
179            instruments: Arc::clone(&self.instruments),
180            cache_tx: Arc::clone(&self.cache_tx),
181            bar_types: Arc::clone(&self.bar_types),
182            asset_context_subs: Arc::clone(&self.asset_context_subs),
183            all_dex_asset_ctxs_instrument_ids: Arc::clone(&self.all_dex_asset_ctxs_instrument_ids),
184            cloid_cache: Arc::clone(&self.cloid_cache),
185            post_router: Arc::clone(&self.post_router),
186            post_ids: Arc::clone(&self.post_ids),
187            rate_limits: Arc::clone(&self.rate_limits),
188            client_id: self.client_id,
189            connection_permit: Arc::clone(&self.connection_permit),
190            post_timeout: self.post_timeout,
191            task_handle: Arc::clone(&self.task_handle),
192            connect_lock: Arc::clone(&self.connect_lock),
193            account_id: self.account_id,
194            transport_backend: self.transport_backend,
195            proxy_url: self.proxy_url.clone(),
196            socket_sink: self.socket_sink.clone(),
197            socket_control: self.socket_control.clone(),
198        }
199    }
200}
201
202impl HyperliquidWebSocketClient {
203    /// Creates a new Hyperliquid WebSocket client without connecting.
204    ///
205    /// If `url` is `None`, the appropriate URL will be determined from the `environment`:
206    /// - `Mainnet`: `wss://api.hyperliquid.xyz/ws`
207    /// - `Testnet`: `wss://api.hyperliquid-testnet.xyz/ws`
208    ///
209    /// The connection will be established when `connect()` is called.
210    pub fn new(
211        url: Option<String>,
212        environment: HyperliquidEnvironment,
213        account_id: Option<AccountId>,
214        transport_backend: TransportBackend,
215        proxy_url: Option<String>,
216    ) -> Self {
217        let url = url.unwrap_or_else(|| ws_url(environment).to_string());
218        let rate_limits = shared_websocket_limits(environment, &url, proxy_url.as_deref());
219        let connection_mode = Arc::new(ArcSwap::new(Arc::new(AtomicU8::new(
220            ConnectionMode::Closed as u8,
221        ))));
222        let (cmd_tx, _) = tokio::sync::mpsc::unbounded_channel();
223
224        Self {
225            url: url.into(),
226            connection_mode,
227            signal: Arc::new(AtomicBool::new(false)),
228            auth_tracker: AuthTracker::new(),
229            subscriptions: SubscriptionState::new(':'),
230            book_streams: BookStreamRegistry::default(),
231            trade_streams: TradeStreamRegistry::default(),
232            trade_stream_lock: Arc::new(Mutex::new(())),
233            quote_streams: Arc::new(DashMap::new()),
234            instruments: Arc::new(AtomicMap::new()),
235            cache_tx: Arc::new(Mutex::new(cmd_tx.clone())),
236            bar_types: Arc::new(AtomicMap::new()),
237            asset_context_subs: Arc::new(DashMap::new()),
238            all_dex_asset_ctxs_instrument_ids: Arc::new(AtomicMap::new()),
239            cloid_cache: Arc::new(Mutex::new(FifoCacheMap::new())),
240            post_router: PostRouter::with_inflight(Arc::clone(&rate_limits.post_slots)),
241            post_ids: Arc::new(PostIds::new(1)),
242            rate_limits,
243            client_id: NEXT_WEBSOCKET_CLIENT_ID.fetch_add(1, Ordering::Relaxed),
244            connection_permit: Arc::new(Mutex::new(None)),
245            post_timeout: HTTP_TIMEOUT,
246            cmd_tx: Arc::new(tokio::sync::RwLock::new(cmd_tx)),
247            out_rx: None,
248            task_handle: Arc::new(SharedTaskSlot::new()),
249            connect_lock: Arc::new(tokio::sync::Mutex::new(())),
250            account_id,
251            transport_backend,
252            proxy_url: proxy_url.map(SecretString::from),
253            socket_sink: None,
254            socket_control: None,
255        }
256    }
257
258    /// Configures socket state reporting for the underlying transport.
259    #[must_use]
260    pub fn with_state_sink(mut self, state_sink: SocketStateSink) -> Self {
261        self.socket_sink = Some(state_sink);
262        self
263    }
264
265    /// Configures state reporting and reconnect control for the underlying transport.
266    #[must_use]
267    pub(crate) fn with_socket_control(mut self, control: SocketControl) -> Self {
268        self.socket_control = Some(control);
269        self
270    }
271
272    /// Establishes the WebSocket connection and waits for the message handler to initialize.
273    pub async fn connect(&mut self) -> anyhow::Result<()> {
274        let connect_lock = Arc::clone(&self.connect_lock);
275        let _guard = connect_lock.lock().await;
276        self.connect_locked().await
277    }
278
279    async fn connect_locked(&mut self) -> anyhow::Result<()> {
280        if self.is_active() {
281            log::warn!("WebSocket already connected");
282            return Ok(());
283        }
284
285        if !self.task_handle.is_empty() {
286            self.disconnect_locked().await?;
287        }
288
289        if self.connection_permit.lock().is_none() {
290            let permit = Arc::clone(&self.rate_limits.connection_slots)
291                .try_acquire_owned()
292                .map_err(|_| {
293                    anyhow::anyhow!(
294                        "Hyperliquid allows at most {} WebSocket connections per route",
295                        crate::common::consts::HYPERLIQUID_WS_CONNECTIONS_MAX,
296                    )
297                })?;
298            *self.connection_permit.lock() = Some(permit);
299        }
300
301        // A fresh socket has no venue-side subscriptions; stale book stream
302        // entries must not gate the venue subscribe for re-subscriptions
303        self.book_streams.clear();
304
305        let (message_handler, raw_rx) = channel_message_handler();
306        let headers = create_standard_nautilus_headers();
307
308        let cfg = WebSocketConfig {
309            url: self.url.expose().to_owned(),
310            headers,
311            heartbeat_interval_secs: None,
312            heartbeat_payload: None,
313            connect_timeout_ms: Some(15_000),
314            reconnect_delay_initial_ms: Some(250),
315            reconnect_delay_max_ms: Some(5_000),
316            reconnect_backoff_factor: Some(2.0),
317            reconnect_jitter_ms: Some(200),
318            reconnect_max_attempts: None,
319            heartbeat_timeout_secs: Some(HEARTBEAT_INTERVAL.as_secs() * 3),
320            idle_timeout_ms: None,
321            writer_capacity: None,
322            backend: self.transport_backend,
323            proxy_url: self
324                .proxy_url
325                .as_ref()
326                .map(|value| value.expose_secret().to_owned()),
327            max_message_size_bytes: None,
328            max_frame_size_bytes: None,
329        };
330        let connection_rate_keys: Arc<[Ustr]> = Arc::from([self.rate_limits.connection_key()]);
331        let client_result = WebSocketClient::builder()
332            .config(cfg)
333            .message_handler(message_handler)
334            .rate_limiter(Arc::clone(&self.rate_limits.messages))
335            .connection_rate_limiter(Arc::clone(&self.rate_limits.connections))
336            .connection_rate_keys(connection_rate_keys)
337            .maybe_state_sink(
338                self.socket_control
339                    .as_ref()
340                    .map(SocketControl::sink)
341                    .or_else(|| self.socket_sink.clone()),
342            )
343            .connect()
344            .await;
345        let client = match client_result {
346            Ok(client) => client,
347            Err(e) => {
348                self.connection_permit.lock().take();
349                return Err(e.into());
350            }
351        };
352
353        if let Some(control) = &self.socket_control {
354            let handle = client.reconnect_handle();
355            control.register(move || handle.request_reconnect());
356        }
357
358        // Create channels for handler communication
359        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
360        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel::<NautilusWsMessage>();
361
362        self.out_rx = Some(out_rx);
363        let connection_mode = client.connection_mode_atomic();
364        let (initialized_tx, initialized_rx) = tokio::sync::oneshot::channel();
365
366        if let Err(e) = cmd_tx.send(HandlerCommand::SetClient {
367            client,
368            initialized: initialized_tx,
369        }) {
370            self.release_limit_reservations();
371            anyhow::bail!("Failed to send SetClient command: {e}");
372        }
373
374        {
375            let mut command_sender = self.cmd_tx.write().await;
376            // Synchronous cache updates share the snapshot and sender handoff
377            let mut cache_sender = self.cache_tx.lock();
378            // Initialize handler with existing instruments
379            let instruments_vec: Vec<InstrumentAny> =
380                self.instruments.load().values().cloned().collect();
381
382            if !instruments_vec.is_empty()
383                && let Err(e) = cmd_tx.send(HandlerCommand::InitializeInstruments(instruments_vec))
384            {
385                log::error!("Failed to send InitializeInstruments: {e}");
386            }
387
388            for (coin, uses) in self.trade_streams.snapshot() {
389                if let Err(e) = cmd_tx.send(HandlerCommand::UpdateTradeSubs { coin, uses }) {
390                    log::error!("Failed to send UpdateTradeSubs: {e}");
391                }
392            }
393
394            let all_dex_asset_ctxs_instrument_ids = self
395                .all_dex_asset_ctxs_instrument_ids
396                .load()
397                .iter()
398                .map(|(dex, instrument_ids)| (*dex, instrument_ids.clone()))
399                .collect();
400
401            if let Err(e) = cmd_tx.send(HandlerCommand::CacheAllDexAssetCtxsInstrumentIds(
402                all_dex_asset_ctxs_instrument_ids,
403            )) {
404                log::error!("Failed to send CacheAllDexAssetCtxsInstrumentIds: {e}");
405            }
406
407            *cache_sender = cmd_tx.clone();
408            *command_sender = cmd_tx.clone();
409        }
410
411        // Spawn handler task
412        let signal = Arc::clone(&self.signal);
413        let account_id = self.account_id;
414        let subscriptions = self.subscriptions.clone();
415        let book_streams = self.book_streams.clone();
416        let cmd_tx_for_reconnect = cmd_tx.clone();
417        let cloid_cache = Arc::clone(&self.cloid_cache);
418        let post_router = Arc::clone(&self.post_router);
419        let rate_limits = Arc::clone(&self.rate_limits);
420        let client_id = self.client_id;
421        let connection_permit = Arc::clone(&self.connection_permit);
422
423        if let Err(e) = self.task_handle.spawn(async move {
424            let mut handler = FeedHandler::new(
425                signal,
426                cmd_rx,
427                raw_rx,
428                out_tx,
429                account_id,
430                subscriptions.clone(),
431                cloid_cache,
432                post_router,
433                Arc::clone(&rate_limits),
434                client_id,
435            );
436
437            let resubscribe_all = || {
438                let topics = subscriptions.all_topics();
439                if topics.is_empty() {
440                    log::debug!("No active subscriptions to restore after reconnection");
441                    return;
442                }
443
444                log::info!(
445                    "Resubscribing to {} active subscriptions after reconnection",
446                    topics.len()
447                );
448
449                for topic in topics {
450                    match subscription_from_topic(&topic) {
451                        Ok(mut subscription) => {
452                            // Topic text cannot carry l2Book precision options;
453                            // replay the shape the stream was opened with
454                            if let SubscriptionRequest::L2Book {
455                                coin,
456                                n_sig_figs,
457                                mantissa,
458                            } = &mut subscription
459                                && let Some(options) = book_streams.options(coin)
460                            {
461                                *n_sig_figs = options.n_sig_figs;
462                                *mantissa = options.mantissa;
463                            }
464
465                            if let Err(e) = cmd_tx_for_reconnect.send(HandlerCommand::Subscribe {
466                                subscriptions: vec![subscription],
467                            }) {
468                                log::error!("Failed to send resubscribe command: {e}");
469                            }
470                        }
471                        Err(e) => {
472                            log::error!(
473                                "Failed to reconstruct subscription from topic: topic={topic}, {e}"
474                            );
475                        }
476                    }
477                }
478            };
479
480            loop {
481                match handler.next().await {
482                    Some(NautilusWsMessage::Reconnected) => {
483                        log::info!("WebSocket reconnected");
484                        let pending_unsubscribe = subscriptions.pending_unsubscribe_topics();
485                        rate_limits.release_subscriptions(
486                            client_id,
487                            pending_unsubscribe.iter().map(String::as_str),
488                        );
489                        subscriptions.reset_after_reconnect();
490                        resubscribe_all();
491
492                        if handler.send(NautilusWsMessage::Reconnected).is_err() {
493                            if handler.is_stopped() {
494                                log::debug!("Failed to send reconnect event (receiver dropped)");
495                            } else {
496                                log::error!("Failed to send reconnect event (receiver dropped)");
497                            }
498                            break;
499                        }
500                    }
501                    Some(msg) => {
502                        if handler.send(msg).is_err() {
503                            if handler.is_stopped() {
504                                log::debug!("Failed to send message (receiver dropped)");
505                            } else {
506                                log::error!("Failed to send message (receiver dropped)");
507                            }
508                            break;
509                        }
510                    }
511                    None => {
512                        if handler.is_stopped() {
513                            log::debug!("Stop signal received, ending message processing");
514                            break;
515                        }
516                        log::warn!("WebSocket stream ended unexpectedly");
517                        break;
518                    }
519                }
520            }
521            rate_limits.release_client(client_id);
522            connection_permit.lock().take();
523            log::debug!("Handler task completed");
524        }) {
525            self.out_rx = None;
526            self.release_limit_reservations();
527            anyhow::bail!("Failed to start Hyperliquid WebSocket handler task: {e}");
528        }
529
530        self.wait_for_initialization(initialized_rx, connection_mode)
531            .await?;
532
533        log::debug!("Hyperliquid WebSocket connected: {}", self.url.origin());
534
535        Ok(())
536    }
537
538    async fn wait_for_initialization(
539        &mut self,
540        initialized: tokio::sync::oneshot::Receiver<()>,
541        connection_mode: Arc<AtomicU8>,
542    ) -> anyhow::Result<()> {
543        let setup_guard = TaskGroupGuard::new(&[], || {
544            self.task_handle.abort();
545            self.release_limit_reservations();
546        });
547
548        let result = tokio::time::timeout(HTTP_TIMEOUT, initialized)
549            .await
550            .context("Hyperliquid WebSocket handler initialization timed out")
551            .and_then(|result| {
552                result.context("Hyperliquid WebSocket handler stopped before initialization")
553            });
554
555        if result.is_ok() {
556            self.connection_mode.store(connection_mode);
557            setup_guard.disarm();
558            return Ok(());
559        }
560
561        drop(setup_guard);
562        self.out_rx = None;
563        self.disconnect_locked().await?;
564        result
565    }
566
567    pub fn set_post_timeout(&mut self, timeout: Duration) {
568        self.post_timeout = timeout;
569    }
570
571    pub(crate) fn begin_shutdown(&self) {
572        self.signal.store(true, Ordering::Relaxed);
573    }
574
575    /// Replaces state owned by a terminated WebSocket generation.
576    ///
577    /// This must run only after the handler task has stopped. Replacing the
578    /// shared containers, rather than clearing them, prevents old clones or
579    /// in-flight work from mutating a subsequent connection generation.
580    pub(crate) fn reset_runtime_state(&mut self) {
581        self.release_limit_reservations();
582        self.subscriptions = SubscriptionState::new(':');
583        self.book_streams = BookStreamRegistry::default();
584        self.trade_streams = TradeStreamRegistry::default();
585        self.trade_stream_lock = Arc::new(Mutex::new(()));
586        self.quote_streams = Arc::new(DashMap::new());
587        self.instruments = Arc::new(AtomicMap::new());
588        let (cache_tx, _) = tokio::sync::mpsc::unbounded_channel();
589        self.cache_tx = Arc::new(Mutex::new(cache_tx));
590        self.bar_types = Arc::new(AtomicMap::new());
591        self.asset_context_subs = Arc::new(DashMap::new());
592        self.all_dex_asset_ctxs_instrument_ids = Arc::new(AtomicMap::new());
593        self.cloid_cache = Arc::new(Mutex::new(FifoCacheMap::new()));
594        self.out_rx = None;
595
596        if let Some(control) = &self.socket_control {
597            control.deregister();
598        }
599        self.connection_mode
600            .store(Arc::new(AtomicU8::new(ConnectionMode::Closed as u8)));
601        self.signal.store(false, Ordering::Relaxed);
602    }
603
604    /// Disconnects the WebSocket connection.
605    pub async fn disconnect(&mut self) -> anyhow::Result<()> {
606        let connect_lock = Arc::clone(&self.connect_lock);
607        let _guard = connect_lock.lock().await;
608        self.disconnect_locked().await
609    }
610
611    async fn disconnect_locked(&self) -> anyhow::Result<()> {
612        log::debug!("Disconnecting Hyperliquid WebSocket");
613
614        if let Some(control) = &self.socket_control {
615            control.deregister();
616        }
617        self.signal.store(true, Ordering::Relaxed);
618
619        if let Err(e) = self.cmd_tx.read().await.send(HandlerCommand::Disconnect) {
620            log::debug!(
621                "Failed to send disconnect command (handler may already be shut down): {e}"
622            );
623        }
624
625        if self.task_handle.is_empty() {
626            log::debug!("No task handle to await");
627        } else {
628            log::debug!("Waiting for task handle to complete");
629
630            if let Some(outcome) = self
631                .task_handle
632                .finish(Duration::from_secs(2), Duration::from_secs(2))
633                .await
634            {
635                match outcome {
636                    TaskJoinOutcome::Completed(()) | TaskJoinOutcome::Aborted => {}
637                    TaskJoinOutcome::Failed(error) => {
638                        self.release_limit_reservations();
639                        anyhow::bail!("Hyperliquid WebSocket handler failed: {error}");
640                    }
641                    TaskJoinOutcome::Incomplete => {
642                        self.release_limit_reservations();
643                        anyhow::bail!("Hyperliquid WebSocket handler did not stop after abort");
644                    }
645                }
646            }
647        }
648        self.release_limit_reservations();
649        log::debug!("Disconnected");
650        Ok(())
651    }
652
653    /// Requests a full transport reconnect.
654    ///
655    /// Transitions the connection from `Active` to `Reconnect`; the network
656    /// layer re-establishes the socket with backoff and the handler replays all
657    /// active subscriptions once reconnected. Returns `false` when the
658    /// connection is not active (already reconnecting, disconnecting, or
659    /// closed), leaving any in-flight transition untouched.
660    pub fn request_reconnect(&self) -> bool {
661        ConnectionMode::request_reconnect(&self.connection_mode.load())
662    }
663
664    /// Send a typed exchange action through the Hyperliquid WebSocket post API.
665    ///
666    /// The supplied HTTP client is used only as the canonical signer for the
667    /// action envelope. The signed payload is sent over the active WebSocket
668    /// connection and the response is correlated by post id.
669    pub async fn post_action_exec(
670        &self,
671        signer: &HyperliquidHttpClient,
672        action: &HyperliquidExchangeAction,
673    ) -> HyperliquidResult<HyperliquidExchangeResponse> {
674        self.post_action_exec_with_timeout(signer, action, self.post_timeout, None)
675            .await
676    }
677
678    /// Send a typed exchange action with a caller-specified timeout and optional expiry.
679    pub async fn post_action_exec_with_timeout(
680        &self,
681        signer: &HyperliquidHttpClient,
682        action: &HyperliquidExchangeAction,
683        timeout: Duration,
684        expires_after: Option<u64>,
685    ) -> HyperliquidResult<HyperliquidExchangeResponse> {
686        self.post_action_result(signer, action, timeout, expires_after)
687            .await
688            .map_err(PostRequestError::into_error)
689    }
690
691    pub(crate) async fn post_action_command(
692        &self,
693        signer: &HyperliquidHttpClient,
694        action: &HyperliquidExchangeAction,
695    ) -> Result<HyperliquidExchangeResponse, PostRequestError> {
696        self.post_action_result(signer, action, self.post_timeout, None)
697            .await
698    }
699
700    async fn post_action_result(
701        &self,
702        signer: &HyperliquidHttpClient,
703        action: &HyperliquidExchangeAction,
704        timeout: Duration,
705        expires_after: Option<u64>,
706    ) -> Result<HyperliquidExchangeResponse, PostRequestError> {
707        let weight = exec_action_weight(action);
708        let payload = signer
709            .sign_action_exec_request(action, expires_after)
710            .map_err(PostRequestError::BeforeDispatch)?;
711        let response = self
712            .send_post_request_result(PostRequest::Action { payload }, timeout)
713            .await?;
714
715        match response.response {
716            PostResponsePayload::Action { payload } => {
717                let parsed = self
718                    .parse_post_action_payload(&payload)
719                    .map_err(PostRequestError::AfterDispatch)?;
720
721                self.check_post_action_response(parsed)
722            }
723            PostResponsePayload::Error { payload } => Err(PostRequestError::AfterDispatch(
724                map_post_payload_error(payload, weight),
725            )),
726            PostResponsePayload::Info { payload } => Err(PostRequestError::AfterDispatch(
727                HyperliquidError::decode(self.post_decode_context(&payload, "unexpected_info")),
728            )),
729        }
730    }
731
732    /// Submit an order through the Hyperliquid WebSocket post API.
733    ///
734    /// The HTTP client supplies signing credentials, builder attribution, and
735    /// cached instrument metadata. The action itself is sent over WebSocket.
736    ///
737    /// Returns an [`OrderStatusReport`] describing the venue's immediate
738    /// response (`Filled` for an atomic IOC fill, `Accepted` for a resting
739    /// order), or `None` when the venue deferred the order without an oid (for
740    /// example a `waitingForFill` trigger child): the order stays `SUBMITTED`
741    /// until the user-events stream delivers the first `OrderAccepted`.
742    #[allow(
743        clippy::too_many_arguments,
744        reason = "matches the Python and HTTP order submit surface"
745    )]
746    pub async fn submit_order(
747        &self,
748        signer: &HyperliquidHttpClient,
749        instrument_id: InstrumentId,
750        client_order_id: ClientOrderId,
751        order_side: OrderSide,
752        order_type: OrderType,
753        quantity: Quantity,
754        time_in_force: TimeInForce,
755        price: Option<Price>,
756        trigger_price: Option<Price>,
757        post_only: bool,
758        reduce_only: bool,
759    ) -> HyperliquidResult<Option<OrderStatusReport>> {
760        let symbol = instrument_id.symbol.inner();
761        let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
762            HyperliquidError::bad_request(format!(
763                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
764            ))
765        })?;
766        let is_buy = matches!(order_side, OrderSide::Buy);
767        let price_precision = signer.get_price_precision_for_symbol(symbol);
768
769        let price_decimal = match price {
770            Some(px) => normalize_or_validate_wire_price(
771                px.as_decimal(),
772                "Price",
773                price_precision,
774                signer.normalize_prices(),
775            )
776            .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?,
777            None if matches!(order_type, OrderType::Market) => Decimal::ZERO,
778            None if matches!(
779                order_type,
780                OrderType::StopMarket | OrderType::MarketIfTouched
781            ) =>
782            {
783                match trigger_price {
784                    Some(tp) => {
785                        let derived = derive_limit_from_trigger(
786                            tp.as_decimal().normalize(),
787                            is_buy,
788                            signer.market_order_slippage_bps(),
789                        );
790                        let sig_rounded = round_to_sig_figs(derived, 5);
791                        clamp_price_to_precision(sig_rounded, price_precision.unwrap_or(2), is_buy)
792                            .normalize()
793                    }
794                    None => Decimal::ZERO,
795                }
796            }
797            None => {
798                return Err(HyperliquidError::bad_request(
799                    "Limit orders require a price",
800                ));
801            }
802        };
803
804        let size_decimal = quantity.as_decimal().normalize();
805        let kind = hyperliquid_order_kind(
806            order_type,
807            time_in_force,
808            post_only,
809            trigger_price,
810            signer.normalize_prices(),
811            price_precision,
812        )?;
813
814        let order = HyperliquidExchangePlaceOrderRequest {
815            asset,
816            is_buy,
817            price: price_decimal,
818            size: size_decimal,
819            reduce_only,
820            kind,
821            cloid: Some(signer.get_or_generate_client_order_id_cloid(client_order_id)),
822        };
823
824        if let Some(cloid) = order.cloid {
825            self.cache_cloid_mapping(Ustr::from(&cloid.to_hex()), client_order_id);
826        }
827        let action = HyperliquidExchangeAction::Order {
828            orders: vec![order],
829            grouping: HyperliquidExchangeGrouping::Na,
830            builder: signer.builder_attribution(),
831        };
832        let response = self.post_action_exec(signer, &action).await?;
833
834        // Verdict first: a real rejection must still error
835        ensure_ws_action_accepted(&response, "Order submission")?;
836
837        let payload_bytes = Self::response_bytes(&response);
838
839        // Past the verdict, a build failure is local; defer to WS, never reject
840        let report = signer.build_submit_order_report(
841            instrument_id,
842            client_order_id,
843            order_side,
844            order_type,
845            quantity,
846            time_in_force,
847            price,
848            trigger_price,
849            response,
850        );
851        Ok(self.resolve_submit_report(report, payload_bytes))
852    }
853
854    /// Submit multiple orders through the Hyperliquid WebSocket post API.
855    ///
856    /// Returns one [`OrderStatusReport`] per accepted order in submission
857    /// order. Deferred trigger children of a `normalTpsl` bracket are absent
858    /// from the result; they stay `SUBMITTED` until the user-events stream
859    /// delivers an `OrderAccepted` with the real oid.
860    ///
861    /// # Errors
862    ///
863    /// Returns an error if any quantity is quote-denominated: this raw path has no cached market
864    /// data for a quote-to-base conversion, so such orders must be submitted through the execution
865    /// client instead.
866    pub async fn submit_orders(
867        &self,
868        signer: &HyperliquidHttpClient,
869        orders: &[&OrderAny],
870    ) -> HyperliquidResult<Vec<OrderStatusReport>> {
871        let mut hyperliquid_orders = Vec::with_capacity(orders.len());
872        let mut client_order_ids = Vec::with_capacity(orders.len());
873
874        for order in orders {
875            if order.is_quote_quantity() {
876                return Err(HyperliquidError::bad_request(format!(
877                    "Quote-denominated quantity order {} must submit through the execution \
878                     client for quote-to-base conversion",
879                    order.client_order_id()
880                )));
881            }
882
883            let instrument_id = order.instrument_id();
884            let symbol = instrument_id.symbol.inner();
885            let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
886                HyperliquidError::bad_request(format!(
887                    "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
888                ))
889            })?;
890            let price_decimals = signer.get_price_precision_for_symbol(symbol);
891            let request = order_to_hyperliquid_request_with_optional_decimals(
892                order,
893                asset,
894                price_decimals,
895                signer.normalize_prices(),
896                signer.market_order_slippage_bps(),
897                None,
898            )
899            .map_err(|e| HyperliquidError::bad_request(format!("Failed to convert order: {e}")))?;
900            client_order_ids.push(order.client_order_id());
901            hyperliquid_orders.push(request);
902        }
903
904        for (request, client_order_id) in hyperliquid_orders.iter_mut().zip(client_order_ids) {
905            let cloid = signer.get_or_generate_client_order_id_cloid(client_order_id);
906            request.cloid = Some(cloid);
907            self.cache_cloid_mapping(Ustr::from(&cloid.to_hex()), client_order_id);
908        }
909
910        let grouping =
911            determine_order_list_grouping(&orders.iter().copied().cloned().collect::<Vec<_>>());
912        let action = HyperliquidExchangeAction::Order {
913            orders: hyperliquid_orders,
914            grouping,
915            builder: signer.builder_attribution(),
916        };
917        let response = self.post_action_exec(signer, &action).await?;
918
919        ensure_ws_action_accepted(&response, "Order list submission")?;
920
921        let payload_bytes = Self::response_bytes(&response);
922
923        // Past the verdict, a build failure is local; defer to WS, never reject
924        let reports = signer.build_submit_orders_reports(orders, grouping, response);
925        Ok(self.resolve_submit_report(reports, payload_bytes))
926    }
927
928    /// Cancel an order through the Hyperliquid WebSocket post API.
929    pub async fn cancel_order(
930        &self,
931        signer: &HyperliquidHttpClient,
932        instrument_id: InstrumentId,
933        client_order_id: Option<ClientOrderId>,
934        venue_order_id: Option<VenueOrderId>,
935    ) -> HyperliquidResult<()> {
936        let symbol = instrument_id.symbol.inner();
937        let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
938            HyperliquidError::bad_request(format!(
939                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
940            ))
941        })?;
942        let action = if let Some(client_order_id) = client_order_id {
943            if let Some(cloid) = signer.cached_client_order_id_cloid(&client_order_id) {
944                HyperliquidExchangeAction::CancelByCloid {
945                    cancels: vec![HyperliquidExchangeCancelByCloidRequest { asset, cloid }],
946                    fast: None,
947                }
948            } else if let Some(oid) = venue_order_id {
949                let oid = oid
950                    .as_str()
951                    .parse::<u64>()
952                    .map_err(|_| HyperliquidError::bad_request("Invalid venue order ID format"))?;
953                HyperliquidExchangeAction::Cancel {
954                    cancels: vec![HyperliquidExchangeCancelOrderRequest { asset, oid }],
955                    fast: None,
956                }
957            } else {
958                let cloid = signer.get_or_generate_client_order_id_cloid(client_order_id);
959                HyperliquidExchangeAction::CancelByCloid {
960                    cancels: vec![HyperliquidExchangeCancelByCloidRequest { asset, cloid }],
961                    fast: None,
962                }
963            }
964        } else if let Some(oid) = venue_order_id {
965            let oid = oid
966                .as_str()
967                .parse::<u64>()
968                .map_err(|_| HyperliquidError::bad_request("Invalid venue order ID format"))?;
969            HyperliquidExchangeAction::Cancel {
970                cancels: vec![HyperliquidExchangeCancelOrderRequest { asset, oid }],
971                fast: None,
972            }
973        } else {
974            return Err(HyperliquidError::bad_request(
975                "Either client_order_id or venue_order_id must be provided",
976            ));
977        };
978        let response = self.post_action_exec(signer, &action).await?;
979
980        ensure_ws_action_accepted(&response, "Cancel order")
981    }
982
983    /// Cancel multiple orders through one Hyperliquid WebSocket post action.
984    pub async fn cancel_orders(
985        &self,
986        signer: &HyperliquidHttpClient,
987        cancels: &[(InstrumentId, ClientOrderId, Option<VenueOrderId>)],
988    ) -> HyperliquidResult<Vec<Option<String>>> {
989        let mut cloid_requests = Vec::new();
990        let mut cloid_indices = Vec::new();
991        let mut oid_requests = Vec::new();
992        let mut oid_indices = Vec::new();
993        let mut results = vec![None; cancels.len()];
994
995        for (index, (instrument_id, client_order_id, venue_order_id)) in cancels.iter().enumerate()
996        {
997            let symbol = instrument_id.symbol.inner();
998            let Some(asset) = signer.get_asset_index_for_symbol(symbol) else {
999                results[index] = Some(format!(
1000                    "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
1001                ));
1002                continue;
1003            };
1004
1005            if let Some(cloid) = signer.cached_client_order_id_cloid(client_order_id) {
1006                cloid_requests.push(HyperliquidExchangeCancelByCloidRequest { asset, cloid });
1007                cloid_indices.push(index);
1008            } else if let Some(venue_order_id) = venue_order_id {
1009                match venue_order_id.as_str().parse::<u64>() {
1010                    Ok(oid) => {
1011                        oid_requests.push(HyperliquidExchangeCancelOrderRequest { asset, oid });
1012                        oid_indices.push(index);
1013                    }
1014                    Err(_) => {
1015                        results[index] = Some("Invalid venue order ID format".to_string());
1016                    }
1017                }
1018            } else {
1019                let cloid = signer.get_or_generate_client_order_id_cloid(*client_order_id);
1020                cloid_requests.push(HyperliquidExchangeCancelByCloidRequest { asset, cloid });
1021                cloid_indices.push(index);
1022            }
1023        }
1024
1025        if cloid_requests.is_empty() && oid_requests.is_empty() {
1026            return Ok(results);
1027        }
1028
1029        if !cloid_requests.is_empty() {
1030            let action = HyperliquidExchangeAction::CancelByCloid {
1031                cancels: cloid_requests,
1032                fast: None,
1033            };
1034            let errors = self
1035                .post_cancel_action_errors(signer, &action, cloid_indices.len())
1036                .await?;
1037
1038            for (index, error) in cloid_indices.into_iter().zip(errors) {
1039                results[index] = error;
1040            }
1041        }
1042
1043        if !oid_requests.is_empty() {
1044            let action = HyperliquidExchangeAction::Cancel {
1045                cancels: oid_requests,
1046                fast: None,
1047            };
1048            let errors = self
1049                .post_cancel_action_errors(signer, &action, oid_indices.len())
1050                .await?;
1051
1052            for (index, error) in oid_indices.into_iter().zip(errors) {
1053                results[index] = error;
1054            }
1055        }
1056
1057        Ok(results)
1058    }
1059
1060    async fn post_cancel_action_errors(
1061        &self,
1062        signer: &HyperliquidHttpClient,
1063        action: &HyperliquidExchangeAction,
1064        request_count: usize,
1065    ) -> HyperliquidResult<Vec<Option<String>>> {
1066        match self.post_cancel_action(signer, action).await {
1067            Ok(response) if response.is_ok() => {
1068                match cancel_errors_for_requests(extract_inner_errors(&response), request_count) {
1069                    Ok(errors) => Ok(errors),
1070                    Err(e) => Ok(vec![Some(e.to_string()); request_count]),
1071                }
1072            }
1073            Ok(response) => Ok(self.cancel_response_errors(&response, request_count)),
1074            Err(e) => Err(e),
1075        }
1076    }
1077
1078    async fn post_cancel_action(
1079        &self,
1080        signer: &HyperliquidHttpClient,
1081        action: &HyperliquidExchangeAction,
1082    ) -> HyperliquidResult<HyperliquidExchangeResponse> {
1083        let weight = exec_action_weight(action);
1084
1085        let payload = signer.sign_action_exec_request(action, None)?;
1086        let response = self
1087            .send_post_request(PostRequest::Action { payload }, self.post_timeout)
1088            .await?;
1089
1090        match response.response {
1091            PostResponsePayload::Action { payload } => self.parse_post_action_payload(&payload),
1092            PostResponsePayload::Error { payload } => Err(map_post_payload_error(payload, weight)),
1093            PostResponsePayload::Info { payload } => Err(HyperliquidError::decode(
1094                self.post_decode_context(&payload, "unexpected_info"),
1095            )),
1096        }
1097    }
1098
1099    fn response_bytes(response: &HyperliquidExchangeResponse) -> usize {
1100        match response {
1101            HyperliquidExchangeResponse::Status { response, .. } => response.to_string().len(),
1102            HyperliquidExchangeResponse::Error { error } => error.len(),
1103        }
1104    }
1105
1106    fn resolve_submit_report<T: Default>(
1107        &self,
1108        result: HyperliquidResult<T>,
1109        payload_bytes: usize,
1110    ) -> T {
1111        match result {
1112            Ok(report) => report,
1113            Err(_) => {
1114                log::warn!(
1115                    "Failed to build WebSocket submit report: class=order_status, client_id={}, payload_bytes={payload_bytes}, category=conversion; awaiting WS reconciliation",
1116                    self.client_id,
1117                );
1118                T::default()
1119            }
1120        }
1121    }
1122
1123    fn parse_post_action_payload(
1124        &self,
1125        payload: &serde_json::Value,
1126    ) -> HyperliquidResult<HyperliquidExchangeResponse> {
1127        HyperliquidExchangeResponse::deserialize(payload).map_err(|e| {
1128            let category = format!("{:?}", e.classify());
1129            let context = self.post_decode_context(payload, &category);
1130            HyperliquidError::Serde(<serde_json::Error as serde::de::Error>::custom(context))
1131        })
1132    }
1133
1134    fn check_post_action_response(
1135        &self,
1136        parsed: HyperliquidExchangeResponse,
1137    ) -> Result<HyperliquidExchangeResponse, PostRequestError> {
1138        self.check_post_status(&parsed)
1139            .map_err(PostRequestError::AfterDispatch)?;
1140
1141        match &parsed {
1142            HyperliquidExchangeResponse::Status { status, response }
1143                if status == RESPONSE_STATUS_ERR =>
1144            {
1145                let reason = response
1146                    .as_str()
1147                    .map_or_else(|| response.to_string(), str::to_string);
1148                let error = HyperliquidError::bad_request(format!("API error: {reason}"));
1149                Err(PostRequestError::Rejected {
1150                    error,
1151                    reason: extract_error_message(&parsed),
1152                })
1153            }
1154            HyperliquidExchangeResponse::Error { error } => Err(PostRequestError::Rejected {
1155                error: HyperliquidError::bad_request(format!("API error: {error}")),
1156                reason: error.clone(),
1157            }),
1158            _ => Ok(parsed),
1159        }
1160    }
1161
1162    fn cancel_response_errors(
1163        &self,
1164        response: &HyperliquidExchangeResponse,
1165        request_count: usize,
1166    ) -> Vec<Option<String>> {
1167        let reason = self
1168            .check_post_status(response)
1169            .err()
1170            .map_or_else(|| extract_error_message(response), |e| e.to_string());
1171        let reason = format!("Cancel orders failed: {reason}");
1172        vec![Some(reason); request_count]
1173    }
1174
1175    fn check_post_status(&self, parsed: &HyperliquidExchangeResponse) -> HyperliquidResult<()> {
1176        if let HyperliquidExchangeResponse::Status { status, response } = parsed
1177            && status != RESPONSE_STATUS_OK
1178            && status != RESPONSE_STATUS_ERR
1179        {
1180            let context = self.post_decode_context(response, "unexpected_status");
1181            return Err(HyperliquidError::bad_request(context));
1182        }
1183
1184        Ok(())
1185    }
1186
1187    fn post_decode_context(&self, payload: &serde_json::Value, category: &str) -> String {
1188        format!(
1189            "Invalid WebSocket post response: class=action, client_id={}, payload_bytes={}, category={category}",
1190            self.client_id,
1191            payload.to_string().len(),
1192        )
1193    }
1194
1195    /// Modify an order through the Hyperliquid WebSocket post API.
1196    #[allow(
1197        clippy::too_many_arguments,
1198        reason = "matches the Python and HTTP order modify surface"
1199    )]
1200    pub async fn modify_order(
1201        &self,
1202        signer: &HyperliquidHttpClient,
1203        instrument_id: InstrumentId,
1204        venue_order_id: Option<VenueOrderId>,
1205        order_side: OrderSide,
1206        order_type: OrderType,
1207        price: Price,
1208        quantity: Quantity,
1209        trigger_price: Option<Price>,
1210        reduce_only: bool,
1211        post_only: bool,
1212        time_in_force: TimeInForce,
1213        client_order_id: Option<ClientOrderId>,
1214    ) -> HyperliquidResult<()> {
1215        let symbol = instrument_id.symbol.inner();
1216        let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
1217            HyperliquidError::bad_request(format!(
1218                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
1219            ))
1220        })?;
1221        let oid = match client_order_id
1222            .as_ref()
1223            .and_then(|id| signer.unique_cached_client_order_id_cloid(id))
1224        {
1225            Some(cloid) => HyperliquidExchangeModifyTarget::Cloid(cloid),
1226            None => {
1227                let Some(venue_order_id) = venue_order_id.as_ref() else {
1228                    return Err(HyperliquidError::bad_request(
1229                        "venue_order_id or unique cached CLOID is required for modify",
1230                    ));
1231                };
1232                HyperliquidExchangeModifyTarget::from_venue_order_id(venue_order_id)
1233                    .map_err(|_| HyperliquidError::bad_request("Invalid venue order ID format"))?
1234            }
1235        };
1236        let is_buy = matches!(order_side, OrderSide::Buy);
1237        let price_decimals = signer.get_price_precision_for_symbol(symbol);
1238        let price = normalize_or_validate_wire_price(
1239            price.as_decimal(),
1240            "Price",
1241            price_decimals,
1242            signer.normalize_prices(),
1243        )
1244        .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?;
1245        let kind = hyperliquid_order_kind(
1246            order_type,
1247            time_in_force,
1248            post_only,
1249            trigger_price,
1250            signer.normalize_prices(),
1251            price_decimals,
1252        )?;
1253        let cloid =
1254            client_order_id.map(|id| (id, signer.get_or_generate_client_order_id_cloid(id)));
1255        let order = HyperliquidExchangePlaceOrderRequest {
1256            asset,
1257            is_buy,
1258            price,
1259            size: quantity.as_decimal().normalize(),
1260            reduce_only,
1261            kind,
1262            cloid: cloid.map(|(_, cloid)| cloid),
1263        };
1264
1265        if let Some((client_order_id, cloid)) = cloid {
1266            self.cache_cloid_mapping(Ustr::from(&cloid.to_hex()), client_order_id);
1267        }
1268        let action = HyperliquidExchangeAction::Modify {
1269            modify: HyperliquidExchangeModifyOrderRequest { oid, order },
1270        };
1271        let response = self.post_action_exec(signer, &action).await?;
1272
1273        ensure_ws_action_accepted(&response, "Modify order")
1274    }
1275
1276    async fn send_post_request(
1277        &self,
1278        request: PostRequest,
1279        timeout: Duration,
1280    ) -> HyperliquidResult<PostResponse> {
1281        self.send_post_request_result(request, timeout)
1282            .await
1283            .map_err(PostRequestError::into_error)
1284    }
1285
1286    async fn send_post_request_result(
1287        &self,
1288        request: PostRequest,
1289        timeout: Duration,
1290    ) -> Result<PostResponse, PostRequestError> {
1291        let id = self.post_ids.next();
1292        let Some(deadline) = tokio::time::Instant::now().checked_add(timeout) else {
1293            return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout));
1294        };
1295
1296        let cancellation_token = CancellationToken::new();
1297        let rx = tokio::select! {
1298            biased;
1299            () = tokio::time::sleep_until(deadline) => return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout)),
1300            result = self.post_router.register_with_cancellation(id, &cancellation_token) => result.map_err(PostRequestError::BeforeDispatch)?,
1301        };
1302
1303        let _cancellation_guard = cancellation_token.drop_guard_ref();
1304
1305        let send_result = {
1306            let cmd_tx = tokio::select! {
1307                biased;
1308                () = tokio::time::sleep_until(deadline) => {
1309                    self.cancel_post_registration(id, &cancellation_token).await;
1310                    return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout));
1311                }
1312                cmd_tx = self.cmd_tx.read() => cmd_tx,
1313            };
1314
1315            if cancellation_token.is_cancelled() || tokio::time::Instant::now() >= deadline {
1316                self.cancel_post_registration(id, &cancellation_token).await;
1317                return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout));
1318            }
1319
1320            cmd_tx.send(HandlerCommand::Post {
1321                id,
1322                request,
1323                deadline,
1324                cancellation_token: cancellation_token.clone(),
1325            })
1326        };
1327
1328        if let Err(e) = send_result {
1329            self.cancel_post_registration(id, &cancellation_token).await;
1330            return Err(PostRequestError::BeforeDispatch(
1331                HyperliquidError::transport(format!("post command channel closed: {e}")),
1332            ));
1333        }
1334
1335        self.await_post_response(id, rx, deadline, &cancellation_token)
1336            .await
1337            .map_err(PostRequestError::AfterDispatch)
1338    }
1339
1340    async fn await_post_response(
1341        &self,
1342        id: u64,
1343        rx: tokio::sync::oneshot::Receiver<PostResponse>,
1344        deadline: tokio::time::Instant,
1345        cancellation_token: &CancellationToken,
1346    ) -> HyperliquidResult<PostResponse> {
1347        tokio::select! {
1348            biased;
1349            result = rx => match result {
1350                Ok(response) => Ok(response),
1351                Err(_closed) => {
1352                    self.cancel_post_registration(id, cancellation_token).await;
1353                    Err(HyperliquidError::transport("post response channel closed"))
1354                },
1355            },
1356            () = tokio::time::sleep_until(deadline) => {
1357                self.cancel_post_registration(id, cancellation_token).await;
1358                Err(HyperliquidError::Timeout)
1359            },
1360        }
1361    }
1362
1363    async fn cancel_post_registration(&self, id: u64, cancellation_token: &CancellationToken) {
1364        cancellation_token.cancel();
1365        self.post_router
1366            .cancel_registration(id, cancellation_token)
1367            .await;
1368    }
1369
1370    /// Returns true if the WebSocket is actively connected.
1371    pub fn is_active(&self) -> bool {
1372        let mode = self.connection_mode.load();
1373        mode.load(Ordering::Relaxed) == ConnectionMode::Active as u8
1374    }
1375
1376    /// Returns the URL of this WebSocket client.
1377    pub fn url(&self) -> &str {
1378        self.url.expose()
1379    }
1380
1381    /// Caches multiple instruments.
1382    ///
1383    /// Clears the existing cache first, then adds all provided instruments.
1384    /// Instruments are keyed by their raw_symbol which is unique per instrument:
1385    /// - Perps use base currency (e.g., "BTC")
1386    /// - Spot uses @{pair_index} format (e.g., "@107") or slash format for PURR
1387    pub fn cache_instruments(&mut self, instruments: Vec<InstrumentAny>) {
1388        let mut map = AHashMap::new();
1389
1390        for inst in instruments {
1391            let coin = inst.raw_symbol().inner();
1392            map.insert(coin, inst);
1393        }
1394        let count = map.len();
1395        let _guard = self.cache_tx.lock();
1396        self.instruments.store(map);
1397        log::debug!("Hyperliquid instrument cache initialized with {count} instruments");
1398    }
1399
1400    /// Caches a single instrument.
1401    ///
1402    /// Any existing instrument with the same raw_symbol will be replaced.
1403    pub fn cache_instrument(&self, instrument: InstrumentAny) {
1404        self.merge_instruments(&[instrument]);
1405    }
1406
1407    pub(crate) fn merge_instruments(&self, instruments: &[InstrumentAny]) {
1408        if instruments.is_empty() {
1409            return;
1410        }
1411
1412        let cmd_tx = self.cache_tx.lock();
1413        self.instruments.rcu(|cache| {
1414            for instrument in instruments {
1415                cache.insert(instrument.raw_symbol().inner(), instrument.clone());
1416            }
1417        });
1418
1419        // Before connect() the handler isn't running; this send will fail and that's expected
1420        // because connect() replays the instruments via InitializeInstruments
1421        for instrument in instruments {
1422            let _ = cmd_tx.send(HandlerCommand::UpdateInstrument(instrument.clone()));
1423        }
1424    }
1425
1426    /// Returns a shared reference to the instrument cache.
1427    #[must_use]
1428    pub fn instruments_cache(&self) -> Arc<AtomicMap<Ustr, InstrumentAny>> {
1429        self.instruments.clone()
1430    }
1431
1432    /// Caches spot fill coin mappings for instrument lookup.
1433    ///
1434    /// Hyperliquid WebSocket fills for spot use `@{pair_index}` format (e.g., `@107`),
1435    /// while instruments are identified by full symbols (e.g., `HYPE-USDC-SPOT`).
1436    /// This mapping allows the handler to look up instruments from spot fills.
1437    pub fn cache_spot_fill_coins(&self, mapping: AHashMap<Ustr, Ustr>) {
1438        if let Ok(cmd_tx) = self.cmd_tx.try_read() {
1439            let _ = cmd_tx.send(HandlerCommand::CacheSpotFillCoins(mapping));
1440        }
1441    }
1442
1443    /// Caches a venue CLOID to client_order_id mapping for order/fill resolution.
1444    ///
1445    /// This mapping allows WebSocket order status and fill reports to be resolved back to
1446    /// the original client_order_id.
1447    ///
1448    /// This writes directly to a shared cache that the handler reads from, avoiding any
1449    /// race conditions between caching and WebSocket message processing.
1450    pub fn cache_cloid_mapping(&self, cloid: Ustr, client_order_id: ClientOrderId) {
1451        log::debug!("Caching cloid mapping: {cloid} -> {client_order_id}");
1452        self.cloid_cache.lock().insert(cloid, client_order_id);
1453    }
1454
1455    /// Removes a cloid mapping from the cache.
1456    ///
1457    /// Called on terminal order state. The cache is FIFO-bounded so missed
1458    /// removals self-evict (see GH-3972 cancel-replace drain).
1459    pub fn remove_cloid_mapping(&self, cloid: &Ustr) {
1460        if self.cloid_cache.lock().remove(cloid).is_some() {
1461            log::debug!("Removed cloid mapping: {cloid}");
1462        }
1463    }
1464
1465    /// Clears all cloid mappings from the cache.
1466    ///
1467    /// Useful for cleanup during reconnection or shutdown.
1468    pub fn clear_cloid_cache(&self) {
1469        let mut cache = self.cloid_cache.lock();
1470        let count = cache.len();
1471        cache.clear();
1472
1473        if count > 0 {
1474            log::debug!("Cleared {count} cloid mappings from cache");
1475        }
1476    }
1477
1478    /// Returns the number of cloid mappings in the cache.
1479    #[must_use]
1480    pub fn cloid_cache_len(&self) -> usize {
1481        self.cloid_cache.lock().len()
1482    }
1483
1484    /// Looks up a client_order_id by its venue CLOID.
1485    ///
1486    /// Returns `Some(ClientOrderId)` if the mapping exists, `None` otherwise.
1487    #[must_use]
1488    pub fn get_cloid_mapping(&self, cloid: &Ustr) -> Option<ClientOrderId> {
1489        self.cloid_cache.lock().get(cloid).copied()
1490    }
1491
1492    /// Gets an instrument from the cache by ID.
1493    ///
1494    /// Searches the cache for a matching instrument ID.
1495    pub fn get_instrument(&self, id: &InstrumentId) -> Option<InstrumentAny> {
1496        self.instruments
1497            .load()
1498            .values()
1499            .find(|inst| inst.id() == *id)
1500            .cloned()
1501    }
1502
1503    /// Gets an instrument from the cache by raw_symbol (coin).
1504    pub fn get_instrument_by_symbol(&self, symbol: &Ustr) -> Option<InstrumentAny> {
1505        self.instruments.get_cloned(symbol)
1506    }
1507
1508    /// Returns the count of confirmed subscriptions.
1509    pub fn subscription_count(&self) -> usize {
1510        self.subscriptions.len()
1511    }
1512
1513    pub(crate) async fn wait_for_subscriptions_confirmed(
1514        &self,
1515        timeout: Duration,
1516    ) -> anyhow::Result<()> {
1517        tokio::time::timeout(timeout, async {
1518            while !self.subscriptions.pending_subscribe_topics().is_empty() {
1519                tokio::time::sleep(Duration::from_millis(10)).await;
1520            }
1521        })
1522        .await
1523        .map_err(|_| {
1524            anyhow::anyhow!(
1525                "Subscriptions still pending after {timeout:?}: {:?}",
1526                self.subscriptions.pending_subscribe_topics()
1527            )
1528        })
1529    }
1530
1531    /// Gets a bar type from the cache by coin and interval.
1532    ///
1533    /// This looks up the subscription key created when subscribing to bars.
1534    pub fn get_bar_type(&self, coin: &str, interval: &str) -> Option<BarType> {
1535        // Use canonical key format matching subscribe_bars
1536        let key = format!("candle:{coin}:{interval}");
1537        self.bar_types.load().get(&key).copied()
1538    }
1539
1540    /// Subscribe to L2 order book for an instrument.
1541    pub async fn subscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1542        self.subscribe_book_with_options(instrument_id, None, None)
1543            .await
1544    }
1545
1546    /// Subscribe to L2 order book with optional `nSigFigs` / `mantissa`
1547    /// precision controls passed through to the venue's `l2Book` stream.
1548    ///
1549    /// One venue `l2Book` stream per coin is shared with depth snapshots;
1550    /// the first logical use opens the stream and its options win. Requesting
1551    /// different options while the stream is active logs a warning.
1552    pub async fn subscribe_book_with_options(
1553        &self,
1554        instrument_id: InstrumentId,
1555        n_sig_figs: Option<u32>,
1556        mantissa: Option<u32>,
1557    ) -> anyhow::Result<()> {
1558        let instrument = self
1559            .get_instrument(&instrument_id)
1560            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1561        let coin = instrument.raw_symbol().inner();
1562
1563        let cmd_tx = self.cmd_tx.read().await;
1564
1565        // Update the handler's coin→instrument mapping for this subscription
1566        cmd_tx
1567            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1568            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1569
1570        self.send_book_stream_subscribe(&cmd_tx, coin, BookStreamUse::Deltas, n_sig_figs, mantissa)
1571    }
1572
1573    /// Subscribes the coin's `l2Book` stream for order book deltas, opening `gate` once the
1574    /// subscription is written.
1575    ///
1576    /// A stream already open for depth snapshots is replaced so the book starts from a fresh
1577    /// snapshot. Returns without registering when `cancel` has already fired, and stops waiting
1578    /// once it fires; a queued write still completes so the venue matches the registry.
1579    pub(crate) async fn subscribe_book_gated(
1580        &self,
1581        instrument_id: InstrumentId,
1582        n_sig_figs: Option<u32>,
1583        mantissa: Option<u32>,
1584        cancel: CancellationToken,
1585        gate: SnapshotGate,
1586    ) -> Result<(), HyperliquidWsError> {
1587        let Some(instrument) = self.get_instrument(&instrument_id) else {
1588            let message = InstrumentLookupError::not_found(instrument_id).to_string();
1589            return Err(HyperliquidWsError::ClientError(message));
1590        };
1591
1592        let coin = instrument.raw_symbol().inner();
1593        let (completion, receiver) = tokio::sync::oneshot::channel();
1594        let cmd_tx = self.cmd_tx.read().await;
1595
1596        if cancel.is_cancelled() {
1597            return Ok(());
1598        }
1599
1600        cmd_tx
1601            .send(HandlerCommand::UpdateInstrument(instrument))
1602            .map_err(|e| HyperliquidWsError::ChannelSend(e.to_string()))?;
1603
1604        let registration =
1605            self.register_book_stream(coin, BookStreamUse::Deltas, n_sig_figs, mantissa);
1606
1607        let subscription = SubscriptionRequest::L2Book {
1608            coin,
1609            mantissa: registration.options.mantissa,
1610            n_sig_figs: registration.options.n_sig_figs,
1611        };
1612
1613        let replace = !registration.subscribe;
1614        let write_cancel = cancel.clone();
1615
1616        let write = move |subscription| HandlerCommand::WriteBook {
1617            subscription,
1618            replace,
1619            cancel: write_cancel,
1620            gate,
1621            completion,
1622        };
1623
1624        let sent = if registration.subscribe {
1625            self.send_reserved_command(&cmd_tx, subscription, write)
1626        } else {
1627            cmd_tx
1628                .send(write(subscription))
1629                .map_err(|e| anyhow::anyhow!("Failed to send book write command: {e}"))
1630        };
1631
1632        if let Err(e) = sent {
1633            if registration.subscribe {
1634                self.book_streams.release(&coin, BookStreamUse::Deltas);
1635            }
1636
1637            return Err(HyperliquidWsError::ChannelSend(e.to_string()));
1638        }
1639
1640        drop(cmd_tx);
1641
1642        tokio::select! {
1643            biased;
1644            () = cancel.cancelled() => Ok(()),
1645            result = receiver => result.map_err(|e| HyperliquidWsError::ChannelSend(e.to_string()))?,
1646        }
1647    }
1648
1649    /// Subscribe to order book depth-10 snapshots.
1650    ///
1651    /// Reuses the same `l2Book` WebSocket subscription as
1652    /// [`Self::subscribe_book`] and flags the handler to additionally emit
1653    /// `NautilusWsMessage::Depth` for this coin.
1654    pub async fn subscribe_book_depth(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1655        self.subscribe_book_depth_with_options(instrument_id, None, None)
1656            .await
1657    }
1658
1659    /// Subscribe to depth-10 snapshots with optional `nSigFigs` /
1660    /// `mantissa` precision controls.
1661    ///
1662    /// Shares the coin's `l2Book` stream with deltas subscribers; the first
1663    /// logical use opens the stream and its options win. Requesting different
1664    /// options while the stream is active logs a warning.
1665    pub async fn subscribe_book_depth_with_options(
1666        &self,
1667        instrument_id: InstrumentId,
1668        n_sig_figs: Option<u32>,
1669        mantissa: Option<u32>,
1670    ) -> anyhow::Result<()> {
1671        let instrument = self
1672            .get_instrument(&instrument_id)
1673            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1674        let coin = instrument.raw_symbol().inner();
1675
1676        let cmd_tx = self.cmd_tx.read().await;
1677
1678        cmd_tx
1679            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1680            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1681
1682        cmd_tx
1683            .send(HandlerCommand::SetDepthSub {
1684                coin,
1685                subscribed: true,
1686            })
1687            .map_err(|e| anyhow::anyhow!("Failed to send SetDepthSub command: {e}"))?;
1688
1689        self.send_book_stream_subscribe(&cmd_tx, coin, BookStreamUse::Depth, n_sig_figs, mantissa)
1690    }
1691
1692    /// Unsubscribe from order book depth-10 snapshots.
1693    ///
1694    /// Clears the depth emission flag and tears down the underlying
1695    /// `l2Book` stream unless active deltas subscribers still need it.
1696    pub async fn unsubscribe_book_depth(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1697        let instrument = self
1698            .get_instrument(&instrument_id)
1699            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1700        let coin = instrument.raw_symbol().inner();
1701
1702        let cmd_tx = self.cmd_tx.read().await;
1703
1704        cmd_tx
1705            .send(HandlerCommand::SetDepthSub {
1706                coin,
1707                subscribed: false,
1708            })
1709            .map_err(|e| anyhow::anyhow!("Failed to send SetDepthSub command: {e}"))?;
1710
1711        self.send_book_stream_unsubscribe(&cmd_tx, coin, BookStreamUse::Depth)
1712    }
1713
1714    /// Subscribe to best bid/offer (BBO) quotes for an instrument.
1715    pub async fn subscribe_quotes(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1716        let instrument = self
1717            .get_instrument(&instrument_id)
1718            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1719        let coin = instrument.raw_symbol().inner();
1720
1721        let cmd_tx = self.cmd_tx.read().await;
1722        self.quote_streams.insert(coin, ());
1723
1724        // Update the handler's coin→instrument mapping for this subscription
1725        if let Err(e) = cmd_tx.send(HandlerCommand::UpdateInstrument(instrument.clone())) {
1726            self.quote_streams.remove(&coin);
1727            anyhow::bail!("Failed to send UpdateInstrument command: {e}");
1728        }
1729
1730        let subscription = SubscriptionRequest::Bbo { coin };
1731
1732        if let Err(e) = self.send_subscription(&cmd_tx, subscription) {
1733            self.quote_streams.remove(&coin);
1734            return Err(e);
1735        }
1736        Ok(())
1737    }
1738
1739    /// Subscribe to all mid prices across markets.
1740    pub async fn subscribe_all_mids(&self) -> anyhow::Result<()> {
1741        self.subscribe_all_mids_with_dex(None).await
1742    }
1743
1744    /// Subscribe to aggregate asset contexts across all perp dexes.
1745    pub async fn subscribe_all_dexs_asset_ctxs(&self) -> anyhow::Result<()> {
1746        self.send_subscription(
1747            &*self.cmd_tx.read().await,
1748            SubscriptionRequest::AllDexsAssetCtxs,
1749        )?;
1750        Ok(())
1751    }
1752
1753    /// Subscribe to all mid prices across markets, optionally scoped to a specific dex.
1754    pub async fn subscribe_all_mids_with_dex(&self, dex: Option<&str>) -> anyhow::Result<()> {
1755        let cmd_tx = self.cmd_tx.read().await;
1756
1757        let subscription = SubscriptionRequest::AllMids {
1758            dex: dex.map(ToString::to_string),
1759        };
1760
1761        self.send_subscription(&cmd_tx, subscription)?;
1762        Ok(())
1763    }
1764
1765    /// Unsubscribe from all mid prices across markets.
1766    pub async fn unsubscribe_all_mids(&self) -> anyhow::Result<()> {
1767        self.unsubscribe_all_mids_with_dex(None).await
1768    }
1769
1770    /// Unsubscribe from aggregate asset contexts across all perp dexes.
1771    pub async fn unsubscribe_all_dexs_asset_ctxs(&self) -> anyhow::Result<()> {
1772        self.send_unsubscription(
1773            &*self.cmd_tx.read().await,
1774            SubscriptionRequest::AllDexsAssetCtxs,
1775        )?;
1776        Ok(())
1777    }
1778
1779    /// Unsubscribe from all mid prices across markets, optionally scoped to a specific dex.
1780    pub async fn unsubscribe_all_mids_with_dex(&self, dex: Option<&str>) -> anyhow::Result<()> {
1781        let cmd_tx = self.cmd_tx.read().await;
1782
1783        let subscription = SubscriptionRequest::AllMids {
1784            dex: dex.map(ToString::to_string),
1785        };
1786
1787        self.send_unsubscription(&cmd_tx, subscription)?;
1788        Ok(())
1789    }
1790
1791    /// Subscribe to trades for an instrument.
1792    pub async fn subscribe_trades(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1793        self.subscribe_trade_stream(instrument_id, TradeStreamUse::Ticks)
1794            .await
1795    }
1796
1797    /// Subscribe to complete public trades for an instrument.
1798    pub async fn subscribe_public_trades(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1799        self.subscribe_trade_stream(instrument_id, TradeStreamUse::PublicTrades)
1800            .await
1801    }
1802
1803    async fn subscribe_trade_stream(
1804        &self,
1805        instrument_id: InstrumentId,
1806        stream_use: TradeStreamUse,
1807    ) -> anyhow::Result<()> {
1808        let instrument = self
1809            .get_instrument(&instrument_id)
1810            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1811        let coin = instrument.raw_symbol().inner();
1812
1813        let cmd_tx = self.cmd_tx.read().await;
1814
1815        // Update the handler's coin→instrument mapping for this subscription
1816        cmd_tx
1817            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1818            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1819
1820        // Keep registry mutations and their handler commands ordered across
1821        // concurrent generic/custom subscriptions for the same coin.
1822        let _trade_stream_guard = self.trade_stream_lock.lock();
1823        let registration = self.trade_streams.register(coin, stream_use);
1824        cmd_tx
1825            .send(HandlerCommand::UpdateTradeSubs {
1826                coin,
1827                uses: registration.uses,
1828            })
1829            .map_err(|e| anyhow::anyhow!("Failed to send UpdateTradeSubs command: {e}"))?;
1830
1831        if registration.subscribe
1832            && let Err(e) = self.send_subscription(&cmd_tx, SubscriptionRequest::Trades { coin })
1833        {
1834            let rollback = self.trade_streams.release(&coin, stream_use);
1835            let _ = cmd_tx.send(HandlerCommand::UpdateTradeSubs {
1836                coin,
1837                uses: rollback.uses,
1838            });
1839            return Err(e);
1840        }
1841        Ok(())
1842    }
1843
1844    /// Subscribe to mark price updates for an instrument.
1845    pub async fn subscribe_mark_prices(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1846        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::MarkPrice)
1847            .await
1848    }
1849
1850    /// Subscribe to index/oracle price updates for an instrument.
1851    pub async fn subscribe_index_prices(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1852        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::IndexPrice)
1853            .await
1854    }
1855
1856    /// Subscribe to candle/bar data for a specific coin and interval.
1857    pub async fn subscribe_bars(&self, bar_type: BarType) -> anyhow::Result<()> {
1858        let instrument_id = bar_type.instrument_id();
1859        let instrument = self
1860            .get_instrument(&instrument_id)
1861            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1862        let coin = instrument.raw_symbol().inner();
1863        let interval = bar_type_to_interval(&bar_type)?;
1864        let subscription = SubscriptionRequest::Candle { coin, interval };
1865
1866        // Cache the bar type for parsing using canonical key
1867        let key = format!("candle:{coin}:{interval}");
1868        self.bar_types.insert(key.clone(), bar_type);
1869
1870        let cmd_tx = self.cmd_tx.read().await;
1871
1872        cmd_tx
1873            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1874            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1875
1876        cmd_tx
1877            .send(HandlerCommand::AddBarType {
1878                key: key.clone(),
1879                bar_type,
1880            })
1881            .map_err(|e| anyhow::anyhow!("Failed to send AddBarType command: {e}"))?;
1882
1883        if let Err(e) = self.send_subscription(&cmd_tx, subscription) {
1884            self.bar_types.remove(&key);
1885            let _ = cmd_tx.send(HandlerCommand::RemoveBarType { key });
1886            return Err(e);
1887        }
1888        Ok(())
1889    }
1890
1891    /// Subscribe to funding rate updates for an instrument.
1892    pub async fn subscribe_funding_rates(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1893        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::FundingRate)
1894            .await
1895    }
1896
1897    /// Subscribe to open interest updates for an instrument.
1898    pub async fn subscribe_open_interest(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1899        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::OpenInterest)
1900            .await
1901    }
1902
1903    /// Subscribe to order updates for a specific user address.
1904    pub async fn subscribe_order_updates(&self, user: &str) -> anyhow::Result<()> {
1905        let subscription = SubscriptionRequest::OrderUpdates {
1906            user: user.to_string(),
1907        };
1908        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1909        Ok(())
1910    }
1911
1912    /// Subscribe to user events (fills, funding, liquidations) for a specific user address.
1913    pub async fn subscribe_user_events(&self, user: &str) -> anyhow::Result<()> {
1914        let subscription = SubscriptionRequest::UserEvents {
1915            user: user.to_string(),
1916        };
1917        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1918        Ok(())
1919    }
1920
1921    /// Subscribes to perp account state and spot balances for a user address.
1922    pub(crate) async fn subscribe_account_state(
1923        &self,
1924        user: &str,
1925        is_portfolio_margin: bool,
1926    ) -> anyhow::Result<()> {
1927        let cmd_tx = self.cmd_tx.read().await;
1928        self.send_subscription(
1929            &cmd_tx,
1930            SubscriptionRequest::ClearinghouseState {
1931                user: user.to_string(),
1932            },
1933        )?;
1934
1935        self.send_subscription(
1936            &cmd_tx,
1937            SubscriptionRequest::SpotState {
1938                user: user.to_string(),
1939                is_portfolio_margin,
1940            },
1941        )?;
1942
1943        Ok(())
1944    }
1945
1946    /// Subscribe to user fills for a specific user address.
1947    ///
1948    /// Note: This channel is redundant with `userEvents` which already includes fills.
1949    /// Prefer using `subscribe_user_events` or `subscribe_all_user_channels` instead.
1950    pub async fn subscribe_user_fills(&self, user: &str) -> anyhow::Result<()> {
1951        let subscription = SubscriptionRequest::UserFills {
1952            user: user.to_string(),
1953            aggregate_by_time: None,
1954        };
1955        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1956        Ok(())
1957    }
1958
1959    /// Subscribe to all user channels (order updates + user events) for convenience.
1960    ///
1961    /// Note: `userEvents` already includes fills, so we don't subscribe to `userFills`
1962    /// separately to avoid duplicate fill messages.
1963    ///
1964    /// This does **not** include opt-in TWAP custom-data channels
1965    /// (`userTwapHistory` / `userTwapSliceFills`).
1966    pub async fn subscribe_all_user_channels(&self, user: &str) -> anyhow::Result<()> {
1967        self.subscribe_order_updates(user).await?;
1968        self.subscribe_user_events(user).await?;
1969        Ok(())
1970    }
1971
1972    /// Subscribe to TWAP history for a user address (`userTwapHistory`).
1973    ///
1974    /// Opt-in custom data. The address need not be the adapter trading account.
1975    pub async fn subscribe_user_twap_history(&self, user: &str) -> anyhow::Result<()> {
1976        let subscription = SubscriptionRequest::UserTwapHistory {
1977            user: user.to_string(),
1978        };
1979        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1980        Ok(())
1981    }
1982
1983    /// Unsubscribe from TWAP history for a user address.
1984    pub async fn unsubscribe_user_twap_history(&self, user: &str) -> anyhow::Result<()> {
1985        let subscription = SubscriptionRequest::UserTwapHistory {
1986            user: user.to_string(),
1987        };
1988        self.send_unsubscription(&*self.cmd_tx.read().await, subscription)?;
1989        Ok(())
1990    }
1991
1992    /// Subscribe to TWAP slice fills for a user address (`userTwapSliceFills`).
1993    ///
1994    /// Opt-in custom data. The address need not be the adapter trading account.
1995    pub async fn subscribe_user_twap_slice_fills(&self, user: &str) -> anyhow::Result<()> {
1996        let subscription = SubscriptionRequest::UserTwapSliceFills {
1997            user: user.to_string(),
1998        };
1999        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
2000        Ok(())
2001    }
2002
2003    /// Unsubscribe from TWAP slice fills for a user address.
2004    pub async fn unsubscribe_user_twap_slice_fills(&self, user: &str) -> anyhow::Result<()> {
2005        let subscription = SubscriptionRequest::UserTwapSliceFills {
2006            user: user.to_string(),
2007        };
2008        self.send_unsubscription(&*self.cmd_tx.read().await, subscription)?;
2009        Ok(())
2010    }
2011
2012    /// Unsubscribe from L2 order book for an instrument.
2013    ///
2014    /// Tears down the venue `l2Book` stream unless active depth subscribers
2015    /// still need it.
2016    pub async fn unsubscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
2017        let instrument = self
2018            .get_instrument(&instrument_id)
2019            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2020        let coin = instrument.raw_symbol().inner();
2021
2022        let cmd_tx = self.cmd_tx.read().await;
2023
2024        self.send_book_stream_unsubscribe(&cmd_tx, coin, BookStreamUse::Deltas)
2025    }
2026
2027    /// Resubscribes the venue `l2Book` stream for an instrument in place.
2028    ///
2029    /// Sends an unsubscribe immediately followed by a subscribe, both echoing
2030    /// the stream's original precision options (the venue matches unsubscribes
2031    /// by full payload). Registry state is left untouched so the logical
2032    /// deltas/depth uses and first-wins options survive the cycle. Used by
2033    /// stale-stream recovery, where a plain subscribe would be gated off by
2034    /// the existing registry entry.
2035    pub async fn resubscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
2036        let instrument = self
2037            .get_instrument(&instrument_id)
2038            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2039        let coin = instrument.raw_symbol().inner();
2040
2041        // Serialize the registry check with read-locked subscribe/unsubscribe senders
2042        let cmd_tx = self.cmd_tx.write().await;
2043
2044        let Some(options) = self.book_streams.options(&coin) else {
2045            log::debug!("Skipping l2Book resubscribe for {coin}: stream no longer registered");
2046            return Ok(());
2047        };
2048
2049        let subscription = SubscriptionRequest::L2Book {
2050            coin,
2051            mantissa: options.mantissa,
2052            n_sig_figs: options.n_sig_figs,
2053        };
2054
2055        self.send_stream_resubscribe(&cmd_tx, subscription)
2056    }
2057
2058    /// Replaces the coin's `l2Book` subscription to request a fresh snapshot, opening `gate`
2059    /// once the subscription is written.
2060    ///
2061    /// Echoes the stream's original precision options and leaves registry state untouched, as
2062    /// [`Self::resubscribe_book`] does.
2063    pub(crate) async fn resubscribe_book_gated(
2064        &self,
2065        instrument_id: InstrumentId,
2066        cancel: CancellationToken,
2067        gate: SnapshotGate,
2068    ) -> Result<(), HyperliquidWsError> {
2069        let Some(instrument) = self.get_instrument(&instrument_id) else {
2070            let message = InstrumentLookupError::not_found(instrument_id).to_string();
2071            return Err(HyperliquidWsError::ClientError(message));
2072        };
2073
2074        let coin = instrument.raw_symbol().inner();
2075        let (completion, receiver) = tokio::sync::oneshot::channel();
2076
2077        // Serialize the registry check with read-locked subscribe/unsubscribe senders
2078        let cmd_tx = self.cmd_tx.write().await;
2079
2080        if cancel.is_cancelled() {
2081            return Err(HyperliquidWsError::ClientError(
2082                "Book recovery canceled".to_string(),
2083            ));
2084        }
2085
2086        let Some(options) = self.book_streams.options(&coin) else {
2087            return Err(HyperliquidWsError::ClientError(format!(
2088                "l2Book stream for {coin} is no longer registered"
2089            )));
2090        };
2091
2092        let subscription = SubscriptionRequest::L2Book {
2093            coin,
2094            mantissa: options.mantissa,
2095            n_sig_figs: options.n_sig_figs,
2096        };
2097
2098        cmd_tx
2099            .send(HandlerCommand::WriteBook {
2100                subscription,
2101                replace: true,
2102                cancel,
2103                gate,
2104                completion,
2105            })
2106            .map_err(|e| HyperliquidWsError::ChannelSend(e.to_string()))?;
2107
2108        drop(cmd_tx);
2109
2110        receiver
2111            .await
2112            .map_err(|e| HyperliquidWsError::ChannelSend(e.to_string()))?
2113    }
2114
2115    fn send_book_stream_subscribe(
2116        &self,
2117        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2118        coin: Ustr,
2119        stream_use: BookStreamUse,
2120        n_sig_figs: Option<u32>,
2121        mantissa: Option<u32>,
2122    ) -> anyhow::Result<()> {
2123        let registration = self.register_book_stream(coin, stream_use, n_sig_figs, mantissa);
2124
2125        if registration.subscribe {
2126            let subscription = SubscriptionRequest::L2Book {
2127                coin,
2128                mantissa: registration.options.mantissa,
2129                n_sig_figs: registration.options.n_sig_figs,
2130            };
2131
2132            if let Err(e) = self.send_subscription(cmd_tx, subscription) {
2133                self.book_streams.release(&coin, stream_use);
2134                return Err(e);
2135            }
2136        }
2137
2138        Ok(())
2139    }
2140
2141    fn register_book_stream(
2142        &self,
2143        coin: Ustr,
2144        stream_use: BookStreamUse,
2145        n_sig_figs: Option<u32>,
2146        mantissa: Option<u32>,
2147    ) -> BookStreamRegistration {
2148        let registration = self.book_streams.register(
2149            coin,
2150            stream_use,
2151            BookStreamOptions {
2152                n_sig_figs,
2153                mantissa,
2154            },
2155        );
2156
2157        if registration.options_mismatch {
2158            log::warn!(
2159                "Requested l2Book options for {coin} (n_sig_figs={n_sig_figs:?}, mantissa={mantissa:?}) \
2160                differ from the active stream ({:?}), keeping active options",
2161                registration.options,
2162            );
2163        }
2164
2165        registration
2166    }
2167
2168    fn send_book_stream_unsubscribe(
2169        &self,
2170        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2171        coin: Ustr,
2172        stream_use: BookStreamUse,
2173    ) -> anyhow::Result<()> {
2174        match self.book_streams.release(&coin, stream_use) {
2175            BookStreamRelease::Unsubscribe(options) => {
2176                let subscription = SubscriptionRequest::L2Book {
2177                    coin,
2178                    mantissa: options.mantissa,
2179                    n_sig_figs: options.n_sig_figs,
2180                };
2181
2182                self.send_unsubscription(cmd_tx, subscription)?;
2183            }
2184            BookStreamRelease::Retained => {
2185                let remaining_use = match stream_use {
2186                    BookStreamUse::Deltas => "depth",
2187                    BookStreamUse::Depth => "deltas",
2188                };
2189                log::debug!("Keeping shared l2Book stream for {coin}: {remaining_use} use remains");
2190            }
2191        }
2192        Ok(())
2193    }
2194
2195    /// Unsubscribe from quote ticks for an instrument.
2196    pub async fn unsubscribe_quotes(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
2197        let instrument = self
2198            .get_instrument(&instrument_id)
2199            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2200        let coin = instrument.raw_symbol().inner();
2201
2202        let subscription = SubscriptionRequest::Bbo { coin };
2203        let cmd_tx = self.cmd_tx.read().await;
2204
2205        self.quote_streams.remove(&coin);
2206
2207        self.send_unsubscription(&cmd_tx, subscription)?;
2208        Ok(())
2209    }
2210
2211    /// Resubscribes the venue `bbo` stream for an instrument in place
2212    /// (unsubscribe immediately followed by subscribe). Used by stale-stream
2213    /// recovery.
2214    pub async fn resubscribe_quotes(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
2215        let instrument = self
2216            .get_instrument(&instrument_id)
2217            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2218        let coin = instrument.raw_symbol().inner();
2219
2220        // Keep the registration check atomic with the resubscribe pair
2221        let cmd_tx = self.cmd_tx.write().await;
2222
2223        if !self.quote_streams.contains_key(&coin) {
2224            log::debug!("Skipping bbo resubscribe for {coin}: stream no longer registered");
2225            return Ok(());
2226        }
2227
2228        self.send_stream_resubscribe(&cmd_tx, SubscriptionRequest::Bbo { coin })
2229    }
2230
2231    fn send_stream_resubscribe(
2232        &self,
2233        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2234        subscription: SubscriptionRequest,
2235    ) -> anyhow::Result<()> {
2236        cmd_tx
2237            .send(HandlerCommand::Resubscribe { subscription })
2238            .map_err(|e| anyhow::anyhow!("Failed to send resubscribe command: {e}"))
2239    }
2240
2241    /// Unsubscribe from trades for an instrument.
2242    pub async fn unsubscribe_trades(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
2243        self.unsubscribe_trade_stream(instrument_id, TradeStreamUse::Ticks)
2244            .await
2245    }
2246
2247    /// Unsubscribe from complete public trades for an instrument.
2248    pub async fn unsubscribe_public_trades(
2249        &self,
2250        instrument_id: InstrumentId,
2251    ) -> anyhow::Result<()> {
2252        self.unsubscribe_trade_stream(instrument_id, TradeStreamUse::PublicTrades)
2253            .await
2254    }
2255
2256    async fn unsubscribe_trade_stream(
2257        &self,
2258        instrument_id: InstrumentId,
2259        stream_use: TradeStreamUse,
2260    ) -> anyhow::Result<()> {
2261        let instrument = self
2262            .get_instrument(&instrument_id)
2263            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2264        let coin = instrument.raw_symbol().inner();
2265
2266        let cmd_tx = self.cmd_tx.read().await;
2267        // Keep registry mutations and their handler commands ordered across
2268        // concurrent generic/custom unsubscriptions for the same coin.
2269        let _trade_stream_guard = self.trade_stream_lock.lock();
2270        let release = self.trade_streams.release(&coin, stream_use);
2271        cmd_tx
2272            .send(HandlerCommand::UpdateTradeSubs {
2273                coin,
2274                uses: release.uses,
2275            })
2276            .map_err(|e| anyhow::anyhow!("Failed to send UpdateTradeSubs command: {e}"))?;
2277
2278        if release.unsubscribe {
2279            self.send_unsubscription(&cmd_tx, SubscriptionRequest::Trades { coin })?;
2280        }
2281        Ok(())
2282    }
2283
2284    /// Unsubscribe from mark price updates for an instrument.
2285    pub async fn unsubscribe_mark_prices(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
2286        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::MarkPrice)
2287            .await
2288    }
2289
2290    /// Unsubscribe from index/oracle price updates for an instrument.
2291    pub async fn unsubscribe_index_prices(
2292        &self,
2293        instrument_id: InstrumentId,
2294    ) -> anyhow::Result<()> {
2295        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::IndexPrice)
2296            .await
2297    }
2298
2299    /// Unsubscribe from candle/bar data.
2300    pub async fn unsubscribe_bars(&self, bar_type: BarType) -> anyhow::Result<()> {
2301        let instrument_id = bar_type.instrument_id();
2302        let instrument = self
2303            .get_instrument(&instrument_id)
2304            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2305        let coin = instrument.raw_symbol().inner();
2306        let interval = bar_type_to_interval(&bar_type)?;
2307        let subscription = SubscriptionRequest::Candle { coin, interval };
2308
2309        let key = format!("candle:{coin}:{interval}");
2310        self.bar_types.remove(&key);
2311
2312        let cmd_tx = self.cmd_tx.read().await;
2313
2314        cmd_tx
2315            .send(HandlerCommand::RemoveBarType { key })
2316            .map_err(|e| anyhow::anyhow!("Failed to send RemoveBarType command: {e}"))?;
2317
2318        self.send_unsubscription(&cmd_tx, subscription)?;
2319        Ok(())
2320    }
2321
2322    /// Unsubscribe from funding rate updates for an instrument.
2323    pub async fn unsubscribe_funding_rates(
2324        &self,
2325        instrument_id: InstrumentId,
2326    ) -> anyhow::Result<()> {
2327        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::FundingRate)
2328            .await
2329    }
2330
2331    /// Unsubscribe from open interest updates for an instrument.
2332    pub async fn unsubscribe_open_interest(
2333        &self,
2334        instrument_id: InstrumentId,
2335    ) -> anyhow::Result<()> {
2336        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::OpenInterest)
2337            .await
2338    }
2339
2340    /// Cache the ordered instrument IDs required to normalize `allDexsAssetCtxs`.
2341    ///
2342    /// Entries merge by dex: each dex in `mapping` replaces its cached entry and
2343    /// dexes absent from `mapping` keep theirs. A mapping built from the
2344    /// standard `meta` fallback covers only the standard dex, and replacing the
2345    /// whole cache with it would drop every HIP-3 context until a later complete
2346    /// build. A stale entry for a dex the venue no longer lists is harmless
2347    /// because no contexts arrive for it.
2348    pub fn cache_all_dex_asset_ctxs_instrument_ids(
2349        &self,
2350        mapping: AHashMap<Ustr, Vec<Option<InstrumentId>>>,
2351    ) {
2352        let cmd_tx = self.cache_tx.lock();
2353        self.all_dex_asset_ctxs_instrument_ids.rcu(|cached| {
2354            cached.extend(mapping.iter().map(|(dex, ids)| (*dex, ids.clone())));
2355        });
2356
2357        if let Err(e) = cmd_tx.send(HandlerCommand::CacheAllDexAssetCtxsInstrumentIds(mapping)) {
2358            log::debug!(
2359                "Failed to send CacheAllDexAssetCtxsInstrumentIds command (handler may not be connected yet): {e}"
2360            );
2361        }
2362    }
2363
2364    async fn subscribe_asset_context_data(
2365        &self,
2366        instrument_id: InstrumentId,
2367        data_type: AssetContextDataType,
2368    ) -> anyhow::Result<()> {
2369        let instrument = self
2370            .get_instrument(&instrument_id)
2371            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2372        let coin = instrument.raw_symbol().inner();
2373
2374        let mut entry = self.asset_context_subs.entry(coin).or_default();
2375        let is_first_subscription = entry.is_empty();
2376        entry.insert(data_type);
2377        let data_types = entry.clone();
2378        drop(entry);
2379
2380        let cmd_tx = self.cmd_tx.read().await;
2381
2382        cmd_tx
2383            .send(HandlerCommand::UpdateAssetContextSubs { coin, data_types })
2384            .map_err(|e| anyhow::anyhow!("Failed to send UpdateAssetContextSubs command: {e}"))?;
2385
2386        if is_first_subscription {
2387            log::debug!(
2388                "First asset context subscription for coin '{coin}', subscribing to ActiveAssetCtx"
2389            );
2390            let subscription = SubscriptionRequest::ActiveAssetCtx { coin };
2391
2392            cmd_tx
2393                .send(HandlerCommand::UpdateInstrument(instrument.clone()))
2394                .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
2395
2396            if let Err(e) = self.send_subscription(&cmd_tx, subscription) {
2397                if let Some(mut entry) = self.asset_context_subs.get_mut(&coin) {
2398                    entry.remove(&data_type);
2399                    let rollback = entry.clone();
2400                    let remove_entry = entry.is_empty();
2401                    drop(entry);
2402
2403                    if remove_entry {
2404                        self.asset_context_subs.remove(&coin);
2405                    }
2406                    let _ = cmd_tx.send(HandlerCommand::UpdateAssetContextSubs {
2407                        coin,
2408                        data_types: rollback,
2409                    });
2410                }
2411                return Err(e);
2412            }
2413        } else {
2414            log::debug!(
2415                "Already subscribed to ActiveAssetCtx for coin '{coin}', adding {data_type:?} to tracked types"
2416            );
2417        }
2418
2419        Ok(())
2420    }
2421
2422    async fn unsubscribe_asset_context_data(
2423        &self,
2424        instrument_id: InstrumentId,
2425        data_type: AssetContextDataType,
2426    ) -> anyhow::Result<()> {
2427        let instrument = self
2428            .get_instrument(&instrument_id)
2429            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2430        let coin = instrument.raw_symbol().inner();
2431
2432        if let Some(mut entry) = self.asset_context_subs.get_mut(&coin) {
2433            entry.remove(&data_type);
2434            let should_unsubscribe = entry.is_empty();
2435            let data_types = entry.clone();
2436            drop(entry);
2437
2438            let cmd_tx = self.cmd_tx.read().await;
2439
2440            if should_unsubscribe {
2441                self.asset_context_subs.remove(&coin);
2442
2443                log::debug!(
2444                    "Last asset context subscription removed for coin '{coin}', unsubscribing from ActiveAssetCtx"
2445                );
2446                let subscription = SubscriptionRequest::ActiveAssetCtx { coin };
2447
2448                cmd_tx
2449                    .send(HandlerCommand::UpdateAssetContextSubs {
2450                        coin,
2451                        data_types: AHashSet::new(),
2452                    })
2453                    .map_err(|e| {
2454                        anyhow::anyhow!("Failed to send UpdateAssetContextSubs command: {e}")
2455                    })?;
2456
2457                self.send_unsubscription(&cmd_tx, subscription)?;
2458            } else {
2459                log::debug!(
2460                    "Removed {data_type:?} from tracked types for coin '{coin}', but keeping ActiveAssetCtx subscription"
2461                );
2462
2463                cmd_tx
2464                    .send(HandlerCommand::UpdateAssetContextSubs { coin, data_types })
2465                    .map_err(|e| {
2466                        anyhow::anyhow!("Failed to send UpdateAssetContextSubs command: {e}")
2467                    })?;
2468            }
2469        }
2470
2471        Ok(())
2472    }
2473
2474    fn send_subscription(
2475        &self,
2476        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2477        subscription: SubscriptionRequest,
2478    ) -> anyhow::Result<()> {
2479        self.send_reserved_command(cmd_tx, subscription, |subscription| {
2480            HandlerCommand::Subscribe {
2481                subscriptions: vec![subscription],
2482            }
2483        })
2484    }
2485
2486    fn send_reserved_command(
2487        &self,
2488        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2489        subscription: SubscriptionRequest,
2490        command: impl FnOnce(SubscriptionRequest) -> HandlerCommand,
2491    ) -> anyhow::Result<()> {
2492        let key = crate::websocket::handler::subscription_to_key(&subscription);
2493        let reserved = self
2494            .rate_limits
2495            .reserve_subscription(self.client_id, &subscription)
2496            .map_err(anyhow::Error::msg)?;
2497
2498        if let Err(e) = cmd_tx.send(command(subscription)) {
2499            if reserved {
2500                self.rate_limits.release_subscription(self.client_id, &key);
2501            }
2502            anyhow::bail!("Failed to send subscribe command: {e}");
2503        }
2504        Ok(())
2505    }
2506
2507    fn send_unsubscription(
2508        &self,
2509        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2510        subscription: SubscriptionRequest,
2511    ) -> anyhow::Result<()> {
2512        cmd_tx
2513            .send(HandlerCommand::Unsubscribe {
2514                subscriptions: vec![subscription],
2515            })
2516            .map_err(|e| anyhow::anyhow!("Failed to send unsubscribe command: {e}"))
2517    }
2518
2519    /// Receives the next message from the WebSocket handler.
2520    ///
2521    /// Returns `None` if the handler has disconnected or the receiver was already taken.
2522    pub async fn next_event(&mut self) -> Option<NautilusWsMessage> {
2523        if let Some(ref mut rx) = self.out_rx {
2524            rx.recv().await
2525        } else {
2526            None
2527        }
2528    }
2529
2530    fn release_limit_reservations(&self) {
2531        self.rate_limits.release_client(self.client_id);
2532        self.connection_permit.lock().take();
2533    }
2534}
2535
2536impl Drop for HyperliquidWebSocketClient {
2537    fn drop(&mut self) {
2538        if Arc::strong_count(&self.task_handle) == 1 {
2539            self.release_limit_reservations();
2540
2541            if self.task_handle.is_empty() {
2542                return;
2543            }
2544
2545            self.signal.store(true, Ordering::Relaxed);
2546            self.task_handle.abort();
2547
2548            if let Some(control) = &self.socket_control {
2549                control.deregister();
2550            }
2551        }
2552    }
2553}
2554
2555#[derive(Debug)]
2556pub(crate) enum PostRequestError {
2557    BeforeDispatch(HyperliquidError),
2558    AfterDispatch(HyperliquidError),
2559    Rejected {
2560        error: HyperliquidError,
2561        reason: String,
2562    },
2563}
2564
2565impl PostRequestError {
2566    fn into_error(self) -> HyperliquidError {
2567        match self {
2568            Self::BeforeDispatch(error)
2569            | Self::AfterDispatch(error)
2570            | Self::Rejected { error, .. } => error,
2571        }
2572    }
2573}
2574
2575fn cancel_errors_for_requests(
2576    errors: Vec<Option<String>>,
2577    request_count: usize,
2578) -> HyperliquidResult<Vec<Option<String>>> {
2579    if errors.is_empty() {
2580        return Ok(vec![None; request_count]);
2581    }
2582
2583    if errors.len() != request_count {
2584        return Err(HyperliquidError::exchange(format!(
2585            "Cancel orders returned {} statuses for {request_count} cancels",
2586            errors.len()
2587        )));
2588    }
2589
2590    Ok(errors)
2591}
2592
2593fn map_post_payload_error(payload: String, weight: u32) -> HyperliquidError {
2594    let lower = payload.to_ascii_lowercase();
2595    let message = format!("WebSocket post error: {payload}");
2596
2597    if starts_with_status(&lower, &["429"])
2598        || lower.contains("too many requests")
2599        || lower.contains("rate limit")
2600    {
2601        HyperliquidError::rate_limit("exchange", weight, None)
2602    } else if starts_with_status(&lower, &["401", "403"])
2603        || lower.contains("unauthorized")
2604        || lower.contains("forbidden")
2605        || lower.contains("authentication")
2606        || lower.contains("authorization")
2607        || lower.contains("invalid signature")
2608        || contains_word(&lower, "auth")
2609    {
2610        HyperliquidError::auth(message)
2611    } else if starts_with_status(&lower, &["400"]) || lower.contains("bad request") {
2612        HyperliquidError::bad_request(message)
2613    } else if starts_with_status(&lower, &["500", "502", "503", "504"]) {
2614        HyperliquidError::exchange(message)
2615    } else {
2616        HyperliquidError::exchange(payload)
2617    }
2618}
2619
2620fn hyperliquid_order_kind(
2621    order_type: OrderType,
2622    time_in_force: TimeInForce,
2623    post_only: bool,
2624    trigger_price: Option<Price>,
2625    normalize_prices_enabled: bool,
2626    price_precision: Option<u8>,
2627) -> HyperliquidResult<HyperliquidExchangeOrderKind> {
2628    match order_type {
2629        OrderType::Market => Ok(HyperliquidExchangeOrderKind::Limit {
2630            limit: HyperliquidExchangeLimitParams {
2631                tif: HyperliquidExchangeTif::Ioc,
2632            },
2633        }),
2634        OrderType::Limit => {
2635            let tif = time_in_force_to_hyperliquid_tif(time_in_force, post_only)
2636                .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?;
2637            Ok(HyperliquidExchangeOrderKind::Limit {
2638                limit: HyperliquidExchangeLimitParams { tif },
2639            })
2640        }
2641        OrderType::StopMarket
2642        | OrderType::StopLimit
2643        | OrderType::MarketIfTouched
2644        | OrderType::LimitIfTouched => {
2645            let trigger_price = trigger_price.ok_or_else(|| {
2646                HyperliquidError::bad_request("Trigger orders require a trigger price")
2647            })?;
2648            let trigger_px = normalize_or_validate_wire_price(
2649                trigger_price.as_decimal(),
2650                "Trigger price",
2651                price_precision,
2652                normalize_prices_enabled,
2653            )
2654            .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?;
2655            let tpsl = match order_type {
2656                OrderType::StopMarket | OrderType::StopLimit => HyperliquidExchangeTpSl::Sl,
2657                OrderType::MarketIfTouched | OrderType::LimitIfTouched => {
2658                    HyperliquidExchangeTpSl::Tp
2659                }
2660                _ => unreachable!(),
2661            };
2662            let is_market = matches!(
2663                order_type,
2664                OrderType::StopMarket | OrderType::MarketIfTouched
2665            );
2666
2667            Ok(HyperliquidExchangeOrderKind::Trigger {
2668                trigger: HyperliquidExchangeTriggerParams {
2669                    is_market,
2670                    trigger_px,
2671                    tpsl,
2672                },
2673            })
2674        }
2675        _ => Err(HyperliquidError::bad_request(format!(
2676            "Order type {order_type:?} not supported"
2677        ))),
2678    }
2679}
2680
2681fn ensure_ws_action_accepted(
2682    response: &HyperliquidExchangeResponse,
2683    action_name: &str,
2684) -> HyperliquidResult<()> {
2685    if response.is_ok() {
2686        if let Some(error_msg) = extract_inner_errors(response).into_iter().flatten().next() {
2687            return Err(HyperliquidError::bad_request(format!(
2688                "{action_name} rejected: {error_msg}"
2689            )));
2690        }
2691
2692        if let Some(error_msg) = extract_inner_error(response) {
2693            return Err(HyperliquidError::bad_request(format!(
2694                "{action_name} rejected: {error_msg}"
2695            )));
2696        }
2697
2698        return Ok(());
2699    }
2700
2701    Err(HyperliquidError::bad_request(format!(
2702        "{action_name} failed: {}",
2703        extract_error_message(response)
2704    )))
2705}
2706
2707fn starts_with_status(payload: &str, statuses: &[&str]) -> bool {
2708    let trimmed = payload.trim_start();
2709    statuses
2710        .iter()
2711        .any(|status| starts_with_status_token(trimmed, status))
2712        || trimmed.strip_prefix("http").is_some_and(|rest| {
2713            let rest = rest
2714                .trim_start_matches(|c: char| c.is_ascii_whitespace() || matches!(c, ':' | '/'));
2715            statuses
2716                .iter()
2717                .any(|status| starts_with_status_token(rest, status))
2718        })
2719}
2720
2721fn starts_with_status_token(payload: &str, status: &str) -> bool {
2722    payload.strip_prefix(status).is_some_and(|rest| {
2723        rest.chars()
2724            .next()
2725            .is_none_or(|c| !c.is_ascii_alphanumeric())
2726    })
2727}
2728
2729fn contains_word(payload: &str, word: &str) -> bool {
2730    payload
2731        .split(|c: char| !c.is_ascii_alphanumeric())
2732        .any(|part| part == word)
2733}
2734
2735// Uses split_once/rsplit_once because coin names can contain colons
2736// (e.g., vault tokens `vntls:vCURSOR`)
2737fn subscription_from_topic(topic: &str) -> anyhow::Result<SubscriptionRequest> {
2738    let (kind, rest) = topic
2739        .split_once(':')
2740        .map_or((topic, None), |(k, r)| (k, Some(r)));
2741
2742    let channel = HyperliquidWsChannel::from_wire_str(kind)
2743        .ok_or_else(|| anyhow::anyhow!("Unknown subscription channel: {kind}"))?;
2744
2745    match channel {
2746        HyperliquidWsChannel::AllMids => Ok(SubscriptionRequest::AllMids {
2747            dex: rest.map(|s| s.to_string()),
2748        }),
2749        HyperliquidWsChannel::AllDexsAssetCtxs => Ok(SubscriptionRequest::AllDexsAssetCtxs),
2750        HyperliquidWsChannel::Notification => Ok(SubscriptionRequest::Notification {
2751            user: rest.context("Missing user")?.to_string(),
2752        }),
2753        HyperliquidWsChannel::WebData2 => Ok(SubscriptionRequest::WebData2 {
2754            user: rest.context("Missing user")?.to_string(),
2755        }),
2756        HyperliquidWsChannel::ClearinghouseState => Ok(SubscriptionRequest::ClearinghouseState {
2757            user: rest.context("Missing user")?.to_string(),
2758        }),
2759        HyperliquidWsChannel::SpotState => {
2760            let (user, is_portfolio_margin) = rest
2761                .context("Missing spot state params")?
2762                .rsplit_once(':')
2763                .context("Missing portfolio margin flag")?;
2764            Ok(SubscriptionRequest::SpotState {
2765                user: user.to_string(),
2766                is_portfolio_margin: is_portfolio_margin.parse()?,
2767            })
2768        }
2769        HyperliquidWsChannel::Candle => {
2770            // Format: candle:{coin}:{interval} - interval is last segment
2771            let rest = rest.context("Missing candle params")?;
2772            let (coin, interval_str) = rest.rsplit_once(':').context("Missing interval")?;
2773            let interval = HyperliquidBarInterval::from_str(interval_str)?;
2774            Ok(SubscriptionRequest::Candle {
2775                coin: Ustr::from(coin),
2776                interval,
2777            })
2778        }
2779        HyperliquidWsChannel::L2Book => Ok(SubscriptionRequest::L2Book {
2780            coin: Ustr::from(rest.context("Missing coin")?),
2781            mantissa: None,
2782            n_sig_figs: None,
2783        }),
2784        HyperliquidWsChannel::Trades => Ok(SubscriptionRequest::Trades {
2785            coin: Ustr::from(rest.context("Missing coin")?),
2786        }),
2787        HyperliquidWsChannel::OrderUpdates => Ok(SubscriptionRequest::OrderUpdates {
2788            user: rest.context("Missing user")?.to_string(),
2789        }),
2790        HyperliquidWsChannel::UserEvents => Ok(SubscriptionRequest::UserEvents {
2791            user: rest.context("Missing user")?.to_string(),
2792        }),
2793        HyperliquidWsChannel::UserFills => Ok(SubscriptionRequest::UserFills {
2794            user: rest.context("Missing user")?.to_string(),
2795            aggregate_by_time: None,
2796        }),
2797        HyperliquidWsChannel::UserFundings => Ok(SubscriptionRequest::UserFundings {
2798            user: rest.context("Missing user")?.to_string(),
2799        }),
2800        HyperliquidWsChannel::UserNonFundingLedgerUpdates => {
2801            Ok(SubscriptionRequest::UserNonFundingLedgerUpdates {
2802                user: rest.context("Missing user")?.to_string(),
2803            })
2804        }
2805        HyperliquidWsChannel::ActiveAssetCtx => Ok(SubscriptionRequest::ActiveAssetCtx {
2806            coin: Ustr::from(rest.context("Missing coin")?),
2807        }),
2808        HyperliquidWsChannel::ActiveSpotAssetCtx => Ok(SubscriptionRequest::ActiveSpotAssetCtx {
2809            coin: Ustr::from(rest.context("Missing coin")?),
2810        }),
2811        HyperliquidWsChannel::ActiveAssetData => {
2812            // Format: activeAssetData:{user}:{coin} - user is eth addr (no colons)
2813            let rest = rest.context("Missing params")?;
2814            let (user, coin) = rest.split_once(':').context("Missing coin")?;
2815            Ok(SubscriptionRequest::ActiveAssetData {
2816                user: user.to_string(),
2817                coin: coin.to_string(),
2818            })
2819        }
2820        HyperliquidWsChannel::UserTwapSliceFills => Ok(SubscriptionRequest::UserTwapSliceFills {
2821            user: rest.context("Missing user")?.to_string(),
2822        }),
2823        HyperliquidWsChannel::UserTwapHistory => Ok(SubscriptionRequest::UserTwapHistory {
2824            user: rest.context("Missing user")?.to_string(),
2825        }),
2826        HyperliquidWsChannel::Bbo => Ok(SubscriptionRequest::Bbo {
2827            coin: Ustr::from(rest.context("Missing coin")?),
2828        }),
2829
2830        // Response-only channels are not valid subscription topics
2831        HyperliquidWsChannel::SubscriptionResponse
2832        | HyperliquidWsChannel::User
2833        | HyperliquidWsChannel::Post
2834        | HyperliquidWsChannel::Pong
2835        | HyperliquidWsChannel::Error => {
2836            anyhow::bail!("Not a subscription channel: {kind}")
2837        }
2838    }
2839}
2840
2841#[cfg(test)]
2842mod tests {
2843    use futures_util::StreamExt;
2844    use nautilus_live::{SocketReconnectRegistry, SocketReconnectRequestOutcome};
2845    use nautilus_model::{identifiers::ClientId, instruments::stubs::crypto_perpetual_ethusdt};
2846    use nautilus_network::mode::ReconnectRequestOutcome;
2847    use nautilus_testkit::connection::race_command_with_publication;
2848    use rstest::rstest;
2849    use ustr::Ustr;
2850
2851    use super::*;
2852    use crate::{
2853        common::{
2854            consts::{HYPERLIQUID_WS_POST_INFLIGHT_MAX, HYPERLIQUID_WS_SUBSCRIPTIONS_MAX},
2855            enums::HyperliquidBarInterval,
2856        },
2857        websocket::handler::subscription_to_key,
2858    };
2859
2860    #[tokio::test]
2861    async fn initialization_waits_for_acknowledgement() {
2862        let mut ws_client = HyperliquidWebSocketClient::new(
2863            None,
2864            HyperliquidEnvironment::Testnet,
2865            None,
2866            TransportBackend::default(),
2867            None,
2868        );
2869        let observer = ws_client.clone();
2870        let mode = Arc::new(AtomicU8::new(ConnectionMode::Active as u8));
2871        let (initialized_tx, initialized_rx) = tokio::sync::oneshot::channel();
2872        let mut initialization =
2873            Box::pin(ws_client.wait_for_initialization(initialized_rx, Arc::clone(&mode)));
2874
2875        let polled =
2876            std::future::poll_fn(|cx| std::task::Poll::Ready(initialization.as_mut().poll(cx)))
2877                .await;
2878        assert!(polled.is_pending());
2879        assert!(!observer.is_active());
2880
2881        initialized_tx.send(()).unwrap();
2882        initialization.await.unwrap();
2883
2884        assert!(observer.is_active());
2885        assert!(Arc::ptr_eq(&observer.connection_mode.load_full(), &mode));
2886    }
2887
2888    #[rstest]
2889    #[case::closed(false)]
2890    #[case::timeout(true)]
2891    #[tokio::test(start_paused = true)]
2892    async fn initialization_failure_releases_runtime(#[case] timeout: bool) {
2893        let mut ws_client = HyperliquidWebSocketClient::new(
2894            None,
2895            HyperliquidEnvironment::Testnet,
2896            None,
2897            TransportBackend::default(),
2898            None,
2899        );
2900        ws_client.rate_limits = Arc::new(WebSocketRateLimits::new());
2901        let available = ws_client.rate_limits.connection_slots.available_permits();
2902        *ws_client.connection_permit.lock() = Some(
2903            Arc::clone(&ws_client.rate_limits.connection_slots)
2904                .try_acquire_owned()
2905                .unwrap(),
2906        );
2907
2908        let (_out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel();
2909        ws_client.out_rx = Some(out_rx);
2910        let (initialized_tx, initialized_rx) = tokio::sync::oneshot::channel();
2911        let initialized_tx = timeout.then_some(initialized_tx);
2912        let mode = Arc::new(AtomicU8::new(ConnectionMode::Active as u8));
2913        let started = tokio::time::Instant::now();
2914
2915        let error = ws_client
2916            .wait_for_initialization(initialized_rx, mode)
2917            .await
2918            .unwrap_err();
2919        drop(initialized_tx);
2920
2921        let expected = if timeout {
2922            "Hyperliquid WebSocket handler initialization timed out"
2923        } else {
2924            "Hyperliquid WebSocket handler stopped before initialization"
2925        };
2926
2927        assert_eq!(error.to_string(), expected);
2928        assert_eq!(
2929            tokio::time::Instant::now() - started,
2930            if timeout {
2931                HTTP_TIMEOUT
2932            } else {
2933                Duration::ZERO
2934            },
2935        );
2936        assert!(!ws_client.is_active());
2937        assert!(ws_client.out_rx.is_none());
2938        assert!(ws_client.task_handle.is_empty());
2939        assert!(ws_client.connection_permit.lock().is_none());
2940        assert_eq!(
2941            ws_client.rate_limits.connection_slots.available_permits(),
2942            available,
2943        );
2944    }
2945
2946    #[tokio::test]
2947    async fn cancelled_initialization_rejects_stale_acknowledgement() {
2948        let mut ws_client = HyperliquidWebSocketClient::new(
2949            None,
2950            HyperliquidEnvironment::Testnet,
2951            None,
2952            TransportBackend::default(),
2953            None,
2954        );
2955        ws_client.rate_limits = Arc::new(WebSocketRateLimits::new());
2956        let available = ws_client.rate_limits.connection_slots.available_permits();
2957        *ws_client.connection_permit.lock() = Some(
2958            Arc::clone(&ws_client.rate_limits.connection_slots)
2959                .try_acquire_owned()
2960                .unwrap(),
2961        );
2962
2963        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
2964        let (stopped_tx, stopped_rx) = tokio::sync::oneshot::channel::<()>();
2965        ws_client
2966            .task_handle
2967            .spawn(async move {
2968                let _stopped_tx = stopped_tx;
2969                started_tx.send(()).unwrap();
2970                std::future::pending::<()>().await;
2971            })
2972            .unwrap();
2973
2974        started_rx.await.unwrap();
2975        let observer = ws_client.clone();
2976        let old_mode = Arc::new(AtomicU8::new(ConnectionMode::Active as u8));
2977        let (old_tx, old_rx) = tokio::sync::oneshot::channel();
2978        let mut initialization =
2979            Box::pin(ws_client.wait_for_initialization(old_rx, Arc::clone(&old_mode)));
2980        let polled =
2981            std::future::poll_fn(|cx| std::task::Poll::Ready(initialization.as_mut().poll(cx)))
2982                .await;
2983        assert!(polled.is_pending());
2984        drop(initialization);
2985        assert!(
2986            tokio::time::timeout(Duration::from_secs(1), stopped_rx)
2987                .await
2988                .unwrap()
2989                .is_err(),
2990        );
2991        assert!(ws_client.connection_permit.lock().is_none());
2992        ws_client.disconnect_locked().await.unwrap();
2993
2994        assert!(ws_client.task_handle.is_empty());
2995        assert_eq!(
2996            ws_client.rate_limits.connection_slots.available_permits(),
2997            available,
2998        );
2999
3000        let new_mode = Arc::new(AtomicU8::new(ConnectionMode::Active as u8));
3001        let (new_tx, new_rx) = tokio::sync::oneshot::channel();
3002        let mut initialization =
3003            Box::pin(ws_client.wait_for_initialization(new_rx, Arc::clone(&new_mode)));
3004        let polled =
3005            std::future::poll_fn(|cx| std::task::Poll::Ready(initialization.as_mut().poll(cx)))
3006                .await;
3007        assert!(polled.is_pending());
3008
3009        assert_eq!(old_tx.send(()), Err(()));
3010        assert!(!observer.is_active());
3011        new_tx.send(()).unwrap();
3012        initialization.await.unwrap();
3013
3014        assert!(observer.is_active());
3015        assert!(Arc::ptr_eq(
3016            &observer.connection_mode.load_full(),
3017            &new_mode
3018        ));
3019        assert!(!Arc::ptr_eq(
3020            &observer.connection_mode.load_full(),
3021            &old_mode
3022        ));
3023    }
3024
3025    #[rstest]
3026    fn cache_sender_reset_isolates_connection_generation() {
3027        let mut ws_client = HyperliquidWebSocketClient::new(
3028            Some("wss://test".to_string()),
3029            HyperliquidEnvironment::Testnet,
3030            None,
3031            TransportBackend::default(),
3032            None,
3033        );
3034        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
3035        *ws_client.cache_tx.lock() = cmd_tx;
3036        let old = ws_client.clone();
3037        ws_client.reset_runtime_state();
3038        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
3039
3040        old.cache_instrument(instrument.clone());
3041        ws_client.cache_instrument(instrument.clone());
3042
3043        assert!(!Arc::ptr_eq(&ws_client.cache_tx, &old.cache_tx));
3044        assert!(ws_client.cache_tx.lock().is_closed());
3045        assert!(!old.cache_tx.lock().is_closed());
3046
3047        match cmd_rx.try_recv().unwrap() {
3048            HandlerCommand::UpdateInstrument(updated) => assert_eq!(updated, instrument),
3049            command => panic!("unexpected instrument command: {command:?}"),
3050        }
3051
3052        assert!(cmd_rx.try_recv().is_err());
3053    }
3054
3055    #[rstest]
3056    fn batch_cache_merges_disjoint_updates_and_preserves_commands() {
3057        let ws_client = HyperliquidWebSocketClient::new(
3058            Some("wss://test".to_string()),
3059            HyperliquidEnvironment::Testnet,
3060            None,
3061            TransportBackend::default(),
3062            None,
3063        );
3064        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
3065        *ws_client.cache_tx.lock() = sender;
3066        let mut first = crypto_perpetual_ethusdt();
3067        first.raw_symbol = "FIRST".into();
3068        first.ts_event = 17.into();
3069        let mut second = first.clone();
3070        second.id = "BTCUSDT.HYPERLIQUID".into();
3071        second.raw_symbol = "SECOND".into();
3072        second.ts_event = 29.into();
3073        let batches = [
3074            vec![InstrumentAny::CryptoPerpetual(first)],
3075            vec![InstrumentAny::CryptoPerpetual(second)],
3076        ];
3077        let barrier = std::sync::Barrier::new(2);
3078        std::thread::scope(|scope| {
3079            for batch in &batches {
3080                let client = &ws_client;
3081                let barrier = &barrier;
3082                scope.spawn(move || {
3083                    barrier.wait();
3084                    client.merge_instruments(batch);
3085                });
3086            }
3087        });
3088
3089        assert_eq!(ws_client.instruments.len(), 2);
3090        let mut received = AHashMap::new();
3091
3092        for _ in 0..2 {
3093            let HandlerCommand::UpdateInstrument(instrument) = receiver.try_recv().unwrap() else {
3094                panic!("expected UpdateInstrument");
3095            };
3096
3097            received.insert(instrument.raw_symbol().inner(), instrument);
3098        }
3099
3100        for instrument in batches.iter().flatten() {
3101            let key = instrument.raw_symbol().inner();
3102            let expected = serde_json::to_value(instrument).unwrap();
3103            assert_eq!(
3104                serde_json::to_value(ws_client.instruments.get_cloned(&key).unwrap()).unwrap(),
3105                expected
3106            );
3107            assert_eq!(serde_json::to_value(&received[&key]).unwrap(), expected);
3108        }
3109
3110        assert!(receiver.try_recv().is_err());
3111    }
3112
3113    #[tokio::test]
3114    async fn cache_updates_reach_handler_while_recovery_holds_sender() {
3115        let ws_client = HyperliquidWebSocketClient::new(
3116            Some("wss://test".to_string()),
3117            HyperliquidEnvironment::Testnet,
3118            None,
3119            TransportBackend::default(),
3120            None,
3121        );
3122        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
3123        *ws_client.cmd_tx.write().await = cmd_tx.clone();
3124        *ws_client.cache_tx.lock() = cmd_tx;
3125        ws_client
3126            .connection_mode
3127            .store(Arc::new(AtomicU8::new(ConnectionMode::Active as u8)));
3128        let writer = ws_client.cmd_tx.write().await;
3129        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
3130        let instrument_id = instrument.id();
3131        let mapping =
3132            AHashMap::from_iter([(Ustr::from("test-dex"), vec![None, Some(instrument_id)])]);
3133
3134        ws_client.cache_instrument(instrument.clone());
3135        ws_client.cache_all_dex_asset_ctxs_instrument_ids(mapping.clone());
3136        drop(writer);
3137
3138        assert_eq!(
3139            ws_client
3140                .instruments
3141                .get_cloned(&instrument.raw_symbol().inner()),
3142            Some(instrument.clone())
3143        );
3144        assert_eq!(
3145            ws_client.all_dex_asset_ctxs_instrument_ids.load().as_ref(),
3146            &mapping
3147        );
3148
3149        match cmd_rx.try_recv().unwrap() {
3150            HandlerCommand::UpdateInstrument(updated) => assert_eq!(updated, instrument),
3151            command => panic!("unexpected instrument command: {command:?}"),
3152        }
3153
3154        match cmd_rx.try_recv().unwrap() {
3155            HandlerCommand::CacheAllDexAssetCtxsInstrumentIds(updated) => {
3156                assert_eq!(updated, mapping);
3157            }
3158            command => panic!("unexpected context command: {command:?}"),
3159        }
3160
3161        assert!(cmd_rx.try_recv().is_err());
3162    }
3163
3164    #[rstest]
3165    #[case::publication(false)]
3166    #[case::readiness(true)]
3167    #[tokio::test]
3168    async fn command_at_publication_or_readiness_reaches_handler(#[case] readiness: bool) {
3169        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3170        let addr = listener.local_addr().unwrap();
3171        let (received_tx, mut received_rx) = tokio::sync::mpsc::unbounded_channel();
3172
3173        let server = tokio::spawn(async move {
3174            let (socket, _) = listener.accept().await.unwrap();
3175            let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
3176            while let Some(Ok(message)) = socket.next().await {
3177                if let tokio_tungstenite::tungstenite::Message::Text(text) = message {
3178                    let payload: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
3179                    let _ = received_tx.send(payload);
3180                }
3181            }
3182        });
3183
3184        let url = format!("ws://{addr}");
3185
3186        let mut ws_client = HyperliquidWebSocketClient::new(
3187            Some(url),
3188            HyperliquidEnvironment::Testnet,
3189            None,
3190            TransportBackend::default(),
3191            None,
3192        );
3193        let observer = ws_client.clone();
3194
3195        let command = HandlerCommand::Subscribe {
3196            subscriptions: vec![SubscriptionRequest::Trades {
3197                coin: Ustr::from("BTC"),
3198            }],
3199        };
3200
3201        if readiness {
3202            let mut connect = Box::pin(ws_client.connect());
3203            let mut command = Some(command);
3204
3205            let result = tokio::time::timeout(
3206                Duration::from_secs(5),
3207                std::future::poll_fn(|cx| {
3208                    let polled = connect.as_mut().poll(cx);
3209
3210                    if observer.is_active()
3211                        && let Some(command) = command.take()
3212                    {
3213                        assert!(polled.is_ready(), "readiness must follow initialization");
3214                        observer.cmd_tx.try_read().unwrap().send(command).unwrap();
3215                    }
3216
3217                    polled
3218                }),
3219            )
3220            .await
3221            .expect("connect must publish readiness");
3222
3223            result.expect("connect failed");
3224            assert!(command.is_none(), "command must be sent at first readiness");
3225        } else {
3226            let publication_observer = observer.clone();
3227            race_command_with_publication(
3228                Arc::clone(&ws_client.cmd_tx),
3229                ws_client.connect(),
3230                move || {
3231                    assert!(!publication_observer.is_active());
3232                    command
3233                },
3234                || observer.is_active(),
3235            )
3236            .await
3237            .expect("connect failed");
3238        }
3239
3240        let command_sender = ws_client.cmd_tx.read().await.clone();
3241        assert!(ws_client.cache_tx.lock().same_channel(&command_sender));
3242        let received = tokio::time::timeout(Duration::from_secs(2), received_rx.recv()).await;
3243        ws_client.disconnect().await.expect("disconnect failed");
3244        server.abort();
3245
3246        let payload = received
3247            .expect("startup command must reach server")
3248            .unwrap();
3249        assert_eq!(
3250            payload,
3251            serde_json::json!({
3252                "method": "subscribe",
3253                "subscription": {
3254                    "type": "trades",
3255                    "coin": "BTC"
3256                }
3257            })
3258        );
3259    }
3260
3261    #[tokio::test]
3262    #[ignore = "connects to Hyperliquid mainnet public market data"]
3263    async fn mainnet_initialization_routes_subscription() {
3264        let http_client =
3265            HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 15, None).unwrap();
3266        let instruments = http_client.request_instruments().await.unwrap();
3267        let instrument = instruments
3268            .into_iter()
3269            .find(|instrument| instrument.raw_symbol().as_str() == "BTC")
3270            .expect("BTC perpetual must exist");
3271        let instrument_id = instrument.id();
3272
3273        let mut ws_client = HyperliquidWebSocketClient::new(
3274            None,
3275            HyperliquidEnvironment::Mainnet,
3276            None,
3277            TransportBackend::default(),
3278            None,
3279        );
3280        ws_client.cache_instrument(instrument);
3281
3282        ws_client.connect().await.unwrap();
3283        assert!(ws_client.is_active());
3284        ws_client.subscribe_trades(instrument_id).await.unwrap();
3285        let received = tokio::time::timeout(Duration::from_secs(15), ws_client.next_event()).await;
3286        ws_client.disconnect().await.unwrap();
3287
3288        let Some(NautilusWsMessage::Trades(trades)) = received.unwrap() else {
3289            panic!("expected BTC trades after immediate subscription");
3290        };
3291
3292        assert!(!trades.is_empty());
3293        assert!(
3294            trades
3295                .iter()
3296                .all(|trade| trade.instrument_id == instrument_id)
3297        );
3298        assert!(!ws_client.is_active());
3299    }
3300
3301    #[rstest]
3302    #[case("wss://stream.example.com/feed", "wss://stream.example.com")]
3303    #[case(
3304        "wss://SYN-user:SYN-password@stream.example.com:9443/SYN-path?token=SYN-query#SYN-fragment",
3305        "wss://stream.example.com:9443"
3306    )]
3307    fn test_debug_preserves_url_origin(#[case] url: &str, #[case] origin: &str) {
3308        let client = HyperliquidWebSocketClient::new(
3309            Some(url.to_string()),
3310            HyperliquidEnvironment::Testnet,
3311            None,
3312            TransportBackend::default(),
3313            None,
3314        );
3315        let debug = format!("{client:?}");
3316        assert!(debug.contains(&format!("url: {origin:?}")));
3317        assert!(!debug.contains("SYN-"));
3318        assert_eq!(client.url.expose(), url);
3319    }
3320
3321    #[rstest]
3322    fn test_debug_redacts_proxy_url() {
3323        let proxy_url = "http://user:password@proxy.example:8080";
3324        let client = HyperliquidWebSocketClient::new(
3325            Some("wss://test".to_string()),
3326            HyperliquidEnvironment::Testnet,
3327            None,
3328            TransportBackend::default(),
3329            Some(proxy_url.to_string()),
3330        );
3331
3332        let debug = format!("{client:?}");
3333
3334        assert!(debug.contains(REDACTED));
3335        assert!(!debug.contains(proxy_url));
3336    }
3337
3338    #[rstest]
3339    fn test_cache_all_dex_asset_ctxs_instrument_ids_keeps_dexes_absent_from_update() {
3340        let client = HyperliquidWebSocketClient::new(
3341            Some("wss://test".to_string()),
3342            HyperliquidEnvironment::Testnet,
3343            None,
3344            TransportBackend::default(),
3345            None,
3346        );
3347        let btc = Some(InstrumentId::from("BTC-USD-PERP.HYPERLIQUID"));
3348        let eth = Some(InstrumentId::from("ETH-USD-PERP.HYPERLIQUID"));
3349        let tsla = Some(InstrumentId::from("xyz:TSLA-USD-PERP.HYPERLIQUID"));
3350
3351        client.cache_all_dex_asset_ctxs_instrument_ids(AHashMap::from_iter([
3352            (Ustr::from(""), vec![btc]),
3353            (Ustr::from("xyz"), vec![tsla]),
3354        ]));
3355        // a `meta` fallback build covers only the default dex
3356        client.cache_all_dex_asset_ctxs_instrument_ids(AHashMap::from_iter([(
3357            Ustr::from(""),
3358            vec![btc, eth],
3359        )]));
3360
3361        let cached = client.all_dex_asset_ctxs_instrument_ids.load();
3362        assert_eq!(cached.len(), 2);
3363        assert_eq!(cached.get(&Ustr::from("")), Some(&vec![btc, eth]));
3364        assert_eq!(cached.get(&Ustr::from("xyz")), Some(&vec![tsla]));
3365    }
3366
3367    #[tokio::test]
3368    async fn test_drop_clone_does_not_stop_handler() {
3369        let client = HyperliquidWebSocketClient::new(
3370            Some("wss://test".to_string()),
3371            HyperliquidEnvironment::Testnet,
3372            None,
3373            TransportBackend::default(),
3374            None,
3375        );
3376        client
3377            .task_handle
3378            .insert(get_runtime().spawn(std::future::pending()));
3379        let clone = client.clone();
3380
3381        drop(clone);
3382
3383        assert!(!client.signal.load(Ordering::Acquire));
3384        assert!(!client.task_handle.is_empty());
3385    }
3386
3387    /// Generates a unique topic key for a subscription request.
3388    fn subscription_topic(sub: &SubscriptionRequest) -> String {
3389        subscription_to_key(sub)
3390    }
3391
3392    #[rstest]
3393    #[case(SubscriptionRequest::Trades { coin: "BTC".into() }, "trades:BTC")]
3394    #[case(SubscriptionRequest::Bbo { coin: "BTC".into() }, "bbo:BTC")]
3395    #[case(SubscriptionRequest::OrderUpdates { user: "0x123".to_string() }, "orderUpdates:0x123")]
3396    #[case(SubscriptionRequest::UserEvents { user: "0xabc".to_string() }, "userEvents:0xabc")]
3397    #[case(SubscriptionRequest::ClearinghouseState { user: "0xabc".to_string() }, "clearinghouseState:0xabc")]
3398    #[case(SubscriptionRequest::SpotState { user: "0xabc".to_string(), is_portfolio_margin: false }, "spotState:0xabc:false")]
3399    #[case(SubscriptionRequest::SpotState { user: "0xabc".to_string(), is_portfolio_margin: true }, "spotState:0xabc:true")]
3400    fn test_subscription_topic_generation(
3401        #[case] subscription: SubscriptionRequest,
3402        #[case] expected_topic: &str,
3403    ) {
3404        assert_eq!(subscription_topic(&subscription), expected_topic);
3405    }
3406
3407    #[rstest]
3408    fn test_subscription_topics_unique() {
3409        let sub1 = SubscriptionRequest::Trades { coin: "BTC".into() };
3410        let sub2 = SubscriptionRequest::Bbo { coin: "BTC".into() };
3411
3412        let topic1 = subscription_topic(&sub1);
3413        let topic2 = subscription_topic(&sub2);
3414
3415        assert_ne!(topic1, topic2);
3416    }
3417
3418    #[rstest]
3419    #[case(SubscriptionRequest::Trades { coin: "BTC".into() })]
3420    #[case(SubscriptionRequest::Bbo { coin: "ETH".into() })]
3421    #[case(SubscriptionRequest::Candle { coin: "SOL".into(), interval: HyperliquidBarInterval::OneHour })]
3422    #[case(SubscriptionRequest::OrderUpdates { user: "0x123".to_string() })]
3423    #[case(SubscriptionRequest::ClearinghouseState { user: "0x123".to_string() })]
3424    #[case(SubscriptionRequest::SpotState { user: "0x123".to_string(), is_portfolio_margin: false })]
3425    #[case(SubscriptionRequest::SpotState { user: "0x123".to_string(), is_portfolio_margin: true })]
3426    #[case(SubscriptionRequest::Trades { coin: "vntls:vCURSOR".into() })]
3427    #[case(SubscriptionRequest::L2Book { coin: "vntls:vCURSOR".into(), mantissa: None, n_sig_figs: None })]
3428    #[case(SubscriptionRequest::Candle { coin: "vntls:vCURSOR".into(), interval: HyperliquidBarInterval::OneHour })]
3429    fn test_subscription_reconstruction(#[case] subscription: SubscriptionRequest) {
3430        let topic = subscription_topic(&subscription);
3431        let reconstructed = subscription_from_topic(&topic).expect("Failed to reconstruct");
3432        assert_eq!(subscription_topic(&reconstructed), topic);
3433    }
3434
3435    #[rstest]
3436    fn malformed_post_payload_errors_omit_private_data() {
3437        let ws_client = HyperliquidWebSocketClient::new(
3438            None,
3439            HyperliquidEnvironment::Mainnet,
3440            None,
3441            TransportBackend::default(),
3442            None,
3443        );
3444        let fixtures: serde_json::Value = serde_json::from_str(include_str!(
3445            "../../test_data/ws_malformed_private_frames.json"
3446        ))
3447        .unwrap();
3448
3449        for payload in fixtures["post_valid_payloads"].as_array().unwrap() {
3450            let parsed = ws_client.parse_post_action_payload(payload).unwrap();
3451            assert_eq!(serde_json::to_value(parsed).unwrap(), *payload);
3452        }
3453
3454        let payload = &fixtures["post_payload"];
3455        let e = ws_client.parse_post_action_payload(payload).unwrap_err();
3456        let diagnostic = e.to_string();
3457        let unexpected =
3458            HyperliquidError::decode(ws_client.post_decode_context(payload, "unexpected_info"))
3459                .to_string();
3460
3461        assert!(matches!(e, HyperliquidError::Serde(_)));
3462        assert_eq!(
3463            diagnostic,
3464            format!(
3465                "serde error: Invalid WebSocket post response: class=action, client_id={}, payload_bytes={}, category=Data",
3466                ws_client.client_id,
3467                payload.to_string().len()
3468            )
3469        );
3470        assert_eq!(
3471            unexpected,
3472            format!(
3473                "decode error: Invalid WebSocket post response: class=action, client_id={}, payload_bytes={}, category=unexpected_info",
3474                ws_client.client_id,
3475                payload.to_string().len()
3476            )
3477        );
3478
3479        for secret in fixtures["secrets"].as_array().unwrap() {
3480            let secret = secret.as_str().unwrap();
3481            assert!(!diagnostic.contains(secret));
3482            assert!(!unexpected.contains(secret));
3483        }
3484    }
3485
3486    #[rstest]
3487    #[case("post_unexpected_status", "post_unexpected_status_bytes")]
3488    #[case("post_unexpected_status_string", "post_unexpected_status_string_bytes")]
3489    fn unknown_post_status_omits_private_data(#[case] payload_key: &str, #[case] bytes_key: &str) {
3490        let ws_client = HyperliquidWebSocketClient::new(
3491            None,
3492            HyperliquidEnvironment::Mainnet,
3493            None,
3494            TransportBackend::default(),
3495            None,
3496        );
3497        let fixtures: serde_json::Value = serde_json::from_str(include_str!(
3498            "../../test_data/ws_malformed_private_frames.json"
3499        ))
3500        .unwrap();
3501        let parsed = ws_client
3502            .parse_post_action_payload(&fixtures[payload_key])
3503            .unwrap();
3504        let cancel_errors = ws_client.cancel_response_errors(&parsed, 2);
3505        let failure = ws_client.check_post_action_response(parsed).unwrap_err();
3506
3507        let PostRequestError::AfterDispatch(e) = failure else {
3508            panic!("unknown status must remain an ambiguous dispatched result");
3509        };
3510
3511        let diagnostic = e.to_string();
3512        let debug = format!("{e:?}");
3513        let success = ws_client
3514            .parse_post_action_payload(&fixtures["post_valid_payloads"][0])
3515            .unwrap();
3516        let success = ws_client.check_post_action_response(success).unwrap();
3517        let rejected = ws_client
3518            .parse_post_action_payload(&fixtures["post_business_rejection"])
3519            .unwrap();
3520        let cancel_rejections = ws_client.cancel_response_errors(&rejected, 3);
3521        let rejected = ws_client.check_post_action_response(rejected).unwrap_err();
3522
3523        let PostRequestError::Rejected { error, reason } = rejected else {
3524            panic!("known rejection must remain rejected");
3525        };
3526
3527        assert!(matches!(&e, HyperliquidError::BadRequest(_)));
3528        assert_eq!(
3529            cancel_errors,
3530            vec![Some(format!("Cancel orders failed: {diagnostic}")); 2]
3531        );
3532        assert_eq!(
3533            cancel_rejections,
3534            vec![Some("Cancel orders failed: Known venue rejection".to_string()); 3]
3535        );
3536        assert_eq!(
3537            diagnostic,
3538            format!(
3539                "bad request: Invalid WebSocket post response: class=action, client_id={}, payload_bytes={}, category=unexpected_status",
3540                ws_client.client_id,
3541                fixtures[bytes_key].as_u64().unwrap(),
3542            )
3543        );
3544        assert_eq!(
3545            serde_json::to_value(success).unwrap(),
3546            fixtures["post_valid_payloads"][0]
3547        );
3548        assert!(matches!(&error, HyperliquidError::BadRequest(_)));
3549        assert_eq!(
3550            error.to_string(),
3551            "bad request: API error: Known venue rejection"
3552        );
3553        assert_eq!(reason, "Known venue rejection");
3554
3555        for secret in fixtures["secrets"].as_array().unwrap() {
3556            let secret = secret.as_str().unwrap();
3557            assert!(!diagnostic.contains(secret));
3558            assert!(!debug.contains(secret));
3559            assert!(
3560                cancel_errors
3561                    .iter()
3562                    .all(|reason| !reason.as_ref().unwrap().contains(secret))
3563            );
3564        }
3565    }
3566
3567    #[tokio::test]
3568    async fn malformed_submit_report_logs_omit_private_data() {
3569        let _capture = crate::websocket::handler::tests::capture_logs().await;
3570
3571        let ws_client = HyperliquidWebSocketClient::new(
3572            None,
3573            HyperliquidEnvironment::Mainnet,
3574            None,
3575            TransportBackend::default(),
3576            None,
3577        );
3578        let signer = HyperliquidHttpClient::new(HyperliquidEnvironment::Mainnet, 10, None).unwrap();
3579        let fixtures: serde_json::Value = serde_json::from_str(include_str!(
3580            "../../test_data/ws_malformed_private_frames.json"
3581        ))
3582        .unwrap();
3583        let mut expected = Vec::new();
3584
3585        for (payload, expected_bytes) in fixtures["post_report_payloads"]
3586            .as_array()
3587            .unwrap()
3588            .iter()
3589            .zip(fixtures["post_report_payload_bytes"].as_array().unwrap())
3590        {
3591            let response: HyperliquidExchangeResponse =
3592                serde_json::from_value(payload.clone()).unwrap();
3593            ensure_ws_action_accepted(&response, "Order submission").unwrap();
3594            let payload_bytes = HyperliquidWebSocketClient::response_bytes(&response);
3595            assert_eq!(payload_bytes as u64, expected_bytes.as_u64().unwrap());
3596            let single = signer.build_submit_order_report(
3597                InstrumentId::from("BTC-PERP.HYPERLIQUID"),
3598                ClientOrderId::from("PRIVATE_ORDER_SENTINEL"),
3599                OrderSide::Buy,
3600                OrderType::Limit,
3601                Quantity::from("1"),
3602                TimeInForce::Gtc,
3603                Some(Price::from("12345")),
3604                None,
3605                response.clone(),
3606            );
3607            let batch =
3608                signer.build_submit_orders_reports(&[], HyperliquidExchangeGrouping::Na, response);
3609
3610            for e in [single.as_ref().unwrap_err(), batch.as_ref().unwrap_err()] {
3611                assert!(
3612                    fixtures["secrets"]
3613                        .as_array()
3614                        .unwrap()
3615                        .iter()
3616                        .any(|secret| e.to_string().contains(secret.as_str().unwrap()))
3617                );
3618                expected.push(format!(
3619                    "Failed to build WebSocket submit report: class=order_status, client_id={}, payload_bytes={payload_bytes}, category=conversion; awaiting WS reconciliation",
3620                    ws_client.client_id,
3621                ));
3622            }
3623
3624            let single = ws_client.resolve_submit_report(single, payload_bytes);
3625            let batch = ws_client.resolve_submit_report(batch, payload_bytes);
3626            assert!(single.is_none());
3627            assert_eq!(batch.len(), 0);
3628        }
3629
3630        let success = ws_client.resolve_submit_report(Ok(Some(42_u64)), 123);
3631        assert_eq!(success, Some(42));
3632        let messages = crate::websocket::handler::tests::captured_logs();
3633
3634        let diagnostics: Vec<_> = messages
3635            .iter()
3636            .filter(|message| {
3637                message.starts_with("Failed to build WebSocket submit report:")
3638                    && message.contains(&format!("client_id={},", ws_client.client_id))
3639            })
3640            .cloned()
3641            .collect();
3642
3643        assert_eq!(diagnostics, expected);
3644
3645        for secret in fixtures["secrets"].as_array().unwrap() {
3646            assert!(
3647                messages
3648                    .iter()
3649                    .all(|message| !message.contains(secret.as_str().unwrap()))
3650            );
3651        }
3652    }
3653
3654    #[rstest]
3655    fn test_subscription_topic_candle() {
3656        let sub = SubscriptionRequest::Candle {
3657            coin: "BTC".into(),
3658            interval: HyperliquidBarInterval::OneHour,
3659        };
3660
3661        let topic = subscription_topic(&sub);
3662        assert_eq!(topic, "candle:BTC:1h");
3663    }
3664
3665    #[rstest]
3666    fn with_state_sink_survives_clone() {
3667        let client = HyperliquidWebSocketClient::new(
3668            None,
3669            HyperliquidEnvironment::Testnet,
3670            None,
3671            TransportBackend::default(),
3672            None,
3673        )
3674        .with_state_sink(SocketStateSink::new(|_| {}));
3675
3676        let cloned = client.clone();
3677        assert!(client.socket_sink.is_some());
3678        assert!(cloned.socket_sink.is_some());
3679    }
3680
3681    #[rstest]
3682    fn clone_can_own_socket_registration() {
3683        let registry = SocketReconnectRegistry::default();
3684        let endpoint = Ustr::from("hyperliquid-data-streams");
3685        let client = HyperliquidWebSocketClient::new(
3686            None,
3687            HyperliquidEnvironment::Testnet,
3688            None,
3689            TransportBackend::default(),
3690            None,
3691        )
3692        .with_socket_control(SocketControl::with_registry(
3693            ClientId::from("HYPERLIQUID"),
3694            None,
3695            endpoint,
3696            &registry,
3697        ));
3698        let cloned = client.clone();
3699        let _sink = cloned.socket_control.as_ref().unwrap().sink();
3700        cloned
3701            .socket_control
3702            .as_ref()
3703            .unwrap()
3704            .register(|| ReconnectRequestOutcome::Accepted);
3705
3706        assert!(cloned.socket_control.is_some());
3707        assert!(cloned.socket_sink.is_none());
3708        assert!(
3709            registry
3710                .handle(ClientId::from("HYPERLIQUID"), endpoint)
3711                .is_some()
3712        );
3713
3714        client.socket_control.as_ref().unwrap().deregister();
3715        assert!(
3716            registry
3717                .handle(ClientId::from("HYPERLIQUID"), endpoint)
3718                .is_some()
3719        );
3720
3721        let handle = registry
3722            .handle(ClientId::from("HYPERLIQUID"), endpoint)
3723            .unwrap();
3724        assert_eq!(
3725            handle.request_reconnect(),
3726            SocketReconnectRequestOutcome::Accepted
3727        );
3728        drop(cloned);
3729        assert!(
3730            registry
3731                .handle(ClientId::from("HYPERLIQUID"), endpoint)
3732                .is_none()
3733        );
3734    }
3735
3736    #[rstest]
3737    fn set_post_timeout_updates_client_and_clone() {
3738        let mut client = HyperliquidWebSocketClient::new(
3739            None,
3740            HyperliquidEnvironment::Testnet,
3741            None,
3742            TransportBackend::default(),
3743            None,
3744        );
3745        let timeout = std::time::Duration::from_secs(7);
3746
3747        client.set_post_timeout(timeout);
3748
3749        assert_eq!(client.post_timeout, timeout);
3750        assert_eq!(client.clone().post_timeout, timeout);
3751    }
3752
3753    #[rstest]
3754    #[tokio::test]
3755    async fn post_action_command_without_credentials_is_not_sent() {
3756        let client = HyperliquidWebSocketClient::new(
3757            None,
3758            HyperliquidEnvironment::Testnet,
3759            None,
3760            TransportBackend::default(),
3761            None,
3762        );
3763        let signer = HyperliquidHttpClient::new(HyperliquidEnvironment::Testnet, 10, None).unwrap();
3764        let action = HyperliquidExchangeAction::Cancel {
3765            cancels: Vec::new(),
3766            fast: None,
3767        };
3768        let result = client.post_action_command(&signer, &action).await;
3769        let PostRequestError::BeforeDispatch(error) = result.unwrap_err() else {
3770            panic!("Expected failure before dispatch");
3771        };
3772        assert_eq!(
3773            error.to_string(),
3774            "auth error: credentials required for exchange operations"
3775        );
3776    }
3777
3778    #[rstest]
3779    #[tokio::test]
3780    async fn wait_for_subscriptions_confirmed_waits_for_pending_topics() {
3781        let client = HyperliquidWebSocketClient::new(
3782            None,
3783            HyperliquidEnvironment::Testnet,
3784            None,
3785            TransportBackend::default(),
3786            None,
3787        );
3788        let topic = "orderUpdates:0xabc";
3789        client.subscriptions.mark_subscribe(topic);
3790
3791        let pending = client
3792            .wait_for_subscriptions_confirmed(Duration::from_millis(30))
3793            .await;
3794        client.subscriptions.confirm_subscribe(topic);
3795        let confirmed = client
3796            .wait_for_subscriptions_confirmed(Duration::from_millis(30))
3797            .await;
3798
3799        assert_eq!(
3800            pending.unwrap_err().to_string(),
3801            r#"Subscriptions still pending after 30ms: ["orderUpdates:0xabc"]"#,
3802        );
3803        assert!(confirmed.is_ok());
3804    }
3805
3806    #[tokio::test]
3807    async fn failed_connect_releases_connection_slot() {
3808        let mut client = HyperliquidWebSocketClient::new(
3809            Some("invalid-websocket-url".to_string()),
3810            HyperliquidEnvironment::Testnet,
3811            None,
3812            TransportBackend::default(),
3813            None,
3814        );
3815        let available_before = client.rate_limits.connection_slots.available_permits();
3816
3817        client
3818            .connect()
3819            .await
3820            .expect_err("invalid URL should fail the connection attempt");
3821
3822        assert!(client.connection_permit.lock().is_none());
3823        assert_eq!(
3824            client.rate_limits.connection_slots.available_permits(),
3825            available_before
3826        );
3827    }
3828
3829    #[rstest]
3830    #[case::before_dispatch(false)]
3831    #[case::after_dispatch(true)]
3832    #[tokio::test(start_paused = true)]
3833    async fn post_request_timeout_preserves_dispatch_evidence(#[case] dispatched: bool) {
3834        let client = HyperliquidWebSocketClient::new(
3835            None,
3836            HyperliquidEnvironment::Testnet,
3837            None,
3838            TransportBackend::default(),
3839            None,
3840        );
3841        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
3842        *client.cmd_tx.write().await = tx;
3843        let timeout = if dispatched {
3844            Duration::from_millis(100)
3845        } else {
3846            Duration::ZERO
3847        };
3848        let started = tokio::time::Instant::now();
3849        let failure = client
3850            .send_post_request_result(
3851                PostRequest::Info {
3852                    payload: serde_json::json!({"type": "meta"}),
3853                },
3854                timeout,
3855            )
3856            .await
3857            .unwrap_err();
3858
3859        assert_eq!(tokio::time::Instant::now() - started, timeout);
3860
3861        if dispatched {
3862            assert!(matches!(
3863                failure,
3864                PostRequestError::AfterDispatch(HyperliquidError::Timeout)
3865            ));
3866            let HandlerCommand::Post {
3867                id,
3868                request,
3869                deadline,
3870                cancellation_token,
3871            } = rx.try_recv().unwrap()
3872            else {
3873                panic!("Expected post command");
3874            };
3875            assert_eq!(id, 1);
3876            assert_eq!(
3877                serde_json::to_value(request).unwrap(),
3878                serde_json::json!({"type": "info", "payload": {"type": "meta"}})
3879            );
3880            assert_eq!(deadline, started + timeout);
3881            assert!(cancellation_token.is_cancelled());
3882        } else {
3883            assert!(matches!(
3884                failure,
3885                PostRequestError::BeforeDispatch(HyperliquidError::Timeout)
3886            ));
3887        }
3888        assert!(matches!(
3889            rx.try_recv(),
3890            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
3891        ));
3892    }
3893
3894    #[rstest]
3895    #[tokio::test(flavor = "multi_thread")]
3896    async fn send_post_request_times_out_while_waiting_for_inflight_slot() {
3897        let client = HyperliquidWebSocketClient::new(
3898            None,
3899            HyperliquidEnvironment::Testnet,
3900            None,
3901            TransportBackend::default(),
3902            None,
3903        );
3904        let mut receivers = Vec::with_capacity(HYPERLIQUID_WS_POST_INFLIGHT_MAX);
3905        for offset in 0..HYPERLIQUID_WS_POST_INFLIGHT_MAX {
3906            receivers.push(
3907                client
3908                    .post_router
3909                    .register(10_000 + offset as u64)
3910                    .await
3911                    .unwrap(),
3912            );
3913        }
3914
3915        let err = client
3916            .send_post_request(
3917                PostRequest::Info {
3918                    payload: serde_json::json!({"type": "clearinghouseState", "user": "0x0"}),
3919                },
3920                std::time::Duration::from_millis(25),
3921            )
3922            .await
3923            .expect_err("request should timeout before acquiring an inflight slot");
3924
3925        assert!(matches!(err, HyperliquidError::Timeout));
3926        assert_eq!(receivers.len(), HYPERLIQUID_WS_POST_INFLIGHT_MAX);
3927    }
3928
3929    #[rstest]
3930    #[tokio::test(flavor = "multi_thread")]
3931    async fn send_post_request_shares_inflight_limit_across_clients() {
3932        let url = Some("wss://shared-post-limit.test/ws".to_string());
3933        let first = HyperliquidWebSocketClient::new(
3934            url.clone(),
3935            HyperliquidEnvironment::Testnet,
3936            None,
3937            TransportBackend::default(),
3938            None,
3939        );
3940        let second = HyperliquidWebSocketClient::new(
3941            url,
3942            HyperliquidEnvironment::Testnet,
3943            None,
3944            TransportBackend::default(),
3945            None,
3946        );
3947        let mut receivers = Vec::with_capacity(HYPERLIQUID_WS_POST_INFLIGHT_MAX);
3948
3949        for offset in 0..HYPERLIQUID_WS_POST_INFLIGHT_MAX / 2 {
3950            receivers.push(first.post_router.register(offset as u64).await.unwrap());
3951            receivers.push(
3952                second
3953                    .post_router
3954                    .register(10_000 + offset as u64)
3955                    .await
3956                    .unwrap(),
3957            );
3958        }
3959
3960        let error = second
3961            .send_post_request(
3962                PostRequest::Info {
3963                    payload: serde_json::json!({"type": "meta"}),
3964                },
3965                Duration::from_millis(25),
3966            )
3967            .await
3968            .expect_err("shared in-flight limit should block the next post");
3969
3970        assert!(matches!(error, HyperliquidError::Timeout));
3971        assert_eq!(receivers.len(), HYPERLIQUID_WS_POST_INFLIGHT_MAX);
3972    }
3973
3974    #[rstest]
3975    fn subscription_limit_is_rejected_before_queueing_across_clients() {
3976        let url = Some("wss://shared-subscription-limit.test/ws".to_string());
3977        let first = HyperliquidWebSocketClient::new(
3978            url.clone(),
3979            HyperliquidEnvironment::Testnet,
3980            None,
3981            TransportBackend::default(),
3982            None,
3983        );
3984        let second = HyperliquidWebSocketClient::new(
3985            url,
3986            HyperliquidEnvironment::Testnet,
3987            None,
3988            TransportBackend::default(),
3989            None,
3990        );
3991        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
3992
3993        for index in 0..HYPERLIQUID_WS_SUBSCRIPTIONS_MAX {
3994            let subscription = SubscriptionRequest::Trades {
3995                coin: Ustr::from(&format!("COIN-{index}")),
3996            };
3997            let client = if index % 2 == 0 { &first } else { &second };
3998            client.send_subscription(&cmd_tx, subscription).unwrap();
3999        }
4000
4001        let error = first
4002            .send_subscription(
4003                &cmd_tx,
4004                SubscriptionRequest::Trades {
4005                    coin: Ustr::from("OVER-LIMIT"),
4006                },
4007            )
4008            .expect_err("shared subscription limit should reject the next subscription");
4009
4010        assert!(error.to_string().contains("at most 1000"));
4011        assert_eq!(cmd_rx.len(), HYPERLIQUID_WS_SUBSCRIPTIONS_MAX);
4012    }
4013
4014    #[rstest]
4015    #[tokio::test]
4016    async fn subscribe_book_gated_at_subscription_limit_releases_book_stream() {
4017        let client = HyperliquidWebSocketClient::new(
4018            Some("wss://gated-book-limit.test/ws".to_string()),
4019            HyperliquidEnvironment::Testnet,
4020            None,
4021            TransportBackend::default(),
4022            None,
4023        );
4024        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
4025        let coin = instrument.raw_symbol().inner();
4026        client.cache_instrument(instrument.clone());
4027        let (cmd_tx, _cmd_rx) = tokio::sync::mpsc::unbounded_channel();
4028        *client.cmd_tx.write().await = cmd_tx.clone();
4029
4030        for index in 0..HYPERLIQUID_WS_SUBSCRIPTIONS_MAX {
4031            let subscription = SubscriptionRequest::Trades {
4032                coin: Ustr::from(&format!("COIN-{index}")),
4033            };
4034
4035            client.send_subscription(&cmd_tx, subscription).unwrap();
4036        }
4037
4038        let result = client
4039            .subscribe_book_gated(
4040                instrument.id(),
4041                None,
4042                None,
4043                CancellationToken::new(),
4044                SnapshotGate::default(),
4045            )
4046            .await;
4047
4048        let error = result.expect_err("subscription limit should reject the book stream");
4049        assert!(error.to_string().contains("at most 1000"));
4050        assert_eq!(client.book_streams.options(&coin), None);
4051    }
4052
4053    #[rstest]
4054    fn stream_resubscribe_queues_one_atomic_command() {
4055        let client = HyperliquidWebSocketClient::new(
4056            Some("wss://atomic-resubscribe.test/ws".to_string()),
4057            HyperliquidEnvironment::Testnet,
4058            None,
4059            TransportBackend::default(),
4060            None,
4061        );
4062        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
4063        let subscription = SubscriptionRequest::Bbo {
4064            coin: Ustr::from("BTC"),
4065        };
4066
4067        client
4068            .send_stream_resubscribe(&cmd_tx, subscription)
4069            .unwrap();
4070
4071        assert!(matches!(
4072            cmd_rx.try_recv(),
4073            Ok(HandlerCommand::Resubscribe { subscription })
4074                if subscription_to_key(&subscription) == "bbo:BTC"
4075        ));
4076        assert!(matches!(
4077            cmd_rx.try_recv(),
4078            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
4079        ));
4080    }
4081
4082    #[rstest]
4083    #[tokio::test(start_paused = true)]
4084    async fn send_post_request_uses_deadline_while_waiting_for_command_channel() {
4085        let client = HyperliquidWebSocketClient::new(
4086            None,
4087            HyperliquidEnvironment::Testnet,
4088            None,
4089            TransportBackend::default(),
4090            None,
4091        );
4092        let _cmd_tx = client.cmd_tx.write().await;
4093        let timeout = Duration::from_millis(100);
4094        let started = tokio::time::Instant::now();
4095
4096        let error = client
4097            .send_post_request(
4098                PostRequest::Info {
4099                    payload: serde_json::json!({"type": "clearinghouseState", "user": "0x0"}),
4100                },
4101                timeout,
4102            )
4103            .await
4104            .unwrap_err();
4105
4106        assert!(matches!(error, HyperliquidError::Timeout));
4107        assert_eq!(tokio::time::Instant::now() - started, timeout);
4108        client
4109            .post_router
4110            .register(1)
4111            .await
4112            .expect("post ID should be reusable when timeout returns");
4113    }
4114
4115    #[rstest]
4116    #[tokio::test(start_paused = true)]
4117    async fn post_response_ready_before_deadline_wins_deadline_race() {
4118        let client = HyperliquidWebSocketClient::new(
4119            None,
4120            HyperliquidEnvironment::Testnet,
4121            None,
4122            TransportBackend::default(),
4123            None,
4124        );
4125        let id = 1;
4126        let cancellation_token = CancellationToken::new();
4127        let rx = client
4128            .post_router
4129            .register_with_cancellation(id, &cancellation_token)
4130            .await
4131            .unwrap();
4132        let payload = serde_json::json!({"type": "meta", "data": {"universe": []}});
4133        client
4134            .post_router
4135            .complete(PostResponse {
4136                id,
4137                response: PostResponsePayload::Info {
4138                    payload: payload.clone(),
4139                },
4140            })
4141            .await;
4142
4143        let response = client
4144            .await_post_response(id, rx, tokio::time::Instant::now(), &cancellation_token)
4145            .await
4146            .expect("ready response should win");
4147
4148        assert_eq!(response.id, id);
4149        let PostResponsePayload::Info {
4150            payload: response_payload,
4151        } = response.response
4152        else {
4153            panic!("expected info response");
4154        };
4155        assert_eq!(response_payload, payload);
4156    }
4157
4158    #[rstest]
4159    #[tokio::test]
4160    async fn dropping_post_request_cancels_work_and_releases_registration() {
4161        let client = HyperliquidWebSocketClient::new(
4162            None,
4163            HyperliquidEnvironment::Testnet,
4164            None,
4165            TransportBackend::default(),
4166            None,
4167        );
4168        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
4169        *client.cmd_tx.write().await = cmd_tx;
4170        let request_client = client.clone();
4171        let task = tokio::spawn(async move {
4172            request_client
4173                .send_post_request(
4174                    PostRequest::Info {
4175                        payload: serde_json::json!({"type": "userRateLimit", "user": "0x123"}),
4176                    },
4177                    Duration::from_secs(60),
4178                )
4179                .await
4180        });
4181        let command = cmd_rx.recv().await.expect("post command should be queued");
4182        let HandlerCommand::Post {
4183            id,
4184            cancellation_token,
4185            ..
4186        } = command
4187        else {
4188            panic!("expected post command");
4189        };
4190
4191        task.abort();
4192        assert!(task.await.unwrap_err().is_cancelled());
4193        assert!(cancellation_token.is_cancelled());
4194
4195        let reused = tokio::time::timeout(Duration::from_secs(1), async {
4196            loop {
4197                match client.post_router.register(id).await {
4198                    Ok(rx) => break Ok(rx),
4199                    Err(e) if e.to_string().contains("already registered") => {
4200                        tokio::task::yield_now().await;
4201                    }
4202                    Err(e) => break Err(e),
4203                }
4204            }
4205        })
4206        .await
4207        .expect("post ID should be reusable after cancellation")
4208        .expect("post ID reuse should succeed");
4209        client
4210            .post_router
4211            .cancel_registration(id, &cancellation_token)
4212            .await;
4213        client
4214            .post_router
4215            .register(id)
4216            .await
4217            .expect_err("stale cancellation must not remove the reused registration");
4218
4219        let mut receivers = vec![reused];
4220        tokio::time::timeout(Duration::from_secs(1), async {
4221            for offset in 1..HYPERLIQUID_WS_POST_INFLIGHT_MAX {
4222                receivers.push(
4223                    client
4224                        .post_router
4225                        .register(10_000 + offset as u64)
4226                        .await
4227                        .unwrap(),
4228                );
4229            }
4230        })
4231        .await
4232        .expect("cancellation should release the inflight permit");
4233
4234        assert_eq!(receivers.len(), HYPERLIQUID_WS_POST_INFLIGHT_MAX);
4235    }
4236
4237    #[rstest]
4238    #[tokio::test(start_paused = true)]
4239    async fn post_timeout_after_queueing_preserves_unknown_outcome_and_releases_registration() {
4240        let client = HyperliquidWebSocketClient::new(
4241            None,
4242            HyperliquidEnvironment::Testnet,
4243            None,
4244            TransportBackend::default(),
4245            None,
4246        );
4247        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
4248        *client.cmd_tx.write().await = cmd_tx;
4249        let request_client = client.clone();
4250        let task = tokio::spawn(async move {
4251            request_client
4252                .send_post_request(
4253                    PostRequest::Info {
4254                        payload: serde_json::json!({"type": "userRateLimit", "user": "0x123"}),
4255                    },
4256                    Duration::from_millis(100),
4257                )
4258                .await
4259        });
4260        let command = cmd_rx.recv().await.expect("post command should be queued");
4261        let HandlerCommand::Post {
4262            id,
4263            cancellation_token,
4264            ..
4265        } = command
4266        else {
4267            panic!("expected post command");
4268        };
4269
4270        let error = task.await.unwrap().unwrap_err();
4271
4272        assert!(matches!(&error, HyperliquidError::Timeout));
4273        assert!(error.is_transport_error());
4274        assert!(cancellation_token.is_cancelled());
4275        client
4276            .post_router
4277            .register(id)
4278            .await
4279            .expect("post ID should be reusable when timeout returns");
4280    }
4281
4282    #[rstest]
4283    fn cancel_errors_for_requests_accepts_empty_as_success() {
4284        let errors = cancel_errors_for_requests(Vec::new(), 2).unwrap();
4285
4286        assert_eq!(errors, vec![None, None]);
4287    }
4288
4289    #[rstest]
4290    fn cancel_errors_for_requests_rejects_status_count_mismatch() {
4291        let err = cancel_errors_for_requests(vec![None], 2).expect_err("mismatch should fail");
4292
4293        assert!(
4294            err.to_string()
4295                .contains("returned 1 statuses for 2 cancels")
4296        );
4297    }
4298
4299    #[rstest]
4300    fn test_post_payload_error_maps_rate_limit() {
4301        let err = map_post_payload_error("429 Too Many Requests".to_string(), 3);
4302
4303        assert!(matches!(
4304            err,
4305            HyperliquidError::RateLimit {
4306                scope: "exchange",
4307                weight: 3,
4308                retry_after_ms: None,
4309            }
4310        ));
4311    }
4312
4313    #[rstest]
4314    #[case("401 Unauthorized")]
4315    #[case("HTTP 403: forbidden")]
4316    #[case("invalid signature")]
4317    #[case("authentication failed")]
4318    fn test_post_payload_error_maps_auth(#[case] payload: &str) {
4319        let err = map_post_payload_error(payload.to_string(), 1);
4320
4321        assert!(matches!(err, HyperliquidError::Auth(_)));
4322    }
4323
4324    #[rstest]
4325    #[case("400 Bad Request")]
4326    #[case("HTTP 400: malformed payload")]
4327    #[case("bad request: missing action")]
4328    fn test_post_payload_error_maps_bad_request(#[case] payload: &str) {
4329        let err = map_post_payload_error(payload.to_string(), 1);
4330
4331        assert!(matches!(err, HyperliquidError::BadRequest(_)));
4332    }
4333
4334    #[rstest]
4335    #[case("500 Internal Server Error")]
4336    #[case("HTTP 503: service unavailable")]
4337    fn test_post_payload_error_maps_exchange_status(#[case] payload: &str) {
4338        let err = map_post_payload_error(payload.to_string(), 1);
4339
4340        assert!(matches!(err, HyperliquidError::Exchange(_)));
4341    }
4342
4343    #[rstest]
4344    #[case("order 429001 rejected")]
4345    #[case("asset 5001 is not tradable")]
4346    #[case("authoritative nonce window exceeded")]
4347    fn test_post_payload_error_does_not_match_embedded_codes_or_words(#[case] payload: &str) {
4348        let err = map_post_payload_error(payload.to_string(), 1);
4349
4350        assert!(matches!(err, HyperliquidError::Exchange(_)));
4351    }
4352}