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