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_rejection};
89use super::order_recovery::{
90    ReconnectWatch, fetch_order_record, listed_cids, lookup_from_record, remember_open,
91    remember_snapshot, send_fills, send_observed, spawn_order_checks,
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},
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 (transport)");
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                        warn!("Spot order accepted but no order ID returned");
1020                        OrderState::inactive(OrderError::Rejected(
1021                            crate::error::ApiError::OrderRejected(
1022                                "no order ID in response".to_string(),
1023                            ),
1024                        ))
1025                    }
1026                }
1027            }
1028            ExchangeResponseStatus::Err(msg) => {
1029                warn!(%msg, "Spot order rejected");
1030                OrderState::inactive(OrderError::Rejected(order_rejection(msg)))
1031            }
1032        };
1033
1034        let order = Order {
1035            key: OrderKey {
1036                exchange: ExchangeId::HyperliquidSpot,
1037                instrument: request.key.instrument.clone(),
1038                strategy: request.key.strategy.clone(),
1039                cid: request.key.cid.clone(),
1040            },
1041            side: request.state.side,
1042            price: request.state.price,
1043            quantity: request.state.quantity,
1044            kind: request.state.kind,
1045            time_in_force: request.state.time_in_force,
1046            state,
1047        };
1048        self.known_live
1049            .lock()
1050            .placed(&order.key, order.quantity, order.kind, &order.state);
1051        order
1052    }
1053
1054    async fn fetch_balances(
1055        &self,
1056        _assets: &[AssetNameExchange],
1057    ) -> Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError> {
1058        let address = self.wallet_h160();
1059
1060        let token_balances = self
1061            .info_client
1062            .user_token_balances(address)
1063            .await
1064            .map_err(map_sdk_error)?;
1065
1066        let now = Utc::now();
1067        Ok(spot_balances(&token_balances.balances, now).collect())
1068    }
1069
1070    async fn fetch_open_orders(
1071        &self,
1072        instruments: &[InstrumentNameExchange],
1073    ) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
1074        let address = self.wallet_h160();
1075
1076        let open_orders = open_orders(&self.info_client, address).await?;
1077        let pairs = self
1078            .spot_coins
1079            .covering(open_orders.iter().map(|order| order.coin.as_str()))
1080            .await;
1081
1082        let orders = spot_open_orders(&open_orders, &pairs, instruments)?;
1083        remember_open(&self.known_live, &orders);
1084        Ok(orders)
1085    }
1086
1087    /// Reads the span with `userFillsByTime`, to its end within the call, so the read is always
1088    /// complete (`resume: None`). Hyperliquid keeps only each wallet's 10,000 most recent fills,
1089    /// so a span reaching further back is read only as far as those go, and
1090    /// [`held_since`](TradesRead::held_since) says where that is.
1091    async fn fetch_trades(
1092        &self,
1093        start: DateTime<Utc>,
1094        end: DateTime<Utc>,
1095        instruments: &[InstrumentNameExchange],
1096    ) -> Result<TradesRead<AssetNameExchange, InstrumentNameExchange>, UnindexedClientError> {
1097        let Some((start_ms, end_ms)) = span_millis(start, end) else {
1098            return Ok(TradesRead::complete(Vec::new()));
1099        };
1100        let address = self.wallet_h160();
1101
1102        let fills = user_fills_by_time(&self.info_client, address, start_ms, end_ms).await?;
1103        let held_since = super::common::held_since(&fills, start_ms);
1104        let pairs = self
1105            .spot_coins
1106            .covering(fills.iter().map(|fill| fill.coin.as_str()))
1107            .await;
1108
1109        spot_trades(&fills, &pairs, start, end, instruments)
1110            .map(|trades| TradesRead::complete(trades).with_held_since(held_since))
1111    }
1112}
1113
1114/// Looks each order up with `orderStatus` (weight 2), as
1115/// [`HyperliquidClient`](super::HyperliquidClient) does; see its implementation for how each
1116/// status is reported. An order on a spot coin missing from `spotMeta` even after it is read again
1117/// (see [Spot coins](self#spot-coins)) fails the call, since it cannot be told apart from an order
1118/// on the key's instrument.
1119///
1120/// The account stream runs the same lookup itself after a reconnect; see
1121/// [`account_stream`](ExecutionClient::account_stream).
1122impl OrderStatusClient for HyperliquidSpotClient {
1123    async fn fetch_ended_orders(
1124        &self,
1125        orders: &[UnindexedOrderKey],
1126    ) -> Result<Vec<UnindexedInactiveOrder>, UnindexedClientError> {
1127        let address = self.wallet_h160();
1128        fetch_ended_by_key(orders, |key| {
1129            spot_order_lookup(
1130                self.info_client.clone(),
1131                self.spot_coins.clone(),
1132                address,
1133                key,
1134            )
1135        })
1136        .await
1137    }
1138}
1139
1140/// Look the order under `key` up with `orderStatus`, on the spot pair its coin names.
1141///
1142/// # Errors
1143///
1144/// When the lookup fails, or the order is on a spot coin missing from `spotMeta`.
1145async fn spot_order_lookup(
1146    info_client: Arc<InfoClient>,
1147    spot_coins: SpotCoins,
1148    address: ethers::types::H160,
1149    key: UnindexedOrderKey,
1150) -> Result<OrderLookup, UnindexedClientError> {
1151    let Some(record) = fetch_order_record(&info_client, address, &key.cid).await? else {
1152        return Ok(OrderLookup::Unknown);
1153    };
1154    let coin = record.order.coin.as_str();
1155    let pairs = spot_coins.covering([coin]).await;
1156    let instrument = spot_pair(&pairs, coin)?.map(spot_pair_to_instrument);
1157    Ok(lookup_from_record(key, &record, instrument))
1158}
1159
1160/// The client order ids `openOrders` (weight 20) lists on the spot `instruments`, for a
1161/// reconnect's check of the orders held as live. An order on a spot coin missing from `spotMeta` is
1162/// left out (see `listed_cids`).
1163///
1164/// # Errors
1165///
1166/// When the listing fails.
1167async fn spot_listed_cids(
1168    info_client: Arc<InfoClient>,
1169    spot_coins: SpotCoins,
1170    address: ethers::types::H160,
1171    instruments: Vec<InstrumentNameExchange>,
1172) -> Result<FnvHashSet<ClientOrderId>, UnindexedClientError> {
1173    let rows = open_orders(&info_client, address).await?;
1174    let pairs = spot_coins
1175        .covering(rows.iter().map(|row| row.coin.as_str()))
1176        .await;
1177    Ok(listed_cids(&rows, &instruments, |coin| {
1178        pairs.get(coin).map(spot_pair_to_instrument)
1179    }))
1180}
1181
1182/// Convert the open-order rows on spot pairs, keeping those on `instruments` (every one when
1183/// empty). Rows on other markets are left out.
1184///
1185/// # Errors
1186///
1187/// When a row is on a spot coin missing from `pairs` (see [`spot_pair`]).
1188fn spot_open_orders(
1189    rows: &[OpenOrder],
1190    pairs: &SpotPairs,
1191    instruments: &[InstrumentNameExchange],
1192) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
1193    let instrument_filter = InstrumentFilter::new(instruments);
1194
1195    let mut orders = Vec::new();
1196    for order in rows {
1197        let Some(pair) = spot_pair(pairs, &order.coin)? else {
1198            continue;
1199        };
1200        let instrument = spot_pair_to_instrument(pair);
1201        if !instrument_filter.matches(&instrument) {
1202            continue;
1203        }
1204        orders.extend(open_order_to_order(
1205            order,
1206            ExchangeId::HyperliquidSpot,
1207            instrument,
1208        ));
1209    }
1210    Ok(orders)
1211}
1212
1213/// Convert the fills on spot pairs within `start..=end`, keeping those on `instruments` (every one
1214/// when empty). Fills on other markets, and fills that do not parse, are left out.
1215///
1216/// # Errors
1217///
1218/// When a fill is on a spot coin missing from `pairs` (see [`spot_pair`]).
1219fn spot_trades(
1220    fills: &[UserFill],
1221    pairs: &SpotPairs,
1222    start: DateTime<Utc>,
1223    end: DateTime<Utc>,
1224    instruments: &[InstrumentNameExchange],
1225) -> Result<Vec<Trade<AssetNameExchange, InstrumentNameExchange>>, UnindexedClientError> {
1226    let instrument_filter = InstrumentFilter::new(instruments);
1227
1228    let mut result = Vec::new();
1229    for fill in fills {
1230        let Some(pair) = spot_pair(pairs, &fill.coin)? else {
1231            continue;
1232        };
1233        let (base_asset, quote_asset) = (pair.base(), pair.quote());
1234        let instrument = spot_pair_to_instrument(pair);
1235
1236        if !instrument_filter.matches(&instrument) {
1237            continue;
1238        }
1239
1240        let Some(side) = parse_side(&fill.side) else {
1241            continue;
1242        };
1243        let Some(price) = parse_decimal(&fill.px, "px") else {
1244            continue;
1245        };
1246        let Some(quantity) = parse_decimal(&fill.sz, "sz") else {
1247            continue;
1248        };
1249        let fee = parse_decimal(&fill.fee, "fee").unwrap_or(Decimal::ZERO);
1250
1251        let Some(time_exchange) = millis_to_datetime(fill.time) else {
1252            warn!(time = fill.time, "Invalid fill timestamp, skipping");
1253            continue;
1254        };
1255        if !(start..=end).contains(&time_exchange) {
1256            continue;
1257        }
1258
1259        // Prefer what the venue says the fee was charged in. The side-based rule below is
1260        // only a guess — spot buys usually pay in base and sells in quote, but a fee can be
1261        // charged in a third asset — and it is reachable only if `feeToken` is absent, which
1262        // has not been observed.
1263        let fee_asset = fill
1264            .fee_token
1265            .as_deref()
1266            .unwrap_or(if matches!(side, Side::Buy) {
1267                base_asset
1268            } else {
1269                quote_asset
1270            });
1271
1272        result.push(Trade {
1273            id: TradeId(format_smolstr!("{}", fill.tid)),
1274            order_id: OrderId(format_smolstr!("{}", fill.oid)),
1275            instrument,
1276            strategy: StrategyId::unknown(),
1277            time_exchange,
1278            side,
1279            price,
1280            quantity,
1281            // `TradeInfo` carries no cumulative filled quantity; Hyperliquid reports order
1282            // state as its own `OrderUpdate` message.
1283            order_filled_quantity: None,
1284            fees: AssetFees {
1285                asset: AssetNameExchange::from(fee_asset),
1286                fees: fee,
1287                // Only set quote-equivalent when the fee is actually denominated in
1288                // the quote asset. The downstream indexer recomputes for base-asset fees.
1289                //
1290                // Case-insensitive, matching the stream path: `fee_asset` is now the venue's
1291                // own `feeToken` rather than a substring of `coin`, so it is no longer equal
1292                // to `quote_asset` byte-for-byte by construction.
1293                fees_quote: if fee_asset.eq_ignore_ascii_case(quote_asset) {
1294                    Some(fee)
1295                } else {
1296                    None
1297                },
1298            },
1299            // As on the stream, whose copy of a fill usually arrives first; see `TradeOrigin`.
1300            origin: TradeOrigin::Order,
1301            position_side: None,
1302            client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1303        });
1304    }
1305
1306    Ok(result)
1307}
1308
1309/// Convert SDK TradeInfo (fill) on `pair` to AccountEvent::Trade for spot.
1310fn fill_to_account_event(
1311    fill: &hyperliquid_rust_sdk::TradeInfo,
1312    pair: &SpotPair,
1313) -> Option<UnindexedAccountEvent> {
1314    let side = parse_side(&fill.side)?;
1315    let price = parse_decimal(&fill.px, "fill.px")?;
1316    let quantity = parse_decimal(&fill.sz, "fill.sz")?;
1317    let fee = parse_decimal(&fill.fee, "fill.fee").unwrap_or(Decimal::ZERO);
1318    let time_exchange = millis_to_datetime(fill.time)?;
1319
1320    let quote_asset = pair.quote();
1321    let instrument = spot_pair_to_instrument(pair);
1322    let order_id = OrderId(format_smolstr!("{}", fill.oid));
1323
1324    // SDK's `TradeInfo` exposes `fee_token` directly, which is the asset the fee is
1325    // denominated in (typically base asset for buys, quote asset for sells).
1326    let fee_asset = fill.fee_token.as_str();
1327
1328    let trade = Trade {
1329        id: TradeId(format_smolstr!("{}", fill.tid)),
1330        order_id,
1331        instrument,
1332        strategy: StrategyId::unknown(),
1333        time_exchange,
1334        side,
1335        price,
1336        quantity,
1337        // `TradeInfo` carries no cumulative filled quantity, so the order's state must be learned
1338        // from an `OrderUpdate` -- which Hyperliquid sends as its own message.
1339        order_filled_quantity: None,
1340        fees: AssetFees {
1341            asset: AssetNameExchange::from(fee_asset),
1342            fees: fee,
1343            // Only set quote-equivalent when the fee is actually denominated in
1344            // the quote asset. The downstream indexer recomputes for base-asset fees.
1345            fees_quote: if fee_asset.eq_ignore_ascii_case(quote_asset) {
1346                Some(fee)
1347            } else {
1348                None
1349            },
1350        },
1351        // The SDK's `TradeInfo` drops the fill's liquidation marker, so every fill is reported
1352        // as `Order`; see `TradeOrigin`.
1353        origin: TradeOrigin::Order,
1354        position_side: None,
1355        client_order_id: fill.cloid.as_deref().and_then(cloid_to_cid),
1356    };
1357
1358    Some(AccountEvent::new(
1359        ExchangeId::HyperliquidSpot,
1360        AccountEventKind::Trade(trade),
1361    ))
1362}
1363
1364/// Convert SDK OrderUpdate on `pair` to AccountEvent::OrderSnapshot for spot.
1365fn order_update_to_account_event(
1366    update: &hyperliquid_rust_sdk::OrderUpdate,
1367    pair: &SpotPair,
1368) -> Option<UnindexedAccountEvent> {
1369    super::common::order_update_to_account_event(
1370        update,
1371        ExchangeId::HyperliquidSpot,
1372        spot_pair_to_instrument(pair),
1373    )
1374}
1375
1376#[cfg(test)]
1377// Test code: panics on bad input are acceptable
1378#[allow(clippy::unwrap_used)]
1379mod tests {
1380    use super::super::spot_coins::test_spot_pairs;
1381    use crate::client::dedup::{dedup_key_from_event, is_duplicate};
1382
1383    mod order_recovery {
1384        use super::super::super::common::info_tests::info_client_against;
1385        use super::super::super::order_recovery::tests::{CID, CLOID, record_json, row};
1386        use super::super::super::spot_coins::TEST_SPOT_META;
1387        use super::*;
1388        use crate::order::state::InactiveOrderState;
1389        use wiremock::matchers::{body_string_contains, method, path};
1390        use wiremock::{Mock, MockServer, ResponseTemplate};
1391
1392        /// A server answering `spotMeta` with [`TEST_SPOT_META`] and every other info request
1393        /// with `body`, and the spot coins read from it.
1394        async fn serve(body: serde_json::Value) -> (MockServer, Arc<InfoClient>, SpotCoins) {
1395            let server = MockServer::start().await;
1396            Mock::given(method("POST"))
1397                .and(path("/info"))
1398                .and(body_string_contains("spotMeta"))
1399                .respond_with(
1400                    ResponseTemplate::new(200).set_body_raw(TEST_SPOT_META, "application/json"),
1401                )
1402                .with_priority(1)
1403                .mount(&server)
1404                .await;
1405            Mock::given(method("POST"))
1406                .and(path("/info"))
1407                .respond_with(ResponseTemplate::new(200).set_body_json(body))
1408                .with_priority(2)
1409                .mount(&server)
1410                .await;
1411            let client = Arc::new(info_client_against(server.uri()).await);
1412            let coins = SpotCoins::fetch(client.clone()).await.unwrap();
1413            (server, client, coins)
1414        }
1415
1416        fn key() -> UnindexedOrderKey {
1417            OrderKey {
1418                exchange: ExchangeId::HyperliquidSpot,
1419                instrument: InstrumentNameExchange::new("HYPE-USDC-SPOT"),
1420                strategy: StrategyId::new("strategy"),
1421                cid: ClientOrderId::new(CID),
1422            }
1423        }
1424
1425        fn order_status(coin: &str) -> serde_json::Value {
1426            serde_json::json!({
1427                "status": "order",
1428                "order": record_json(coin, "canceled", "0.01", Some(CLOID)),
1429            })
1430        }
1431
1432        #[tokio::test]
1433        async fn a_spot_lookup_names_the_pair_from_spot_meta() {
1434            let (_server, client, coins) = serve(order_status("@107")).await;
1435
1436            let lookup = spot_order_lookup(client, coins, ethers::types::H160::zero(), key())
1437                .await
1438                .unwrap();
1439
1440            let OrderLookup::Ended(order) = lookup else {
1441                panic!("expected an ended order, got {lookup:?}");
1442            };
1443            assert_eq!(order.key, key());
1444            assert!(matches!(order.state, InactiveOrderState::Cancelled(_)));
1445        }
1446
1447        #[tokio::test]
1448        async fn a_spot_lookup_of_a_perp_order_is_unknown() {
1449            let (_server, client, coins) = serve(order_status("BTC")).await;
1450
1451            let lookup = spot_order_lookup(client, coins, ethers::types::H160::zero(), key())
1452                .await
1453                .unwrap();
1454
1455            assert!(matches!(lookup, OrderLookup::Unknown));
1456        }
1457
1458        #[tokio::test]
1459        async fn a_spot_lookup_fails_on_a_coin_missing_from_spot_meta() {
1460            let (_server, client, coins) = serve(order_status("@999")).await;
1461
1462            let lookup = spot_order_lookup(client, coins, ethers::types::H160::zero(), key()).await;
1463
1464            assert!(lookup.is_err());
1465        }
1466
1467        #[tokio::test]
1468        async fn a_spot_listing_names_only_the_orders_on_the_pairs_asked_about() {
1469            let rows = serde_json::json!([
1470                row("@107", 1, Some(CLOID)),
1471                row("@207", 2, None),
1472                row("BTC", 3, None),
1473            ]);
1474            let (_server, client, coins) = serve(rows).await;
1475
1476            let listed = spot_listed_cids(
1477                client,
1478                coins,
1479                ethers::types::H160::zero(),
1480                vec![InstrumentNameExchange::new("HYPE-USDC-SPOT")],
1481            )
1482            .await
1483            .unwrap();
1484
1485            assert_eq!(
1486                listed.into_iter().collect::<Vec<_>>(),
1487                [ClientOrderId::new(CID)]
1488            );
1489        }
1490
1491        #[tokio::test]
1492        async fn a_spot_listing_leaves_out_a_coin_missing_from_spot_meta() {
1493            let rows = serde_json::json!([row("@999", 1, None), row("@107", 2, Some(CLOID))]);
1494            let (_server, client, coins) = serve(rows).await;
1495
1496            let listed = spot_listed_cids(
1497                client,
1498                coins,
1499                ethers::types::H160::zero(),
1500                vec![InstrumentNameExchange::new("HYPE-USDC-SPOT")],
1501            )
1502            .await
1503            .unwrap();
1504
1505            assert_eq!(
1506                listed.into_iter().collect::<Vec<_>>(),
1507                [ClientOrderId::new(CID)]
1508            );
1509        }
1510    }
1511
1512    mod open_order {
1513        use super::super::super::common::info_tests::{
1514            exchange_client_against, info_client_against, test_wallet,
1515        };
1516        use super::super::super::config::Network;
1517        use super::super::super::spot_coins::TEST_SPOT_META;
1518        use super::*;
1519        use crate::error::{ApiError, OrderField, PrecisionLimit, PrecisionViolation};
1520        use crate::order::{OrderEvent, request::RequestOpen, state::InactiveOrderState};
1521        use std::collections::HashMap;
1522        use wiremock::matchers::{method, path};
1523        use wiremock::{Mock, MockServer, ResponseTemplate};
1524
1525        /// A spot client on [`TEST_SPOT_META`]'s pairs whose exchange endpoint rests every order.
1526        async fn resting_client() -> (MockServer, HyperliquidSpotClient) {
1527            client_responding(serde_json::json!({
1528                "status": "ok",
1529                "response": {"type": "order", "data": {"statuses": [{"resting": {"oid": 77}}]}},
1530            }))
1531            .await
1532        }
1533
1534        /// A spot client on [`TEST_SPOT_META`]'s pairs whose exchange endpoint answers every
1535        /// request with `body`.
1536        async fn client_responding(body: serde_json::Value) -> (MockServer, HyperliquidSpotClient) {
1537            let server = MockServer::start().await;
1538            Mock::given(method("POST"))
1539                .and(path("/info"))
1540                .respond_with(
1541                    ResponseTemplate::new(200).set_body_raw(TEST_SPOT_META, "application/json"),
1542                )
1543                .mount(&server)
1544                .await;
1545            Mock::given(method("POST"))
1546                .and(path("/exchange"))
1547                .respond_with(ResponseTemplate::new(200).set_body_json(body))
1548                .mount(&server)
1549                .await;
1550            let info_client = Arc::new(info_client_against(server.uri()).await);
1551            let client = HyperliquidSpotClient {
1552                config: HyperliquidConfig::new(test_wallet(), Network::Testnet),
1553                spot_coins: SpotCoins::fetch(info_client.clone()).await.unwrap(),
1554                info_client,
1555                exchange_client: Arc::new(
1556                    exchange_client_against(
1557                        server.uri(),
1558                        HashMap::from([("HYPE/USDC".to_owned(), 10_107)]),
1559                    )
1560                    .await,
1561                ),
1562                known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidSpot),
1563            };
1564            (server, client)
1565        }
1566
1567        /// A spot order refused for want of balance is a balance shortfall, as on other venues;
1568        /// any other refusal stays a rejection. Hyperliquid names no asset. The refusal is read
1569        /// both as an order's status and as the error of the whole response.
1570        #[tokio::test]
1571        async fn a_spot_order_refused_for_balance_is_balance_insufficient() {
1572            const BALANCE: &str = "Order has insufficient spot balance to trade";
1573            const MINIMUM: &str = "Order must have minimum value of 10 USDC.";
1574            for (body, expected) in [
1575                (
1576                    serde_json::json!({
1577                        "status": "ok",
1578                        "response": {"type": "order", "data": {"statuses": [{"error": BALANCE}]}},
1579                    }),
1580                    ApiError::BalanceInsufficient(None, BALANCE.to_owned()),
1581                ),
1582                (
1583                    serde_json::json!({"status": "err", "response": BALANCE}),
1584                    ApiError::BalanceInsufficient(None, BALANCE.to_owned()),
1585                ),
1586                (
1587                    serde_json::json!({
1588                        "status": "ok",
1589                        "response": {"type": "order", "data": {"statuses": [{"error": MINIMUM}]}},
1590                    }),
1591                    ApiError::OrderRejected(MINIMUM.to_owned()),
1592                ),
1593            ] {
1594                let (_server, client) = client_responding(body.clone()).await;
1595                let order = place_hype(&client, dec!(10), dec!(1)).await;
1596                let OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1597                    reported,
1598                ))) = &order.state
1599                else {
1600                    panic!("{body}: expected a rejection, got {:?}", order.state);
1601                };
1602                assert_eq!(reported, &expected, "{body}");
1603            }
1604        }
1605
1606        async fn place_hype(
1607            client: &HyperliquidSpotClient,
1608            price: Decimal,
1609            quantity: Decimal,
1610        ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1611            place(client, "HYPE-USDC-SPOT", price, quantity).await
1612        }
1613
1614        async fn place(
1615            client: &HyperliquidSpotClient,
1616            instrument: &str,
1617            price: Decimal,
1618            quantity: Decimal,
1619        ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
1620            let instrument = InstrumentNameExchange::new(instrument);
1621            client
1622                .open_order(OrderEvent {
1623                    key: OrderKey {
1624                        exchange: ExchangeId::HyperliquidSpot,
1625                        instrument: &instrument,
1626                        strategy: StrategyId::new("strategy"),
1627                        cid: ClientOrderId::uuid(),
1628                    },
1629                    state: RequestOpen::new(
1630                        Side::Buy,
1631                        Some(price),
1632                        quantity,
1633                        OrderKind::Limit,
1634                        TimeInForce::GoodUntilCancelled { post_only: false },
1635                    ),
1636                })
1637                .await
1638        }
1639
1640        /// The orders the server was sent, as the SDK wrote them.
1641        async fn sent_orders(server: &MockServer) -> Vec<serde_json::Value> {
1642            server
1643                .received_requests()
1644                .await
1645                .unwrap_or_default()
1646                .into_iter()
1647                .filter(|request| request.url.path() == "/exchange")
1648                .map(|request| {
1649                    let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
1650                    body["action"]["orders"][0].clone()
1651                })
1652                .collect()
1653        }
1654
1655        #[tokio::test]
1656        async fn every_margin_effect_is_refused_without_sending() {
1657            use crate::margin::MarginEffect;
1658
1659            let (server, client) = resting_client().await;
1660            let instrument = InstrumentNameExchange::new("HYPE-USDC-SPOT");
1661
1662            for effect in [
1663                MarginEffect::NoSideEffect,
1664                MarginEffect::Borrow,
1665                MarginEffect::Repay,
1666            ] {
1667                let order = client
1668                    .open_order(OrderEvent {
1669                        key: OrderKey {
1670                            exchange: ExchangeId::HyperliquidSpot,
1671                            instrument: &instrument,
1672                            strategy: StrategyId::new("strategy"),
1673                            cid: ClientOrderId::uuid(),
1674                        },
1675                        state: RequestOpen::new(
1676                            Side::Buy,
1677                            Some(dec!(10)),
1678                            dec!(2),
1679                            OrderKind::Limit,
1680                            TimeInForce::GoodUntilCancelled { post_only: false },
1681                        )
1682                        .with_margin_effect(effect),
1683                    })
1684                    .await;
1685
1686                assert!(
1687                    matches!(
1688                        order.state,
1689                        OrderState::Inactive(InactiveOrderState::OpenFailed(
1690                            OrderError::UnsupportedMarginEffect(refused)
1691                        )) if refused == effect
1692                    ),
1693                    "{order:?}"
1694                );
1695            }
1696            assert!(sent_orders(&server).await.is_empty());
1697        }
1698
1699        #[tokio::test]
1700        async fn a_spot_pairs_precision_is_its_base_tokens() {
1701            let (_server, client) = resting_client().await;
1702
1703            assert_eq!(
1704                client
1705                    .order_precision(&InstrumentNameExchange::new("HYPE-USDC-SPOT"))
1706                    .await,
1707                Some(OrderPrecision::spot(2))
1708            );
1709            assert_eq!(
1710                client
1711                    .order_precision(&InstrumentNameExchange::new("PURR-USDC-SPOT"))
1712                    .await,
1713                Some(OrderPrecision::spot(0))
1714            );
1715            assert_eq!(
1716                client
1717                    .order_precision(&InstrumentNameExchange::new("BTC-USDC-PERP"))
1718                    .await,
1719                None
1720            );
1721        }
1722
1723        #[tokio::test]
1724        async fn a_spot_order_spelling_the_pair_differently_is_refused_unsent() {
1725            let (server, client) = resting_client().await;
1726
1727            // Hyperliquid spells the pair HYPE/USDC, and reports its orders under HYPE-USDC-SPOT.
1728            for instrument in ["hype-usdc-SPOT", "Hype-USDC-SPOT"] {
1729                let order = place(&client, instrument, dec!(25), dec!(1)).await;
1730                assert_eq!(
1731                    order.state,
1732                    OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1733                        ApiError::InstrumentInvalid(
1734                            InstrumentNameExchange::new(instrument),
1735                            "Hyperliquid spells this spot pair HYPE/USDC, and reports its orders \
1736                             under HYPE-USDC-SPOT; name the instrument that way"
1737                                .to_owned(),
1738                        )
1739                    )))
1740                );
1741                assert_eq!(
1742                    client
1743                        .order_precision(&InstrumentNameExchange::new(instrument))
1744                        .await,
1745                    None
1746                );
1747            }
1748            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1749        }
1750
1751        #[tokio::test]
1752        async fn a_spot_order_on_an_unlisted_pair_is_refused_unsent() {
1753            let (server, client) = resting_client().await;
1754
1755            let order = place(&client, "HYPE-PURR-SPOT", dec!(25), dec!(1)).await;
1756            assert_eq!(
1757                order.state,
1758                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
1759                    ApiError::InstrumentInvalid(
1760                        InstrumentNameExchange::new("HYPE-PURR-SPOT"),
1761                        "Hyperliquid's spotMeta lists no spot pair HYPE/PURR".to_owned(),
1762                    )
1763                )))
1764            );
1765            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1766        }
1767
1768        #[tokio::test]
1769        async fn a_spot_order_breaking_the_precision_rules_is_refused_unsent() {
1770            let (server, client) = resting_client().await;
1771
1772            // HYPE's szDecimals is 2, so a size has at most 2 decimal places and a price 6.
1773            for (price, quantity, violation) in [
1774                (
1775                    dec!(25),
1776                    dec!(1.234),
1777                    PrecisionViolation {
1778                        field: OrderField::Quantity,
1779                        value: dec!(1.234),
1780                        limit: PrecisionLimit::DecimalPlaces { max: 2 },
1781                    },
1782                ),
1783                (
1784                    dec!(25.1234567),
1785                    dec!(1),
1786                    PrecisionViolation {
1787                        field: OrderField::Price,
1788                        value: dec!(25.1234567),
1789                        limit: PrecisionLimit::DecimalPlaces { max: 6 },
1790                    },
1791                ),
1792            ] {
1793                let order = place_hype(&client, price, quantity).await;
1794                assert_eq!(
1795                    order.state,
1796                    OrderState::Inactive(InactiveOrderState::OpenFailed(
1797                        OrderError::InvalidPrecision(violation)
1798                    ))
1799                );
1800            }
1801            assert_eq!(sent_orders(&server).await, Vec::<serde_json::Value>::new());
1802        }
1803
1804        #[tokio::test]
1805        async fn a_valid_spot_order_is_sent_unchanged() {
1806            let (server, client) = resting_client().await;
1807
1808            let order = place_hype(&client, dec!(25.123), dec!(1.25)).await;
1809            assert!(
1810                matches!(order.state, OrderState::Active(_)),
1811                "{:?}",
1812                order.state
1813            );
1814
1815            let sent = sent_orders(&server).await;
1816            assert_eq!(sent.len(), 1);
1817            assert_eq!(
1818                (&sent[0]["p"], &sent[0]["s"]),
1819                (&serde_json::json!("25.123"), &serde_json::json!("1.25"))
1820            );
1821        }
1822    }
1823
1824    mod cancel {
1825        use super::super::super::common::info_tests::{
1826            CANCEL_NOT_APPLIED, cancel_answer, exchange_client_against, info_client_against,
1827            test_wallet,
1828        };
1829        use super::super::super::config::Network;
1830        use super::super::super::spot_coins::TEST_SPOT_META;
1831        use super::*;
1832        use crate::error::ApiError;
1833        use crate::order::{OrderEvent, request::RequestCancel};
1834        use std::collections::HashMap;
1835        use wiremock::matchers::{method, path};
1836        use wiremock::{Mock, MockServer, ResponseTemplate};
1837
1838        /// Cancel a live `HYPE-USDC-SPOT` order through a client whose exchange endpoint answers
1839        /// `answer`. Returns the response, and whether the order is still held live afterwards.
1840        async fn cancel_answered(
1841            answer: serde_json::Value,
1842        ) -> (UnindexedOrderResponseCancel, bool) {
1843            let server = MockServer::start().await;
1844            Mock::given(method("POST"))
1845                .and(path("/info"))
1846                .respond_with(
1847                    ResponseTemplate::new(200).set_body_raw(TEST_SPOT_META, "application/json"),
1848                )
1849                .mount(&server)
1850                .await;
1851            Mock::given(method("POST"))
1852                .and(path("/exchange"))
1853                .respond_with(ResponseTemplate::new(200).set_body_json(answer))
1854                .mount(&server)
1855                .await;
1856            let info_client = Arc::new(info_client_against(server.uri()).await);
1857            let client = HyperliquidSpotClient {
1858                config: HyperliquidConfig::new(test_wallet(), Network::Testnet),
1859                spot_coins: SpotCoins::fetch(info_client.clone()).await.unwrap(),
1860                info_client,
1861                exchange_client: Arc::new(
1862                    exchange_client_against(
1863                        server.uri(),
1864                        HashMap::from([("HYPE/USDC".to_owned(), 10_107)]),
1865                    )
1866                    .await,
1867                ),
1868                known_live: KnownLiveOrders::shared(ExchangeId::HyperliquidSpot),
1869            };
1870            let instrument = InstrumentNameExchange::new("HYPE-USDC-SPOT");
1871            let key = OrderKey {
1872                exchange: ExchangeId::HyperliquidSpot,
1873                instrument: instrument.clone(),
1874                strategy: StrategyId::new("strategy"),
1875                cid: ClientOrderId::uuid(),
1876            };
1877            let id = VenueOrderId::Assigned(OrderId::new("7"));
1878            let open = Open {
1879                id: id.clone(),
1880                time_exchange: Utc::now(),
1881                filled_quantity: Decimal::ZERO,
1882            };
1883            client
1884                .known_live
1885                .lock()
1886                .live(&key, dec!(1), OrderKind::Limit, &open);
1887
1888            let response = client
1889                .cancel_order(OrderEvent {
1890                    key: OrderKey {
1891                        exchange: key.exchange,
1892                        instrument: &instrument,
1893                        strategy: key.strategy.clone(),
1894                        cid: key.cid.clone(),
1895                    },
1896                    state: RequestCancel { id: Some(id) },
1897                })
1898                .await;
1899            let live = client.known_live.lock().contains(&key.cid);
1900            (response, live)
1901        }
1902
1903        #[tokio::test]
1904        async fn a_success_status_cancels_the_spot_order() {
1905            let (response, live) =
1906                cancel_answered(cancel_answer(serde_json::json!(["success"]))).await;
1907            assert!(response.state.is_ok(), "{:?}", response.state);
1908            assert!(!live, "a cancelled order is no longer held live");
1909        }
1910
1911        /// An order that filled before the cancel arrived is answered this way, so it must not be
1912        /// reported cancelled, and stays held live until the account stream or a lookup ends it.
1913        #[tokio::test]
1914        async fn an_error_status_is_a_rejected_spot_cancel_and_the_order_stays_live() {
1915            let (response, live) = cancel_answered(cancel_answer(serde_json::json!([
1916                {"error": CANCEL_NOT_APPLIED}
1917            ])))
1918            .await;
1919            let Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(reason))) =
1920                &response.state
1921            else {
1922                panic!("expected a rejected cancel, got {:?}", response.state);
1923            };
1924            assert_eq!(reason, CANCEL_NOT_APPLIED);
1925            assert!(live, "the order is still held live");
1926        }
1927
1928        #[tokio::test]
1929        async fn an_answer_without_a_status_is_a_rejected_spot_cancel() {
1930            let (response, live) = cancel_answered(serde_json::json!({
1931                "status": "ok",
1932                "response": {"type": "cancel"},
1933            }))
1934            .await;
1935            assert!(
1936                matches!(
1937                    response.state,
1938                    Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(_)))
1939                ),
1940                "{:?}",
1941                response.state
1942            );
1943            assert!(live, "the order is still held live");
1944        }
1945    }
1946
1947    use super::*;
1948    use rust_decimal_macros::dec;
1949    use rustrade_integration::collection::snapshot::Snapshot;
1950
1951    /// The pair `coin` names in [`test_spot_pairs`].
1952    fn pair(coin: &str) -> SpotPair {
1953        test_spot_pairs().get(coin).unwrap().clone()
1954    }
1955
1956    #[test]
1957    fn test_fill_to_account_event_spot() {
1958        let fill_json = r#"{
1959            "coin": "PURR/USDC",
1960            "side": "B",
1961            "px": "0.05",
1962            "sz": "1000",
1963            "time": 1714100000000,
1964            "hash": "0xspot123",
1965            "startPosition": "0",
1966            "dir": "Open Long",
1967            "closedPnl": "0",
1968            "oid": 12345,
1969            "cloid": null,
1970            "crossed": false,
1971            "fee": "0.025",
1972            "feeToken": "USDC",
1973            "tid": 99999
1974        }"#;
1975
1976        let fill: hyperliquid_rust_sdk::TradeInfo = serde_json::from_str(fill_json).unwrap();
1977        let event = fill_to_account_event(&fill, &pair("PURR/USDC")).unwrap();
1978
1979        assert_eq!(event.exchange, ExchangeId::HyperliquidSpot);
1980        match event.kind {
1981            AccountEventKind::Trade(trade) => {
1982                assert_eq!(trade.instrument.as_ref(), "PURR-USDC-SPOT");
1983                assert_eq!(
1984                    trade.id.0, "99999",
1985                    "the id is the fill's tid, not its hash"
1986                );
1987                assert_eq!(trade.side, Side::Buy);
1988                assert_eq!(trade.price, dec!(0.05));
1989                assert_eq!(trade.quantity, dec!(1000));
1990                assert_eq!(trade.fees.fees, dec!(0.025));
1991                assert_eq!(trade.fees.asset.as_ref(), "USDC");
1992            }
1993            _ => panic!("Expected Trade event"),
1994        }
1995    }
1996
1997    /// Build a spot `TradeInfo` sharing one transaction hash with its siblings.
1998    fn spot_sweep_fill(tid: u64, px: &str) -> hyperliquid_rust_sdk::TradeInfo {
1999        let json = format!(
2000            r#"{{
2001                "coin": "PURR/USDC", "side": "B", "px": "{px}", "sz": "1000",
2002                "time": 1714100000000, "hash": "0xonesweep", "startPosition": "0",
2003                "dir": "Open Long", "closedPnl": "0", "oid": 4242, "cloid": null,
2004                "crossed": true, "fee": "0.025", "feeToken": "USDC", "tid": {tid}
2005            }}"#
2006        );
2007        serde_json::from_str(&json).unwrap()
2008    }
2009
2010    #[test]
2011    fn a_spot_trade_id_identifies_the_fill_not_the_transaction() {
2012        let first =
2013            fill_to_account_event(&spot_sweep_fill(111, "0.05"), &pair("PURR/USDC")).unwrap();
2014        let second =
2015            fill_to_account_event(&spot_sweep_fill(222, "0.051"), &pair("PURR/USDC")).unwrap();
2016
2017        let (AccountEventKind::Trade(first), AccountEventKind::Trade(second)) =
2018            (first.kind, second.kind)
2019        else {
2020            panic!("Expected Trade events");
2021        };
2022
2023        assert_eq!(first.order_id, second.order_id, "one order produced both");
2024        assert_ne!(first.id, second.id, "but they are distinct fills");
2025    }
2026
2027    #[test]
2028    fn a_replayed_spot_fill_is_delivered_once() {
2029        let cache = new_dedup_cache();
2030        let event =
2031            fill_to_account_event(&spot_sweep_fill(111, "0.05"), &pair("PURR/USDC")).unwrap();
2032        let replay =
2033            fill_to_account_event(&spot_sweep_fill(111, "0.05"), &pair("PURR/USDC")).unwrap();
2034
2035        assert!(!is_duplicate(&cache, dedup_key_from_event(&event).unwrap()));
2036        assert!(is_duplicate(&cache, dedup_key_from_event(&replay).unwrap()));
2037        // And the sibling fill of the same sweep still gets through.
2038        let sibling =
2039            fill_to_account_event(&spot_sweep_fill(222, "0.051"), &pair("PURR/USDC")).unwrap();
2040        assert!(!is_duplicate(
2041            &cache,
2042            dedup_key_from_event(&sibling).unwrap()
2043        ));
2044    }
2045
2046    #[test]
2047    fn test_order_update_to_account_event_spot() {
2048        let update_json = r#"{
2049            "order": {
2050                "coin": "@107",
2051                "side": "A",
2052                "limitPx": "25.5",
2053                "sz": "10",
2054                "oid": 12346,
2055                "timestamp": 1714100000000,
2056                "origSz": "10",
2057                "cloid": null
2058            },
2059            "status": "open",
2060            "statusTimestamp": 1714100000000
2061        }"#;
2062
2063        let update: hyperliquid_rust_sdk::OrderUpdate = serde_json::from_str(update_json).unwrap();
2064        let event = order_update_to_account_event(&update, &pair("@107")).unwrap();
2065
2066        assert_eq!(event.exchange, ExchangeId::HyperliquidSpot);
2067        match event.kind {
2068            AccountEventKind::OrderSnapshot(Snapshot(order)) => {
2069                assert_eq!(order.key.instrument.as_ref(), "HYPE-USDC-SPOT");
2070                assert_eq!(order.side, Side::Sell);
2071                assert_eq!(order.price, Some(dec!(25.5)));
2072                assert_eq!(order.quantity, dec!(10));
2073                assert!(matches!(
2074                    order.state,
2075                    crate::order::state::OrderState::Active(_)
2076                ));
2077            }
2078            _ => panic!("Expected OrderSnapshot event"),
2079        }
2080    }
2081    /// A stream fill on `coin`, bought, with its fee in `fee_token`.
2082    fn stream_fill(coin: &str, fee_token: &str) -> hyperliquid_rust_sdk::TradeInfo {
2083        let json = format!(
2084            r#"{{
2085                "coin": "{coin}", "side": "B", "px": "25.5", "sz": "2",
2086                "time": 1714100000000, "hash": "0xindexed", "startPosition": "0",
2087                "dir": "Buy", "closedPnl": "0", "oid": 4343, "cloid": null,
2088                "crossed": true, "fee": "0.01", "feeToken": "{fee_token}", "tid": 333
2089            }}"#
2090        );
2091        serde_json::from_str(&json).unwrap()
2092    }
2093
2094    #[test]
2095    fn a_fill_on_an_indexed_coin_is_named_from_its_tokens() {
2096        let event = fill_to_account_event(&stream_fill("@107", "HYPE"), &pair("@107")).unwrap();
2097        let AccountEventKind::Trade(trade) = event.kind else {
2098            panic!("Expected Trade event");
2099        };
2100        assert_eq!(trade.instrument.as_ref(), "HYPE-USDC-SPOT");
2101        assert_eq!(trade.fees.asset.as_ref(), "HYPE");
2102        assert_eq!(
2103            trade.fees.fees_quote, None,
2104            "a fee in the base asset is not in quote"
2105        );
2106    }
2107
2108    #[test]
2109    fn a_fill_quoted_in_another_token_takes_its_quote_from_the_pair() {
2110        let event = fill_to_account_event(&stream_fill("@207", "USDT0"), &pair("@207")).unwrap();
2111        let AccountEventKind::Trade(trade) = event.kind else {
2112            panic!("Expected Trade event");
2113        };
2114        assert_eq!(trade.instrument.as_ref(), "HYPE-USDT0-SPOT");
2115        assert_eq!(
2116            trade.fees.fees_quote,
2117            Some(dec!(0.01)),
2118            "USDT0 is this pair's quote, not USDC"
2119        );
2120    }
2121
2122    /// Open-order rows on a perpetual, an indexed spot coin, PURR/USDC and an outcome coin, in
2123    /// the `openOrders` response's shape. Values are synthetic.
2124    fn open_order_rows(spot_coin: &str) -> Vec<OpenOrder> {
2125        serde_json::from_value(serde_json::json!([
2126            {"coin": "BTC", "side": "B", "limitPx": "50000", "sz": "0.1", "oid": 1,
2127             "timestamp": 1714100000000u64},
2128            {"coin": spot_coin, "side": "B", "limitPx": "25.5", "sz": "2", "oid": 2,
2129             "timestamp": 1714100000000u64},
2130            {"coin": "PURR/USDC", "side": "A", "limitPx": "0.05", "sz": "100", "oid": 3,
2131             "timestamp": 1714100000000u64},
2132            {"coin": "#12", "side": "B", "limitPx": "0.5", "sz": "10", "oid": 4,
2133             "timestamp": 1714100000000u64}
2134        ]))
2135        .unwrap()
2136    }
2137
2138    #[test]
2139    fn open_orders_on_indexed_coins_are_listed_and_other_markets_left_out() {
2140        let orders = spot_open_orders(&open_order_rows("@107"), &test_spot_pairs(), &[]).unwrap();
2141
2142        let instruments: Vec<_> = orders.iter().map(|o| o.key.instrument.as_ref()).collect();
2143        assert_eq!(instruments, ["HYPE-USDC-SPOT", "PURR-USDC-SPOT"]);
2144
2145        let hype_only = [InstrumentNameExchange::from("HYPE-USDC-SPOT")];
2146        let orders =
2147            spot_open_orders(&open_order_rows("@107"), &test_spot_pairs(), &hype_only).unwrap();
2148        assert_eq!(orders.len(), 1);
2149    }
2150
2151    #[test]
2152    fn an_open_order_on_a_spot_coin_missing_from_spot_meta_fails_the_list() {
2153        let result = spot_open_orders(&open_order_rows("@999"), &test_spot_pairs(), &[]);
2154        assert!(
2155            matches!(&result, Err(UnindexedClientError::Internal(msg)) if msg.contains("@999")),
2156            "a list missing an order must not read as complete: {result:?}"
2157        );
2158    }
2159
2160    /// `userFillsByTime` rows on a perpetual, an indexed spot coin and PURR/USDC, at
2161    /// [`fill_time`].
2162    fn user_fills(spot_coin: &str) -> Vec<UserFill> {
2163        serde_json::from_value(serde_json::json!([
2164            {"coin": "BTC", "side": "B", "px": "50000", "sz": "0.1", "time": 1714100000000u64,
2165             "oid": 1, "fee": "0.5", "feeToken": "USDC", "tid": 11},
2166            {"coin": spot_coin, "side": "B", "px": "25.5", "sz": "2", "time": 1714100000000u64,
2167             "oid": 2, "fee": "0.01", "feeToken": "HYPE", "tid": 12},
2168            {"coin": "PURR/USDC", "side": "A", "px": "0.05", "sz": "100",
2169             "time": 1714100000000u64, "oid": 3, "fee": "0.002", "tid": 13}
2170        ]))
2171        .unwrap()
2172    }
2173
2174    fn fill_time() -> DateTime<Utc> {
2175        millis_to_datetime(1714100000000).unwrap()
2176    }
2177
2178    #[test]
2179    fn trades_on_indexed_coins_are_read_with_assets_from_spot_meta() {
2180        let trades = spot_trades(
2181            &user_fills("@107"),
2182            &test_spot_pairs(),
2183            fill_time(),
2184            fill_time(),
2185            &[],
2186        )
2187        .unwrap();
2188
2189        let read: Vec<_> = trades
2190            .iter()
2191            .map(|t| (t.instrument.as_ref(), t.fees.asset.as_ref()))
2192            .collect();
2193        assert_eq!(
2194            read,
2195            [("HYPE-USDC-SPOT", "HYPE"), ("PURR-USDC-SPOT", "USDC")],
2196            "the perpetual is left out; PURR/USDC's missing feeToken falls back to the quote, \
2197             since it sold"
2198        );
2199    }
2200
2201    #[test]
2202    fn a_trade_on_a_spot_coin_missing_from_spot_meta_fails_the_read() {
2203        let result = spot_trades(
2204            &user_fills("@999"),
2205            &test_spot_pairs(),
2206            fill_time(),
2207            fill_time(),
2208            &[],
2209        );
2210        assert!(
2211            matches!(&result, Err(UnindexedClientError::Internal(msg)) if msg.contains("@999")),
2212            "a read missing a fill must not read as complete: {result:?}"
2213        );
2214    }
2215}