Skip to main content

rustrade_execution/client/hyperliquid/
spot.rs

1//! Hyperliquid spot trading ExecutionClient implementation.
2//!
3//! Uses the same `hyperliquid_rust_sdk` clients as the perpetuals client, but with
4//! spot-specific endpoints and data handling.
5//!
6//! # Differences from Perpetuals
7//!
8//! - **Coin naming**: Spot pairs are named `@{index}` (`"@107"` is HYPE/USDC), except
9//!   `"PURR/USDC"`; perps by their asset (`"BTC"`). See [Spot coins](#spot-coins).
10//! - **Asset indices**: Spot uses 10000+ (vs 0-9999 for perps)
11//! - **Balances**: Uses `user_token_balances()` instead of `user_state()` margin summary
12//! - **No positions**: a spot order opens no position. Under portfolio margin it can still
13//!   borrow, implicitly, when the account falls short; there is no order flag for it, so this
14//!   client refuses every `RequestOpen::margin_effect`
15//!   ([`OrderError::UnsupportedMarginEffect`])
16//! - **$10 minimum**: Spot orders require minimum $10 notional value
17//!
18//! # Unified Account Model
19//!
20//! Hyperliquid uses a unified account model:
21//! - Spot balances count as perpetual collateral
22//! - Separate wallets within the unified account (explicit transfer required)
23//! - Perpetual liquidation cannot sweep spot holdings
24//!
25//! # WebSocket Events
26//!
27//! `UserFills` and `OrderUpdates` subscriptions deliver **both** spot and perp events,
28//! intermingled in the same stream. Events are filtered by the shape of the coin name, with
29//! [`CoinKind::of`]: this client keeps only spot coins (`"@107"`, `"PURR/USDC"`).
30//!
31//! If a user has both perp and spot clients for the same wallet, events will be
32//! duplicated. Consumers should use one client type per account, or deduplicate externally.
33//!
34//! # Spot coins
35//!
36//! Hyperliquid names every spot pair but PURR/USDC by its index (`"@107"`), which does not name
37//! its assets. The client reads Hyperliquid's `spotMeta` when it is created, and fails to be
38//! created if it cannot, and resolves each coin through it to the instrument `BASE-QUOTE-SPOT`,
39//! named from the pair's tokens (`"@107"` is `HYPE-USDC-SPOT`, `"@207"` is `HYPE-USDT0-SPOT`).
40//!
41//! A spot coin missing from `spotMeta`, such as a pair listed after the client was created, makes
42//! it read `spotMeta` again, at most once every ten seconds, each read abandoned after five. A coin still missing after that is:
43//! - an error from [`ExecutionClient::account_snapshot`], [`ExecutionClient::fetch_open_orders`]
44//!   and [`ExecutionClient::fetch_trades`], whose lists would otherwise be short with nothing to
45//!   say so. This holds whichever instruments were asked for: the coin's instrument is unknown,
46//!   so it cannot be told apart from them;
47//! - left out of the account stream, logged once per stream and coin, with `error!` for fills
48//!   and `warn!` for order updates. [`ExecutionClient::fetch_trades`] recovers a fill left out
49//!   once the pair resolves.
50//!
51//! Since every report names a pair from its tokens as Hyperliquid spells them, an order's
52//! instrument must spell them the same way: `kPEPE-USDC-SPOT`, not `KPEPE-USDC-SPOT`.
53//! [`ExecutionClient::open_order`] refuses an order under another spelling unsent, with
54//! [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) naming the one to
55//! use. An order is then reported under the name it was placed under, and the reads that take
56//! `instruments`, which match names exactly, find it. The perpetuals client matches names
57//! exactly too.
58//!
59//! Neither the reads nor `cancel_order` check the spelling. An `instruments` filter naming a pair
60//! in another spelling, or no listed pair, matches nothing, so the read returns nothing for it
61//! without an error. [`ExecutionClient::cancel_order`] sends the coin as the instrument spells it, so a
62//! cancel under another spelling fails in the SDK.
63//!
64//! Orders are placed through the SDK's `ExchangeClient`, which reads `spotMeta` once, when it is
65//! created, and is never refreshed. So a pair listed after the client was created can be reported
66//! but not traded until the client is created again.
67//!
68//! # Conditional Orders (Stop, TakeProfit)
69//!
70//! See [`super`] module documentation for conditional order support details.
71//! The same constraints apply to spot:
72//! - Supported: `Stop`, `StopLimit`, `TakeProfit`, `TakeProfitLimit`
73//! - Unsupported: `TrailingStop`, `TrailingStopLimit`, `Market`
74//!
75//! # Client order ids
76//!
77//! As for perpetuals, every order must be placed under a client id in
78//! [`ClientOrderId::uuid()`](crate::order::id::ClientOrderId::uuid) form. See the
79//! [`super`] module documentation for why.
80
81use super::common::{
82    CLOID_REQUIRED, CancelOnDropStream, InstrumentFilter, OpenOrder, OpenOrderListing, UserFill,
83    cancel_outcome, cid_to_cloid, cloid_to_cid, instrument_to_spot_coin, map_tif,
84    millis_to_datetime, open_order_to_order, open_orders, parse_decimal, parse_side, span_millis,
85    spot_balances, spot_base_quote, spot_pair_to_instrument, user_fills_by_time,
86};
87use super::config::HyperliquidConfig;
88use super::error::{map_order_error, map_sdk_error, order_outcome_unanswered, order_rejection};
89use super::order_recovery::{
90    ReconnectWatch, fetch_order_record, listed_cids, lookup_of, remember_open, remember_snapshot,
91    send_fills, send_observed, spawn_order_checks, status_from_record, unreadable_record,
92};
93use super::precision::{OrderPrecision, WireOrderError, wire_order};
94use super::spot_coins::{SpotCoins, spot_pair};
95use crate::client::dedup::new_dedup_cache;
96use crate::client::order_recovery::{
97    KnownLiveOrders, OrderLookup, SharedKnownLiveOrders, fetch_ended_by_key,
98};
99use crate::{
100    AccountEvent, AccountEventKind, AccountSnapshot, UnindexedAccountEvent,
101    UnindexedAccountSnapshot,
102    balance::AssetBalance,
103    client::{ExecutionClient, OrderStatusClient, VenueOrderStatus},
104    emit_stream_terminated,
105    error::{
106        ConnectivityError, OrderError, StreamTerminationReason, UnindexedClientError,
107        UnindexedOrderError,
108    },
109    order::{
110        Order, OrderKey, OrderKind, TimeInForce, UnindexedInactiveOrder, UnindexedOrderKey,
111        id::{ClientOrderId, OrderId, StrategyId, VenueOrderId},
112        request::{OrderRequestCancel, OrderRequestOpen, UnindexedOrderResponseCancel},
113        state::{Filled, Open, OrderState, UnindexedOrderState},
114    },
115    trade::{AssetFees, Trade, TradeId, TradeOrigin, TradesRead},
116};
117use chrono::{DateTime, Utc};
118use ethers::signers::Signer;
119use fnv::FnvHashSet;
120use futures::{StreamExt, stream::BoxStream};
121use hyperliquid_rust_sdk::{ExchangeClient, InfoClient, Message, Subscription};
122use rust_decimal::Decimal;
123use rustrade_instrument::{
124    Side,
125    asset::name::AssetNameExchange,
126    exchange::ExchangeId,
127    hyperliquid::{CoinKind, SpotPair, SpotPairs},
128    instrument::{kind::InstrumentKindDiscriminant, name::InstrumentNameExchange},
129};
130use smol_str::format_smolstr;
131use std::{
132    collections::HashSet,
133    sync::{
134        Arc,
135        atomic::{AtomicBool, Ordering},
136    },
137};
138use tokio::sync::{Notify, mpsc};
139use tokio_util::sync::CancellationToken;
140use tracing::{debug, error, info, warn};
141
142/// Hyperliquid spot trading execution client.
143///
144/// Wraps the official `hyperliquid_rust_sdk` to implement the `ExecutionClient` trait
145/// for spot trading on Hyperliquid DEX.
146#[derive(Debug, Clone)]
147pub struct HyperliquidSpotClient {
148    config: HyperliquidConfig,
149    info_client: Arc<InfoClient>,
150    exchange_client: Arc<ExchangeClient>,
151    spot_coins: SpotCoins,
152    /// The orders seen live and not yet seen end, which a reconnect asks about. Shared by every
153    /// clone and every account stream, since an order placed through one ends on any of them.
154    known_live: SharedKnownLiveOrders,
155}
156
157impl HyperliquidSpotClient {
158    /// Create a new spot client asynchronously.
159    ///
160    /// Use this when calling from an async context (e.g., tokio tests).
161    /// For sync contexts, use `ExecutionClient::new()`.
162    ///
163    /// # Errors
164    ///
165    /// [`ConnectivityError::Socket`] when the SDK clients cannot be created, or Hyperliquid's
166    /// `spotMeta` cannot be read (see [Spot coins](self#spot-coins)).
167    pub async fn connect(config: HyperliquidConfig) -> Result<Self, ConnectivityError> {
168        let base_url = config.base_url();
169
170        let info_client = InfoClient::new(None, Some(base_url))
171            .await
172            .map_err(|e| ConnectivityError::Socket(format!("InfoClient: {e}")))?;
173
174        let wallet = config.wallet.clone();
175        let exchange_client = ExchangeClient::new(None, wallet, Some(base_url), None, None)
176            .await
177            .map_err(|e| ConnectivityError::Socket(format!("ExchangeClient: {e}")))?;
178
179        let info_client = Arc::new(info_client);
180        let spot_coins = SpotCoins::fetch(Arc::clone(&info_client))
181            .await
182            .map_err(|e| ConnectivityError::Socket(format!("spotMeta: {e}")))?;
183
184        info!(
185            network = ?config.network,
186            wallet = %config.wallet_address_hex(),
187            "Created HyperliquidSpotClient"
188        );
189
190        Ok(Self {
191            config,
192            info_client,
193            exchange_client: Arc::new(exchange_client),
194            spot_coins,
195            known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidSpot),
196        })
197    }
198
199    /// Returns the wallet address as a hex string (for logging/debugging).
200    pub fn wallet_address(&self) -> String {
201        self.config.wallet_address_hex()
202    }
203
204    /// The precision rules for orders on the spot pair `instrument` (`BASE-QUOTE-SPOT`), from
205    /// its base token's `szDecimals`.
206    ///
207    /// [`open_order`](ExecutionClient::open_order) refuses an order that breaks them with
208    /// [`OrderError::InvalidPrecision`] and sends nothing. Round with these rules first. See
209    /// [`OrderPrecision`].
210    ///
211    /// `None` when `instrument` is not of that form, or Hyperliquid lists no such pair. A pair
212    /// missing from the pairs this client holds is looked for in `spotMeta` again first, at most
213    /// once every 10 seconds, so a pair listed since the client connected is found.
214    ///
215    /// `None` too when `instrument` spells the pair's tokens differently from Hyperliquid, even
216    /// only in ASCII case (`KPEPE-USDC-SPOT` for `kPEPE/USDC`). Every order report names the
217    /// pair as Hyperliquid spells it, so [`open_order`](ExecutionClient::open_order) refuses an
218    /// order under any other spelling, naming the one to use.
219    pub async fn order_precision(
220        &self,
221        instrument: &InstrumentNameExchange,
222    ) -> Option<OrderPrecision> {
223        let (base, quote) = spot_base_quote(instrument)?;
224        let pair = self.traded_pair(base, quote).await.ok()?;
225        Some(OrderPrecision::spot(pair.base_sz_decimals()))
226    }
227
228    /// The pair of `base` quoted in `quote`, spelled exactly as Hyperliquid spells its tokens,
229    /// looked for as [`order_precision`](Self::order_precision) describes.
230    async fn traded_pair(&self, base: &str, quote: &str) -> Result<SpotPair, UntradedPair> {
231        let pair = self
232            .spot_coins
233            .find(base, quote)
234            .await
235            .ok_or(UntradedPair::Unlisted)?;
236        if pair.base() == base && pair.quote() == quote {
237            Ok(pair)
238        } else {
239            Err(UntradedPair::Misspelled(pair))
240        }
241    }
242
243    /// Returns the wallet address as ethers H160.
244    fn wallet_h160(&self) -> ethers::types::H160 {
245        self.config.wallet.address()
246    }
247}
248
249/// Why a spot instrument names no pair the client places orders on.
250#[derive(Debug)]
251enum UntradedPair {
252    /// Hyperliquid lists no such pair, even after `spotMeta` is read again.
253    Unlisted,
254    /// Hyperliquid lists the pair, but spells its tokens differently, if only in ASCII case.
255    /// Every report names the pair as Hyperliquid spells it, so an order placed under this
256    /// spelling would be reported under another name, and left out of reads filtered by this one.
257    Misspelled(SpotPair),
258}
259
260impl ExecutionClient for HyperliquidSpotClient {
261    const EXCHANGE: ExchangeId = ExchangeId::HyperliquidSpot;
262
263    // Spot only — the perpetual counterpart is `HyperliquidClient`.
264    const SUPPORTED_KINDS: &'static [InstrumentKindDiscriminant] =
265        &[InstrumentKindDiscriminant::Spot];
266
267    type Config = HyperliquidConfig;
268    type AccountStream = BoxStream<'static, UnindexedAccountEvent>;
269
270    /// Creates a new Hyperliquid spot client synchronously.
271    ///
272    /// # Panics
273    ///
274    /// - If no Tokio runtime is available on the current thread
275    /// - If called from within an async context (e.g., inside `async fn`, `spawn`, or `block_on`)
276    /// - If SDK initialization fails (network error, invalid credentials), or Hyperliquid's
277    ///   `spotMeta` cannot be read
278    ///
279    /// # Recommended Usage
280    ///
281    /// Use [`HyperliquidSpotClient::connect`] instead — it's async-safe and returns `Result`.
282    /// This method exists only for trait compliance; prefer `connect()` in all new code.
283    fn new(config: Self::Config) -> Self {
284        let base_url = config.base_url();
285
286        let handle = tokio::runtime::Handle::current();
287
288        let info_client = handle.block_on(async {
289            InfoClient::new(None, Some(base_url))
290                .await
291                .unwrap_or_else(|e| panic!("Failed to create Hyperliquid InfoClient: {e}"))
292        });
293
294        let wallet = config.wallet.clone();
295        let exchange_client = handle.block_on(async {
296            ExchangeClient::new(None, wallet, Some(base_url), None, None)
297                .await
298                .unwrap_or_else(|e| panic!("Failed to create Hyperliquid ExchangeClient: {e}"))
299        });
300
301        let info_client = Arc::new(info_client);
302        let spot_coins = handle.block_on(async {
303            SpotCoins::fetch(Arc::clone(&info_client))
304                .await
305                .unwrap_or_else(|e| panic!("Failed to read Hyperliquid spotMeta: {e}"))
306        });
307
308        info!(
309            network = ?config.network,
310            wallet = %config.wallet_address_hex(),
311            "Created HyperliquidSpotClient"
312        );
313
314        Self {
315            config,
316            info_client,
317            exchange_client: Arc::new(exchange_client),
318            spot_coins,
319            known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidSpot),
320        }
321    }
322
323    async fn account_snapshot(
324        &self,
325        _assets: &[AssetNameExchange],
326        instruments: &[InstrumentNameExchange],
327    ) -> Result<UnindexedAccountSnapshot, UnindexedClientError> {
328        let address = self.wallet_h160();
329
330        // Fetch spot token balances and open orders concurrently
331        let (token_balances, open_orders) = tokio::try_join!(
332            async {
333                self.info_client
334                    .user_token_balances(address)
335                    .await
336                    .map_err(map_sdk_error)
337            },
338            open_orders(&self.info_client, address)
339        )?;
340
341        let now = Utc::now();
342        let balances = spot_balances(&token_balances.balances, now).collect();
343
344        let coins = open_orders.iter().map(|order| order.coin.as_str());
345        let pairs = self.spot_coins.covering(coins.clone()).await;
346        for coin in coins {
347            spot_pair(&pairs, coin)?;
348        }
349
350        // Spot has no positions, so the open orders are the whole of each instrument's entry.
351        let instrument_snapshots = OpenOrderListing::new(
352            &open_orders,
353            ExchangeId::HyperliquidSpot,
354            instruments,
355            |coin| pairs.get(coin).map(spot_pair_to_instrument),
356        )
357        .into_snapshots()
358        .collect();
359
360        let snapshot = AccountSnapshot {
361            exchange: ExchangeId::HyperliquidSpot,
362            balances,
363            instruments: instrument_snapshots,
364        };
365        remember_snapshot(&self.known_live, &snapshot);
366        Ok(snapshot)
367    }
368
369    /// Returns a live stream of account events (fills, order updates) for spot orders.
370    ///
371    /// # Instrument filtering
372    ///
373    /// The `instruments` parameter is **ignored** — Hyperliquid's WebSocket API does not
374    /// support per-instrument subscriptions for user events. All fills and order updates
375    /// are delivered, but we filter client-side to only emit spot events (see
376    /// [Spot coins](self#spot-coins)).
377    ///
378    /// # Task lifecycle
379    ///
380    /// Spawns three background tasks (fills, orders, and the reconnect's order check) that are
381    /// automatically cancelled when the returned stream is dropped.
382    ///
383    /// # Orders that ended while disconnected
384    ///
385    /// After each reconnect the stream reports how each order the client holds as live ended,
386    /// where it did, exactly as [`HyperliquidClient`](super::HyperliquidClient)'s does; see its
387    /// `account_stream`. The listing leaves out an order on a spot coin missing from `spotMeta`,
388    /// which cannot be on an instrument the client holds an order on, but a lookup that finds an
389    /// order on one, even after `spotMeta` is read again (see [Spot coins](self#spot-coins)),
390    /// fails, and is retried.
391    async fn account_stream(
392        &self,
393        _assets: &[AssetNameExchange],
394        _instruments: &[InstrumentNameExchange],
395    ) -> Result<Self::AccountStream, UnindexedClientError> {
396        let user = self.wallet_h160();
397        let base_url = self.config.base_url();
398
399        let mut ws_client = InfoClient::with_reconnect(None, Some(base_url))
400            .await
401            .map_err(|e| ConnectivityError::Socket(e.to_string()))?;
402
403        let (fills_tx, mut fills_rx) = mpsc::unbounded_channel::<Message>();
404        let (orders_tx, mut orders_rx) = mpsc::unbounded_channel::<Message>();
405
406        ws_client
407            .subscribe(Subscription::UserFills { user }, fills_tx)
408            .await
409            .map_err(|e| ConnectivityError::Socket(format!("UserFills subscribe: {e}")))?;
410
411        ws_client
412            .subscribe(Subscription::OrderUpdates { user }, orders_tx)
413            .await
414            .map_err(|e| ConnectivityError::Socket(format!("OrderUpdates subscribe: {e}")))?;
415
416        info!(%user, "Subscribed to Hyperliquid spot account stream");
417
418        let (event_tx, event_rx) = mpsc::unbounded_channel::<UnindexedAccountEvent>();
419        let cancel_token = CancellationToken::new();
420
421        // Both tasks share `event_tx` and both observe `recv() -> None` when the SDK gives up on the
422        // socket, so guard the terminal emit with a shared flag — only the first non-cancellation
423        // terminal sends `StreamTerminated`, avoiding a double-emit.
424        let terminated = Arc::new(AtomicBool::new(false));
425
426        // Scoped to this stream rather than to the client: a fresh `account_stream` opens a fresh
427        // subscription, whose snapshot the new consumer has not seen. It must outlive a reconnect,
428        // which it does -- the SDK reconnects underneath this task, not around it.
429        let fills_dedup = new_dedup_cache();
430
431        // How the orders held as live ended while the socket was down: checked after each
432        // reconnect, once the fills snapshot that opens the resubscription has been sent on. Its
433        // own token also stops it promptly when the stream terminates.
434        let reconnected = Arc::new(Notify::new());
435        let checks_cancel = cancel_token.child_token();
436        let (list_client, list_coins) = (self.info_client.clone(), self.spot_coins.clone());
437        let (lookup_client, lookup_coins) = (self.info_client.clone(), self.spot_coins.clone());
438        spawn_order_checks(
439            ExchangeId::HyperliquidSpot,
440            self.known_live.clone(),
441            reconnected.clone(),
442            checks_cancel.clone(),
443            event_tx.clone(),
444            move |instruments| {
445                spot_listed_cids(list_client.clone(), list_coins.clone(), user, instruments)
446            },
447            move |key| spot_order_lookup(lookup_client.clone(), lookup_coins.clone(), user, key),
448        );
449
450        // Spawn task to process fills (filtered to spot only)
451        let fills_event_tx = event_tx.clone();
452        let fills_cancel = cancel_token.clone();
453        let fills_terminated = terminated.clone();
454        let fills_coins = self.spot_coins.clone();
455        let fills_checks_cancel = checks_cancel.clone();
456        tokio::spawn(async move {
457            // Spot coins already logged as missing from spotMeta, so each is logged once.
458            let mut missing_coins = HashSet::new();
459            let mut reconnects = ReconnectWatch::new(reconnected);
460            loop {
461                tokio::select! {
462                    biased;
463                    () = fills_cancel.cancelled() => {
464                        debug!("Spot fills task cancelled");
465                        return;
466                    }
467                    msg = fills_rx.recv() => {
468                        let Some(msg) = msg else {
469                            debug!("Spot fills receiver closed");
470                            fills_checks_cancel.cancel();
471                            // SDK gave up on the stream (channel closed). Emit a single terminal
472                            // StreamTerminated across both tasks (guarded by the shared flag).
473                            if fills_terminated
474                                .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
475                                .is_ok()
476                            {
477                                emit_stream_terminated(
478                                    &fills_event_tx,
479                                    ExchangeId::HyperliquidSpot,
480                                    StreamTerminationReason::Error(
481                                        "hyperliquid spot account stream closed".to_string(),
482                                    ),
483                                );
484                            }
485                            return;
486                        };
487                        match msg {
488                            Message::UserFills(fills) => {
489                                let pairs = fills_coins
490                                    .covering(fills.data.fills.iter().map(|fill| fill.coin.as_str()))
491                                    .await;
492                                let convert = |fill: &hyperliquid_rust_sdk::TradeInfo| {
493                                    // Filter: only spot coins
494                                    if CoinKind::of(&fill.coin) != CoinKind::Spot {
495                                        return None;
496                                    }
497                                    let Some(pair) = pairs.get(&fill.coin) else {
498                                        if missing_coins.insert(fill.coin.clone()) {
499                                            error!(
500                                                coin = %fill.coin,
501                                                tid = fill.tid,
502                                                "Hyperliquid spot fills on a coin not in \
503                                                 spotMeta are left out (fetch_trades recovers \
504                                                 them); logged once per stream"
505                                            );
506                                        }
507                                        return None;
508                                    };
509                                    fill_to_account_event(fill, pair)
510                                };
511                                if !send_fills(
512                                    &fills.data,
513                                    convert,
514                                    &fills_dedup,
515                                    &fills_event_tx,
516                                    &mut reconnects,
517                                ) {
518                                    debug!("Spot fills event channel closed");
519                                    return;
520                                }
521                            }
522                            Message::NoData => {
523                                warn!("Spot UserFills WebSocket disconnected");
524                                reconnects.dropped();
525                            }
526                            Message::HyperliquidError(e) => {
527                                // Transient, non-terminal: the loop continues. Log only — no
528                                // in-band event (consumers took no action on the old StreamError).
529                                error!(%e, "Spot UserFills WebSocket error");
530                            }
531                            _ => {}
532                        }
533                    }
534                }
535            }
536        });
537
538        // Spawn task to process order updates (filtered to spot only)
539        // NOTE: ws_client is moved here to keep the WebSocket alive. When this task
540        // exits (via cancellation or channel close), the WebSocket connection closes,
541        // which causes fills_rx to also close.
542        let orders_event_tx = event_tx;
543        let orders_cancel = cancel_token.clone();
544        let orders_terminated = terminated;
545        let orders_coins = self.spot_coins.clone();
546        let orders_known = self.known_live.clone();
547        tokio::spawn(async move {
548            let _ws_client = ws_client;
549            // Spot coins already logged as missing from spotMeta, so each is logged once.
550            let mut missing_coins = HashSet::new();
551
552            loop {
553                tokio::select! {
554                    biased;
555                    () = orders_cancel.cancelled() => {
556                        debug!("Spot orders task cancelled");
557                        return;
558                    }
559                    msg = orders_rx.recv() => {
560                        let Some(msg) = msg else {
561                            debug!("Spot orders receiver closed");
562                            checks_cancel.cancel();
563                            // SDK gave up on the stream (channel closed). Emit a single terminal
564                            // StreamTerminated across both tasks (guarded by the shared flag).
565                            if orders_terminated
566                                .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
567                                .is_ok()
568                            {
569                                emit_stream_terminated(
570                                    &orders_event_tx,
571                                    ExchangeId::HyperliquidSpot,
572                                    StreamTerminationReason::Error(
573                                        "hyperliquid spot account stream closed".to_string(),
574                                    ),
575                                );
576                            }
577                            return;
578                        };
579                        match msg {
580                            Message::OrderUpdates(updates) => {
581                                let pairs = orders_coins
582                                    .covering(updates.data.iter().map(|update| update.order.coin.as_str()))
583                                    .await;
584                                for update in updates.data {
585                                    // Filter: only spot coins
586                                    let coin = update.order.coin.as_str();
587                                    if CoinKind::of(coin) != CoinKind::Spot {
588                                        continue;
589                                    }
590                                    let Some(pair) = pairs.get(coin) else {
591                                        if missing_coins.insert(coin.to_owned()) {
592                                            warn!(
593                                                %coin,
594                                                oid = update.order.oid,
595                                                "Hyperliquid spot order updates on a coin not in \
596                                                 spotMeta are left out; logged once per stream"
597                                            );
598                                        }
599                                        continue;
600                                    };
601                                    if let Some(event) = order_update_to_account_event(&update, pair)
602                                        && !send_observed(&orders_known, &orders_event_tx, event)
603                                    {
604                                        debug!("Spot orders event channel closed");
605                                        return;
606                                    }
607                                }
608                            }
609                            Message::NoData => {
610                                warn!("Spot OrderUpdates WebSocket disconnected");
611                            }
612                            Message::HyperliquidError(e) => {
613                                // Transient, non-terminal: the loop continues. Log only — no
614                                // in-band event (consumers took no action on the old StreamError).
615                                error!(%e, "Spot OrderUpdates WebSocket error");
616                            }
617                            _ => {}
618                        }
619                    }
620                }
621            }
622        });
623
624        let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(event_rx);
625        let guarded_stream = CancelOnDropStream::new(stream, cancel_token);
626        Ok(guarded_stream.boxed())
627    }
628
629    async fn cancel_order(
630        &self,
631        request: OrderRequestCancel<ExchangeId, &InstrumentNameExchange>,
632    ) -> UnindexedOrderResponseCancel {
633        use crate::order::{request::OrderResponseCancel, state::Cancelled};
634        use hyperliquid_rust_sdk::{ClientCancelRequest, ClientCancelRequestCloid};
635        use uuid::Uuid;
636
637        // An order is placed, and reported, only under its pair's exact spelling (see
638        // `open_order`), so the instrument of any order this client placed or reported spells
639        // the coin as the SDK keys it. A name in another spelling fails in the SDK.
640        let coin = match instrument_to_spot_coin(request.key.instrument) {
641            Some(c) => c,
642            None => {
643                warn!(
644                    instrument = %request.key.instrument,
645                    "Invalid spot instrument format (expected BASE-QUOTE-SPOT)"
646                );
647                return OrderResponseCancel {
648                    key: OrderKey {
649                        exchange: ExchangeId::HyperliquidSpot,
650                        instrument: request.key.instrument.clone(),
651                        strategy: request.key.strategy.clone(),
652                        cid: request.key.cid.clone(),
653                    },
654                    state: Err(UnindexedOrderError::Rejected(
655                        crate::error::ApiError::OrderRejected(format!(
656                            "Invalid instrument format: {}",
657                            request.key.instrument
658                        )),
659                    )),
660                };
661            }
662        };
663
664        enum CancelMethod {
665            ByOid(u64),
666            ByCloid(Uuid),
667        }
668
669        // How the venue addresses the order decides which endpoint cancels it. This reads the
670        // identifier's kind rather than inferring it from the string's shape: an oid and a cloid
671        // are different identifiers that happen to both be text, and telling them apart by parsing
672        // means a cloid which parses as a number gets cancelled as somebody else's oid.
673        let cancel_method = match &request.state.id {
674            Some(VenueOrderId::Assigned(id)) => {
675                id.0.parse::<u64>()
676                    .map(CancelMethod::ByOid)
677                    .map_err(|_| "venue order id is not a numeric Hyperliquid oid")
678            }
679            // The venue accepted the order without assigning an oid, so the only handle on it is
680            // the cloid it was placed with -- which placement derives from the client id the same
681            // way, and refuses the order if it cannot.
682            Some(VenueOrderId::ClientAssigned) => cid_to_cloid(&request.key.cid)
683                .map(CancelMethod::ByCloid)
684                .ok_or("order is addressable only by its client id, which is not a canonical UUID"),
685            None => Err("order is still in flight; the venue has acknowledged nothing to cancel"),
686        };
687
688        let cancel_method = match cancel_method {
689            Ok(method) => method,
690            Err(reason) => {
691                warn!(%reason, cid = %request.key.cid, "Cannot determine how to cancel order");
692                return OrderResponseCancel {
693                    key: OrderKey {
694                        exchange: ExchangeId::HyperliquidSpot,
695                        instrument: request.key.instrument.clone(),
696                        strategy: request.key.strategy.clone(),
697                        cid: request.key.cid.clone(),
698                    },
699                    state: Err(UnindexedOrderError::Rejected(
700                        crate::error::ApiError::OrderRejected(reason.to_string()),
701                    )),
702                };
703            }
704        };
705
706        // Terminal states keep a plain `OrderId`: nothing compares them for identity, so an order
707        // the venue never named records the client id it was addressed by instead.
708        let cancelled_id = match &request.state.id {
709            Some(venue_id) => venue_id.or_client_id(&request.key.cid),
710            None => OrderId(request.key.cid.0.clone()),
711        };
712
713        let response = match cancel_method {
714            CancelMethod::ByOid(oid) => {
715                debug!(oid, "Cancelling spot order by OID");
716                let cancel_request = ClientCancelRequest { asset: coin, oid };
717                self.exchange_client.cancel(cancel_request, None).await
718            }
719            CancelMethod::ByCloid(cloid) => {
720                debug!(%cloid, "Cancelling spot order by cloid (no oid assigned)");
721                let cancel_request = ClientCancelRequestCloid { asset: coin, cloid };
722                self.exchange_client
723                    .cancel_by_cloid(cancel_request, None)
724                    .await
725            }
726        };
727
728        let response = match response {
729            Ok(r) => r,
730            Err(e) => {
731                warn!(%e, "Spot cancel order failed");
732                return OrderResponseCancel {
733                    key: OrderKey {
734                        exchange: ExchangeId::HyperliquidSpot,
735                        instrument: request.key.instrument.clone(),
736                        strategy: request.key.strategy.clone(),
737                        cid: request.key.cid.clone(),
738                    },
739                    state: Err(map_order_error(e, request.key.instrument)),
740                };
741            }
742        };
743
744        match cancel_outcome(response) {
745            Ok(()) => {
746                debug!("Spot cancel order accepted");
747                // Hyperliquid answers a cancel once the order has left the book.
748                self.known_live.lock().ended(&request.key.cid);
749                OrderResponseCancel {
750                    key: OrderKey {
751                        exchange: ExchangeId::HyperliquidSpot,
752                        instrument: request.key.instrument.clone(),
753                        strategy: request.key.strategy.clone(),
754                        cid: request.key.cid.clone(),
755                    },
756                    state: Ok(Cancelled::new(
757                        cancelled_id.clone(),
758                        // SDK cancel response omits server timestamp; use local clock.
759                        Utc::now(),
760                        // Nor does it carry the filled quantity.
761                        None,
762                    )),
763                }
764            }
765            // Not reported ended: if the order did end, the account stream or a lookup says how.
766            Err(reason) => {
767                warn!(%reason, cid = %request.key.cid, "Spot cancel rejected by exchange");
768                OrderResponseCancel {
769                    key: OrderKey {
770                        exchange: ExchangeId::HyperliquidSpot,
771                        instrument: request.key.instrument.clone(),
772                        strategy: request.key.strategy.clone(),
773                        cid: request.key.cid.clone(),
774                    },
775                    state: Err(UnindexedOrderError::Rejected(
776                        crate::error::ApiError::OrderRejected(reason),
777                    )),
778                }
779            }
780        }
781    }
782
783    async fn open_order(
784        &self,
785        request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
786    ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
787        use hyperliquid_rust_sdk::{
788            ClientOrderRequest, ExchangeDataStatus, ExchangeResponseStatus,
789        };
790
791        let make_inactive =
792            |error: UnindexedOrderError| -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
793                Order {
794                    key: OrderKey {
795                        exchange: ExchangeId::HyperliquidSpot,
796                        instrument: request.key.instrument.clone(),
797                        strategy: request.key.strategy.clone(),
798                        cid: request.key.cid.clone(),
799                    },
800                    side: request.state.side,
801                    price: request.state.price,
802                    quantity: request.state.quantity,
803                    kind: request.state.kind,
804                    time_in_force: request.state.time_in_force,
805                    state: OrderState::inactive(error),
806                }
807            };
808        let make_rejected = |msg: String| {
809            make_inactive(OrderError::Rejected(crate::error::ApiError::OrderRejected(
810                msg,
811            )))
812        };
813        let make_unsupported = |msg: String| make_inactive(OrderError::UnsupportedOrderType(msg));
814
815        // Hyperliquid has no order flag for borrowing, and under portfolio margin an order borrows
816        // implicitly when it falls short, so the client cannot promise either way: no effect,
817        // not even `NoSideEffect`, is honoured.
818        if let Some(effect) = request.state.margin_effect {
819            return make_inactive(OrderError::UnsupportedMarginEffect(effect));
820        }
821
822        let Some((base, quote)) = spot_base_quote(request.key.instrument) else {
823            warn!(
824                instrument = %request.key.instrument,
825                "Invalid spot instrument format (expected BASE-QUOTE-SPOT)"
826            );
827            return make_rejected(format!(
828                "Invalid instrument format: {}",
829                request.key.instrument
830            ));
831        };
832        let is_buy = request.state.side == Side::Buy;
833
834        match request.state.kind {
835            OrderKind::Market => {
836                return make_unsupported(
837                    "Hyperliquid does not support market orders; use Limit with IOC time-in-force"
838                        .to_string(),
839                );
840            }
841            OrderKind::TrailingStop { .. }
842            | OrderKind::TrailingStopLimit { .. }
843            | OrderKind::TrailingStopFixedLimit { .. } => {
844                return make_unsupported(
845                    "Hyperliquid does not support trailing stop orders".to_string(),
846                );
847            }
848            OrderKind::Limit
849            | OrderKind::Stop { .. }
850            | OrderKind::StopLimit { .. }
851            | OrderKind::TakeProfit { .. }
852            | OrderKind::TakeProfitLimit { .. } => {}
853        }
854
855        // The venue reports every order under its cloid, so an order placed without one could
856        // not be matched to the id the caller tracks it by. See the module docs.
857        let Some(cloid) = cid_to_cloid(&request.key.cid) else {
858            return make_rejected(CLOID_REQUIRED.to_string());
859        };
860
861        let tif = map_tif(&request.state.time_in_force).to_string();
862
863        let pair = match self.traded_pair(base, quote).await {
864            Ok(pair) => pair,
865            Err(untraded) => {
866                let reason = match untraded {
867                    UntradedPair::Unlisted => {
868                        format!("Hyperliquid's spotMeta lists no spot pair {base}/{quote}")
869                    }
870                    UntradedPair::Misspelled(pair) => format!(
871                        "Hyperliquid spells this spot pair {}/{}, and reports its orders under \
872                         {}; name the instrument that way",
873                        pair.base(),
874                        pair.quote(),
875                        spot_pair_to_instrument(&pair)
876                    ),
877                };
878                warn!(instrument = %request.key.instrument, %reason, "Spot order refused unsent");
879                return make_inactive(OrderError::Rejected(
880                    crate::error::ApiError::InstrumentInvalid(
881                        request.key.instrument.clone(),
882                        reason,
883                    ),
884                ));
885            }
886        };
887        let precision = OrderPrecision::spot(pair.base_sz_decimals());
888        // The SDK addresses a spot pair by `BASE/QUOTE` spelled exactly as `spotMeta` spells its
889        // tokens, which the pair's own names are.
890        let coin = format!("{}/{}", pair.base(), pair.quote());
891        let wire = match wire_order(
892            &precision,
893            request.state.kind,
894            tif,
895            request.state.price,
896            request.state.quantity,
897        ) {
898            Ok(wire) => wire,
899            Err(WireOrderError::Precision(violation)) => {
900                return make_inactive(OrderError::InvalidPrecision(violation));
901            }
902            Err(WireOrderError::MissingPrice) => {
903                return make_rejected(
904                    "Hyperliquid requires limit price for Limit/StopLimit/TakeProfitLimit orders"
905                        .to_string(),
906                );
907            }
908            Err(WireOrderError::UnsupportedKind) => {
909                return make_unsupported(format!(
910                    "Hyperliquid does not support {} orders",
911                    request.state.kind
912                ));
913            }
914        };
915
916        // Hyperliquid spot requires minimum $10 notional value
917        // For market triggers, use trigger_price for notional calculation
918        let notional_price = match request.state.kind {
919            OrderKind::Stop { trigger_price } | OrderKind::TakeProfit { trigger_price } => {
920                trigger_price
921            }
922            _ => request.state.price.unwrap_or(Decimal::ZERO),
923        };
924        let notional = notional_price * request.state.quantity;
925        if notional < Decimal::TEN {
926            warn!(
927                instrument = %request.key.instrument,
928                %notional,
929                "Spot order below $10 minimum notional value"
930            );
931            return make_rejected(format!("Spot order notional ${notional} below $10 minimum"));
932        }
933
934        // Logged only for an order about to be sent.
935        if matches!(request.state.time_in_force, TimeInForce::FillOrKill) {
936            warn!(
937                instrument = %request.key.instrument,
938                "FillOrKill not supported by Hyperliquid, using ImmediateOrCancel (may result in partial fills)"
939            );
940        }
941
942        let order_request = ClientOrderRequest {
943            asset: coin,
944            is_buy,
945            reduce_only: request.state.reduce_only,
946            limit_px: wire.limit_px,
947            sz: wire.sz,
948            cloid: Some(cloid),
949            order_type: wire.order_type,
950        };
951
952        let response = match self.exchange_client.order(order_request, None).await {
953            Ok(r) => r,
954            Err(e) => {
955                warn!(%e, "Spot open order failed");
956                return Order {
957                    key: OrderKey {
958                        exchange: ExchangeId::HyperliquidSpot,
959                        instrument: request.key.instrument.clone(),
960                        strategy: request.key.strategy.clone(),
961                        cid: request.key.cid.clone(),
962                    },
963                    side: request.state.side,
964                    price: request.state.price,
965                    quantity: request.state.quantity,
966                    kind: request.state.kind,
967                    time_in_force: request.state.time_in_force,
968                    state: OrderState::inactive(map_order_error(e, request.key.instrument)),
969                };
970            }
971        };
972
973        let state = match response {
974            ExchangeResponseStatus::Ok(exchange_resp) => {
975                let status = exchange_resp
976                    .data
977                    .and_then(|d| d.statuses.into_iter().next());
978
979                match status {
980                    Some(ExchangeDataStatus::Resting(resting)) => {
981                        debug!(oid = resting.oid, "Spot order resting");
982                        OrderState::active(Open {
983                            id: VenueOrderId::Assigned(OrderId(format_smolstr!("{}", resting.oid))),
984                            // SDK does not return exchange timestamp on order placement; use local clock.
985                            time_exchange: Utc::now(),
986                            filled_quantity: Decimal::ZERO,
987                        })
988                    }
989                    Some(ExchangeDataStatus::Filled(filled)) => {
990                        debug!(oid = filled.oid, avg_px = %filled.avg_px, "Spot order filled");
991                        let avg_price = parse_decimal(&filled.avg_px, "avg_px");
992                        OrderState::fully_filled(Filled::new(
993                            OrderId(format_smolstr!("{}", filled.oid)),
994                            // SDK does not return exchange timestamp on order placement; use local clock.
995                            Utc::now(),
996                            parse_decimal(&filled.total_sz, "total_sz")
997                                .unwrap_or(request.state.quantity),
998                            avg_price,
999                        ))
1000                    }
1001                    Some(ExchangeDataStatus::Error(msg)) => {
1002                        warn!(%msg, "Spot order rejected by exchange");
1003                        OrderState::inactive(OrderError::Rejected(order_rejection(msg)))
1004                    }
1005                    Some(
1006                        ExchangeDataStatus::WaitingForFill | ExchangeDataStatus::WaitingForTrigger,
1007                    ) => {
1008                        // The venue answered without an oid, so the order's only handle is the
1009                        // cloid it was placed with. A standalone trigger order is answered
1010                        // `resting` with an oid; these statuses belong to grouped orders.
1011                        debug!(cid = %request.key.cid, "Spot order waiting under its cloid");
1012                        OrderState::active(Open {
1013                            id: VenueOrderId::ClientAssigned,
1014                            time_exchange: Utc::now(),
1015                            filled_quantity: Decimal::ZERO,
1016                        })
1017                    }
1018                    Some(ExchangeDataStatus::Success) | None => {
1019                        // The venue took the request without saying what became of the order,
1020                        // so it may be live: the outcome is unknown, not a refusal.
1021                        warn!(cid = %request.key.cid, "Spot order answered without its status; outcome unknown");
1022                        OrderState::inactive(order_outcome_unanswered())
1023                    }
1024                }
1025            }
1026            ExchangeResponseStatus::Err(msg) => {
1027                warn!(%msg, "Spot order rejected");
1028                OrderState::inactive(OrderError::Rejected(order_rejection(msg)))
1029            }
1030        };
1031
1032        let order = Order {
1033            key: OrderKey {
1034                exchange: ExchangeId::HyperliquidSpot,
1035                instrument: request.key.instrument.clone(),
1036                strategy: request.key.strategy.clone(),
1037                cid: request.key.cid.clone(),
1038            },
1039            side: request.state.side,
1040            price: request.state.price,
1041            quantity: request.state.quantity,
1042            kind: request.state.kind,
1043            time_in_force: request.state.time_in_force,
1044            state,
1045        };
1046        self.known_live
1047            .lock()
1048            .placed(&order.key, order.quantity, order.kind, &order.state);
1049        order
1050    }
1051
1052    async fn fetch_balances(
1053        &self,
1054        _assets: &[AssetNameExchange],
1055    ) -> Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError> {
1056        let address = self.wallet_h160();
1057
1058        let token_balances = self
1059            .info_client
1060            .user_token_balances(address)
1061            .await
1062            .map_err(map_sdk_error)?;
1063
1064        let now = Utc::now();
1065        Ok(spot_balances(&token_balances.balances, now).collect())
1066    }
1067
1068    async fn fetch_open_orders(
1069        &self,
1070        instruments: &[InstrumentNameExchange],
1071    ) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
1072        let address = self.wallet_h160();
1073
1074        let open_orders = open_orders(&self.info_client, address).await?;
1075        let pairs = self
1076            .spot_coins
1077            .covering(open_orders.iter().map(|order| order.coin.as_str()))
1078            .await;
1079
1080        let orders = spot_open_orders(&open_orders, &pairs, instruments)?;
1081        remember_open(&self.known_live, &orders);
1082        Ok(orders)
1083    }
1084
1085    /// Reads the span with `userFillsByTime`, to its end within the call, so the read is always
1086    /// complete (`resume: None`). Hyperliquid keeps only each wallet's 10,000 most recent fills,
1087    /// so a span reaching further back is read only as far as those go, and
1088    /// [`held_since`](TradesRead::held_since) says where that is.
1089    async fn fetch_trades(
1090        &self,
1091        start: DateTime<Utc>,
1092        end: DateTime<Utc>,
1093        instruments: &[InstrumentNameExchange],
1094    ) -> Result<TradesRead<AssetNameExchange, InstrumentNameExchange>, UnindexedClientError> {
1095        let Some((start_ms, end_ms)) = span_millis(start, end) else {
1096            return Ok(TradesRead::complete(Vec::new()));
1097        };
1098        let address = self.wallet_h160();
1099
1100        let fills = user_fills_by_time(&self.info_client, address, start_ms, end_ms).await?;
1101        let held_since = super::common::held_since(&fills, start_ms);
1102        let pairs = self
1103            .spot_coins
1104            .covering(fills.iter().map(|fill| fill.coin.as_str()))
1105            .await;
1106
1107        spot_trades(&fills, &pairs, start, end, instruments)
1108            .map(|trades| TradesRead::complete(trades).with_held_since(held_since))
1109    }
1110}
1111
1112/// Looks each order up with `orderStatus` (weight 2), as
1113/// [`HyperliquidClient`](super::HyperliquidClient) does; see its implementation for how each
1114/// status is reported. An order on a spot coin missing from `spotMeta` even after it is read again
1115/// (see [Spot coins](self#spot-coins)) fails the call, since it cannot be told apart from an order
1116/// on the key's instrument.
1117///
1118/// The account stream runs the same lookup itself after a reconnect; see
1119/// [`account_stream`](ExecutionClient::account_stream).
1120impl OrderStatusClient for HyperliquidSpotClient {
1121    async fn fetch_ended_orders(
1122        &self,
1123        orders: &[UnindexedOrderKey],
1124    ) -> Result<Vec<UnindexedInactiveOrder>, UnindexedClientError> {
1125        let address = self.wallet_h160();
1126        fetch_ended_by_key(orders, |key| {
1127            spot_order_lookup(
1128                self.info_client.clone(),
1129                self.spot_coins.clone(),
1130                address,
1131                key,
1132            )
1133        })
1134        .await
1135    }
1136
1137    /// One `orderStatus` (weight 2), which reports a live order as well as an ended one, read
1138    /// as [`fetch_ended_orders`](OrderStatusClient::fetch_ended_orders) reads it.
1139    ///
1140    /// # Errors
1141    ///
1142    /// When the lookup fails, the order is on a spot coin missing from `spotMeta`, or
1143    /// Hyperliquid's record of the order does not convert.
1144    async fn fetch_order_status(
1145        &self,
1146        key: &UnindexedOrderKey,
1147    ) -> Result<VenueOrderStatus, UnindexedClientError> {
1148        spot_order_status(
1149            self.info_client.clone(),
1150            self.spot_coins.clone(),
1151            self.wallet_h160(),
1152            key.clone(),
1153        )
1154        .await?
1155        .ok_or_else(|| unreadable_record(&key.cid))
1156    }
1157}
1158
1159/// Look the order under `key` up with `orderStatus`, on the spot pair its coin names.
1160///
1161/// # Errors
1162///
1163/// When the lookup fails, or the order is on a spot coin missing from `spotMeta`.
1164async fn spot_order_lookup(
1165    info_client: Arc<InfoClient>,
1166    spot_coins: SpotCoins,
1167    address: ethers::types::H160,
1168    key: UnindexedOrderKey,
1169) -> Result<OrderLookup, UnindexedClientError> {
1170    Ok(lookup_of(
1171        spot_order_status(info_client, spot_coins, address, key).await?,
1172    ))
1173}
1174
1175/// What `orderStatus` says of the order under `key`, on the spot pair its coin names: see
1176/// `status_from_record`.
1177///
1178/// # Errors
1179///
1180/// When the lookup fails, or the order is on a spot coin missing from `spotMeta`.
1181async fn spot_order_status(
1182    info_client: Arc<InfoClient>,
1183    spot_coins: SpotCoins,
1184    address: ethers::types::H160,
1185    key: UnindexedOrderKey,
1186) -> Result<Option<VenueOrderStatus>, UnindexedClientError> {
1187    let Some(record) = fetch_order_record(&info_client, address, &key.cid).await? else {
1188        return Ok(Some(VenueOrderStatus::Unknown));
1189    };
1190    let coin = record.order.coin.as_str();
1191    let pairs = spot_coins.covering([coin]).await;
1192    let instrument = spot_pair(&pairs, coin)?.map(spot_pair_to_instrument);
1193    Ok(status_from_record(key, &record, instrument))
1194}
1195
1196/// The client order ids `openOrders` (weight 20) lists on the spot `instruments`, for a
1197/// reconnect's check of the orders held as live. An order on a spot coin missing from `spotMeta` is
1198/// left out (see `listed_cids`).
1199///
1200/// # Errors
1201///
1202/// When the listing fails.
1203async fn spot_listed_cids(
1204    info_client: Arc<InfoClient>,
1205    spot_coins: SpotCoins,
1206    address: ethers::types::H160,
1207    instruments: Vec<InstrumentNameExchange>,
1208) -> Result<FnvHashSet<ClientOrderId>, UnindexedClientError> {
1209    let rows = open_orders(&info_client, address).await?;
1210    let pairs = spot_coins
1211        .covering(rows.iter().map(|row| row.coin.as_str()))
1212        .await;
1213    Ok(listed_cids(&rows, &instruments, |coin| {
1214        pairs.get(coin).map(spot_pair_to_instrument)
1215    }))
1216}
1217
1218/// Convert the open-order rows on spot pairs, keeping those on `instruments` (every one when
1219/// empty). Rows on other markets are left out.
1220///
1221/// # Errors
1222///
1223/// When a row is on a spot coin missing from `pairs` (see [`spot_pair`]).
1224fn spot_open_orders(
1225    rows: &[OpenOrder],
1226    pairs: &SpotPairs,
1227    instruments: &[InstrumentNameExchange],
1228) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
1229    let instrument_filter = InstrumentFilter::new(instruments);
1230
1231    let mut orders = Vec::new();
1232    for order in rows {
1233        let Some(pair) = spot_pair(pairs, &order.coin)? else {
1234            continue;
1235        };
1236        let instrument = spot_pair_to_instrument(pair);
1237        if !instrument_filter.matches(&instrument) {
1238            continue;
1239        }
1240        orders.extend(open_order_to_order(
1241            order,
1242            ExchangeId::HyperliquidSpot,
1243            instrument,
1244        ));
1245    }
1246    Ok(orders)
1247}
1248
1249/// Convert the fills on spot pairs within `start..=end`, keeping those on `instruments` (every one
1250/// when empty). Fills on other markets, and fills that do not parse, are left out.
1251///
1252/// # Errors
1253///
1254/// When a fill is on a spot coin missing from `pairs` (see [`spot_pair`]).
1255fn spot_trades(
1256    fills: &[UserFill],
1257    pairs: &SpotPairs,
1258    start: DateTime<Utc>,
1259    end: DateTime<Utc>,
1260    instruments: &[InstrumentNameExchange],
1261) -> Result<Vec<Trade<AssetNameExchange, InstrumentNameExchange>>, UnindexedClientError> {
1262    let instrument_filter = InstrumentFilter::new(instruments);
1263
1264    let mut result = Vec::new();
1265    for fill in fills {
1266        let Some(pair) = spot_pair(pairs, &fill.coin)? else {
1267            continue;
1268        };
1269        let (base_asset, quote_asset) = (pair.base(), pair.quote());
1270        let instrument = spot_pair_to_instrument(pair);
1271
1272        if !instrument_filter.matches(&instrument) {
1273            continue;
1274        }
1275
1276        let Some(side) = parse_side(&fill.side) else {
1277            continue;
1278        };
1279        let Some(price) = parse_decimal(&fill.px, "px") else {
1280            continue;
1281        };
1282        let Some(quantity) = parse_decimal(&fill.sz, "sz") else {
1283            continue;
1284        };
1285        let fee = parse_decimal(&fill.fee, "fee").unwrap_or(Decimal::ZERO);
1286
1287        let Some(time_exchange) = millis_to_datetime(fill.time) else {
1288            warn!(time = fill.time, "Invalid fill timestamp, skipping");
1289            continue;
1290        };
1291        if !(start..=end).contains(&time_exchange) {
1292            continue;
1293        }
1294
1295        // Prefer what the venue says the fee was charged in. The side-based rule below is
1296        // only a guess — spot buys usually pay in base and sells in quote, but a fee can be
1297        // charged in a third asset — and it is reachable only if `feeToken` is absent, which
1298        // has not been observed.
1299        let fee_asset = fill
1300            .fee_token
1301            .as_deref()
1302            .unwrap_or(if matches!(side, Side::Buy) {
1303                base_asset
1304            } else {
1305                quote_asset
1306            });
1307
1308        result.push(Trade {
1309            id: TradeId(format_smolstr!("{}", fill.tid)),
1310            order_id: OrderId(format_smolstr!("{}", fill.oid)),
1311            instrument,
1312            strategy: StrategyId::unknown(),
1313            time_exchange,
1314            side,
1315            price,
1316            quantity,
1317            // `TradeInfo` carries no cumulative filled quantity; Hyperliquid reports order
1318            // state as its own `OrderUpdate` message.
1319            order_filled_quantity: None,
1320            fees: AssetFees {
1321                asset: AssetNameExchange::from(fee_asset),
1322                fees: fee,
1323                // Only set quote-equivalent when the fee is actually denominated in
1324                // the quote asset. The downstream indexer recomputes for base-asset fees.
1325                //
1326                // Case-insensitive, matching the stream path: `fee_asset` is now the venue's
1327                // own `feeToken` rather than a substring of `coin`, so it is no longer equal
1328                // to `quote_asset` byte-for-byte by construction.
1329                fees_quote: if fee_asset.eq_ignore_ascii_case(quote_asset) {
1330                    Some(fee)
1331                } else {
1332                    None
1333                },
1334            },
1335            // As on the stream, whose copy of a fill usually arrives first; see `TradeOrigin`.
1336            origin: TradeOrigin::Order,
1337            position_side: None,
1338            client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1339        });
1340    }
1341
1342    Ok(result)
1343}
1344
1345/// Convert SDK TradeInfo (fill) on `pair` to AccountEvent::Trade for spot.
1346fn fill_to_account_event(
1347    fill: &hyperliquid_rust_sdk::TradeInfo,
1348    pair: &SpotPair,
1349) -> Option<UnindexedAccountEvent> {
1350    let side = parse_side(&fill.side)?;
1351    let price = parse_decimal(&fill.px, "fill.px")?;
1352    let quantity = parse_decimal(&fill.sz, "fill.sz")?;
1353    let fee = parse_decimal(&fill.fee, "fill.fee").unwrap_or(Decimal::ZERO);
1354    let time_exchange = millis_to_datetime(fill.time)?;
1355
1356    let quote_asset = pair.quote();
1357    let instrument = spot_pair_to_instrument(pair);
1358    let order_id = OrderId(format_smolstr!("{}", fill.oid));
1359
1360    // SDK's `TradeInfo` exposes `fee_token` directly, which is the asset the fee is
1361    // denominated in (typically base asset for buys, quote asset for sells).
1362    let fee_asset = fill.fee_token.as_str();
1363
1364    let trade = Trade {
1365        id: TradeId(format_smolstr!("{}", fill.tid)),
1366        order_id,
1367        instrument,
1368        strategy: StrategyId::unknown(),
1369        time_exchange,
1370        side,
1371        price,
1372        quantity,
1373        // `TradeInfo` carries no cumulative filled quantity, so the order's state must be learned
1374        // from an `OrderUpdate` -- which Hyperliquid sends as its own message.
1375        order_filled_quantity: None,
1376        fees: AssetFees {
1377            asset: AssetNameExchange::from(fee_asset),
1378            fees: fee,
1379            // Only set quote-equivalent when the fee is actually denominated in
1380            // the quote asset. The downstream indexer recomputes for base-asset fees.
1381            fees_quote: if fee_asset.eq_ignore_ascii_case(quote_asset) {
1382                Some(fee)
1383            } else {
1384                None
1385            },
1386        },
1387        // The SDK's `TradeInfo` drops the fill's liquidation marker, so every fill is reported
1388        // as `Order`; see `TradeOrigin`.
1389        origin: TradeOrigin::Order,
1390        position_side: None,
1391        client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1392    };
1393
1394    Some(AccountEvent::new(
1395        ExchangeId::HyperliquidSpot,
1396        AccountEventKind::Trade(trade),
1397    ))
1398}
1399
1400/// Convert SDK OrderUpdate on `pair` to AccountEvent::OrderSnapshot for spot.
1401fn order_update_to_account_event(
1402    update: &hyperliquid_rust_sdk::OrderUpdate,
1403    pair: &SpotPair,
1404) -> Option<UnindexedAccountEvent> {
1405    super::common::order_update_to_account_event(
1406        update,
1407        ExchangeId::HyperliquidSpot,
1408        spot_pair_to_instrument(pair),
1409    )
1410}
1411
1412#[cfg(test)]
1413// Test code: panics on bad input are acceptable
1414#[allow(clippy::unwrap_used)]
1415mod tests {
1416    use super::super::spot_coins::test_spot_pairs;
1417    use crate::client::dedup::{dedup_key_from_event, is_duplicate};
1418
1419    mod order_recovery {
1420        use super::super::super::common::info_tests::info_client_against;
1421        use super::super::super::order_recovery::tests::{CID, CLOID, record_json, row};
1422        use super::super::super::spot_coins::TEST_SPOT_META;
1423        use super::*;
1424        use crate::order::state::InactiveOrderState;
1425        use wiremock::matchers::{body_string_contains, method, path};
1426        use wiremock::{Mock, MockServer, ResponseTemplate};
1427
1428        /// A server answering `spotMeta` with [`TEST_SPOT_META`] and every other info request
1429        /// with `body`, and the spot coins read from it.
1430        async fn serve(body: serde_json::Value) -> (MockServer, Arc<InfoClient>, SpotCoins) {
1431            let server = MockServer::start().await;
1432            Mock::given(method("POST"))
1433                .and(path("/info"))
1434                .and(body_string_contains("spotMeta"))
1435                .respond_with(
1436                    ResponseTemplate::new(200).set_body_raw(TEST_SPOT_META, "application/json"),
1437                )
1438                .with_priority(1)
1439                .mount(&server)
1440                .await;
1441            Mock::given(method("POST"))
1442                .and(path("/info"))
1443                .respond_with(ResponseTemplate::new(200).set_body_json(body))
1444                .with_priority(2)
1445                .mount(&server)
1446                .await;
1447            let client = Arc::new(info_client_against(server.uri()).await);
1448            let coins = SpotCoins::fetch(client.clone()).await.unwrap();
1449            (server, client, coins)
1450        }
1451
1452        fn key() -> UnindexedOrderKey {
1453            OrderKey {
1454                exchange: ExchangeId::HyperliquidSpot,
1455                instrument: InstrumentNameExchange::new("HYPE-USDC-SPOT"),
1456                strategy: StrategyId::new("strategy"),
1457                cid: ClientOrderId::new(CID),
1458            }
1459        }
1460
1461        fn order_status(coin: &str) -> serde_json::Value {
1462            serde_json::json!({
1463                "status": "order",
1464                "order": record_json(coin, "canceled", "0.01", Some(CLOID)),
1465            })
1466        }
1467
1468        #[tokio::test]
1469        async fn a_spot_lookup_names_the_pair_from_spot_meta() {
1470            let (_server, client, coins) = serve(order_status("@107")).await;
1471
1472            let lookup = spot_order_lookup(client, coins, ethers::types::H160::zero(), key())
1473                .await
1474                .unwrap();
1475
1476            let OrderLookup::Ended(order) = lookup else {
1477                panic!("expected an ended order, got {lookup:?}");
1478            };
1479            assert_eq!(order.key, key());
1480            assert!(matches!(order.state, InactiveOrderState::Cancelled(_)));
1481        }
1482
1483        /// One `orderStatus` answers a lookup without listing the open orders; a record that does
1484        /// not convert is an error, never `Unknown`.
1485        #[tokio::test]
1486        async fn a_spot_order_status_is_one_order_status_request() {
1487            use super::super::super::common::info_tests::{exchange_client_against, test_wallet};
1488            use super::super::super::config::Network;
1489
1490            for (status, live) in [("open", true), ("aStatusAddedLater", false)] {
1491                let (server, info_client, spot_coins) = serve(serde_json::json!({
1492                    "status": "order",
1493                    "order": record_json("@107", status, "0.01", Some(CLOID)),
1494                }))
1495                .await;
1496                let client = HyperliquidSpotClient {
1497                    config: HyperliquidConfig::new(test_wallet(), Network::Testnet),
1498                    spot_coins,
1499                    info_client,
1500                    exchange_client: Arc::new(
1501                        exchange_client_against(server.uri(), std::collections::HashMap::new())
1502                            .await,
1503                    ),
1504                    known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidSpot),
1505                };
1506
1507                let found = client.fetch_order_status(&key()).await;
1508
1509                if live {
1510                    assert!(
1511                        matches!(&found, Ok(VenueOrderStatus::Live(order)) if order.key == key()),
1512                        "{found:?}"
1513                    );
1514                } else {
1515                    assert!(
1516                        matches!(found, Err(UnindexedClientError::Internal(_))),
1517                        "{found:?}"
1518                    );
1519                }
1520                let lookups = server
1521                    .received_requests()
1522                    .await
1523                    .unwrap()
1524                    .into_iter()
1525                    .filter(|request| !String::from_utf8_lossy(&request.body).contains("spotMeta"))
1526                    .count();
1527                assert_eq!(lookups, 1, "{status}");
1528            }
1529        }
1530
1531        #[tokio::test]
1532        async fn a_spot_lookup_of_a_perp_order_is_unknown() {
1533            let (_server, client, coins) = serve(order_status("BTC")).await;
1534
1535            let lookup = spot_order_lookup(client, coins, ethers::types::H160::zero(), key())
1536                .await
1537                .unwrap();
1538
1539            assert!(matches!(lookup, OrderLookup::Unknown));
1540        }
1541
1542        #[tokio::test]
1543        async fn a_spot_lookup_fails_on_a_coin_missing_from_spot_meta() {
1544            let (_server, client, coins) = serve(order_status("@999")).await;
1545
1546            let lookup = spot_order_lookup(client, coins, ethers::types::H160::zero(), key()).await;
1547
1548            assert!(lookup.is_err());
1549        }
1550
1551        #[tokio::test]
1552        async fn a_spot_listing_names_only_the_orders_on_the_pairs_asked_about() {
1553            let rows = serde_json::json!([
1554                row("@107", 1, Some(CLOID)),
1555                row("@207", 2, None),
1556                row("BTC", 3, None),
1557            ]);
1558            let (_server, client, coins) = serve(rows).await;
1559
1560            let listed = spot_listed_cids(
1561                client,
1562                coins,
1563                ethers::types::H160::zero(),
1564                vec![InstrumentNameExchange::new("HYPE-USDC-SPOT")],
1565            )
1566            .await
1567            .unwrap();
1568
1569            assert_eq!(
1570                listed.into_iter().collect::<Vec<_>>(),
1571                [ClientOrderId::new(CID)]
1572            );
1573        }
1574
1575        #[tokio::test]
1576        async fn a_spot_listing_leaves_out_a_coin_missing_from_spot_meta() {
1577            let rows = serde_json::json!([row("@999", 1, None), row("@107", 2, Some(CLOID))]);
1578            let (_server, client, coins) = serve(rows).await;
1579
1580            let listed = spot_listed_cids(
1581                client,
1582                coins,
1583                ethers::types::H160::zero(),
1584                vec![InstrumentNameExchange::new("HYPE-USDC-SPOT")],
1585            )
1586            .await
1587            .unwrap();
1588
1589            assert_eq!(
1590                listed.into_iter().collect::<Vec<_>>(),
1591                [ClientOrderId::new(CID)]
1592            );
1593        }
1594    }
1595
1596    mod open_order {
1597        use super::super::super::common::info_tests::{
1598            exchange_client_against, info_client_against, test_wallet,
1599        };
1600        use super::super::super::config::Network;
1601        use super::super::super::spot_coins::TEST_SPOT_META;
1602        use super::*;
1603        use crate::error::{ApiError, OrderField, PrecisionLimit, PrecisionViolation};
1604        use crate::order::{OrderEvent, request::RequestOpen, state::InactiveOrderState};
1605        use std::collections::HashMap;
1606        use wiremock::matchers::{method, path};
1607        use wiremock::{Mock, MockServer, ResponseTemplate};
1608
1609        /// A spot client on [`TEST_SPOT_META`]'s pairs whose exchange endpoint rests every order.
1610        async fn resting_client() -> (MockServer, HyperliquidSpotClient) {
1611            client_responding(serde_json::json!({
1612                "status": "ok",
1613                "response": {"type": "order", "data": {"statuses": [{"resting": {"oid": 77}}]}},
1614            }))
1615            .await
1616        }
1617
1618        /// A spot client on [`TEST_SPOT_META`]'s pairs whose exchange endpoint answers every
1619        /// request with `body`.
1620        async fn client_responding(body: serde_json::Value) -> (MockServer, HyperliquidSpotClient) {
1621            client_with(ResponseTemplate::new(200).set_body_json(body)).await
1622        }
1623
1624        /// [`client_responding`], with the exchange endpoint giving `response`.
1625        async fn client_with(response: ResponseTemplate) -> (MockServer, HyperliquidSpotClient) {
1626            let server = MockServer::start().await;
1627            Mock::given(method("POST"))
1628                .and(path("/info"))
1629                .respond_with(
1630                    ResponseTemplate::new(200).set_body_raw(TEST_SPOT_META, "application/json"),
1631                )
1632                .mount(&server)
1633                .await;
1634            Mock::given(method("POST"))
1635                .and(path("/exchange"))
1636                .respond_with(response)
1637                .mount(&server)
1638                .await;
1639            let info_client = Arc::new(info_client_against(server.uri()).await);
1640            let client = HyperliquidSpotClient {
1641                config: HyperliquidConfig::new(test_wallet(), Network::Testnet),
1642                spot_coins: SpotCoins::fetch(info_client.clone()).await.unwrap(),
1643                info_client,
1644                exchange_client: Arc::new(
1645                    exchange_client_against(
1646                        server.uri(),
1647                        HashMap::from([("HYPE/USDC".to_owned(), 10_107)]),
1648                    )
1649                    .await,
1650                ),
1651                known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidSpot),
1652            };
1653            (server, client)
1654        }
1655
1656        /// A spot order refused for want of balance is a balance shortfall, as on other venues;
1657        /// any other refusal stays a rejection. Hyperliquid names no asset. The refusal is read
1658        /// both as an order's status and as the error of the whole response.
1659        #[tokio::test]
1660        async fn a_spot_order_refused_for_balance_is_balance_insufficient() {
1661            const BALANCE: &str = "Order has insufficient spot balance to trade";
1662            const MINIMUM: &str = "Order must have minimum value of 10 USDC.";
1663            for (body, expected) in [
1664                (
1665                    serde_json::json!({
1666                        "status": "ok",
1667                        "response": {"type": "order", "data": {"statuses": [{"error": BALANCE}]}},
1668                    }),
1669                    ApiError::BalanceInsufficient(None, BALANCE.to_owned()),
1670                ),
1671                (
1672                    serde_json::json!({"status": "err", "response": BALANCE}),
1673                    ApiError::BalanceInsufficient(None, BALANCE.to_owned()),
1674                ),
1675                (
1676                    serde_json::json!({
1677                        "status": "ok",
1678                        "response": {"type": "order", "data": {"statuses": [{"error": MINIMUM}]}},
1679                    }),
1680                    ApiError::OrderRejected(MINIMUM.to_owned()),
1681                ),
1682            ] {
1683                let (_server, client) = client_responding(body.clone()).await;
1684                let order = place_hype(&client, dec!(10), dec!(1)).await;
1685                let OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1686                    reported,
1687                ))) = &order.state
1688                else {
1689                    panic!("{body}: expected a rejection, got {:?}", order.state);
1690                };
1691                assert_eq!(reported, &expected, "{body}");
1692            }
1693        }
1694
1695        /// An `ok` answer that does not say what became of the order leaves its outcome unknown,
1696        /// so the engine looks it up rather than ending it.
1697        #[tokio::test]
1698        async fn a_spot_order_answered_without_its_status_has_an_unknown_outcome() {
1699            for body in [
1700                serde_json::json!({"status": "ok", "response": {"type": "order"}}),
1701                serde_json::json!({
1702                    "status": "ok",
1703                    "response": {"type": "order", "data": {"statuses": ["success"]}},
1704                }),
1705            ] {
1706                let (_server, client) = client_responding(body.clone()).await;
1707                let order = place_hype(&client, dec!(10), dec!(1)).await;
1708                assert!(
1709                    matches!(
1710                        order.state,
1711                        OrderState::Inactive(InactiveOrderState::OpenFailed(
1712                            OrderError::Connectivity(_)
1713                        ))
1714                    ),
1715                    "{body}: {:?}",
1716                    order.state
1717                );
1718            }
1719        }
1720
1721        /// A 5xx may have reached the venue, so its outcome is unknown; a 4xx turned the
1722        /// request away, so it is refused.
1723        #[tokio::test]
1724        async fn a_spot_order_failing_after_the_send_is_unknown_unless_turned_away() {
1725            let (_server, client) = client_with(ResponseTemplate::new(502)).await;
1726            let order = place_hype(&client, dec!(10), dec!(1)).await;
1727            assert!(order.state.is_outcome_unknown(), "{:?}", order.state);
1728
1729            let (_server, client) =
1730                client_with(ResponseTemplate::new(422).set_body_string("bad request")).await;
1731            let order = place_hype(&client, dec!(10), dec!(1)).await;
1732            assert!(
1733                matches!(
1734                    order.state,
1735                    OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1736                        ApiError::OrderRejected(_)
1737                    )))
1738                ),
1739                "{:?}",
1740                order.state
1741            );
1742        }
1743
1744        async fn place_hype(
1745            client: &HyperliquidSpotClient,
1746            price: Decimal,
1747            quantity: Decimal,
1748        ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1749            place(client, "HYPE-USDC-SPOT", price, quantity).await
1750        }
1751
1752        async fn place(
1753            client: &HyperliquidSpotClient,
1754            instrument: &str,
1755            price: Decimal,
1756            quantity: Decimal,
1757        ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1758            let instrument = InstrumentNameExchange::new(instrument);
1759            client
1760                .open_order(OrderEvent {
1761                    key: OrderKey {
1762                        exchange: ExchangeId::HyperliquidSpot,
1763                        instrument: &instrument,
1764                        strategy: StrategyId::new("strategy"),
1765                        cid: ClientOrderId::uuid(),
1766                    },
1767                    state: RequestOpen::new(
1768                        Side::Buy,
1769                        Some(price),
1770                        quantity,
1771                        OrderKind::Limit,
1772                        TimeInForce::GoodUntilCancelled { post_only: false },
1773                    ),
1774                })
1775                .await
1776        }
1777
1778        /// The orders the server was sent, as the SDK wrote them.
1779        async fn sent_orders(server: &MockServer) -> Vec<serde_json::Value> {
1780            server
1781                .received_requests()
1782                .await
1783                .unwrap_or_default()
1784                .into_iter()
1785                .filter(|request| request.url.path() == "/exchange")
1786                .map(|request| {
1787                    let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
1788                    body["action"]["orders"][0].clone()
1789                })
1790                .collect()
1791        }
1792
1793        #[tokio::test]
1794        async fn every_margin_effect_is_refused_without_sending() {
1795            use crate::margin::MarginEffect;
1796
1797            let (server, client) = resting_client().await;
1798            let instrument = InstrumentNameExchange::new("HYPE-USDC-SPOT");
1799
1800            for effect in [
1801                MarginEffect::NoSideEffect,
1802                MarginEffect::Borrow,
1803                MarginEffect::Repay,
1804            ] {
1805                let order = client
1806                    .open_order(OrderEvent {
1807                        key: OrderKey {
1808                            exchange: ExchangeId::HyperliquidSpot,
1809                            instrument: &instrument,
1810                            strategy: StrategyId::new("strategy"),
1811                            cid: ClientOrderId::uuid(),
1812                        },
1813                        state: RequestOpen::new(
1814                            Side::Buy,
1815                            Some(dec!(10)),
1816                            dec!(2),
1817                            OrderKind::Limit,
1818                            TimeInForce::GoodUntilCancelled { post_only: false },
1819                        )
1820                        .with_margin_effect(effect),
1821                    })
1822                    .await;
1823
1824                assert!(
1825                    matches!(
1826                        order.state,
1827                        OrderState::Inactive(InactiveOrderState::OpenFailed(
1828                            OrderError::UnsupportedMarginEffect(refused)
1829                        )) if refused == effect
1830                    ),
1831                    "{order:?}"
1832                );
1833            }
1834            assert!(sent_orders(&server).await.is_empty());
1835        }
1836
1837        #[tokio::test]
1838        async fn a_spot_pairs_precision_is_its_base_tokens() {
1839            let (_server, client) = resting_client().await;
1840
1841            assert_eq!(
1842                client
1843                    .order_precision(&InstrumentNameExchange::new("HYPE-USDC-SPOT"))
1844                    .await,
1845                Some(OrderPrecision::spot(2))
1846            );
1847            assert_eq!(
1848                client
1849                    .order_precision(&InstrumentNameExchange::new("PURR-USDC-SPOT"))
1850                    .await,
1851                Some(OrderPrecision::spot(0))
1852            );
1853            assert_eq!(
1854                client
1855                    .order_precision(&InstrumentNameExchange::new("BTC-USDC-PERP"))
1856                    .await,
1857                None
1858            );
1859        }
1860
1861        #[tokio::test]
1862        async fn a_spot_order_spelling_the_pair_differently_is_refused_unsent() {
1863            let (server, client) = resting_client().await;
1864
1865            // Hyperliquid spells the pair HYPE/USDC, and reports its orders under HYPE-USDC-SPOT.
1866            for instrument in ["hype-usdc-SPOT", "Hype-USDC-SPOT"] {
1867                let order = place(&client, instrument, dec!(25), dec!(1)).await;
1868                assert_eq!(
1869                    order.state,
1870                    OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1871                        ApiError::InstrumentInvalid(
1872                            InstrumentNameExchange::new(instrument),
1873                            "Hyperliquid spells this spot pair HYPE/USDC, and reports its orders \
1874                             under HYPE-USDC-SPOT; name the instrument that way"
1875                                .to_owned(),
1876                        )
1877                    )))
1878                );
1879                assert_eq!(
1880                    client
1881                        .order_precision(&InstrumentNameExchange::new(instrument))
1882                        .await,
1883                    None
1884                );
1885            }
1886            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1887        }
1888
1889        #[tokio::test]
1890        async fn a_spot_order_on_an_unlisted_pair_is_refused_unsent() {
1891            let (server, client) = resting_client().await;
1892
1893            let order = place(&client, "HYPE-PURR-SPOT", dec!(25), dec!(1)).await;
1894            assert_eq!(
1895                order.state,
1896                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1897                    ApiError::InstrumentInvalid(
1898                        InstrumentNameExchange::new("HYPE-PURR-SPOT"),
1899                        "Hyperliquid's spotMeta lists no spot pair HYPE/PURR".to_owned(),
1900                    )
1901                )))
1902            );
1903            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1904        }
1905
1906        #[tokio::test]
1907        async fn a_spot_order_breaking_the_precision_rules_is_refused_unsent() {
1908            let (server, client) = resting_client().await;
1909
1910            // HYPE's szDecimals is 2, so a size has at most 2 decimal places and a price 6.
1911            for (price, quantity, violation) in [
1912                (
1913                    dec!(25),
1914                    dec!(1.234),
1915                    PrecisionViolation {
1916                        field: OrderField::Quantity,
1917                        value: dec!(1.234),
1918                        limit: PrecisionLimit::DecimalPlaces { max: 2 },
1919                    },
1920                ),
1921                (
1922                    dec!(25.1234567),
1923                    dec!(1),
1924                    PrecisionViolation {
1925                        field: OrderField::Price,
1926                        value: dec!(25.1234567),
1927                        limit: PrecisionLimit::DecimalPlaces { max: 6 },
1928                    },
1929                ),
1930            ] {
1931                let order = place_hype(&client, price, quantity).await;
1932                assert_eq!(
1933                    order.state,
1934                    OrderState::Inactive(InactiveOrderState::OpenFailed(
1935                        OrderError::InvalidPrecision(violation)
1936                    ))
1937                );
1938            }
1939            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1940        }
1941
1942        #[tokio::test]
1943        async fn a_valid_spot_order_is_sent_unchanged() {
1944            let (server, client) = resting_client().await;
1945
1946            let order = place_hype(&client, dec!(25.123), dec!(1.25)).await;
1947            assert!(
1948                matches!(order.state, OrderState::Active(_)),
1949                "{:?}",
1950                order.state
1951            );
1952
1953            let sent = sent_orders(&server).await;
1954            assert_eq!(sent.len(), 1);
1955            assert_eq!(
1956                (&sent[0]["p"], &sent[0]["s"]),
1957                (&serde_json::json!("25.123"), &serde_json::json!("1.25"))
1958            );
1959        }
1960    }
1961
1962    mod cancel {
1963        use super::super::super::common::info_tests::{
1964            CANCEL_NOT_APPLIED, cancel_answer, exchange_client_against, info_client_against,
1965            test_wallet,
1966        };
1967        use super::super::super::config::Network;
1968        use super::super::super::spot_coins::TEST_SPOT_META;
1969        use super::*;
1970        use crate::error::ApiError;
1971        use crate::order::{OrderEvent, request::RequestCancel};
1972        use std::collections::HashMap;
1973        use wiremock::matchers::{method, path};
1974        use wiremock::{Mock, MockServer, ResponseTemplate};
1975
1976        /// Cancel a live `HYPE-USDC-SPOT` order through a client whose exchange endpoint answers
1977        /// `answer`. Returns the response, and whether the order is still held live afterwards.
1978        async fn cancel_answered(
1979            answer: serde_json::Value,
1980        ) -> (UnindexedOrderResponseCancel, bool) {
1981            cancel_responded(ResponseTemplate::new(200).set_body_json(answer)).await
1982        }
1983
1984        /// [`cancel_answered`], with the exchange endpoint giving `response`.
1985        async fn cancel_responded(
1986            response: ResponseTemplate,
1987        ) -> (UnindexedOrderResponseCancel, bool) {
1988            let server = MockServer::start().await;
1989            Mock::given(method("POST"))
1990                .and(path("/info"))
1991                .respond_with(
1992                    ResponseTemplate::new(200).set_body_raw(TEST_SPOT_META, "application/json"),
1993                )
1994                .mount(&server)
1995                .await;
1996            Mock::given(method("POST"))
1997                .and(path("/exchange"))
1998                .respond_with(response)
1999                .mount(&server)
2000                .await;
2001            let info_client = Arc::new(info_client_against(server.uri()).await);
2002            let client = HyperliquidSpotClient {
2003                config: HyperliquidConfig::new(test_wallet(), Network::Testnet),
2004                spot_coins: SpotCoins::fetch(info_client.clone()).await.unwrap(),
2005                info_client,
2006                exchange_client: Arc::new(
2007                    exchange_client_against(
2008                        server.uri(),
2009                        HashMap::from([("HYPE/USDC".to_owned(), 10_107)]),
2010                    )
2011                    .await,
2012                ),
2013                known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidSpot),
2014            };
2015            let instrument = InstrumentNameExchange::new("HYPE-USDC-SPOT");
2016            let key = OrderKey {
2017                exchange: ExchangeId::HyperliquidSpot,
2018                instrument: instrument.clone(),
2019                strategy: StrategyId::new("strategy"),
2020                cid: ClientOrderId::uuid(),
2021            };
2022            let id = VenueOrderId::Assigned(OrderId::new("7"));
2023            let open = Open {
2024                id: id.clone(),
2025                time_exchange: Utc::now(),
2026                filled_quantity: Decimal::ZERO,
2027            };
2028            client
2029                .known_live
2030                .lock()
2031                .live(&key, dec!(1), OrderKind::Limit, &open);
2032
2033            let response = client
2034                .cancel_order(OrderEvent {
2035                    key: OrderKey {
2036                        exchange: key.exchange,
2037                        instrument: &instrument,
2038                        strategy: key.strategy.clone(),
2039                        cid: key.cid.clone(),
2040                    },
2041                    state: RequestCancel { id: Some(id) },
2042                })
2043                .await;
2044            let live = client.known_live.lock().contains(&key.cid);
2045            (response, live)
2046        }
2047
2048        #[tokio::test]
2049        async fn a_spot_cancel_failing_after_the_send_has_an_unknown_outcome() {
2050            let (response, live) = cancel_responded(ResponseTemplate::new(503)).await;
2051            assert!(
2052                matches!(response.state, Err(UnindexedOrderError::Connectivity(_))),
2053                "{:?}",
2054                response.state
2055            );
2056            assert!(live, "the order is still held live");
2057
2058            let (response, live) =
2059                cancel_responded(ResponseTemplate::new(422).set_body_string("bad request")).await;
2060            assert!(
2061                matches!(
2062                    response.state,
2063                    Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(_)))
2064                ),
2065                "{:?}",
2066                response.state
2067            );
2068            assert!(live, "the order is still held live");
2069        }
2070
2071        #[tokio::test]
2072        async fn a_success_status_cancels_the_spot_order() {
2073            let (response, live) =
2074                cancel_answered(cancel_answer(serde_json::json!(["success"]))).await;
2075            assert!(response.state.is_ok(), "{:?}", response.state);
2076            assert!(!live, "a cancelled order is no longer held live");
2077        }
2078
2079        /// An order that filled before the cancel arrived is answered this way, so it must not be
2080        /// reported cancelled, and stays held live until the account stream or a lookup ends it.
2081        #[tokio::test]
2082        async fn an_error_status_is_a_rejected_spot_cancel_and_the_order_stays_live() {
2083            let (response, live) = cancel_answered(cancel_answer(serde_json::json!([
2084                {"error": CANCEL_NOT_APPLIED}
2085            ])))
2086            .await;
2087            let Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(reason))) =
2088                &response.state
2089            else {
2090                panic!("expected a rejected cancel, got {:?}", response.state);
2091            };
2092            assert_eq!(reason, CANCEL_NOT_APPLIED);
2093            assert!(live, "the order is still held live");
2094        }
2095
2096        #[tokio::test]
2097        async fn an_answer_without_a_status_is_a_rejected_spot_cancel() {
2098            let (response, live) = cancel_answered(serde_json::json!({
2099                "status": "ok",
2100                "response": {"type": "cancel"},
2101            }))
2102            .await;
2103            assert!(
2104                matches!(
2105                    response.state,
2106                    Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(_)))
2107                ),
2108                "{:?}",
2109                response.state
2110            );
2111            assert!(live, "the order is still held live");
2112        }
2113    }
2114
2115    use super::*;
2116    use rust_decimal_macros::dec;
2117    use rustrade_integration::collection::snapshot::Snapshot;
2118
2119    /// The pair `coin` names in [`test_spot_pairs`].
2120    fn pair(coin: &str) -> SpotPair {
2121        test_spot_pairs().get(coin).unwrap().clone()
2122    }
2123
2124    #[test]
2125    fn test_fill_to_account_event_spot() {
2126        let fill_json = r#"{
2127            "coin": "PURR/USDC",
2128            "side": "B",
2129            "px": "0.05",
2130            "sz": "1000",
2131            "time": 1714100000000,
2132            "hash": "0xspot123",
2133            "startPosition": "0",
2134            "dir": "Open Long",
2135            "closedPnl": "0",
2136            "oid": 12345,
2137            "cloid": null,
2138            "crossed": false,
2139            "fee": "0.025",
2140            "feeToken": "USDC",
2141            "tid": 99999
2142        }"#;
2143
2144        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
2145        let event = fill_to_account_event(&fill, &pair("PURR/USDC")).unwrap();
2146
2147        assert_eq!(event.exchange, ExchangeId::HyperliquidSpot);
2148        match event.kind {
2149            AccountEventKind::Trade(trade) => {
2150                assert_eq!(trade.instrument.as_ref(), "PURR-USDC-SPOT");
2151                assert_eq!(
2152                    trade.id.0, "99999",
2153                    "the id is the fill's tid, not its hash"
2154                );
2155                assert_eq!(trade.side, Side::Buy);
2156                assert_eq!(trade.price, dec!(0.05));
2157                assert_eq!(trade.quantity, dec!(1000));
2158                assert_eq!(trade.fees.fees, dec!(0.025));
2159                assert_eq!(trade.fees.asset.as_ref(), "USDC");
2160            }
2161            _ => panic!("Expected Trade event"),
2162        }
2163    }
2164
2165    /// Build a spot `TradeInfo` sharing one transaction hash with its siblings.
2166    fn spot_sweep_fill(tid: u64, px: &str) -> hyperliquid_rust_sdk::TradeInfo {
2167        let json = format!(
2168            r#"{{
2169                "coin": "PURR/USDC", "side": "B", "px": "{px}", "sz": "1000",
2170                "time": 1714100000000, "hash": "0xonesweep", "startPosition": "0",
2171                "dir": "Open Long", "closedPnl": "0", "oid": 4242, "cloid": null,
2172                "crossed": true, "fee": "0.025", "feeToken": "USDC", "tid": {tid}
2173            }}"#
2174        );
2175        serde_json::from_str(&json).unwrap()
2176    }
2177
2178    #[test]
2179    fn a_spot_trade_id_identifies_the_fill_not_the_transaction() {
2180        let first =
2181            fill_to_account_event(&spot_sweep_fill(111, "0.05"), &pair("PURR/USDC")).unwrap();
2182        let second =
2183            fill_to_account_event(&spot_sweep_fill(222, "0.051"), &pair("PURR/USDC")).unwrap();
2184
2185        let (AccountEventKind::Trade(first), AccountEventKind::Trade(second)) =
2186            (first.kind, second.kind)
2187        else {
2188            panic!("Expected Trade events");
2189        };
2190
2191        assert_eq!(first.order_id, second.order_id, "one order produced both");
2192        assert_ne!(first.id, second.id, "but they are distinct fills");
2193    }
2194
2195    #[test]
2196    fn a_replayed_spot_fill_is_delivered_once() {
2197        let cache = new_dedup_cache();
2198        let event =
2199            fill_to_account_event(&spot_sweep_fill(111, "0.05"), &pair("PURR/USDC")).unwrap();
2200        let replay =
2201            fill_to_account_event(&spot_sweep_fill(111, "0.05"), &pair("PURR/USDC")).unwrap();
2202
2203        assert!(!is_duplicate(&cache, dedup_key_from_event(&event).unwrap()));
2204        assert!(is_duplicate(&cache, dedup_key_from_event(&replay).unwrap()));
2205        // And the sibling fill of the same sweep still gets through.
2206        let sibling =
2207            fill_to_account_event(&spot_sweep_fill(222, "0.051"), &pair("PURR/USDC")).unwrap();
2208        assert!(!is_duplicate(
2209            &cache,
2210            dedup_key_from_event(&sibling).unwrap()
2211        ));
2212    }
2213
2214    #[test]
2215    fn test_order_update_to_account_event_spot() {
2216        let update_json = r#"{
2217            "order": {
2218                "coin": "@107",
2219                "side": "A",
2220                "limitPx": "25.5",
2221                "sz": "10",
2222                "oid": 12346,
2223                "timestamp": 1714100000000,
2224                "origSz": "10",
2225                "cloid": null
2226            },
2227            "status": "open",
2228            "statusTimestamp": 1714100000000
2229        }"#;
2230
2231        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2232        let event = order_update_to_account_event(&update, &pair("@107")).unwrap();
2233
2234        assert_eq!(event.exchange, ExchangeId::HyperliquidSpot);
2235        match event.kind {
2236            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2237                assert_eq!(order.key.instrument.as_ref(), "HYPE-USDC-SPOT");
2238                assert_eq!(order.side, Side::Sell);
2239                assert_eq!(order.price, Some(dec!(25.5)));
2240                assert_eq!(order.quantity, dec!(10));
2241                assert!(matches!(
2242                    order.state,
2243                    crate::order::state::OrderState::Active(_)
2244                ));
2245            }
2246            _ => panic!("Expected OrderSnapshot event"),
2247        }
2248    }
2249    /// A stream fill on `coin`, bought, with its fee in `fee_token`.
2250    fn stream_fill(coin: &str, fee_token: &str) -> hyperliquid_rust_sdk::TradeInfo {
2251        let json = format!(
2252            r#"{{
2253                "coin": "{coin}", "side": "B", "px": "25.5", "sz": "2",
2254                "time": 1714100000000, "hash": "0xindexed", "startPosition": "0",
2255                "dir": "Buy", "closedPnl": "0", "oid": 4343, "cloid": null,
2256                "crossed": true, "fee": "0.01", "feeToken": "{fee_token}", "tid": 333
2257            }}"#
2258        );
2259        serde_json::from_str(&json).unwrap()
2260    }
2261
2262    #[test]
2263    fn a_fill_on_an_indexed_coin_is_named_from_its_tokens() {
2264        let event = fill_to_account_event(&stream_fill("@107", "HYPE"), &pair("@107")).unwrap();
2265        let AccountEventKind::Trade(trade) = event.kind else {
2266            panic!("Expected Trade event");
2267        };
2268        assert_eq!(trade.instrument.as_ref(), "HYPE-USDC-SPOT");
2269        assert_eq!(trade.fees.asset.as_ref(), "HYPE");
2270        assert_eq!(
2271            trade.fees.fees_quote, None,
2272            "a fee in the base asset is not in quote"
2273        );
2274    }
2275
2276    #[test]
2277    fn a_fill_quoted_in_another_token_takes_its_quote_from_the_pair() {
2278        let event = fill_to_account_event(&stream_fill("@207", "USDT0"), &pair("@207")).unwrap();
2279        let AccountEventKind::Trade(trade) = event.kind else {
2280            panic!("Expected Trade event");
2281        };
2282        assert_eq!(trade.instrument.as_ref(), "HYPE-USDT0-SPOT");
2283        assert_eq!(
2284            trade.fees.fees_quote,
2285            Some(dec!(0.01)),
2286            "USDT0 is this pair's quote, not USDC"
2287        );
2288    }
2289
2290    /// Open-order rows on a perpetual, an indexed spot coin, PURR/USDC and an outcome coin, in
2291    /// the `openOrders` response's shape. Values are synthetic.
2292    fn open_order_rows(spot_coin: &str) -> Vec<OpenOrder> {
2293        serde_json::from_value(serde_json::json!([
2294            {"coin": "BTC", "side": "B", "limitPx": "50000", "sz": "0.1", "oid": 1,
2295             "timestamp": 1714100000000u64},
2296            {"coin": spot_coin, "side": "B", "limitPx": "25.5", "sz": "2", "oid": 2,
2297             "timestamp": 1714100000000u64},
2298            {"coin": "PURR/USDC", "side": "A", "limitPx": "0.05", "sz": "100", "oid": 3,
2299             "timestamp": 1714100000000u64},
2300            {"coin": "#12", "side": "B", "limitPx": "0.5", "sz": "10", "oid": 4,
2301             "timestamp": 1714100000000u64}
2302        ]))
2303        .unwrap()
2304    }
2305
2306    #[test]
2307    fn open_orders_on_indexed_coins_are_listed_and_other_markets_left_out() {
2308        let orders = spot_open_orders(&open_order_rows("@107"), &test_spot_pairs(), &[]).unwrap();
2309
2310        let instruments: Vec<_> = orders.iter().map(|o| o.key.instrument.as_ref()).collect();
2311        assert_eq!(instruments, ["HYPE-USDC-SPOT", "PURR-USDC-SPOT"]);
2312
2313        let hype_only = [InstrumentNameExchange::from("HYPE-USDC-SPOT")];
2314        let orders =
2315            spot_open_orders(&open_order_rows("@107"), &test_spot_pairs(), &hype_only).unwrap();
2316        assert_eq!(orders.len(), 1);
2317    }
2318
2319    #[test]
2320    fn an_open_order_on_a_spot_coin_missing_from_spot_meta_fails_the_list() {
2321        let result = spot_open_orders(&open_order_rows("@999"), &test_spot_pairs(), &[]);
2322        assert!(
2323            matches!(&result, Err(UnindexedClientError::Internal(msg)) if msg.contains("@999")),
2324            "a list missing an order must not read as complete: {result:?}"
2325        );
2326    }
2327
2328    /// `userFillsByTime` rows on a perpetual, an indexed spot coin and PURR/USDC, at
2329    /// [`fill_time`].
2330    fn user_fills(spot_coin: &str) -> Vec<UserFill> {
2331        serde_json::from_value(serde_json::json!([
2332            {"coin": "BTC", "side": "B", "px": "50000", "sz": "0.1", "time": 1714100000000u64,
2333             "oid": 1, "fee": "0.5", "feeToken": "USDC", "tid": 11},
2334            {"coin": spot_coin, "side": "B", "px": "25.5", "sz": "2", "time": 1714100000000u64,
2335             "oid": 2, "fee": "0.01", "feeToken": "HYPE", "tid": 12},
2336            {"coin": "PURR/USDC", "side": "A", "px": "0.05", "sz": "100",
2337             "time": 1714100000000u64, "oid": 3, "fee": "0.002", "tid": 13}
2338        ]))
2339        .unwrap()
2340    }
2341
2342    fn fill_time() -> DateTime<Utc> {
2343        millis_to_datetime(1714100000000).unwrap()
2344    }
2345
2346    #[test]
2347    fn trades_on_indexed_coins_are_read_with_assets_from_spot_meta() {
2348        let trades = spot_trades(
2349            &user_fills("@107"),
2350            &test_spot_pairs(),
2351            fill_time(),
2352            fill_time(),
2353            &[],
2354        )
2355        .unwrap();
2356
2357        let read: Vec<_> = trades
2358            .iter()
2359            .map(|t| (t.instrument.as_ref(), t.fees.asset.as_ref()))
2360            .collect();
2361        assert_eq!(
2362            read,
2363            [("HYPE-USDC-SPOT", "HYPE"), ("PURR-USDC-SPOT", "USDC")],
2364            "the perpetual is left out; PURR/USDC's missing feeToken falls back to the quote, \
2365             since it sold"
2366        );
2367    }
2368
2369    #[test]
2370    fn a_trade_on_a_spot_coin_missing_from_spot_meta_fails_the_read() {
2371        let result = spot_trades(
2372            &user_fills("@999"),
2373            &test_spot_pairs(),
2374            fill_time(),
2375            fill_time(),
2376            &[],
2377        );
2378        assert!(
2379            matches!(&result, Err(UnindexedClientError::Internal(msg)) if msg.contains("@999")),
2380            "a read missing a fill must not read as complete: {result:?}"
2381        );
2382    }
2383}