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    fmt::Debug,
18    str::FromStr,
19    sync::{
20        Arc,
21        atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
22    },
23    time::Duration,
24};
25
26use ahash::{AHashMap, AHashSet};
27use anyhow::Context;
28use arc_swap::ArcSwap;
29use dashmap::DashMap;
30use nautilus_common::cache::{InstrumentLookupError, fifo::FifoCacheMap};
31#[cfg(test)]
32use nautilus_common::live::get_runtime;
33#[cfg(test)]
34use nautilus_core::string::secret::REDACTED;
35use nautilus_core::{AtomicMap, string::secret::SecretString};
36use nautilus_live::{
37    SocketControl,
38    task::{SharedTaskSlot, TaskJoinOutcome},
39};
40use nautilus_model::{
41    data::BarType,
42    enums::{OrderSide, OrderType, TimeInForce},
43    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
44    instruments::{Instrument, InstrumentAny},
45    orders::{Order, OrderAny},
46    reports::OrderStatusReport,
47    types::{Price, Quantity},
48};
49use nautilus_network::{
50    SocketStateSink,
51    http::create_standard_nautilus_headers,
52    mode::ConnectionMode,
53    websocket::{
54        AuthTracker, SubscriptionState, TransportBackend, WebSocketClient, WebSocketConfig,
55        channel_message_handler,
56    },
57};
58use parking_lot::Mutex;
59use rust_decimal::Decimal;
60use tokio_util::sync::CancellationToken;
61use ustr::Ustr;
62
63use crate::{
64    common::{
65        consts::{HEARTBEAT_INTERVAL, HTTP_TIMEOUT, ws_url},
66        enums::{HyperliquidBarInterval, HyperliquidEnvironment},
67        parse::{
68            bar_type_to_interval, clamp_price_to_precision, derive_limit_from_trigger,
69            determine_order_list_grouping, extract_error_message, extract_inner_error,
70            extract_inner_errors, normalize_or_validate_wire_price,
71            order_to_hyperliquid_request_with_optional_decimals, round_to_sig_figs,
72            time_in_force_to_hyperliquid_tif,
73        },
74    },
75    http::{
76        client::HyperliquidHttpClient,
77        error::{Error as HyperliquidError, Result as HyperliquidResult},
78        models::{
79            HyperliquidExchangeAction, HyperliquidExchangeCancelByCloidRequest,
80            HyperliquidExchangeCancelOrderRequest, HyperliquidExchangeGrouping,
81            HyperliquidExchangeLimitParams, HyperliquidExchangeModifyOrderRequest,
82            HyperliquidExchangeModifyTarget, HyperliquidExchangeOrderKind,
83            HyperliquidExchangePlaceOrderRequest, HyperliquidExchangeResponse,
84            HyperliquidExchangeTif, HyperliquidExchangeTpSl, HyperliquidExchangeTriggerParams,
85            RESPONSE_STATUS_OK,
86        },
87        rate_limits::exec_action_weight,
88    },
89    websocket::{
90        book::{BookStreamOptions, BookStreamRegistry, BookStreamRelease, BookStreamUse},
91        enums::HyperliquidWsChannel,
92        handler::{FeedHandler, HandlerCommand},
93        messages::{
94            NautilusWsMessage, PostRequest, PostResponse, PostResponsePayload, SubscriptionRequest,
95        },
96        post::{PostIds, PostRouter},
97        rate_limits::{WebSocketRateLimits, shared_websocket_limits},
98        trades::{TradeStreamRegistry, TradeStreamUse},
99    },
100};
101
102static NEXT_WEBSOCKET_CLIENT_ID: AtomicU64 = AtomicU64::new(1);
103
104/// FIFO bound on the cloid -> `ClientOrderId` resolution cache so missed
105/// evictions self-recover (see GH-3972 cancel-replace drain path).
106pub(super) const CLOID_CACHE_CAPACITY: usize = 10_000;
107
108/// Shared cloid -> `ClientOrderId` cache used by the WS handler.
109pub(super) type CloidCache = Arc<Mutex<FifoCacheMap<Ustr, ClientOrderId, CLOID_CACHE_CAPACITY>>>;
110
111/// Represents the different data types available from asset context subscriptions.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub(super) enum AssetContextDataType {
114    MarkPrice,
115    IndexPrice,
116    FundingRate,
117    OpenInterest,
118}
119
120/// Hyperliquid WebSocket client following the BitMEX pattern.
121///
122/// Orchestrates WebSocket connection and subscriptions using a command-based architecture,
123/// where the inner FeedHandler owns the WebSocketClient and handles all I/O.
124#[derive(Debug)]
125pub struct HyperliquidWebSocketClient {
126    url: String,
127    connection_mode: Arc<ArcSwap<AtomicU8>>,
128    signal: Arc<AtomicBool>,
129    cmd_tx: Arc<tokio::sync::RwLock<tokio::sync::mpsc::UnboundedSender<HandlerCommand>>>,
130    out_rx: Option<tokio::sync::mpsc::UnboundedReceiver<NautilusWsMessage>>,
131    auth_tracker: AuthTracker,
132    subscriptions: SubscriptionState,
133    book_streams: BookStreamRegistry,
134    trade_streams: TradeStreamRegistry,
135    trade_stream_lock: Arc<Mutex<()>>,
136    quote_streams: Arc<DashMap<Ustr, ()>>,
137    instruments: Arc<AtomicMap<Ustr, InstrumentAny>>,
138    bar_types: Arc<AtomicMap<String, BarType>>,
139    asset_context_subs: Arc<DashMap<Ustr, AHashSet<AssetContextDataType>>>,
140    all_dex_asset_ctxs_instrument_ids: Arc<AtomicMap<Ustr, Vec<Option<InstrumentId>>>>,
141    cloid_cache: CloidCache,
142    post_router: Arc<PostRouter>,
143    post_ids: Arc<PostIds>,
144    rate_limits: Arc<WebSocketRateLimits>,
145    client_id: u64,
146    connection_permit: Arc<Mutex<Option<tokio::sync::OwnedSemaphorePermit>>>,
147    post_timeout: Duration,
148    task_handle: Arc<SharedTaskSlot<()>>,
149    connect_lock: Arc<tokio::sync::Mutex<()>>,
150    account_id: Option<AccountId>,
151    transport_backend: TransportBackend,
152    proxy_url: Option<SecretString>,
153    socket_sink: Option<SocketStateSink>,
154    socket_control: Option<SocketControl>,
155}
156
157impl Clone for HyperliquidWebSocketClient {
158    fn clone(&self) -> Self {
159        Self {
160            url: self.url.clone(),
161            connection_mode: Arc::clone(&self.connection_mode),
162            signal: Arc::clone(&self.signal),
163            cmd_tx: Arc::clone(&self.cmd_tx),
164            out_rx: None,
165            auth_tracker: self.auth_tracker.clone(),
166            subscriptions: self.subscriptions.clone(),
167            book_streams: self.book_streams.clone(),
168            trade_streams: self.trade_streams.clone(),
169            trade_stream_lock: Arc::clone(&self.trade_stream_lock),
170            quote_streams: Arc::clone(&self.quote_streams),
171            instruments: Arc::clone(&self.instruments),
172            bar_types: Arc::clone(&self.bar_types),
173            asset_context_subs: Arc::clone(&self.asset_context_subs),
174            all_dex_asset_ctxs_instrument_ids: Arc::clone(&self.all_dex_asset_ctxs_instrument_ids),
175            cloid_cache: Arc::clone(&self.cloid_cache),
176            post_router: Arc::clone(&self.post_router),
177            post_ids: Arc::clone(&self.post_ids),
178            rate_limits: Arc::clone(&self.rate_limits),
179            client_id: self.client_id,
180            connection_permit: Arc::clone(&self.connection_permit),
181            post_timeout: self.post_timeout,
182            task_handle: Arc::clone(&self.task_handle),
183            connect_lock: Arc::clone(&self.connect_lock),
184            account_id: self.account_id,
185            transport_backend: self.transport_backend,
186            proxy_url: self.proxy_url.clone(),
187            socket_sink: self.socket_sink.clone(),
188            socket_control: self.socket_control.clone(),
189        }
190    }
191}
192
193impl HyperliquidWebSocketClient {
194    /// Creates a new Hyperliquid WebSocket client without connecting.
195    ///
196    /// If `url` is `None`, the appropriate URL will be determined from the `environment`:
197    /// - `Mainnet`: `wss://api.hyperliquid.xyz/ws`
198    /// - `Testnet`: `wss://api.hyperliquid-testnet.xyz/ws`
199    ///
200    /// The connection will be established when `connect()` is called.
201    pub fn new(
202        url: Option<String>,
203        environment: HyperliquidEnvironment,
204        account_id: Option<AccountId>,
205        transport_backend: TransportBackend,
206        proxy_url: Option<String>,
207    ) -> Self {
208        let url = url.unwrap_or_else(|| ws_url(environment).to_string());
209        let rate_limits = shared_websocket_limits(environment, &url, proxy_url.as_deref());
210        let connection_mode = Arc::new(ArcSwap::new(Arc::new(AtomicU8::new(
211            ConnectionMode::Closed as u8,
212        ))));
213        Self {
214            url,
215            connection_mode,
216            signal: Arc::new(AtomicBool::new(false)),
217            auth_tracker: AuthTracker::new(),
218            subscriptions: SubscriptionState::new(':'),
219            book_streams: BookStreamRegistry::default(),
220            trade_streams: TradeStreamRegistry::default(),
221            trade_stream_lock: Arc::new(Mutex::new(())),
222            quote_streams: Arc::new(DashMap::new()),
223            instruments: Arc::new(AtomicMap::new()),
224            bar_types: Arc::new(AtomicMap::new()),
225            asset_context_subs: Arc::new(DashMap::new()),
226            all_dex_asset_ctxs_instrument_ids: Arc::new(AtomicMap::new()),
227            cloid_cache: Arc::new(Mutex::new(FifoCacheMap::new())),
228            post_router: PostRouter::with_inflight(Arc::clone(&rate_limits.post_slots)),
229            post_ids: Arc::new(PostIds::new(1)),
230            rate_limits,
231            client_id: NEXT_WEBSOCKET_CLIENT_ID.fetch_add(1, Ordering::Relaxed),
232            connection_permit: Arc::new(Mutex::new(None)),
233            post_timeout: HTTP_TIMEOUT,
234            cmd_tx: {
235                // Placeholder channel until connect() creates the real handler and replays queued instruments
236                let (tx, _) = tokio::sync::mpsc::unbounded_channel();
237                Arc::new(tokio::sync::RwLock::new(tx))
238            },
239            out_rx: None,
240            task_handle: Arc::new(SharedTaskSlot::new()),
241            connect_lock: Arc::new(tokio::sync::Mutex::new(())),
242            account_id,
243            transport_backend,
244            proxy_url: proxy_url.map(SecretString::from),
245            socket_sink: None,
246            socket_control: None,
247        }
248    }
249
250    /// Configures socket state reporting for the underlying transport.
251    #[must_use]
252    pub fn with_state_sink(mut self, state_sink: SocketStateSink) -> Self {
253        self.socket_sink = Some(state_sink);
254        self
255    }
256
257    /// Configures state reporting and reconnect control for the underlying transport.
258    #[must_use]
259    pub(crate) fn with_socket_control(mut self, control: SocketControl) -> Self {
260        self.socket_control = Some(control);
261        self
262    }
263
264    /// Establishes WebSocket connection and spawns the message handler.
265    pub async fn connect(&mut self) -> anyhow::Result<()> {
266        let connect_lock = Arc::clone(&self.connect_lock);
267        let _guard = connect_lock.lock().await;
268        self.connect_locked().await
269    }
270
271    async fn connect_locked(&mut self) -> anyhow::Result<()> {
272        if self.is_active() {
273            log::warn!("WebSocket already connected");
274            return Ok(());
275        }
276
277        if !self.task_handle.is_empty() {
278            self.disconnect_locked().await?;
279        }
280
281        if self.connection_permit.lock().is_none() {
282            let permit = Arc::clone(&self.rate_limits.connection_slots)
283                .try_acquire_owned()
284                .map_err(|_| {
285                    anyhow::anyhow!(
286                        "Hyperliquid allows at most {} WebSocket connections per route",
287                        crate::common::consts::HYPERLIQUID_WS_CONNECTIONS_MAX,
288                    )
289                })?;
290            *self.connection_permit.lock() = Some(permit);
291        }
292
293        // A fresh socket has no venue-side subscriptions; stale book stream
294        // entries must not gate the venue subscribe for re-subscriptions
295        self.book_streams.clear();
296
297        let (message_handler, raw_rx) = channel_message_handler();
298        let headers = create_standard_nautilus_headers();
299
300        let cfg = WebSocketConfig {
301            url: self.url.clone(),
302            headers,
303            heartbeat_interval_secs: None,
304            heartbeat_payload: None,
305            connect_timeout_ms: Some(15_000),
306            reconnect_delay_initial_ms: Some(250),
307            reconnect_delay_max_ms: Some(5_000),
308            reconnect_backoff_factor: Some(2.0),
309            reconnect_jitter_ms: Some(200),
310            reconnect_max_attempts: None,
311            heartbeat_timeout_secs: Some(HEARTBEAT_INTERVAL.as_secs() * 3),
312            idle_timeout_ms: None,
313            backend: self.transport_backend,
314            proxy_url: self
315                .proxy_url
316                .as_ref()
317                .map(|value| value.expose_secret().to_owned()),
318        };
319        let connection_rate_keys: Arc<[Ustr]> = Arc::from([self.rate_limits.connection_key()]);
320        let client_result = WebSocketClient::builder()
321            .config(cfg)
322            .message_handler(message_handler)
323            .rate_limiter(Arc::clone(&self.rate_limits.messages))
324            .connection_rate_limiter(Arc::clone(&self.rate_limits.connections))
325            .connection_rate_keys(connection_rate_keys)
326            .maybe_state_sink(
327                self.socket_control
328                    .as_ref()
329                    .map(SocketControl::sink)
330                    .or_else(|| self.socket_sink.clone()),
331            )
332            .connect()
333            .await;
334        let client = match client_result {
335            Ok(client) => client,
336            Err(e) => {
337                self.connection_permit.lock().take();
338                return Err(e.into());
339            }
340        };
341
342        if let Some(control) = &self.socket_control {
343            let handle = client.reconnect_handle();
344            control.register(move || handle.request_reconnect());
345        }
346
347        // Create channels for handler communication
348        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();
349        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel::<NautilusWsMessage>();
350
351        // Update cmd_tx before connection_mode to avoid race where is_active() returns
352        // true but subscriptions still go to the old placeholder channel
353        *self.cmd_tx.write().await = cmd_tx.clone();
354        self.out_rx = Some(out_rx);
355
356        self.connection_mode.store(client.connection_mode_atomic());
357        log::debug!("Hyperliquid WebSocket connected: {}", self.url);
358
359        // Send SetClient command immediately
360        if let Err(e) = cmd_tx.send(HandlerCommand::SetClient(client)) {
361            self.release_limit_reservations();
362            anyhow::bail!("Failed to send SetClient command: {e}");
363        }
364
365        // Initialize handler with existing instruments
366        let instruments_vec: Vec<InstrumentAny> =
367            self.instruments.load().values().cloned().collect();
368
369        if !instruments_vec.is_empty()
370            && let Err(e) = cmd_tx.send(HandlerCommand::InitializeInstruments(instruments_vec))
371        {
372            log::error!("Failed to send InitializeInstruments: {e}");
373        }
374
375        for (coin, uses) in self.trade_streams.snapshot() {
376            if let Err(e) = cmd_tx.send(HandlerCommand::UpdateTradeSubs { coin, uses }) {
377                log::error!("Failed to send UpdateTradeSubs: {e}");
378            }
379        }
380
381        let all_dex_asset_ctxs_instrument_ids = self
382            .all_dex_asset_ctxs_instrument_ids
383            .load()
384            .iter()
385            .map(|(dex, instrument_ids)| (*dex, instrument_ids.clone()))
386            .collect();
387
388        if let Err(e) = cmd_tx.send(HandlerCommand::CacheAllDexAssetCtxsInstrumentIds(
389            all_dex_asset_ctxs_instrument_ids,
390        )) {
391            log::error!("Failed to send CacheAllDexAssetCtxsInstrumentIds: {e}");
392        }
393
394        // Spawn handler task
395        let signal = Arc::clone(&self.signal);
396        let account_id = self.account_id;
397        let subscriptions = self.subscriptions.clone();
398        let book_streams = self.book_streams.clone();
399        let cmd_tx_for_reconnect = cmd_tx.clone();
400        let cloid_cache = Arc::clone(&self.cloid_cache);
401        let post_router = Arc::clone(&self.post_router);
402        let rate_limits = Arc::clone(&self.rate_limits);
403        let client_id = self.client_id;
404        let connection_permit = Arc::clone(&self.connection_permit);
405
406        if let Err(e) = self.task_handle.spawn(async move {
407            let mut handler = FeedHandler::new(
408                signal,
409                cmd_rx,
410                raw_rx,
411                out_tx,
412                account_id,
413                subscriptions.clone(),
414                cloid_cache,
415                post_router,
416                Arc::clone(&rate_limits),
417                client_id,
418            );
419
420            let resubscribe_all = || {
421                let topics = subscriptions.all_topics();
422                if topics.is_empty() {
423                    log::debug!("No active subscriptions to restore after reconnection");
424                    return;
425                }
426
427                log::info!(
428                    "Resubscribing to {} active subscriptions after reconnection",
429                    topics.len()
430                );
431
432                for topic in topics {
433                    match subscription_from_topic(&topic) {
434                        Ok(mut subscription) => {
435                            // Topic text cannot carry l2Book precision options;
436                            // replay the shape the stream was opened with
437                            if let SubscriptionRequest::L2Book {
438                                coin,
439                                n_sig_figs,
440                                mantissa,
441                            } = &mut subscription
442                                && let Some(options) = book_streams.options(coin)
443                            {
444                                *n_sig_figs = options.n_sig_figs;
445                                *mantissa = options.mantissa;
446                            }
447
448                            if let Err(e) = cmd_tx_for_reconnect.send(HandlerCommand::Subscribe {
449                                subscriptions: vec![subscription],
450                            }) {
451                                log::error!("Failed to send resubscribe command: {e}");
452                            }
453                        }
454                        Err(e) => {
455                            log::error!(
456                                "Failed to reconstruct subscription from topic: topic={topic}, {e}"
457                            );
458                        }
459                    }
460                }
461            };
462
463            loop {
464                match handler.next().await {
465                    Some(NautilusWsMessage::Reconnected) => {
466                        log::info!("WebSocket reconnected");
467                        let pending_unsubscribe = subscriptions.pending_unsubscribe_topics();
468                        rate_limits.release_subscriptions(
469                            client_id,
470                            pending_unsubscribe.iter().map(String::as_str),
471                        );
472                        subscriptions.reset_after_reconnect();
473                        resubscribe_all();
474
475                        if handler.send(NautilusWsMessage::Reconnected).is_err() {
476                            if handler.is_stopped() {
477                                log::debug!("Failed to send reconnect event (receiver dropped)");
478                            } else {
479                                log::error!("Failed to send reconnect event (receiver dropped)");
480                            }
481                            break;
482                        }
483                    }
484                    Some(msg) => {
485                        if handler.send(msg).is_err() {
486                            if handler.is_stopped() {
487                                log::debug!("Failed to send message (receiver dropped)");
488                            } else {
489                                log::error!("Failed to send message (receiver dropped)");
490                            }
491                            break;
492                        }
493                    }
494                    None => {
495                        if handler.is_stopped() {
496                            log::debug!("Stop signal received, ending message processing");
497                            break;
498                        }
499                        log::warn!("WebSocket stream ended unexpectedly");
500                        break;
501                    }
502                }
503            }
504            rate_limits.release_client(client_id);
505            connection_permit.lock().take();
506            log::debug!("Handler task completed");
507        }) {
508            self.out_rx = None;
509            self.release_limit_reservations();
510            anyhow::bail!("Failed to start Hyperliquid WebSocket handler task: {e}");
511        }
512        Ok(())
513    }
514
515    pub fn set_post_timeout(&mut self, timeout: Duration) {
516        self.post_timeout = timeout;
517    }
518
519    pub(crate) fn begin_shutdown(&self) {
520        self.signal.store(true, Ordering::Relaxed);
521    }
522
523    /// Replaces state owned by a terminated WebSocket generation.
524    ///
525    /// This must run only after the handler task has stopped. Replacing the
526    /// shared containers, rather than clearing them, prevents old clones or
527    /// in-flight work from mutating a subsequent connection generation.
528    pub(crate) fn reset_runtime_state(&mut self) {
529        self.release_limit_reservations();
530        self.subscriptions = SubscriptionState::new(':');
531        self.book_streams = BookStreamRegistry::default();
532        self.trade_streams = TradeStreamRegistry::default();
533        self.trade_stream_lock = Arc::new(Mutex::new(()));
534        self.quote_streams = Arc::new(DashMap::new());
535        self.instruments = Arc::new(AtomicMap::new());
536        self.bar_types = Arc::new(AtomicMap::new());
537        self.asset_context_subs = Arc::new(DashMap::new());
538        self.all_dex_asset_ctxs_instrument_ids = Arc::new(AtomicMap::new());
539        self.cloid_cache = Arc::new(Mutex::new(FifoCacheMap::new()));
540        self.out_rx = None;
541
542        if let Some(control) = &self.socket_control {
543            control.deregister();
544        }
545        self.connection_mode
546            .store(Arc::new(AtomicU8::new(ConnectionMode::Closed as u8)));
547        self.signal.store(false, Ordering::Relaxed);
548    }
549
550    /// Disconnects the WebSocket connection.
551    pub async fn disconnect(&mut self) -> anyhow::Result<()> {
552        let connect_lock = Arc::clone(&self.connect_lock);
553        let _guard = connect_lock.lock().await;
554        self.disconnect_locked().await
555    }
556
557    async fn disconnect_locked(&self) -> anyhow::Result<()> {
558        log::debug!("Disconnecting Hyperliquid WebSocket");
559
560        if let Some(control) = &self.socket_control {
561            control.deregister();
562        }
563        self.signal.store(true, Ordering::Relaxed);
564
565        if let Err(e) = self.cmd_tx.read().await.send(HandlerCommand::Disconnect) {
566            log::debug!(
567                "Failed to send disconnect command (handler may already be shut down): {e}"
568            );
569        }
570
571        if self.task_handle.is_empty() {
572            log::debug!("No task handle to await");
573        } else {
574            log::debug!("Waiting for task handle to complete");
575
576            if let Some(outcome) = self
577                .task_handle
578                .finish(Duration::from_secs(2), Duration::from_secs(2))
579                .await
580            {
581                match outcome {
582                    TaskJoinOutcome::Completed(()) | TaskJoinOutcome::Aborted => {}
583                    TaskJoinOutcome::Failed(error) => {
584                        self.release_limit_reservations();
585                        anyhow::bail!("Hyperliquid WebSocket handler failed: {error}");
586                    }
587                    TaskJoinOutcome::Incomplete => {
588                        self.release_limit_reservations();
589                        anyhow::bail!("Hyperliquid WebSocket handler did not stop after abort");
590                    }
591                }
592            }
593        }
594        self.release_limit_reservations();
595        log::debug!("Disconnected");
596        Ok(())
597    }
598
599    /// Requests a full transport reconnect.
600    ///
601    /// Transitions the connection from `Active` to `Reconnect`; the network
602    /// layer re-establishes the socket with backoff and the handler replays all
603    /// active subscriptions once reconnected. Returns `false` when the
604    /// connection is not active (already reconnecting, disconnecting, or
605    /// closed), leaving any in-flight transition untouched.
606    pub fn request_reconnect(&self) -> bool {
607        ConnectionMode::request_reconnect(&self.connection_mode.load())
608    }
609
610    /// Send a typed exchange action through the Hyperliquid WebSocket post API.
611    ///
612    /// The supplied HTTP client is used only as the canonical signer for the
613    /// action envelope. The signed payload is sent over the active WebSocket
614    /// connection and the response is correlated by post id.
615    pub async fn post_action_exec(
616        &self,
617        signer: &HyperliquidHttpClient,
618        action: &HyperliquidExchangeAction,
619    ) -> HyperliquidResult<HyperliquidExchangeResponse> {
620        self.post_action_exec_with_timeout(signer, action, self.post_timeout, None)
621            .await
622    }
623
624    /// Send a typed exchange action with a caller-specified timeout and optional expiry.
625    pub async fn post_action_exec_with_timeout(
626        &self,
627        signer: &HyperliquidHttpClient,
628        action: &HyperliquidExchangeAction,
629        timeout: Duration,
630        expires_after: Option<u64>,
631    ) -> HyperliquidResult<HyperliquidExchangeResponse> {
632        self.post_action_result(signer, action, timeout, expires_after)
633            .await
634            .map_err(PostRequestError::into_error)
635    }
636
637    pub(crate) async fn post_action_command(
638        &self,
639        signer: &HyperliquidHttpClient,
640        action: &HyperliquidExchangeAction,
641    ) -> Result<HyperliquidExchangeResponse, PostRequestError> {
642        self.post_action_result(signer, action, self.post_timeout, None)
643            .await
644    }
645
646    async fn post_action_result(
647        &self,
648        signer: &HyperliquidHttpClient,
649        action: &HyperliquidExchangeAction,
650        timeout: Duration,
651        expires_after: Option<u64>,
652    ) -> Result<HyperliquidExchangeResponse, PostRequestError> {
653        let weight = exec_action_weight(action);
654        let payload = signer
655            .sign_action_exec_request(action, expires_after)
656            .map_err(PostRequestError::BeforeDispatch)?;
657        let response = self
658            .send_post_request_result(PostRequest::Action { payload }, timeout)
659            .await?;
660
661        match response.response {
662            PostResponsePayload::Action { payload } => {
663                let parsed: HyperliquidExchangeResponse = serde_json::from_value(payload)
664                    .map_err(HyperliquidError::Serde)
665                    .map_err(PostRequestError::AfterDispatch)?;
666
667                match &parsed {
668                    HyperliquidExchangeResponse::Status { status, response }
669                        if status != RESPONSE_STATUS_OK =>
670                    {
671                        let reason = response
672                            .as_str()
673                            .map_or_else(|| response.to_string(), str::to_string);
674                        let error = HyperliquidError::bad_request(format!("API error: {reason}"));
675
676                        if status == "err" {
677                            Err(PostRequestError::Rejected {
678                                error,
679                                reason: extract_error_message(&parsed),
680                            })
681                        } else {
682                            Err(PostRequestError::AfterDispatch(error))
683                        }
684                    }
685                    HyperliquidExchangeResponse::Error { error } => {
686                        Err(PostRequestError::Rejected {
687                            error: HyperliquidError::bad_request(format!("API error: {error}")),
688                            reason: error.clone(),
689                        })
690                    }
691                    _ => Ok(parsed),
692                }
693            }
694            PostResponsePayload::Error { payload } => Err(PostRequestError::AfterDispatch(
695                map_post_payload_error(payload, weight),
696            )),
697            PostResponsePayload::Info { payload } => {
698                Err(PostRequestError::AfterDispatch(HyperliquidError::decode(
699                    format!("expected action post response, received info payload: {payload}"),
700                )))
701            }
702        }
703    }
704
705    /// Submit an order through the Hyperliquid WebSocket post API.
706    ///
707    /// The HTTP client supplies signing credentials, builder attribution, and
708    /// cached instrument metadata. The action itself is sent over WebSocket.
709    ///
710    /// Returns an [`OrderStatusReport`] describing the venue's immediate
711    /// response (`Filled` for an atomic IOC fill, `Accepted` for a resting
712    /// order), or `None` when the venue deferred the order without an oid (for
713    /// example a `waitingForFill` trigger child): the order stays `SUBMITTED`
714    /// until the user-events stream delivers the first `OrderAccepted`.
715    #[allow(
716        clippy::too_many_arguments,
717        reason = "matches the Python and HTTP order submit surface"
718    )]
719    pub async fn submit_order(
720        &self,
721        signer: &HyperliquidHttpClient,
722        instrument_id: InstrumentId,
723        client_order_id: ClientOrderId,
724        order_side: OrderSide,
725        order_type: OrderType,
726        quantity: Quantity,
727        time_in_force: TimeInForce,
728        price: Option<Price>,
729        trigger_price: Option<Price>,
730        post_only: bool,
731        reduce_only: bool,
732    ) -> HyperliquidResult<Option<OrderStatusReport>> {
733        let symbol = instrument_id.symbol.inner();
734        let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
735            HyperliquidError::bad_request(format!(
736                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
737            ))
738        })?;
739        let is_buy = matches!(order_side, OrderSide::Buy);
740        let price_precision = signer.get_price_precision_for_symbol(symbol);
741
742        let price_decimal = match price {
743            Some(px) => normalize_or_validate_wire_price(
744                px.as_decimal(),
745                "Price",
746                price_precision,
747                signer.normalize_prices(),
748            )
749            .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?,
750            None if matches!(order_type, OrderType::Market) => Decimal::ZERO,
751            None if matches!(
752                order_type,
753                OrderType::StopMarket | OrderType::MarketIfTouched
754            ) =>
755            {
756                match trigger_price {
757                    Some(tp) => {
758                        let derived = derive_limit_from_trigger(
759                            tp.as_decimal().normalize(),
760                            is_buy,
761                            signer.market_order_slippage_bps(),
762                        );
763                        let sig_rounded = round_to_sig_figs(derived, 5);
764                        clamp_price_to_precision(sig_rounded, price_precision.unwrap_or(2), is_buy)
765                            .normalize()
766                    }
767                    None => Decimal::ZERO,
768                }
769            }
770            None => {
771                return Err(HyperliquidError::bad_request(
772                    "Limit orders require a price",
773                ));
774            }
775        };
776
777        let size_decimal = quantity.as_decimal().normalize();
778        let kind = hyperliquid_order_kind(
779            order_type,
780            time_in_force,
781            post_only,
782            trigger_price,
783            signer.normalize_prices(),
784            price_precision,
785        )?;
786
787        let order = HyperliquidExchangePlaceOrderRequest {
788            asset,
789            is_buy,
790            price: price_decimal,
791            size: size_decimal,
792            reduce_only,
793            kind,
794            cloid: Some(signer.get_or_generate_client_order_id_cloid(client_order_id)),
795        };
796
797        if let Some(cloid) = order.cloid {
798            self.cache_cloid_mapping(Ustr::from(&cloid.to_hex()), client_order_id);
799        }
800        let action = HyperliquidExchangeAction::Order {
801            orders: vec![order],
802            grouping: HyperliquidExchangeGrouping::Na,
803            builder: signer.builder_attribution(),
804        };
805        let response = self.post_action_exec(signer, &action).await?;
806
807        // Verdict first: a real rejection must still error
808        ensure_ws_action_accepted(&response, "Order submission")?;
809
810        // Past the verdict, a build failure is local; defer to WS, never reject
811        match signer.build_submit_order_report(
812            instrument_id,
813            client_order_id,
814            order_side,
815            order_type,
816            quantity,
817            time_in_force,
818            price,
819            trigger_price,
820            response,
821        ) {
822            Ok(report) => Ok(report),
823            Err(e) => {
824                log::warn!(
825                    "Failed to build submit report for {client_order_id}: {e}; awaiting WS reconciliation"
826                );
827                Ok(None)
828            }
829        }
830    }
831
832    /// Submit multiple orders through the Hyperliquid WebSocket post API.
833    ///
834    /// Returns one [`OrderStatusReport`] per accepted order in submission
835    /// order. Deferred trigger children of a `normalTpsl` bracket are absent
836    /// from the result; they stay `SUBMITTED` until the user-events stream
837    /// delivers an `OrderAccepted` with the real oid.
838    ///
839    /// # Errors
840    ///
841    /// Returns an error for any quote-denominated quantity: this raw path has
842    /// no cached market data for a quote-to-base conversion, so such orders
843    /// must be submitted through the execution client instead.
844    pub async fn submit_orders(
845        &self,
846        signer: &HyperliquidHttpClient,
847        orders: &[&OrderAny],
848    ) -> HyperliquidResult<Vec<OrderStatusReport>> {
849        let mut hyperliquid_orders = Vec::with_capacity(orders.len());
850        let mut client_order_ids = Vec::with_capacity(orders.len());
851
852        for order in orders {
853            if order.is_quote_quantity() {
854                return Err(HyperliquidError::bad_request(format!(
855                    "Quote-denominated quantity order {} must submit through the execution \
856                     client for quote-to-base conversion",
857                    order.client_order_id()
858                )));
859            }
860
861            let instrument_id = order.instrument_id();
862            let symbol = instrument_id.symbol.inner();
863            let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
864                HyperliquidError::bad_request(format!(
865                    "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
866                ))
867            })?;
868            let price_decimals = signer.get_price_precision_for_symbol(symbol);
869            let request = order_to_hyperliquid_request_with_optional_decimals(
870                order,
871                asset,
872                price_decimals,
873                signer.normalize_prices(),
874                signer.market_order_slippage_bps(),
875                None,
876            )
877            .map_err(|e| HyperliquidError::bad_request(format!("Failed to convert order: {e}")))?;
878            client_order_ids.push(order.client_order_id());
879            hyperliquid_orders.push(request);
880        }
881
882        for (request, client_order_id) in hyperliquid_orders.iter_mut().zip(client_order_ids) {
883            let cloid = signer.get_or_generate_client_order_id_cloid(client_order_id);
884            request.cloid = Some(cloid);
885            self.cache_cloid_mapping(Ustr::from(&cloid.to_hex()), client_order_id);
886        }
887
888        let grouping =
889            determine_order_list_grouping(&orders.iter().copied().cloned().collect::<Vec<_>>());
890        let action = HyperliquidExchangeAction::Order {
891            orders: hyperliquid_orders,
892            grouping,
893            builder: signer.builder_attribution(),
894        };
895        let response = self.post_action_exec(signer, &action).await?;
896
897        ensure_ws_action_accepted(&response, "Order list submission")?;
898
899        // Past the verdict, a build failure is local; defer to WS, never reject
900        match signer.build_submit_orders_reports(orders, grouping, response) {
901            Ok(reports) => Ok(reports),
902            Err(e) => {
903                log::warn!(
904                    "Failed to build submit reports for order list: {e}; awaiting WS reconciliation"
905                );
906                Ok(Vec::new())
907            }
908        }
909    }
910
911    /// Cancel an order through the Hyperliquid WebSocket post API.
912    pub async fn cancel_order(
913        &self,
914        signer: &HyperliquidHttpClient,
915        instrument_id: InstrumentId,
916        client_order_id: Option<ClientOrderId>,
917        venue_order_id: Option<VenueOrderId>,
918    ) -> HyperliquidResult<()> {
919        let symbol = instrument_id.symbol.inner();
920        let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
921            HyperliquidError::bad_request(format!(
922                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
923            ))
924        })?;
925        let action = if let Some(client_order_id) = client_order_id {
926            if let Some(cloid) = signer.cached_client_order_id_cloid(&client_order_id) {
927                HyperliquidExchangeAction::CancelByCloid {
928                    cancels: vec![HyperliquidExchangeCancelByCloidRequest { asset, cloid }],
929                    fast: None,
930                }
931            } else if let Some(oid) = venue_order_id {
932                let oid = oid
933                    .as_str()
934                    .parse::<u64>()
935                    .map_err(|_| HyperliquidError::bad_request("Invalid venue order ID format"))?;
936                HyperliquidExchangeAction::Cancel {
937                    cancels: vec![HyperliquidExchangeCancelOrderRequest { asset, oid }],
938                    fast: None,
939                }
940            } else {
941                let cloid = signer.get_or_generate_client_order_id_cloid(client_order_id);
942                HyperliquidExchangeAction::CancelByCloid {
943                    cancels: vec![HyperliquidExchangeCancelByCloidRequest { asset, cloid }],
944                    fast: None,
945                }
946            }
947        } else if let Some(oid) = venue_order_id {
948            let oid = oid
949                .as_str()
950                .parse::<u64>()
951                .map_err(|_| HyperliquidError::bad_request("Invalid venue order ID format"))?;
952            HyperliquidExchangeAction::Cancel {
953                cancels: vec![HyperliquidExchangeCancelOrderRequest { asset, oid }],
954                fast: None,
955            }
956        } else {
957            return Err(HyperliquidError::bad_request(
958                "Either client_order_id or venue_order_id must be provided",
959            ));
960        };
961        let response = self.post_action_exec(signer, &action).await?;
962
963        ensure_ws_action_accepted(&response, "Cancel order")
964    }
965
966    /// Cancel multiple orders through one Hyperliquid WebSocket post action.
967    pub async fn cancel_orders(
968        &self,
969        signer: &HyperliquidHttpClient,
970        cancels: &[(InstrumentId, ClientOrderId, Option<VenueOrderId>)],
971    ) -> HyperliquidResult<Vec<Option<String>>> {
972        let mut cloid_requests = Vec::new();
973        let mut cloid_indices = Vec::new();
974        let mut oid_requests = Vec::new();
975        let mut oid_indices = Vec::new();
976        let mut results = vec![None; cancels.len()];
977
978        for (index, (instrument_id, client_order_id, venue_order_id)) in cancels.iter().enumerate()
979        {
980            let symbol = instrument_id.symbol.inner();
981            let Some(asset) = signer.get_asset_index_for_symbol(symbol) else {
982                results[index] = Some(format!(
983                    "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
984                ));
985                continue;
986            };
987
988            if let Some(cloid) = signer.cached_client_order_id_cloid(client_order_id) {
989                cloid_requests.push(HyperliquidExchangeCancelByCloidRequest { asset, cloid });
990                cloid_indices.push(index);
991            } else if let Some(venue_order_id) = venue_order_id {
992                match venue_order_id.as_str().parse::<u64>() {
993                    Ok(oid) => {
994                        oid_requests.push(HyperliquidExchangeCancelOrderRequest { asset, oid });
995                        oid_indices.push(index);
996                    }
997                    Err(_) => {
998                        results[index] = Some("Invalid venue order ID format".to_string());
999                    }
1000                }
1001            } else {
1002                let cloid = signer.get_or_generate_client_order_id_cloid(*client_order_id);
1003                cloid_requests.push(HyperliquidExchangeCancelByCloidRequest { asset, cloid });
1004                cloid_indices.push(index);
1005            }
1006        }
1007
1008        if cloid_requests.is_empty() && oid_requests.is_empty() {
1009            return Ok(results);
1010        }
1011
1012        if !cloid_requests.is_empty() {
1013            let action = HyperliquidExchangeAction::CancelByCloid {
1014                cancels: cloid_requests,
1015                fast: None,
1016            };
1017            let errors = self
1018                .post_cancel_action_errors(signer, &action, cloid_indices.len())
1019                .await?;
1020
1021            for (index, error) in cloid_indices.into_iter().zip(errors) {
1022                results[index] = error;
1023            }
1024        }
1025
1026        if !oid_requests.is_empty() {
1027            let action = HyperliquidExchangeAction::Cancel {
1028                cancels: oid_requests,
1029                fast: None,
1030            };
1031            let errors = self
1032                .post_cancel_action_errors(signer, &action, oid_indices.len())
1033                .await?;
1034
1035            for (index, error) in oid_indices.into_iter().zip(errors) {
1036                results[index] = error;
1037            }
1038        }
1039
1040        Ok(results)
1041    }
1042
1043    async fn post_cancel_action_errors(
1044        &self,
1045        signer: &HyperliquidHttpClient,
1046        action: &HyperliquidExchangeAction,
1047        request_count: usize,
1048    ) -> HyperliquidResult<Vec<Option<String>>> {
1049        match self.post_cancel_action(signer, action).await {
1050            Ok(response) if response.is_ok() => {
1051                match cancel_errors_for_requests(extract_inner_errors(&response), request_count) {
1052                    Ok(errors) => Ok(errors),
1053                    Err(e) => Ok(vec![Some(e.to_string()); request_count]),
1054                }
1055            }
1056            Ok(response) => Ok(vec![
1057                Some(format!(
1058                    "Cancel orders failed: {}",
1059                    extract_error_message(&response)
1060                ));
1061                request_count
1062            ]),
1063            Err(e) => Err(e),
1064        }
1065    }
1066
1067    async fn post_cancel_action(
1068        &self,
1069        signer: &HyperliquidHttpClient,
1070        action: &HyperliquidExchangeAction,
1071    ) -> HyperliquidResult<HyperliquidExchangeResponse> {
1072        let weight = exec_action_weight(action);
1073
1074        let payload = signer.sign_action_exec_request(action, None)?;
1075        let response = self
1076            .send_post_request(PostRequest::Action { payload }, self.post_timeout)
1077            .await?;
1078
1079        match response.response {
1080            PostResponsePayload::Action { payload } => {
1081                serde_json::from_value(payload).map_err(HyperliquidError::Serde)
1082            }
1083            PostResponsePayload::Error { payload } => Err(map_post_payload_error(payload, weight)),
1084            PostResponsePayload::Info { payload } => Err(HyperliquidError::decode(format!(
1085                "expected action post response, received info payload: {payload}"
1086            ))),
1087        }
1088    }
1089
1090    /// Modify an order through the Hyperliquid WebSocket post API.
1091    #[allow(
1092        clippy::too_many_arguments,
1093        reason = "matches the Python and HTTP order modify surface"
1094    )]
1095    pub async fn modify_order(
1096        &self,
1097        signer: &HyperliquidHttpClient,
1098        instrument_id: InstrumentId,
1099        venue_order_id: Option<VenueOrderId>,
1100        order_side: OrderSide,
1101        order_type: OrderType,
1102        price: Price,
1103        quantity: Quantity,
1104        trigger_price: Option<Price>,
1105        reduce_only: bool,
1106        post_only: bool,
1107        time_in_force: TimeInForce,
1108        client_order_id: Option<ClientOrderId>,
1109    ) -> HyperliquidResult<()> {
1110        let symbol = instrument_id.symbol.inner();
1111        let asset = signer.get_asset_index_for_symbol(symbol).ok_or_else(|| {
1112            HyperliquidError::bad_request(format!(
1113                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
1114            ))
1115        })?;
1116        let oid = match client_order_id
1117            .as_ref()
1118            .and_then(|id| signer.unique_cached_client_order_id_cloid(id))
1119        {
1120            Some(cloid) => HyperliquidExchangeModifyTarget::Cloid(cloid),
1121            None => {
1122                let Some(venue_order_id) = venue_order_id.as_ref() else {
1123                    return Err(HyperliquidError::bad_request(
1124                        "venue_order_id or unique cached CLOID is required for modify",
1125                    ));
1126                };
1127                HyperliquidExchangeModifyTarget::from_venue_order_id(venue_order_id)
1128                    .map_err(|_| HyperliquidError::bad_request("Invalid venue order ID format"))?
1129            }
1130        };
1131        let is_buy = matches!(order_side, OrderSide::Buy);
1132        let price_decimals = signer.get_price_precision_for_symbol(symbol);
1133        let price = normalize_or_validate_wire_price(
1134            price.as_decimal(),
1135            "Price",
1136            price_decimals,
1137            signer.normalize_prices(),
1138        )
1139        .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?;
1140        let kind = hyperliquid_order_kind(
1141            order_type,
1142            time_in_force,
1143            post_only,
1144            trigger_price,
1145            signer.normalize_prices(),
1146            price_decimals,
1147        )?;
1148        let cloid =
1149            client_order_id.map(|id| (id, signer.get_or_generate_client_order_id_cloid(id)));
1150        let order = HyperliquidExchangePlaceOrderRequest {
1151            asset,
1152            is_buy,
1153            price,
1154            size: quantity.as_decimal().normalize(),
1155            reduce_only,
1156            kind,
1157            cloid: cloid.map(|(_, cloid)| cloid),
1158        };
1159
1160        if let Some((client_order_id, cloid)) = cloid {
1161            self.cache_cloid_mapping(Ustr::from(&cloid.to_hex()), client_order_id);
1162        }
1163        let action = HyperliquidExchangeAction::Modify {
1164            modify: HyperliquidExchangeModifyOrderRequest { oid, order },
1165        };
1166        let response = self.post_action_exec(signer, &action).await?;
1167
1168        ensure_ws_action_accepted(&response, "Modify order")
1169    }
1170
1171    async fn send_post_request(
1172        &self,
1173        request: PostRequest,
1174        timeout: Duration,
1175    ) -> HyperliquidResult<PostResponse> {
1176        self.send_post_request_result(request, timeout)
1177            .await
1178            .map_err(PostRequestError::into_error)
1179    }
1180
1181    async fn send_post_request_result(
1182        &self,
1183        request: PostRequest,
1184        timeout: Duration,
1185    ) -> Result<PostResponse, PostRequestError> {
1186        let id = self.post_ids.next();
1187        let Some(deadline) = tokio::time::Instant::now().checked_add(timeout) else {
1188            return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout));
1189        };
1190
1191        let cancellation_token = CancellationToken::new();
1192        let rx = tokio::select! {
1193            biased;
1194            () = tokio::time::sleep_until(deadline) => return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout)),
1195            result = self.post_router.register_with_cancellation(id, &cancellation_token) => result.map_err(PostRequestError::BeforeDispatch)?,
1196        };
1197
1198        let _cancellation_guard = cancellation_token.drop_guard_ref();
1199
1200        let send_result = {
1201            let cmd_tx = tokio::select! {
1202                biased;
1203                () = tokio::time::sleep_until(deadline) => {
1204                    self.cancel_post_registration(id, &cancellation_token).await;
1205                    return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout));
1206                }
1207                cmd_tx = self.cmd_tx.read() => cmd_tx,
1208            };
1209
1210            if cancellation_token.is_cancelled() || tokio::time::Instant::now() >= deadline {
1211                self.cancel_post_registration(id, &cancellation_token).await;
1212                return Err(PostRequestError::BeforeDispatch(HyperliquidError::Timeout));
1213            }
1214
1215            cmd_tx.send(HandlerCommand::Post {
1216                id,
1217                request,
1218                deadline,
1219                cancellation_token: cancellation_token.clone(),
1220            })
1221        };
1222
1223        if let Err(e) = send_result {
1224            self.cancel_post_registration(id, &cancellation_token).await;
1225            return Err(PostRequestError::BeforeDispatch(
1226                HyperliquidError::transport(format!("post command channel closed: {e}")),
1227            ));
1228        }
1229
1230        self.await_post_response(id, rx, deadline, &cancellation_token)
1231            .await
1232            .map_err(PostRequestError::AfterDispatch)
1233    }
1234
1235    async fn await_post_response(
1236        &self,
1237        id: u64,
1238        rx: tokio::sync::oneshot::Receiver<PostResponse>,
1239        deadline: tokio::time::Instant,
1240        cancellation_token: &CancellationToken,
1241    ) -> HyperliquidResult<PostResponse> {
1242        tokio::select! {
1243            biased;
1244            result = rx => match result {
1245                Ok(response) => Ok(response),
1246                Err(_closed) => {
1247                    self.cancel_post_registration(id, cancellation_token).await;
1248                    Err(HyperliquidError::transport("post response channel closed"))
1249                },
1250            },
1251            () = tokio::time::sleep_until(deadline) => {
1252                self.cancel_post_registration(id, cancellation_token).await;
1253                Err(HyperliquidError::Timeout)
1254            },
1255        }
1256    }
1257
1258    async fn cancel_post_registration(&self, id: u64, cancellation_token: &CancellationToken) {
1259        cancellation_token.cancel();
1260        self.post_router
1261            .cancel_registration(id, cancellation_token)
1262            .await;
1263    }
1264
1265    /// Returns true if the WebSocket is actively connected.
1266    pub fn is_active(&self) -> bool {
1267        let mode = self.connection_mode.load();
1268        mode.load(Ordering::Relaxed) == ConnectionMode::Active as u8
1269    }
1270
1271    /// Returns the URL of this WebSocket client.
1272    pub fn url(&self) -> &str {
1273        &self.url
1274    }
1275
1276    /// Caches multiple instruments.
1277    ///
1278    /// Clears the existing cache first, then adds all provided instruments.
1279    /// Instruments are keyed by their raw_symbol which is unique per instrument:
1280    /// - Perps use base currency (e.g., "BTC")
1281    /// - Spot uses @{pair_index} format (e.g., "@107") or slash format for PURR
1282    pub fn cache_instruments(&mut self, instruments: Vec<InstrumentAny>) {
1283        let mut map = AHashMap::new();
1284
1285        for inst in instruments {
1286            let coin = inst.raw_symbol().inner();
1287            map.insert(coin, inst);
1288        }
1289        let count = map.len();
1290        self.instruments.store(map);
1291        log::debug!("Hyperliquid instrument cache initialized with {count} instruments");
1292    }
1293
1294    /// Caches a single instrument.
1295    ///
1296    /// Any existing instrument with the same raw_symbol will be replaced.
1297    pub fn cache_instrument(&self, instrument: InstrumentAny) {
1298        let coin = instrument.raw_symbol().inner();
1299        self.instruments.insert(coin, instrument.clone());
1300
1301        // Before connect() the handler isn't running; this send will fail and that's expected
1302        // because connect() replays the instruments via InitializeInstruments
1303        if let Ok(cmd_tx) = self.cmd_tx.try_read() {
1304            let _ = cmd_tx.send(HandlerCommand::UpdateInstrument(instrument));
1305        }
1306    }
1307
1308    /// Returns a shared reference to the instrument cache.
1309    #[must_use]
1310    pub fn instruments_cache(&self) -> Arc<AtomicMap<Ustr, InstrumentAny>> {
1311        self.instruments.clone()
1312    }
1313
1314    /// Caches spot fill coin mappings for instrument lookup.
1315    ///
1316    /// Hyperliquid WebSocket fills for spot use `@{pair_index}` format (e.g., `@107`),
1317    /// while instruments are identified by full symbols (e.g., `HYPE-USDC-SPOT`).
1318    /// This mapping allows the handler to look up instruments from spot fills.
1319    pub fn cache_spot_fill_coins(&self, mapping: AHashMap<Ustr, Ustr>) {
1320        if let Ok(cmd_tx) = self.cmd_tx.try_read() {
1321            let _ = cmd_tx.send(HandlerCommand::CacheSpotFillCoins(mapping));
1322        }
1323    }
1324
1325    /// Caches a venue CLOID to client_order_id mapping for order/fill resolution.
1326    ///
1327    /// This mapping allows WebSocket order status and fill reports to be resolved back to
1328    /// the original client_order_id.
1329    ///
1330    /// This writes directly to a shared cache that the handler reads from, avoiding any
1331    /// race conditions between caching and WebSocket message processing.
1332    pub fn cache_cloid_mapping(&self, cloid: Ustr, client_order_id: ClientOrderId) {
1333        log::debug!("Caching cloid mapping: {cloid} -> {client_order_id}");
1334        self.cloid_cache.lock().insert(cloid, client_order_id);
1335    }
1336
1337    /// Removes a cloid mapping from the cache.
1338    ///
1339    /// Called on terminal order state. The cache is FIFO-bounded so missed
1340    /// removals self-evict (see GH-3972 cancel-replace drain).
1341    pub fn remove_cloid_mapping(&self, cloid: &Ustr) {
1342        if self.cloid_cache.lock().remove(cloid).is_some() {
1343            log::debug!("Removed cloid mapping: {cloid}");
1344        }
1345    }
1346
1347    /// Clears all cloid mappings from the cache.
1348    ///
1349    /// Useful for cleanup during reconnection or shutdown.
1350    pub fn clear_cloid_cache(&self) {
1351        let mut cache = self.cloid_cache.lock();
1352        let count = cache.len();
1353        cache.clear();
1354
1355        if count > 0 {
1356            log::debug!("Cleared {count} cloid mappings from cache");
1357        }
1358    }
1359
1360    /// Returns the number of cloid mappings in the cache.
1361    #[must_use]
1362    pub fn cloid_cache_len(&self) -> usize {
1363        self.cloid_cache.lock().len()
1364    }
1365
1366    /// Looks up a client_order_id by its venue CLOID.
1367    ///
1368    /// Returns `Some(ClientOrderId)` if the mapping exists, `None` otherwise.
1369    #[must_use]
1370    pub fn get_cloid_mapping(&self, cloid: &Ustr) -> Option<ClientOrderId> {
1371        self.cloid_cache.lock().get(cloid).copied()
1372    }
1373
1374    /// Gets an instrument from the cache by ID.
1375    ///
1376    /// Searches the cache for a matching instrument ID.
1377    pub fn get_instrument(&self, id: &InstrumentId) -> Option<InstrumentAny> {
1378        self.instruments
1379            .load()
1380            .values()
1381            .find(|inst| inst.id() == *id)
1382            .cloned()
1383    }
1384
1385    /// Gets an instrument from the cache by raw_symbol (coin).
1386    pub fn get_instrument_by_symbol(&self, symbol: &Ustr) -> Option<InstrumentAny> {
1387        self.instruments.get_cloned(symbol)
1388    }
1389
1390    /// Returns the count of confirmed subscriptions.
1391    pub fn subscription_count(&self) -> usize {
1392        self.subscriptions.len()
1393    }
1394
1395    /// Gets a bar type from the cache by coin and interval.
1396    ///
1397    /// This looks up the subscription key created when subscribing to bars.
1398    pub fn get_bar_type(&self, coin: &str, interval: &str) -> Option<BarType> {
1399        // Use canonical key format matching subscribe_bars
1400        let key = format!("candle:{coin}:{interval}");
1401        self.bar_types.load().get(&key).copied()
1402    }
1403
1404    /// Subscribe to L2 order book for an instrument.
1405    pub async fn subscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1406        self.subscribe_book_with_options(instrument_id, None, None)
1407            .await
1408    }
1409
1410    /// Subscribe to L2 order book with optional `nSigFigs` / `mantissa`
1411    /// precision controls passed through to the venue's `l2Book` stream.
1412    ///
1413    /// One venue `l2Book` stream per coin is shared with depth snapshots;
1414    /// the first logical use opens the stream and its options win. Requesting
1415    /// different options while the stream is active logs a warning.
1416    pub async fn subscribe_book_with_options(
1417        &self,
1418        instrument_id: InstrumentId,
1419        n_sig_figs: Option<u32>,
1420        mantissa: Option<u32>,
1421    ) -> anyhow::Result<()> {
1422        let instrument = self
1423            .get_instrument(&instrument_id)
1424            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1425        let coin = instrument.raw_symbol().inner();
1426
1427        let cmd_tx = self.cmd_tx.read().await;
1428
1429        // Update the handler's coin→instrument mapping for this subscription
1430        cmd_tx
1431            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1432            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1433
1434        self.send_book_stream_subscribe(&cmd_tx, coin, BookStreamUse::Deltas, n_sig_figs, mantissa)
1435    }
1436
1437    /// Subscribe to order book depth-10 snapshots.
1438    ///
1439    /// Reuses the same `l2Book` WebSocket subscription as
1440    /// [`Self::subscribe_book`] and flags the handler to additionally emit
1441    /// `NautilusWsMessage::Depth` for this coin.
1442    pub async fn subscribe_book_depth(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1443        self.subscribe_book_depth_with_options(instrument_id, None, None)
1444            .await
1445    }
1446
1447    /// Subscribe to depth-10 snapshots with optional `nSigFigs` /
1448    /// `mantissa` precision controls.
1449    ///
1450    /// Shares the coin's `l2Book` stream with deltas subscribers; the first
1451    /// logical use opens the stream and its options win. Requesting different
1452    /// options while the stream is active logs a warning.
1453    pub async fn subscribe_book_depth_with_options(
1454        &self,
1455        instrument_id: InstrumentId,
1456        n_sig_figs: Option<u32>,
1457        mantissa: Option<u32>,
1458    ) -> anyhow::Result<()> {
1459        let instrument = self
1460            .get_instrument(&instrument_id)
1461            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1462        let coin = instrument.raw_symbol().inner();
1463
1464        let cmd_tx = self.cmd_tx.read().await;
1465
1466        cmd_tx
1467            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1468            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1469
1470        cmd_tx
1471            .send(HandlerCommand::SetDepthSub {
1472                coin,
1473                subscribed: true,
1474            })
1475            .map_err(|e| anyhow::anyhow!("Failed to send SetDepthSub command: {e}"))?;
1476
1477        self.send_book_stream_subscribe(&cmd_tx, coin, BookStreamUse::Depth, n_sig_figs, mantissa)
1478    }
1479
1480    /// Unsubscribe from order book depth-10 snapshots.
1481    ///
1482    /// Clears the depth emission flag and tears down the underlying
1483    /// `l2Book` stream unless active deltas subscribers still need it.
1484    pub async fn unsubscribe_book_depth(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1485        let instrument = self
1486            .get_instrument(&instrument_id)
1487            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1488        let coin = instrument.raw_symbol().inner();
1489
1490        let cmd_tx = self.cmd_tx.read().await;
1491
1492        cmd_tx
1493            .send(HandlerCommand::SetDepthSub {
1494                coin,
1495                subscribed: false,
1496            })
1497            .map_err(|e| anyhow::anyhow!("Failed to send SetDepthSub command: {e}"))?;
1498
1499        self.send_book_stream_unsubscribe(&cmd_tx, coin, BookStreamUse::Depth)
1500    }
1501
1502    /// Subscribe to best bid/offer (BBO) quotes for an instrument.
1503    pub async fn subscribe_quotes(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1504        let instrument = self
1505            .get_instrument(&instrument_id)
1506            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1507        let coin = instrument.raw_symbol().inner();
1508
1509        let cmd_tx = self.cmd_tx.read().await;
1510        self.quote_streams.insert(coin, ());
1511
1512        // Update the handler's coin→instrument mapping for this subscription
1513        if let Err(e) = cmd_tx.send(HandlerCommand::UpdateInstrument(instrument.clone())) {
1514            self.quote_streams.remove(&coin);
1515            anyhow::bail!("Failed to send UpdateInstrument command: {e}");
1516        }
1517
1518        let subscription = SubscriptionRequest::Bbo { coin };
1519
1520        if let Err(e) = self.send_subscription(&cmd_tx, subscription) {
1521            self.quote_streams.remove(&coin);
1522            return Err(e);
1523        }
1524        Ok(())
1525    }
1526
1527    /// Subscribe to all mid prices across markets.
1528    pub async fn subscribe_all_mids(&self) -> anyhow::Result<()> {
1529        self.subscribe_all_mids_with_dex(None).await
1530    }
1531
1532    /// Subscribe to aggregate asset contexts across all perp dexes.
1533    pub async fn subscribe_all_dexs_asset_ctxs(&self) -> anyhow::Result<()> {
1534        self.send_subscription(
1535            &*self.cmd_tx.read().await,
1536            SubscriptionRequest::AllDexsAssetCtxs,
1537        )?;
1538        Ok(())
1539    }
1540
1541    /// Subscribe to all mid prices across markets, optionally scoped to a specific dex.
1542    pub async fn subscribe_all_mids_with_dex(&self, dex: Option<&str>) -> anyhow::Result<()> {
1543        let cmd_tx = self.cmd_tx.read().await;
1544
1545        let subscription = SubscriptionRequest::AllMids {
1546            dex: dex.map(ToString::to_string),
1547        };
1548
1549        self.send_subscription(&cmd_tx, subscription)?;
1550        Ok(())
1551    }
1552
1553    /// Unsubscribe from all mid prices across markets.
1554    pub async fn unsubscribe_all_mids(&self) -> anyhow::Result<()> {
1555        self.unsubscribe_all_mids_with_dex(None).await
1556    }
1557
1558    /// Unsubscribe from aggregate asset contexts across all perp dexes.
1559    pub async fn unsubscribe_all_dexs_asset_ctxs(&self) -> anyhow::Result<()> {
1560        self.send_unsubscription(
1561            &*self.cmd_tx.read().await,
1562            SubscriptionRequest::AllDexsAssetCtxs,
1563        )?;
1564        Ok(())
1565    }
1566
1567    /// Unsubscribe from all mid prices across markets, optionally scoped to a specific dex.
1568    pub async fn unsubscribe_all_mids_with_dex(&self, dex: Option<&str>) -> anyhow::Result<()> {
1569        let cmd_tx = self.cmd_tx.read().await;
1570
1571        let subscription = SubscriptionRequest::AllMids {
1572            dex: dex.map(ToString::to_string),
1573        };
1574
1575        self.send_unsubscription(&cmd_tx, subscription)?;
1576        Ok(())
1577    }
1578
1579    /// Subscribe to trades for an instrument.
1580    pub async fn subscribe_trades(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1581        self.subscribe_trade_stream(instrument_id, TradeStreamUse::Ticks)
1582            .await
1583    }
1584
1585    /// Subscribe to complete public trades for an instrument.
1586    pub async fn subscribe_public_trades(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1587        self.subscribe_trade_stream(instrument_id, TradeStreamUse::PublicTrades)
1588            .await
1589    }
1590
1591    async fn subscribe_trade_stream(
1592        &self,
1593        instrument_id: InstrumentId,
1594        stream_use: TradeStreamUse,
1595    ) -> anyhow::Result<()> {
1596        let instrument = self
1597            .get_instrument(&instrument_id)
1598            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1599        let coin = instrument.raw_symbol().inner();
1600
1601        let cmd_tx = self.cmd_tx.read().await;
1602
1603        // Update the handler's coin→instrument mapping for this subscription
1604        cmd_tx
1605            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1606            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1607
1608        // Keep registry mutations and their handler commands ordered across
1609        // concurrent generic/custom subscriptions for the same coin.
1610        let _trade_stream_guard = self.trade_stream_lock.lock();
1611        let registration = self.trade_streams.register(coin, stream_use);
1612        cmd_tx
1613            .send(HandlerCommand::UpdateTradeSubs {
1614                coin,
1615                uses: registration.uses,
1616            })
1617            .map_err(|e| anyhow::anyhow!("Failed to send UpdateTradeSubs command: {e}"))?;
1618
1619        if registration.subscribe
1620            && let Err(e) = self.send_subscription(&cmd_tx, SubscriptionRequest::Trades { coin })
1621        {
1622            let rollback = self.trade_streams.release(&coin, stream_use);
1623            let _ = cmd_tx.send(HandlerCommand::UpdateTradeSubs {
1624                coin,
1625                uses: rollback.uses,
1626            });
1627            return Err(e);
1628        }
1629        Ok(())
1630    }
1631
1632    /// Subscribe to mark price updates for an instrument.
1633    pub async fn subscribe_mark_prices(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1634        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::MarkPrice)
1635            .await
1636    }
1637
1638    /// Subscribe to index/oracle price updates for an instrument.
1639    pub async fn subscribe_index_prices(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1640        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::IndexPrice)
1641            .await
1642    }
1643
1644    /// Subscribe to candle/bar data for a specific coin and interval.
1645    pub async fn subscribe_bars(&self, bar_type: BarType) -> anyhow::Result<()> {
1646        let instrument_id = bar_type.instrument_id();
1647        let instrument = self
1648            .get_instrument(&instrument_id)
1649            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1650        let coin = instrument.raw_symbol().inner();
1651        let interval = bar_type_to_interval(&bar_type)?;
1652        let subscription = SubscriptionRequest::Candle { coin, interval };
1653
1654        // Cache the bar type for parsing using canonical key
1655        let key = format!("candle:{coin}:{interval}");
1656        self.bar_types.insert(key.clone(), bar_type);
1657
1658        let cmd_tx = self.cmd_tx.read().await;
1659
1660        cmd_tx
1661            .send(HandlerCommand::UpdateInstrument(instrument.clone()))
1662            .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
1663
1664        cmd_tx
1665            .send(HandlerCommand::AddBarType {
1666                key: key.clone(),
1667                bar_type,
1668            })
1669            .map_err(|e| anyhow::anyhow!("Failed to send AddBarType command: {e}"))?;
1670
1671        if let Err(e) = self.send_subscription(&cmd_tx, subscription) {
1672            self.bar_types.remove(&key);
1673            let _ = cmd_tx.send(HandlerCommand::RemoveBarType { key });
1674            return Err(e);
1675        }
1676        Ok(())
1677    }
1678
1679    /// Subscribe to funding rate updates for an instrument.
1680    pub async fn subscribe_funding_rates(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1681        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::FundingRate)
1682            .await
1683    }
1684
1685    /// Subscribe to open interest updates for an instrument.
1686    pub async fn subscribe_open_interest(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1687        self.subscribe_asset_context_data(instrument_id, AssetContextDataType::OpenInterest)
1688            .await
1689    }
1690
1691    /// Subscribe to order updates for a specific user address.
1692    pub async fn subscribe_order_updates(&self, user: &str) -> anyhow::Result<()> {
1693        let subscription = SubscriptionRequest::OrderUpdates {
1694            user: user.to_string(),
1695        };
1696        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1697        Ok(())
1698    }
1699
1700    /// Subscribe to user events (fills, funding, liquidations) for a specific user address.
1701    pub async fn subscribe_user_events(&self, user: &str) -> anyhow::Result<()> {
1702        let subscription = SubscriptionRequest::UserEvents {
1703            user: user.to_string(),
1704        };
1705        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1706        Ok(())
1707    }
1708
1709    /// Subscribe to user fills for a specific user address.
1710    ///
1711    /// Note: This channel is redundant with `userEvents` which already includes fills.
1712    /// Prefer using `subscribe_user_events` or `subscribe_all_user_channels` instead.
1713    pub async fn subscribe_user_fills(&self, user: &str) -> anyhow::Result<()> {
1714        let subscription = SubscriptionRequest::UserFills {
1715            user: user.to_string(),
1716            aggregate_by_time: None,
1717        };
1718        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1719        Ok(())
1720    }
1721
1722    /// Subscribe to all user channels (order updates + user events) for convenience.
1723    ///
1724    /// Note: `userEvents` already includes fills, so we don't subscribe to `userFills`
1725    /// separately to avoid duplicate fill messages.
1726    ///
1727    /// This does **not** include opt-in TWAP custom-data channels
1728    /// (`userTwapHistory` / `userTwapSliceFills`).
1729    pub async fn subscribe_all_user_channels(&self, user: &str) -> anyhow::Result<()> {
1730        self.subscribe_order_updates(user).await?;
1731        self.subscribe_user_events(user).await?;
1732        Ok(())
1733    }
1734
1735    /// Subscribe to TWAP history for a user address (`userTwapHistory`).
1736    ///
1737    /// Opt-in custom data. The address need not be the adapter trading account.
1738    pub async fn subscribe_user_twap_history(&self, user: &str) -> anyhow::Result<()> {
1739        let subscription = SubscriptionRequest::UserTwapHistory {
1740            user: user.to_string(),
1741        };
1742        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1743        Ok(())
1744    }
1745
1746    /// Unsubscribe from TWAP history for a user address.
1747    pub async fn unsubscribe_user_twap_history(&self, user: &str) -> anyhow::Result<()> {
1748        let subscription = SubscriptionRequest::UserTwapHistory {
1749            user: user.to_string(),
1750        };
1751        self.send_unsubscription(&*self.cmd_tx.read().await, subscription)?;
1752        Ok(())
1753    }
1754
1755    /// Subscribe to TWAP slice fills for a user address (`userTwapSliceFills`).
1756    ///
1757    /// Opt-in custom data. The address need not be the adapter trading account.
1758    pub async fn subscribe_user_twap_slice_fills(&self, user: &str) -> anyhow::Result<()> {
1759        let subscription = SubscriptionRequest::UserTwapSliceFills {
1760            user: user.to_string(),
1761        };
1762        self.send_subscription(&*self.cmd_tx.read().await, subscription)?;
1763        Ok(())
1764    }
1765
1766    /// Unsubscribe from TWAP slice fills for a user address.
1767    pub async fn unsubscribe_user_twap_slice_fills(&self, user: &str) -> anyhow::Result<()> {
1768        let subscription = SubscriptionRequest::UserTwapSliceFills {
1769            user: user.to_string(),
1770        };
1771        self.send_unsubscription(&*self.cmd_tx.read().await, subscription)?;
1772        Ok(())
1773    }
1774
1775    /// Unsubscribe from L2 order book for an instrument.
1776    ///
1777    /// Tears down the venue `l2Book` stream unless active depth subscribers
1778    /// still need it.
1779    pub async fn unsubscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1780        let instrument = self
1781            .get_instrument(&instrument_id)
1782            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1783        let coin = instrument.raw_symbol().inner();
1784
1785        let cmd_tx = self.cmd_tx.read().await;
1786
1787        self.send_book_stream_unsubscribe(&cmd_tx, coin, BookStreamUse::Deltas)
1788    }
1789
1790    /// Resubscribes the venue `l2Book` stream for an instrument in place.
1791    ///
1792    /// Sends an unsubscribe immediately followed by a subscribe, both echoing
1793    /// the stream's original precision options (the venue matches unsubscribes
1794    /// by full payload). Registry state is left untouched so the logical
1795    /// deltas/depth uses and first-wins options survive the cycle. Used by
1796    /// stale-stream recovery, where a plain subscribe would be gated off by
1797    /// the existing registry entry.
1798    pub async fn resubscribe_book(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1799        let instrument = self
1800            .get_instrument(&instrument_id)
1801            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1802        let coin = instrument.raw_symbol().inner();
1803
1804        // Serialize the registry check with read-locked subscribe/unsubscribe senders
1805        let cmd_tx = self.cmd_tx.write().await;
1806
1807        let Some(options) = self.book_streams.options(&coin) else {
1808            log::debug!("Skipping l2Book resubscribe for {coin}: stream no longer registered");
1809            return Ok(());
1810        };
1811
1812        let subscription = SubscriptionRequest::L2Book {
1813            coin,
1814            mantissa: options.mantissa,
1815            n_sig_figs: options.n_sig_figs,
1816        };
1817
1818        self.send_stream_resubscribe(&cmd_tx, subscription)
1819    }
1820
1821    fn send_book_stream_subscribe(
1822        &self,
1823        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
1824        coin: Ustr,
1825        stream_use: BookStreamUse,
1826        n_sig_figs: Option<u32>,
1827        mantissa: Option<u32>,
1828    ) -> anyhow::Result<()> {
1829        let registration = self.book_streams.register(
1830            coin,
1831            stream_use,
1832            BookStreamOptions {
1833                n_sig_figs,
1834                mantissa,
1835            },
1836        );
1837
1838        if registration.options_mismatch {
1839            log::warn!(
1840                "Requested l2Book options for {coin} (n_sig_figs={n_sig_figs:?}, mantissa={mantissa:?}) \
1841                differ from the active stream ({:?}), keeping active options",
1842                registration.options,
1843            );
1844        }
1845
1846        if registration.subscribe {
1847            let subscription = SubscriptionRequest::L2Book {
1848                coin,
1849                mantissa: registration.options.mantissa,
1850                n_sig_figs: registration.options.n_sig_figs,
1851            };
1852
1853            if let Err(e) = self.send_subscription(cmd_tx, subscription) {
1854                self.book_streams.release(&coin, stream_use);
1855                return Err(e);
1856            }
1857        }
1858        Ok(())
1859    }
1860
1861    fn send_book_stream_unsubscribe(
1862        &self,
1863        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
1864        coin: Ustr,
1865        stream_use: BookStreamUse,
1866    ) -> anyhow::Result<()> {
1867        match self.book_streams.release(&coin, stream_use) {
1868            BookStreamRelease::Unsubscribe(options) => {
1869                let subscription = SubscriptionRequest::L2Book {
1870                    coin,
1871                    mantissa: options.mantissa,
1872                    n_sig_figs: options.n_sig_figs,
1873                };
1874
1875                self.send_unsubscription(cmd_tx, subscription)?;
1876            }
1877            BookStreamRelease::Retained => {
1878                let remaining_use = match stream_use {
1879                    BookStreamUse::Deltas => "depth",
1880                    BookStreamUse::Depth => "deltas",
1881                };
1882                log::debug!("Keeping shared l2Book stream for {coin}: {remaining_use} use remains");
1883            }
1884        }
1885        Ok(())
1886    }
1887
1888    /// Unsubscribe from quote ticks for an instrument.
1889    pub async fn unsubscribe_quotes(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1890        let instrument = self
1891            .get_instrument(&instrument_id)
1892            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1893        let coin = instrument.raw_symbol().inner();
1894
1895        let subscription = SubscriptionRequest::Bbo { coin };
1896        let cmd_tx = self.cmd_tx.read().await;
1897
1898        self.quote_streams.remove(&coin);
1899
1900        self.send_unsubscription(&cmd_tx, subscription)?;
1901        Ok(())
1902    }
1903
1904    /// Resubscribes the venue `bbo` stream for an instrument in place
1905    /// (unsubscribe immediately followed by subscribe). Used by stale-stream
1906    /// recovery.
1907    pub async fn resubscribe_quotes(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1908        let instrument = self
1909            .get_instrument(&instrument_id)
1910            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1911        let coin = instrument.raw_symbol().inner();
1912
1913        // Keep the registration check atomic with the resubscribe pair
1914        let cmd_tx = self.cmd_tx.write().await;
1915
1916        if !self.quote_streams.contains_key(&coin) {
1917            log::debug!("Skipping bbo resubscribe for {coin}: stream no longer registered");
1918            return Ok(());
1919        }
1920
1921        self.send_stream_resubscribe(&cmd_tx, SubscriptionRequest::Bbo { coin })
1922    }
1923
1924    fn send_stream_resubscribe(
1925        &self,
1926        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
1927        subscription: SubscriptionRequest,
1928    ) -> anyhow::Result<()> {
1929        cmd_tx
1930            .send(HandlerCommand::Resubscribe { subscription })
1931            .map_err(|e| anyhow::anyhow!("Failed to send resubscribe command: {e}"))
1932    }
1933
1934    /// Unsubscribe from trades for an instrument.
1935    pub async fn unsubscribe_trades(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1936        self.unsubscribe_trade_stream(instrument_id, TradeStreamUse::Ticks)
1937            .await
1938    }
1939
1940    /// Unsubscribe from complete public trades for an instrument.
1941    pub async fn unsubscribe_public_trades(
1942        &self,
1943        instrument_id: InstrumentId,
1944    ) -> anyhow::Result<()> {
1945        self.unsubscribe_trade_stream(instrument_id, TradeStreamUse::PublicTrades)
1946            .await
1947    }
1948
1949    async fn unsubscribe_trade_stream(
1950        &self,
1951        instrument_id: InstrumentId,
1952        stream_use: TradeStreamUse,
1953    ) -> anyhow::Result<()> {
1954        let instrument = self
1955            .get_instrument(&instrument_id)
1956            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1957        let coin = instrument.raw_symbol().inner();
1958
1959        let cmd_tx = self.cmd_tx.read().await;
1960        // Keep registry mutations and their handler commands ordered across
1961        // concurrent generic/custom unsubscriptions for the same coin.
1962        let _trade_stream_guard = self.trade_stream_lock.lock();
1963        let release = self.trade_streams.release(&coin, stream_use);
1964        cmd_tx
1965            .send(HandlerCommand::UpdateTradeSubs {
1966                coin,
1967                uses: release.uses,
1968            })
1969            .map_err(|e| anyhow::anyhow!("Failed to send UpdateTradeSubs command: {e}"))?;
1970
1971        if release.unsubscribe {
1972            self.send_unsubscription(&cmd_tx, SubscriptionRequest::Trades { coin })?;
1973        }
1974        Ok(())
1975    }
1976
1977    /// Unsubscribe from mark price updates for an instrument.
1978    pub async fn unsubscribe_mark_prices(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
1979        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::MarkPrice)
1980            .await
1981    }
1982
1983    /// Unsubscribe from index/oracle price updates for an instrument.
1984    pub async fn unsubscribe_index_prices(
1985        &self,
1986        instrument_id: InstrumentId,
1987    ) -> anyhow::Result<()> {
1988        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::IndexPrice)
1989            .await
1990    }
1991
1992    /// Unsubscribe from candle/bar data.
1993    pub async fn unsubscribe_bars(&self, bar_type: BarType) -> anyhow::Result<()> {
1994        let instrument_id = bar_type.instrument_id();
1995        let instrument = self
1996            .get_instrument(&instrument_id)
1997            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
1998        let coin = instrument.raw_symbol().inner();
1999        let interval = bar_type_to_interval(&bar_type)?;
2000        let subscription = SubscriptionRequest::Candle { coin, interval };
2001
2002        let key = format!("candle:{coin}:{interval}");
2003        self.bar_types.remove(&key);
2004
2005        let cmd_tx = self.cmd_tx.read().await;
2006
2007        cmd_tx
2008            .send(HandlerCommand::RemoveBarType { key })
2009            .map_err(|e| anyhow::anyhow!("Failed to send RemoveBarType command: {e}"))?;
2010
2011        self.send_unsubscription(&cmd_tx, subscription)?;
2012        Ok(())
2013    }
2014
2015    /// Unsubscribe from funding rate updates for an instrument.
2016    pub async fn unsubscribe_funding_rates(
2017        &self,
2018        instrument_id: InstrumentId,
2019    ) -> anyhow::Result<()> {
2020        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::FundingRate)
2021            .await
2022    }
2023
2024    /// Unsubscribe from open interest updates for an instrument.
2025    pub async fn unsubscribe_open_interest(
2026        &self,
2027        instrument_id: InstrumentId,
2028    ) -> anyhow::Result<()> {
2029        self.unsubscribe_asset_context_data(instrument_id, AssetContextDataType::OpenInterest)
2030            .await
2031    }
2032
2033    /// Cache the ordered instrument IDs required to normalize `allDexsAssetCtxs`.
2034    ///
2035    /// Entries merge by dex: each dex in `mapping` replaces its cached entry and
2036    /// dexes absent from `mapping` keep theirs. A mapping built from the
2037    /// standard `meta` fallback covers only the standard dex, and replacing the
2038    /// whole cache with it would drop every HIP-3 context until a later complete
2039    /// build. A stale entry for a dex the venue no longer lists is harmless
2040    /// because no contexts arrive for it.
2041    pub fn cache_all_dex_asset_ctxs_instrument_ids(
2042        &self,
2043        mapping: AHashMap<Ustr, Vec<Option<InstrumentId>>>,
2044    ) {
2045        self.all_dex_asset_ctxs_instrument_ids.rcu(|cached| {
2046            cached.extend(mapping.iter().map(|(dex, ids)| (*dex, ids.clone())));
2047        });
2048
2049        if let Ok(cmd_tx) = self.cmd_tx.try_read()
2050            && let Err(e) = cmd_tx.send(HandlerCommand::CacheAllDexAssetCtxsInstrumentIds(mapping))
2051        {
2052            log::debug!(
2053                "Failed to send CacheAllDexAssetCtxsInstrumentIds command (handler may not be connected yet): {e}"
2054            );
2055        }
2056    }
2057
2058    async fn subscribe_asset_context_data(
2059        &self,
2060        instrument_id: InstrumentId,
2061        data_type: AssetContextDataType,
2062    ) -> anyhow::Result<()> {
2063        let instrument = self
2064            .get_instrument(&instrument_id)
2065            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2066        let coin = instrument.raw_symbol().inner();
2067
2068        let mut entry = self.asset_context_subs.entry(coin).or_default();
2069        let is_first_subscription = entry.is_empty();
2070        entry.insert(data_type);
2071        let data_types = entry.clone();
2072        drop(entry);
2073
2074        let cmd_tx = self.cmd_tx.read().await;
2075
2076        cmd_tx
2077            .send(HandlerCommand::UpdateAssetContextSubs { coin, data_types })
2078            .map_err(|e| anyhow::anyhow!("Failed to send UpdateAssetContextSubs command: {e}"))?;
2079
2080        if is_first_subscription {
2081            log::debug!(
2082                "First asset context subscription for coin '{coin}', subscribing to ActiveAssetCtx"
2083            );
2084            let subscription = SubscriptionRequest::ActiveAssetCtx { coin };
2085
2086            cmd_tx
2087                .send(HandlerCommand::UpdateInstrument(instrument.clone()))
2088                .map_err(|e| anyhow::anyhow!("Failed to send UpdateInstrument command: {e}"))?;
2089
2090            if let Err(e) = self.send_subscription(&cmd_tx, subscription) {
2091                if let Some(mut entry) = self.asset_context_subs.get_mut(&coin) {
2092                    entry.remove(&data_type);
2093                    let rollback = entry.clone();
2094                    let remove_entry = entry.is_empty();
2095                    drop(entry);
2096
2097                    if remove_entry {
2098                        self.asset_context_subs.remove(&coin);
2099                    }
2100                    let _ = cmd_tx.send(HandlerCommand::UpdateAssetContextSubs {
2101                        coin,
2102                        data_types: rollback,
2103                    });
2104                }
2105                return Err(e);
2106            }
2107        } else {
2108            log::debug!(
2109                "Already subscribed to ActiveAssetCtx for coin '{coin}', adding {data_type:?} to tracked types"
2110            );
2111        }
2112
2113        Ok(())
2114    }
2115
2116    async fn unsubscribe_asset_context_data(
2117        &self,
2118        instrument_id: InstrumentId,
2119        data_type: AssetContextDataType,
2120    ) -> anyhow::Result<()> {
2121        let instrument = self
2122            .get_instrument(&instrument_id)
2123            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
2124        let coin = instrument.raw_symbol().inner();
2125
2126        if let Some(mut entry) = self.asset_context_subs.get_mut(&coin) {
2127            entry.remove(&data_type);
2128            let should_unsubscribe = entry.is_empty();
2129            let data_types = entry.clone();
2130            drop(entry);
2131
2132            let cmd_tx = self.cmd_tx.read().await;
2133
2134            if should_unsubscribe {
2135                self.asset_context_subs.remove(&coin);
2136
2137                log::debug!(
2138                    "Last asset context subscription removed for coin '{coin}', unsubscribing from ActiveAssetCtx"
2139                );
2140                let subscription = SubscriptionRequest::ActiveAssetCtx { coin };
2141
2142                cmd_tx
2143                    .send(HandlerCommand::UpdateAssetContextSubs {
2144                        coin,
2145                        data_types: AHashSet::new(),
2146                    })
2147                    .map_err(|e| {
2148                        anyhow::anyhow!("Failed to send UpdateAssetContextSubs command: {e}")
2149                    })?;
2150
2151                self.send_unsubscription(&cmd_tx, subscription)?;
2152            } else {
2153                log::debug!(
2154                    "Removed {data_type:?} from tracked types for coin '{coin}', but keeping ActiveAssetCtx subscription"
2155                );
2156
2157                cmd_tx
2158                    .send(HandlerCommand::UpdateAssetContextSubs { coin, data_types })
2159                    .map_err(|e| {
2160                        anyhow::anyhow!("Failed to send UpdateAssetContextSubs command: {e}")
2161                    })?;
2162            }
2163        }
2164
2165        Ok(())
2166    }
2167
2168    fn send_subscription(
2169        &self,
2170        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2171        subscription: SubscriptionRequest,
2172    ) -> anyhow::Result<()> {
2173        let key = crate::websocket::handler::subscription_to_key(&subscription);
2174        let reserved = self
2175            .rate_limits
2176            .reserve_subscription(self.client_id, &subscription)
2177            .map_err(anyhow::Error::msg)?;
2178
2179        if let Err(e) = cmd_tx.send(HandlerCommand::Subscribe {
2180            subscriptions: vec![subscription],
2181        }) {
2182            if reserved {
2183                self.rate_limits.release_subscription(self.client_id, &key);
2184            }
2185            anyhow::bail!("Failed to send subscribe command: {e}");
2186        }
2187        Ok(())
2188    }
2189
2190    fn send_unsubscription(
2191        &self,
2192        cmd_tx: &tokio::sync::mpsc::UnboundedSender<HandlerCommand>,
2193        subscription: SubscriptionRequest,
2194    ) -> anyhow::Result<()> {
2195        cmd_tx
2196            .send(HandlerCommand::Unsubscribe {
2197                subscriptions: vec![subscription],
2198            })
2199            .map_err(|e| anyhow::anyhow!("Failed to send unsubscribe command: {e}"))
2200    }
2201
2202    /// Receives the next message from the WebSocket handler.
2203    ///
2204    /// Returns `None` if the handler has disconnected or the receiver was already taken.
2205    pub async fn next_event(&mut self) -> Option<NautilusWsMessage> {
2206        if let Some(ref mut rx) = self.out_rx {
2207            rx.recv().await
2208        } else {
2209            None
2210        }
2211    }
2212
2213    fn release_limit_reservations(&self) {
2214        self.rate_limits.release_client(self.client_id);
2215        self.connection_permit.lock().take();
2216    }
2217}
2218
2219impl Drop for HyperliquidWebSocketClient {
2220    fn drop(&mut self) {
2221        if Arc::strong_count(&self.task_handle) == 1 {
2222            self.release_limit_reservations();
2223
2224            if self.task_handle.is_empty() {
2225                return;
2226            }
2227
2228            self.signal.store(true, Ordering::Relaxed);
2229            self.task_handle.abort();
2230
2231            if let Some(control) = &self.socket_control {
2232                control.deregister();
2233            }
2234        }
2235    }
2236}
2237
2238#[derive(Debug)]
2239pub(crate) enum PostRequestError {
2240    BeforeDispatch(HyperliquidError),
2241    AfterDispatch(HyperliquidError),
2242    Rejected {
2243        error: HyperliquidError,
2244        reason: String,
2245    },
2246}
2247
2248impl PostRequestError {
2249    fn into_error(self) -> HyperliquidError {
2250        match self {
2251            Self::BeforeDispatch(error)
2252            | Self::AfterDispatch(error)
2253            | Self::Rejected { error, .. } => error,
2254        }
2255    }
2256}
2257
2258fn cancel_errors_for_requests(
2259    errors: Vec<Option<String>>,
2260    request_count: usize,
2261) -> HyperliquidResult<Vec<Option<String>>> {
2262    if errors.is_empty() {
2263        return Ok(vec![None; request_count]);
2264    }
2265
2266    if errors.len() != request_count {
2267        return Err(HyperliquidError::exchange(format!(
2268            "Cancel orders returned {} statuses for {request_count} cancels",
2269            errors.len()
2270        )));
2271    }
2272
2273    Ok(errors)
2274}
2275
2276fn map_post_payload_error(payload: String, weight: u32) -> HyperliquidError {
2277    let lower = payload.to_ascii_lowercase();
2278    let message = format!("WebSocket post error: {payload}");
2279
2280    if starts_with_status(&lower, &["429"])
2281        || lower.contains("too many requests")
2282        || lower.contains("rate limit")
2283    {
2284        HyperliquidError::rate_limit("exchange", weight, None)
2285    } else if starts_with_status(&lower, &["401", "403"])
2286        || lower.contains("unauthorized")
2287        || lower.contains("forbidden")
2288        || lower.contains("authentication")
2289        || lower.contains("authorization")
2290        || lower.contains("invalid signature")
2291        || contains_word(&lower, "auth")
2292    {
2293        HyperliquidError::auth(message)
2294    } else if starts_with_status(&lower, &["400"]) || lower.contains("bad request") {
2295        HyperliquidError::bad_request(message)
2296    } else if starts_with_status(&lower, &["500", "502", "503", "504"]) {
2297        HyperliquidError::exchange(message)
2298    } else {
2299        HyperliquidError::exchange(payload)
2300    }
2301}
2302
2303fn hyperliquid_order_kind(
2304    order_type: OrderType,
2305    time_in_force: TimeInForce,
2306    post_only: bool,
2307    trigger_price: Option<Price>,
2308    normalize_prices_enabled: bool,
2309    price_precision: Option<u8>,
2310) -> HyperliquidResult<HyperliquidExchangeOrderKind> {
2311    match order_type {
2312        OrderType::Market => Ok(HyperliquidExchangeOrderKind::Limit {
2313            limit: HyperliquidExchangeLimitParams {
2314                tif: HyperliquidExchangeTif::Ioc,
2315            },
2316        }),
2317        OrderType::Limit => {
2318            let tif = time_in_force_to_hyperliquid_tif(time_in_force, post_only)
2319                .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?;
2320            Ok(HyperliquidExchangeOrderKind::Limit {
2321                limit: HyperliquidExchangeLimitParams { tif },
2322            })
2323        }
2324        OrderType::StopMarket
2325        | OrderType::StopLimit
2326        | OrderType::MarketIfTouched
2327        | OrderType::LimitIfTouched => {
2328            let trigger_price = trigger_price.ok_or_else(|| {
2329                HyperliquidError::bad_request("Trigger orders require a trigger price")
2330            })?;
2331            let trigger_px = normalize_or_validate_wire_price(
2332                trigger_price.as_decimal(),
2333                "Trigger price",
2334                price_precision,
2335                normalize_prices_enabled,
2336            )
2337            .map_err(|e| HyperliquidError::bad_request(format!("{e}")))?;
2338            let tpsl = match order_type {
2339                OrderType::StopMarket | OrderType::StopLimit => HyperliquidExchangeTpSl::Sl,
2340                OrderType::MarketIfTouched | OrderType::LimitIfTouched => {
2341                    HyperliquidExchangeTpSl::Tp
2342                }
2343                _ => unreachable!(),
2344            };
2345            let is_market = matches!(
2346                order_type,
2347                OrderType::StopMarket | OrderType::MarketIfTouched
2348            );
2349
2350            Ok(HyperliquidExchangeOrderKind::Trigger {
2351                trigger: HyperliquidExchangeTriggerParams {
2352                    is_market,
2353                    trigger_px,
2354                    tpsl,
2355                },
2356            })
2357        }
2358        _ => Err(HyperliquidError::bad_request(format!(
2359            "Order type {order_type:?} not supported"
2360        ))),
2361    }
2362}
2363
2364fn ensure_ws_action_accepted(
2365    response: &HyperliquidExchangeResponse,
2366    action_name: &str,
2367) -> HyperliquidResult<()> {
2368    if response.is_ok() {
2369        if let Some(error_msg) = extract_inner_errors(response).into_iter().flatten().next() {
2370            return Err(HyperliquidError::bad_request(format!(
2371                "{action_name} rejected: {error_msg}"
2372            )));
2373        }
2374
2375        if let Some(error_msg) = extract_inner_error(response) {
2376            return Err(HyperliquidError::bad_request(format!(
2377                "{action_name} rejected: {error_msg}"
2378            )));
2379        }
2380
2381        return Ok(());
2382    }
2383
2384    Err(HyperliquidError::bad_request(format!(
2385        "{action_name} failed: {}",
2386        extract_error_message(response)
2387    )))
2388}
2389
2390fn starts_with_status(payload: &str, statuses: &[&str]) -> bool {
2391    let trimmed = payload.trim_start();
2392    statuses
2393        .iter()
2394        .any(|status| starts_with_status_token(trimmed, status))
2395        || trimmed.strip_prefix("http").is_some_and(|rest| {
2396            let rest = rest
2397                .trim_start_matches(|c: char| c.is_ascii_whitespace() || matches!(c, ':' | '/'));
2398            statuses
2399                .iter()
2400                .any(|status| starts_with_status_token(rest, status))
2401        })
2402}
2403
2404fn starts_with_status_token(payload: &str, status: &str) -> bool {
2405    payload.strip_prefix(status).is_some_and(|rest| {
2406        rest.chars()
2407            .next()
2408            .is_none_or(|c| !c.is_ascii_alphanumeric())
2409    })
2410}
2411
2412fn contains_word(payload: &str, word: &str) -> bool {
2413    payload
2414        .split(|c: char| !c.is_ascii_alphanumeric())
2415        .any(|part| part == word)
2416}
2417
2418// Uses split_once/rsplit_once because coin names can contain colons
2419// (e.g., vault tokens `vntls:vCURSOR`)
2420fn subscription_from_topic(topic: &str) -> anyhow::Result<SubscriptionRequest> {
2421    let (kind, rest) = topic
2422        .split_once(':')
2423        .map_or((topic, None), |(k, r)| (k, Some(r)));
2424
2425    let channel = HyperliquidWsChannel::from_wire_str(kind)
2426        .ok_or_else(|| anyhow::anyhow!("Unknown subscription channel: {kind}"))?;
2427
2428    match channel {
2429        HyperliquidWsChannel::AllMids => Ok(SubscriptionRequest::AllMids {
2430            dex: rest.map(|s| s.to_string()),
2431        }),
2432        HyperliquidWsChannel::AllDexsAssetCtxs => Ok(SubscriptionRequest::AllDexsAssetCtxs),
2433        HyperliquidWsChannel::Notification => Ok(SubscriptionRequest::Notification {
2434            user: rest.context("Missing user")?.to_string(),
2435        }),
2436        HyperliquidWsChannel::WebData2 => Ok(SubscriptionRequest::WebData2 {
2437            user: rest.context("Missing user")?.to_string(),
2438        }),
2439        HyperliquidWsChannel::Candle => {
2440            // Format: candle:{coin}:{interval} - interval is last segment
2441            let rest = rest.context("Missing candle params")?;
2442            let (coin, interval_str) = rest.rsplit_once(':').context("Missing interval")?;
2443            let interval = HyperliquidBarInterval::from_str(interval_str)?;
2444            Ok(SubscriptionRequest::Candle {
2445                coin: Ustr::from(coin),
2446                interval,
2447            })
2448        }
2449        HyperliquidWsChannel::L2Book => Ok(SubscriptionRequest::L2Book {
2450            coin: Ustr::from(rest.context("Missing coin")?),
2451            mantissa: None,
2452            n_sig_figs: None,
2453        }),
2454        HyperliquidWsChannel::Trades => Ok(SubscriptionRequest::Trades {
2455            coin: Ustr::from(rest.context("Missing coin")?),
2456        }),
2457        HyperliquidWsChannel::OrderUpdates => Ok(SubscriptionRequest::OrderUpdates {
2458            user: rest.context("Missing user")?.to_string(),
2459        }),
2460        HyperliquidWsChannel::UserEvents => Ok(SubscriptionRequest::UserEvents {
2461            user: rest.context("Missing user")?.to_string(),
2462        }),
2463        HyperliquidWsChannel::UserFills => Ok(SubscriptionRequest::UserFills {
2464            user: rest.context("Missing user")?.to_string(),
2465            aggregate_by_time: None,
2466        }),
2467        HyperliquidWsChannel::UserFundings => Ok(SubscriptionRequest::UserFundings {
2468            user: rest.context("Missing user")?.to_string(),
2469        }),
2470        HyperliquidWsChannel::UserNonFundingLedgerUpdates => {
2471            Ok(SubscriptionRequest::UserNonFundingLedgerUpdates {
2472                user: rest.context("Missing user")?.to_string(),
2473            })
2474        }
2475        HyperliquidWsChannel::ActiveAssetCtx => Ok(SubscriptionRequest::ActiveAssetCtx {
2476            coin: Ustr::from(rest.context("Missing coin")?),
2477        }),
2478        HyperliquidWsChannel::ActiveSpotAssetCtx => Ok(SubscriptionRequest::ActiveSpotAssetCtx {
2479            coin: Ustr::from(rest.context("Missing coin")?),
2480        }),
2481        HyperliquidWsChannel::ActiveAssetData => {
2482            // Format: activeAssetData:{user}:{coin} - user is eth addr (no colons)
2483            let rest = rest.context("Missing params")?;
2484            let (user, coin) = rest.split_once(':').context("Missing coin")?;
2485            Ok(SubscriptionRequest::ActiveAssetData {
2486                user: user.to_string(),
2487                coin: coin.to_string(),
2488            })
2489        }
2490        HyperliquidWsChannel::UserTwapSliceFills => Ok(SubscriptionRequest::UserTwapSliceFills {
2491            user: rest.context("Missing user")?.to_string(),
2492        }),
2493        HyperliquidWsChannel::UserTwapHistory => Ok(SubscriptionRequest::UserTwapHistory {
2494            user: rest.context("Missing user")?.to_string(),
2495        }),
2496        HyperliquidWsChannel::Bbo => Ok(SubscriptionRequest::Bbo {
2497            coin: Ustr::from(rest.context("Missing coin")?),
2498        }),
2499
2500        // Response-only channels are not valid subscription topics
2501        HyperliquidWsChannel::SubscriptionResponse
2502        | HyperliquidWsChannel::User
2503        | HyperliquidWsChannel::Post
2504        | HyperliquidWsChannel::Pong
2505        | HyperliquidWsChannel::Error => {
2506            anyhow::bail!("Not a subscription channel: {kind}")
2507        }
2508    }
2509}
2510
2511#[cfg(test)]
2512mod tests {
2513    use nautilus_live::{SocketReconnectRegistry, SocketReconnectRequestOutcome};
2514    use nautilus_model::identifiers::ClientId;
2515    use nautilus_network::mode::ReconnectRequestOutcome;
2516    use rstest::rstest;
2517    use ustr::Ustr;
2518
2519    use super::*;
2520    use crate::{
2521        common::{
2522            consts::{HYPERLIQUID_WS_POST_INFLIGHT_MAX, HYPERLIQUID_WS_SUBSCRIPTIONS_MAX},
2523            enums::HyperliquidBarInterval,
2524        },
2525        websocket::handler::subscription_to_key,
2526    };
2527
2528    #[rstest]
2529    fn test_debug_redacts_proxy_url() {
2530        let proxy_url = "http://user:password@proxy.example:8080";
2531        let client = HyperliquidWebSocketClient::new(
2532            Some("wss://test".to_string()),
2533            HyperliquidEnvironment::Testnet,
2534            None,
2535            TransportBackend::default(),
2536            Some(proxy_url.to_string()),
2537        );
2538
2539        let debug = format!("{client:?}");
2540
2541        assert!(debug.contains(REDACTED));
2542        assert!(!debug.contains(proxy_url));
2543    }
2544
2545    #[rstest]
2546    fn test_cache_all_dex_asset_ctxs_instrument_ids_keeps_dexes_absent_from_update() {
2547        let client = HyperliquidWebSocketClient::new(
2548            Some("wss://test".to_string()),
2549            HyperliquidEnvironment::Testnet,
2550            None,
2551            TransportBackend::default(),
2552            None,
2553        );
2554        let btc = Some(InstrumentId::from("BTC-USD-PERP.HYPERLIQUID"));
2555        let eth = Some(InstrumentId::from("ETH-USD-PERP.HYPERLIQUID"));
2556        let tsla = Some(InstrumentId::from("xyz:TSLA-USD-PERP.HYPERLIQUID"));
2557
2558        client.cache_all_dex_asset_ctxs_instrument_ids(AHashMap::from_iter([
2559            (Ustr::from(""), vec![btc]),
2560            (Ustr::from("xyz"), vec![tsla]),
2561        ]));
2562        // a `meta` fallback build covers only the default dex
2563        client.cache_all_dex_asset_ctxs_instrument_ids(AHashMap::from_iter([(
2564            Ustr::from(""),
2565            vec![btc, eth],
2566        )]));
2567
2568        let cached = client.all_dex_asset_ctxs_instrument_ids.load();
2569        assert_eq!(cached.len(), 2);
2570        assert_eq!(cached.get(&Ustr::from("")), Some(&vec![btc, eth]));
2571        assert_eq!(cached.get(&Ustr::from("xyz")), Some(&vec![tsla]));
2572    }
2573
2574    #[tokio::test]
2575    async fn test_drop_clone_does_not_stop_handler() {
2576        let client = HyperliquidWebSocketClient::new(
2577            Some("wss://test".to_string()),
2578            HyperliquidEnvironment::Testnet,
2579            None,
2580            TransportBackend::default(),
2581            None,
2582        );
2583        client
2584            .task_handle
2585            .insert(get_runtime().spawn(std::future::pending()));
2586        let clone = client.clone();
2587
2588        drop(clone);
2589
2590        assert!(!client.signal.load(Ordering::Acquire));
2591        assert!(!client.task_handle.is_empty());
2592    }
2593
2594    /// Generates a unique topic key for a subscription request.
2595    fn subscription_topic(sub: &SubscriptionRequest) -> String {
2596        subscription_to_key(sub)
2597    }
2598
2599    #[rstest]
2600    #[case(SubscriptionRequest::Trades { coin: "BTC".into() }, "trades:BTC")]
2601    #[case(SubscriptionRequest::Bbo { coin: "BTC".into() }, "bbo:BTC")]
2602    #[case(SubscriptionRequest::OrderUpdates { user: "0x123".to_string() }, "orderUpdates:0x123")]
2603    #[case(SubscriptionRequest::UserEvents { user: "0xabc".to_string() }, "userEvents:0xabc")]
2604    fn test_subscription_topic_generation(
2605        #[case] subscription: SubscriptionRequest,
2606        #[case] expected_topic: &str,
2607    ) {
2608        assert_eq!(subscription_topic(&subscription), expected_topic);
2609    }
2610
2611    #[rstest]
2612    fn test_subscription_topics_unique() {
2613        let sub1 = SubscriptionRequest::Trades { coin: "BTC".into() };
2614        let sub2 = SubscriptionRequest::Bbo { coin: "BTC".into() };
2615
2616        let topic1 = subscription_topic(&sub1);
2617        let topic2 = subscription_topic(&sub2);
2618
2619        assert_ne!(topic1, topic2);
2620    }
2621
2622    #[rstest]
2623    #[case(SubscriptionRequest::Trades { coin: "BTC".into() })]
2624    #[case(SubscriptionRequest::Bbo { coin: "ETH".into() })]
2625    #[case(SubscriptionRequest::Candle { coin: "SOL".into(), interval: HyperliquidBarInterval::OneHour })]
2626    #[case(SubscriptionRequest::OrderUpdates { user: "0x123".to_string() })]
2627    #[case(SubscriptionRequest::Trades { coin: "vntls:vCURSOR".into() })]
2628    #[case(SubscriptionRequest::L2Book { coin: "vntls:vCURSOR".into(), mantissa: None, n_sig_figs: None })]
2629    #[case(SubscriptionRequest::Candle { coin: "vntls:vCURSOR".into(), interval: HyperliquidBarInterval::OneHour })]
2630    fn test_subscription_reconstruction(#[case] subscription: SubscriptionRequest) {
2631        let topic = subscription_topic(&subscription);
2632        let reconstructed = subscription_from_topic(&topic).expect("Failed to reconstruct");
2633        assert_eq!(subscription_topic(&reconstructed), topic);
2634    }
2635
2636    #[rstest]
2637    fn test_subscription_topic_candle() {
2638        let sub = SubscriptionRequest::Candle {
2639            coin: "BTC".into(),
2640            interval: HyperliquidBarInterval::OneHour,
2641        };
2642
2643        let topic = subscription_topic(&sub);
2644        assert_eq!(topic, "candle:BTC:1h");
2645    }
2646
2647    #[rstest]
2648    fn with_state_sink_survives_clone() {
2649        let client = HyperliquidWebSocketClient::new(
2650            None,
2651            HyperliquidEnvironment::Testnet,
2652            None,
2653            TransportBackend::default(),
2654            None,
2655        )
2656        .with_state_sink(SocketStateSink::new(|_| {}));
2657
2658        let cloned = client.clone();
2659        assert!(client.socket_sink.is_some());
2660        assert!(cloned.socket_sink.is_some());
2661    }
2662
2663    #[rstest]
2664    fn clone_can_own_socket_registration() {
2665        let registry = SocketReconnectRegistry::default();
2666        let endpoint = Ustr::from("hyperliquid-data-streams");
2667        let client = HyperliquidWebSocketClient::new(
2668            None,
2669            HyperliquidEnvironment::Testnet,
2670            None,
2671            TransportBackend::default(),
2672            None,
2673        )
2674        .with_socket_control(SocketControl::with_registry(
2675            ClientId::from("HYPERLIQUID"),
2676            None,
2677            endpoint,
2678            &registry,
2679        ));
2680        let cloned = client.clone();
2681        let _sink = cloned.socket_control.as_ref().unwrap().sink();
2682        cloned
2683            .socket_control
2684            .as_ref()
2685            .unwrap()
2686            .register(|| ReconnectRequestOutcome::Accepted);
2687
2688        assert!(cloned.socket_control.is_some());
2689        assert!(cloned.socket_sink.is_none());
2690        assert!(
2691            registry
2692                .handle(ClientId::from("HYPERLIQUID"), endpoint)
2693                .is_some()
2694        );
2695
2696        client.socket_control.as_ref().unwrap().deregister();
2697        assert!(
2698            registry
2699                .handle(ClientId::from("HYPERLIQUID"), endpoint)
2700                .is_some()
2701        );
2702
2703        let handle = registry
2704            .handle(ClientId::from("HYPERLIQUID"), endpoint)
2705            .unwrap();
2706        assert_eq!(
2707            handle.request_reconnect(),
2708            SocketReconnectRequestOutcome::Accepted
2709        );
2710        drop(cloned);
2711        assert!(
2712            registry
2713                .handle(ClientId::from("HYPERLIQUID"), endpoint)
2714                .is_none()
2715        );
2716    }
2717
2718    #[rstest]
2719    fn set_post_timeout_updates_client_and_clone() {
2720        let mut client = HyperliquidWebSocketClient::new(
2721            None,
2722            HyperliquidEnvironment::Testnet,
2723            None,
2724            TransportBackend::default(),
2725            None,
2726        );
2727        let timeout = std::time::Duration::from_secs(7);
2728
2729        client.set_post_timeout(timeout);
2730
2731        assert_eq!(client.post_timeout, timeout);
2732        assert_eq!(client.clone().post_timeout, timeout);
2733    }
2734
2735    #[rstest]
2736    #[tokio::test]
2737    async fn post_action_command_without_credentials_is_not_sent() {
2738        let client = HyperliquidWebSocketClient::new(
2739            None,
2740            HyperliquidEnvironment::Testnet,
2741            None,
2742            TransportBackend::default(),
2743            None,
2744        );
2745        let signer = HyperliquidHttpClient::new(HyperliquidEnvironment::Testnet, 10, None).unwrap();
2746        let action = HyperliquidExchangeAction::Cancel {
2747            cancels: Vec::new(),
2748            fast: None,
2749        };
2750        let result = client.post_action_command(&signer, &action).await;
2751        let PostRequestError::BeforeDispatch(error) = result.unwrap_err() else {
2752            panic!("Expected failure before dispatch");
2753        };
2754        assert_eq!(
2755            error.to_string(),
2756            "auth error: credentials required for exchange operations"
2757        );
2758    }
2759
2760    #[tokio::test]
2761    async fn failed_connect_releases_connection_slot() {
2762        let mut client = HyperliquidWebSocketClient::new(
2763            Some("invalid-websocket-url".to_string()),
2764            HyperliquidEnvironment::Testnet,
2765            None,
2766            TransportBackend::default(),
2767            None,
2768        );
2769        let available_before = client.rate_limits.connection_slots.available_permits();
2770
2771        client
2772            .connect()
2773            .await
2774            .expect_err("invalid URL should fail the connection attempt");
2775
2776        assert!(client.connection_permit.lock().is_none());
2777        assert_eq!(
2778            client.rate_limits.connection_slots.available_permits(),
2779            available_before
2780        );
2781    }
2782
2783    #[rstest]
2784    #[case::before_dispatch(false)]
2785    #[case::after_dispatch(true)]
2786    #[tokio::test(start_paused = true)]
2787    async fn post_request_timeout_preserves_dispatch_evidence(#[case] dispatched: bool) {
2788        let client = HyperliquidWebSocketClient::new(
2789            None,
2790            HyperliquidEnvironment::Testnet,
2791            None,
2792            TransportBackend::default(),
2793            None,
2794        );
2795        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2796        *client.cmd_tx.write().await = tx;
2797        let timeout = if dispatched {
2798            Duration::from_millis(100)
2799        } else {
2800            Duration::ZERO
2801        };
2802        let started = tokio::time::Instant::now();
2803        let failure = client
2804            .send_post_request_result(
2805                PostRequest::Info {
2806                    payload: serde_json::json!({"type": "meta"}),
2807                },
2808                timeout,
2809            )
2810            .await
2811            .unwrap_err();
2812
2813        assert_eq!(tokio::time::Instant::now() - started, timeout);
2814
2815        if dispatched {
2816            assert!(matches!(
2817                failure,
2818                PostRequestError::AfterDispatch(HyperliquidError::Timeout)
2819            ));
2820            let HandlerCommand::Post {
2821                id,
2822                request,
2823                deadline,
2824                cancellation_token,
2825            } = rx.try_recv().unwrap()
2826            else {
2827                panic!("Expected post command");
2828            };
2829            assert_eq!(id, 1);
2830            assert_eq!(
2831                serde_json::to_value(request).unwrap(),
2832                serde_json::json!({"type": "info", "payload": {"type": "meta"}})
2833            );
2834            assert_eq!(deadline, started + timeout);
2835            assert!(cancellation_token.is_cancelled());
2836        } else {
2837            assert!(matches!(
2838                failure,
2839                PostRequestError::BeforeDispatch(HyperliquidError::Timeout)
2840            ));
2841        }
2842        assert!(matches!(
2843            rx.try_recv(),
2844            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
2845        ));
2846    }
2847
2848    #[rstest]
2849    #[tokio::test(flavor = "multi_thread")]
2850    async fn send_post_request_times_out_while_waiting_for_inflight_slot() {
2851        let client = HyperliquidWebSocketClient::new(
2852            None,
2853            HyperliquidEnvironment::Testnet,
2854            None,
2855            TransportBackend::default(),
2856            None,
2857        );
2858        let mut receivers = Vec::with_capacity(HYPERLIQUID_WS_POST_INFLIGHT_MAX);
2859        for offset in 0..HYPERLIQUID_WS_POST_INFLIGHT_MAX {
2860            receivers.push(
2861                client
2862                    .post_router
2863                    .register(10_000 + offset as u64)
2864                    .await
2865                    .unwrap(),
2866            );
2867        }
2868
2869        let err = client
2870            .send_post_request(
2871                PostRequest::Info {
2872                    payload: serde_json::json!({"type": "clearinghouseState", "user": "0x0"}),
2873                },
2874                std::time::Duration::from_millis(25),
2875            )
2876            .await
2877            .expect_err("request should timeout before acquiring an inflight slot");
2878
2879        assert!(matches!(err, HyperliquidError::Timeout));
2880        assert_eq!(receivers.len(), HYPERLIQUID_WS_POST_INFLIGHT_MAX);
2881    }
2882
2883    #[rstest]
2884    #[tokio::test(flavor = "multi_thread")]
2885    async fn send_post_request_shares_inflight_limit_across_clients() {
2886        let url = Some("wss://shared-post-limit.test/ws".to_string());
2887        let first = HyperliquidWebSocketClient::new(
2888            url.clone(),
2889            HyperliquidEnvironment::Testnet,
2890            None,
2891            TransportBackend::default(),
2892            None,
2893        );
2894        let second = HyperliquidWebSocketClient::new(
2895            url,
2896            HyperliquidEnvironment::Testnet,
2897            None,
2898            TransportBackend::default(),
2899            None,
2900        );
2901        let mut receivers = Vec::with_capacity(HYPERLIQUID_WS_POST_INFLIGHT_MAX);
2902
2903        for offset in 0..HYPERLIQUID_WS_POST_INFLIGHT_MAX / 2 {
2904            receivers.push(first.post_router.register(offset as u64).await.unwrap());
2905            receivers.push(
2906                second
2907                    .post_router
2908                    .register(10_000 + offset as u64)
2909                    .await
2910                    .unwrap(),
2911            );
2912        }
2913
2914        let error = second
2915            .send_post_request(
2916                PostRequest::Info {
2917                    payload: serde_json::json!({"type": "meta"}),
2918                },
2919                Duration::from_millis(25),
2920            )
2921            .await
2922            .expect_err("shared in-flight limit should block the next post");
2923
2924        assert!(matches!(error, HyperliquidError::Timeout));
2925        assert_eq!(receivers.len(), HYPERLIQUID_WS_POST_INFLIGHT_MAX);
2926    }
2927
2928    #[rstest]
2929    fn subscription_limit_is_rejected_before_queueing_across_clients() {
2930        let url = Some("wss://shared-subscription-limit.test/ws".to_string());
2931        let first = HyperliquidWebSocketClient::new(
2932            url.clone(),
2933            HyperliquidEnvironment::Testnet,
2934            None,
2935            TransportBackend::default(),
2936            None,
2937        );
2938        let second = HyperliquidWebSocketClient::new(
2939            url,
2940            HyperliquidEnvironment::Testnet,
2941            None,
2942            TransportBackend::default(),
2943            None,
2944        );
2945        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
2946
2947        for index in 0..HYPERLIQUID_WS_SUBSCRIPTIONS_MAX {
2948            let subscription = SubscriptionRequest::Trades {
2949                coin: Ustr::from(&format!("COIN-{index}")),
2950            };
2951            let client = if index % 2 == 0 { &first } else { &second };
2952            client.send_subscription(&cmd_tx, subscription).unwrap();
2953        }
2954
2955        let error = first
2956            .send_subscription(
2957                &cmd_tx,
2958                SubscriptionRequest::Trades {
2959                    coin: Ustr::from("OVER-LIMIT"),
2960                },
2961            )
2962            .expect_err("shared subscription limit should reject the next subscription");
2963
2964        assert!(error.to_string().contains("at most 1000"));
2965        assert_eq!(cmd_rx.len(), HYPERLIQUID_WS_SUBSCRIPTIONS_MAX);
2966    }
2967
2968    #[rstest]
2969    fn stream_resubscribe_queues_one_atomic_command() {
2970        let client = HyperliquidWebSocketClient::new(
2971            Some("wss://atomic-resubscribe.test/ws".to_string()),
2972            HyperliquidEnvironment::Testnet,
2973            None,
2974            TransportBackend::default(),
2975            None,
2976        );
2977        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
2978        let subscription = SubscriptionRequest::Bbo {
2979            coin: Ustr::from("BTC"),
2980        };
2981
2982        client
2983            .send_stream_resubscribe(&cmd_tx, subscription)
2984            .unwrap();
2985
2986        assert!(matches!(
2987            cmd_rx.try_recv(),
2988            Ok(HandlerCommand::Resubscribe { subscription })
2989                if subscription_to_key(&subscription) == "bbo:BTC"
2990        ));
2991        assert!(matches!(
2992            cmd_rx.try_recv(),
2993            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
2994        ));
2995    }
2996
2997    #[rstest]
2998    #[tokio::test(start_paused = true)]
2999    async fn send_post_request_uses_deadline_while_waiting_for_command_channel() {
3000        let client = HyperliquidWebSocketClient::new(
3001            None,
3002            HyperliquidEnvironment::Testnet,
3003            None,
3004            TransportBackend::default(),
3005            None,
3006        );
3007        let _cmd_tx = client.cmd_tx.write().await;
3008        let timeout = Duration::from_millis(100);
3009        let started = tokio::time::Instant::now();
3010
3011        let error = client
3012            .send_post_request(
3013                PostRequest::Info {
3014                    payload: serde_json::json!({"type": "clearinghouseState", "user": "0x0"}),
3015                },
3016                timeout,
3017            )
3018            .await
3019            .unwrap_err();
3020
3021        assert!(matches!(error, HyperliquidError::Timeout));
3022        assert_eq!(tokio::time::Instant::now() - started, timeout);
3023        client
3024            .post_router
3025            .register(1)
3026            .await
3027            .expect("post ID should be reusable when timeout returns");
3028    }
3029
3030    #[rstest]
3031    #[tokio::test(start_paused = true)]
3032    async fn post_response_ready_before_deadline_wins_deadline_race() {
3033        let client = HyperliquidWebSocketClient::new(
3034            None,
3035            HyperliquidEnvironment::Testnet,
3036            None,
3037            TransportBackend::default(),
3038            None,
3039        );
3040        let id = 1;
3041        let cancellation_token = CancellationToken::new();
3042        let rx = client
3043            .post_router
3044            .register_with_cancellation(id, &cancellation_token)
3045            .await
3046            .unwrap();
3047        let payload = serde_json::json!({"type": "meta", "data": {"universe": []}});
3048        client
3049            .post_router
3050            .complete(PostResponse {
3051                id,
3052                response: PostResponsePayload::Info {
3053                    payload: payload.clone(),
3054                },
3055            })
3056            .await;
3057
3058        let response = client
3059            .await_post_response(id, rx, tokio::time::Instant::now(), &cancellation_token)
3060            .await
3061            .expect("ready response should win");
3062
3063        assert_eq!(response.id, id);
3064        let PostResponsePayload::Info {
3065            payload: response_payload,
3066        } = response.response
3067        else {
3068            panic!("expected info response");
3069        };
3070        assert_eq!(response_payload, payload);
3071    }
3072
3073    #[rstest]
3074    #[tokio::test]
3075    async fn dropping_post_request_cancels_work_and_releases_registration() {
3076        let client = HyperliquidWebSocketClient::new(
3077            None,
3078            HyperliquidEnvironment::Testnet,
3079            None,
3080            TransportBackend::default(),
3081            None,
3082        );
3083        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
3084        *client.cmd_tx.write().await = cmd_tx;
3085        let request_client = client.clone();
3086        let task = tokio::spawn(async move {
3087            request_client
3088                .send_post_request(
3089                    PostRequest::Info {
3090                        payload: serde_json::json!({"type": "userRateLimit", "user": "0x123"}),
3091                    },
3092                    Duration::from_secs(60),
3093                )
3094                .await
3095        });
3096        let command = cmd_rx.recv().await.expect("post command should be queued");
3097        let HandlerCommand::Post {
3098            id,
3099            cancellation_token,
3100            ..
3101        } = command
3102        else {
3103            panic!("expected post command");
3104        };
3105
3106        task.abort();
3107        assert!(task.await.unwrap_err().is_cancelled());
3108        assert!(cancellation_token.is_cancelled());
3109
3110        let reused = tokio::time::timeout(Duration::from_secs(1), async {
3111            loop {
3112                match client.post_router.register(id).await {
3113                    Ok(rx) => break Ok(rx),
3114                    Err(e) if e.to_string().contains("already registered") => {
3115                        tokio::task::yield_now().await;
3116                    }
3117                    Err(e) => break Err(e),
3118                }
3119            }
3120        })
3121        .await
3122        .expect("post ID should be reusable after cancellation")
3123        .expect("post ID reuse should succeed");
3124        client
3125            .post_router
3126            .cancel_registration(id, &cancellation_token)
3127            .await;
3128        client
3129            .post_router
3130            .register(id)
3131            .await
3132            .expect_err("stale cancellation must not remove the reused registration");
3133
3134        let mut receivers = vec![reused];
3135        tokio::time::timeout(Duration::from_secs(1), async {
3136            for offset in 1..HYPERLIQUID_WS_POST_INFLIGHT_MAX {
3137                receivers.push(
3138                    client
3139                        .post_router
3140                        .register(10_000 + offset as u64)
3141                        .await
3142                        .unwrap(),
3143                );
3144            }
3145        })
3146        .await
3147        .expect("cancellation should release the inflight permit");
3148
3149        assert_eq!(receivers.len(), HYPERLIQUID_WS_POST_INFLIGHT_MAX);
3150    }
3151
3152    #[rstest]
3153    #[tokio::test(start_paused = true)]
3154    async fn post_timeout_after_queueing_preserves_unknown_outcome_and_releases_registration() {
3155        let client = HyperliquidWebSocketClient::new(
3156            None,
3157            HyperliquidEnvironment::Testnet,
3158            None,
3159            TransportBackend::default(),
3160            None,
3161        );
3162        let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel();
3163        *client.cmd_tx.write().await = cmd_tx;
3164        let request_client = client.clone();
3165        let task = tokio::spawn(async move {
3166            request_client
3167                .send_post_request(
3168                    PostRequest::Info {
3169                        payload: serde_json::json!({"type": "userRateLimit", "user": "0x123"}),
3170                    },
3171                    Duration::from_millis(100),
3172                )
3173                .await
3174        });
3175        let command = cmd_rx.recv().await.expect("post command should be queued");
3176        let HandlerCommand::Post {
3177            id,
3178            cancellation_token,
3179            ..
3180        } = command
3181        else {
3182            panic!("expected post command");
3183        };
3184
3185        let error = task.await.unwrap().unwrap_err();
3186
3187        assert!(matches!(&error, HyperliquidError::Timeout));
3188        assert!(error.is_transport_error());
3189        assert!(cancellation_token.is_cancelled());
3190        client
3191            .post_router
3192            .register(id)
3193            .await
3194            .expect("post ID should be reusable when timeout returns");
3195    }
3196
3197    #[rstest]
3198    fn cancel_errors_for_requests_accepts_empty_as_success() {
3199        let errors = cancel_errors_for_requests(Vec::new(), 2).unwrap();
3200
3201        assert_eq!(errors, vec![None, None]);
3202    }
3203
3204    #[rstest]
3205    fn cancel_errors_for_requests_rejects_status_count_mismatch() {
3206        let err = cancel_errors_for_requests(vec![None], 2).expect_err("mismatch should fail");
3207
3208        assert!(
3209            err.to_string()
3210                .contains("returned 1 statuses for 2 cancels")
3211        );
3212    }
3213
3214    #[rstest]
3215    fn test_post_payload_error_maps_rate_limit() {
3216        let err = map_post_payload_error("429 Too Many Requests".to_string(), 3);
3217
3218        assert!(matches!(
3219            err,
3220            HyperliquidError::RateLimit {
3221                scope: "exchange",
3222                weight: 3,
3223                retry_after_ms: None,
3224            }
3225        ));
3226    }
3227
3228    #[rstest]
3229    #[case("401 Unauthorized")]
3230    #[case("HTTP 403: forbidden")]
3231    #[case("invalid signature")]
3232    #[case("authentication failed")]
3233    fn test_post_payload_error_maps_auth(#[case] payload: &str) {
3234        let err = map_post_payload_error(payload.to_string(), 1);
3235
3236        assert!(matches!(err, HyperliquidError::Auth(_)));
3237    }
3238
3239    #[rstest]
3240    #[case("400 Bad Request")]
3241    #[case("HTTP 400: malformed payload")]
3242    #[case("bad request: missing action")]
3243    fn test_post_payload_error_maps_bad_request(#[case] payload: &str) {
3244        let err = map_post_payload_error(payload.to_string(), 1);
3245
3246        assert!(matches!(err, HyperliquidError::BadRequest(_)));
3247    }
3248
3249    #[rstest]
3250    #[case("500 Internal Server Error")]
3251    #[case("HTTP 503: service unavailable")]
3252    fn test_post_payload_error_maps_exchange_status(#[case] payload: &str) {
3253        let err = map_post_payload_error(payload.to_string(), 1);
3254
3255        assert!(matches!(err, HyperliquidError::Exchange(_)));
3256    }
3257
3258    #[rstest]
3259    #[case("order 429001 rejected")]
3260    #[case("asset 5001 is not tradable")]
3261    #[case("authoritative nonce window exceeded")]
3262    fn test_post_payload_error_does_not_match_embedded_codes_or_words(#[case] payload: &str) {
3263        let err = map_post_payload_error(payload.to_string(), 1);
3264
3265        assert!(matches!(err, HyperliquidError::Exchange(_)));
3266    }
3267}