Skip to main content

guilder_client_hyperliquid/
client.rs

1use alloy_primitives::Address;
2use guilder_abstraction::{self, L2Update, Fill, AssetContext, PredictedFunding, Liquidation, BoxStream, Side, OrderSide, OrderStatus, OrderType, TimeInForce, OrderPlacement, Position, OpenOrder, UserFill, OrderUpdate, FundingPayment, Deposit, Withdrawal};
3use futures_util::{stream, SinkExt, StreamExt};
4use reqwest::Client;
5use rust_decimal::Decimal;
6use serde::Deserialize;
7use serde_json::Value;
8use std::collections::HashMap;
9use std::str::FromStr;
10use tokio_tungstenite::{connect_async, tungstenite::Message};
11
12const HYPERLIQUID_INFO_URL: &str = "https://api.hyperliquid.xyz/info";
13const HYPERLIQUID_EXCHANGE_URL: &str = "https://api.hyperliquid.xyz/exchange";
14const HYPERLIQUID_WS_URL: &str = "wss://api.hyperliquid.xyz/ws";
15
16async fn parse_response<T: for<'de> serde::Deserialize<'de>>(resp: reqwest::Response) -> Result<T, String> {
17    let text = resp.text().await.map_err(|e| e.to_string())?;
18    serde_json::from_str(&text).map_err(|e| format!("{e}: {text}"))
19}
20
21pub struct HyperliquidClient {
22    client: Client,
23    user_address: Option<Address>,
24    private_key: Option<String>,
25}
26
27impl HyperliquidClient {
28    pub fn new() -> Self {
29        HyperliquidClient { client: Client::new(), user_address: None, private_key: None }
30    }
31
32    pub fn with_auth(user_address: Address, private_key: String) -> Self {
33        HyperliquidClient { client: Client::new(), user_address: Some(user_address), private_key: Some(private_key) }
34    }
35
36    fn require_user_address(&self) -> Result<String, String> {
37        self.user_address
38            .map(|a| format!("{:#x}", a))
39            .ok_or_else(|| "user address required: use HyperliquidClient::with_auth".to_string())
40    }
41
42    fn require_private_key(&self) -> Result<&str, String> {
43        self.private_key.as_deref().ok_or_else(|| "private key required: use HyperliquidClient::with_auth".to_string())
44    }
45
46    async fn get_asset_index(&self, symbol: &str) -> Result<usize, String> {
47        let resp = self.client
48            .post(HYPERLIQUID_INFO_URL)
49            .json(&serde_json::json!({"type": "meta"}))
50            .send()
51            .await
52            .map_err(|e| e.to_string())?;
53        let meta: MetaResponse = parse_response(resp).await?;
54        meta.universe.iter()
55            .position(|a| a.name == symbol)
56            .ok_or_else(|| format!("symbol {} not found", symbol))
57    }
58
59    async fn submit_signed_action(&self, action: Value, vault_address: Option<&str>) -> Result<Value, String> {
60        let private_key = self.require_private_key()?;
61        let nonce = std::time::SystemTime::now()
62            .duration_since(std::time::UNIX_EPOCH)
63            .unwrap()
64            .as_millis() as u64;
65
66        let (r, s, v) = sign_action(private_key, &action, vault_address, nonce)?;
67
68        let payload = serde_json::json!({
69            "action": action,
70            "nonce": nonce,
71            "signature": {"r": r, "s": s, "v": v},
72            "vaultAddress": null
73        });
74
75        let resp = self.client
76            .post(HYPERLIQUID_EXCHANGE_URL)
77            .json(&payload)
78            .send()
79            .await
80            .map_err(|e| e.to_string())?;
81
82        let body: Value = parse_response(resp).await?;
83        if body["status"].as_str() == Some("err") {
84            return Err(body["response"].as_str().unwrap_or("unknown error").to_string());
85        }
86        Ok(body)
87    }
88}
89
90// --- REST deserialization types ---
91
92#[derive(Deserialize)]
93struct MetaResponse {
94    universe: Vec<AssetInfo>,
95}
96
97#[derive(Deserialize)]
98struct AssetInfo {
99    name: String,
100}
101
102type MetaAndAssetCtxsResponse = (MetaResponse, Vec<RestAssetCtx>);
103
104#[derive(Deserialize)]
105#[serde(rename_all = "camelCase")]
106#[allow(dead_code)]
107struct RestAssetCtx {
108    open_interest: String,
109    funding: String,
110    mark_px: String,
111    day_ntl_vlm: String,
112    mid_px: Option<String>,
113    oracle_px: Option<String>,
114    premium: Option<String>,
115    prev_day_px: Option<String>,
116}
117
118#[derive(Deserialize)]
119#[serde(rename_all = "camelCase")]
120struct ClearinghouseStateResponse {
121    margin_summary: MarginSummary,
122    asset_positions: Vec<AssetPosition>,
123}
124
125#[derive(Deserialize)]
126#[serde(rename_all = "camelCase")]
127struct MarginSummary {
128    account_value: String,
129}
130
131#[derive(Deserialize)]
132struct AssetPosition {
133    position: PositionDetail,
134}
135
136#[derive(Deserialize)]
137#[serde(rename_all = "camelCase")]
138struct PositionDetail {
139    coin: String,
140    /// positive = long, negative = short
141    szi: String,
142    entry_px: Option<String>,
143}
144
145#[derive(Deserialize)]
146#[serde(rename_all = "camelCase")]
147struct RestOpenOrder {
148    coin: String,
149    side: String,
150    limit_px: String,
151    sz: String,
152    oid: i64,
153    orig_sz: String,
154}
155
156// predictedFundings response: Vec<(coin, Vec<(venue, entry_or_null)>)>
157// The API returns null for venues that don't list the coin.
158type PredictedFundingsResponse = Vec<(String, Vec<(String, Option<PredictedFundingEntry>)>)>;
159
160#[derive(Deserialize)]
161#[serde(rename_all = "camelCase")]
162struct PredictedFundingEntry {
163    funding_rate: String,
164    next_funding_time: i64,
165}
166
167// --- WebSocket envelope and data shapes ---
168
169#[derive(Deserialize)]
170struct WsEnvelope {
171    channel: String,
172    data: Value,
173}
174
175#[derive(Deserialize)]
176struct WsBook {
177    coin: String,
178    levels: Vec<Vec<WsLevel>>,
179    time: i64,
180}
181
182#[derive(Deserialize)]
183struct WsLevel {
184    px: String,
185    sz: String,
186}
187
188#[derive(Deserialize)]
189#[serde(rename_all = "camelCase")]
190struct WsAssetCtx {
191    coin: String,
192    ctx: WsPerpsCtx,
193}
194
195#[derive(Deserialize)]
196#[serde(rename_all = "camelCase")]
197struct WsPerpsCtx {
198    open_interest: String,
199    funding: String,
200    mark_px: String,
201    day_ntl_vlm: String,
202    mid_px: Option<String>,
203    oracle_px: Option<String>,
204    premium: Option<String>,
205    prev_day_px: Option<String>,
206}
207
208#[derive(Deserialize)]
209struct WsUserEvent {
210    liquidation: Option<WsLiquidation>,
211    fills: Option<Vec<WsUserFill>>,
212    funding: Option<WsFunding>,
213}
214
215#[derive(Deserialize)]
216struct WsLiquidation {
217    liquidated_user: String,
218    liquidated_ntl_pos: String,
219    liquidated_account_value: String,
220}
221
222#[derive(Deserialize)]
223struct WsUserFill {
224    coin: String,
225    px: String,
226    sz: String,
227    side: String,
228    time: i64,
229    oid: i64,
230    fee: String,
231}
232
233#[derive(Deserialize)]
234struct WsFunding {
235    time: i64,
236    coin: String,
237    usdc: String,
238}
239
240#[derive(Deserialize)]
241struct WsTrade {
242    coin: String,
243    side: String,
244    px: String,
245    sz: String,
246    time: i64,
247    tid: i64,
248}
249
250#[derive(Deserialize)]
251struct WsOrderUpdate {
252    order: WsOrderInfo,
253    status: String,
254    #[serde(rename = "statusTimestamp")]
255    status_timestamp: i64,
256}
257
258#[derive(Deserialize)]
259#[serde(rename_all = "camelCase")]
260struct WsOrderInfo {
261    coin: String,
262    side: String,
263    limit_px: String,
264    sz: String,
265    oid: i64,
266    orig_sz: String,
267}
268
269// --- WebSocket ledger update shapes (deposits / withdrawals) ---
270
271#[derive(Deserialize)]
272struct WsLedgerUpdates {
273    updates: Vec<WsLedgerEntry>,
274}
275
276#[derive(Deserialize)]
277struct WsLedgerEntry {
278    time: i64,
279    delta: WsLedgerDelta,
280}
281
282#[derive(Deserialize)]
283struct WsLedgerDelta {
284    #[serde(rename = "type")]
285    kind: String,
286    usdc: Option<String>,
287}
288
289// --- Helpers ---
290
291fn parse_decimal(s: &str) -> Option<Decimal> {
292    Decimal::from_str(s).ok()
293}
294
295fn keccak256(data: &[u8]) -> [u8; 32] {
296    use sha3::{Digest, Keccak256};
297    Keccak256::digest(data).into()
298}
299
300/// EIP-712 domain separator for Hyperliquid mainnet (Arbitrum, chainId=42161).
301fn hyperliquid_domain_separator() -> [u8; 32] {
302    let type_hash = keccak256(b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
303    let name_hash = keccak256(b"Exchange");
304    let version_hash = keccak256(b"1");
305    let mut chain_id = [0u8; 32];
306    chain_id[28..32].copy_from_slice(&42161u32.to_be_bytes());
307    let verifying_contract = [0u8; 32];
308
309    let mut data = [0u8; 160];
310    data[..32].copy_from_slice(&type_hash);
311    data[32..64].copy_from_slice(&name_hash);
312    data[64..96].copy_from_slice(&version_hash);
313    data[96..128].copy_from_slice(&chain_id);
314    data[128..160].copy_from_slice(&verifying_contract);
315    keccak256(&data)
316}
317
318/// Signs a Hyperliquid exchange action using EIP-712.
319/// Returns (r, s, v) where r and s are "0x"-prefixed hex strings and v is 27 or 28.
320fn sign_action(private_key: &str, action: &Value, vault_address: Option<&str>, nonce: u64) -> Result<(String, String, u8), String> {
321    use k256::ecdsa::SigningKey;
322
323    // Step 1: msgpack-encode the action, append nonce + vault flag
324    let msgpack_bytes = rmp_serde::to_vec(action).map_err(|e| e.to_string())?;
325    let mut data = msgpack_bytes;
326    data.extend_from_slice(&nonce.to_be_bytes());
327    match vault_address {
328        None => data.push(0u8),
329        Some(addr) => {
330            data.push(1u8);
331            let addr_bytes = hex::decode(addr.trim_start_matches("0x"))
332                .map_err(|e| format!("invalid vault address: {}", e))?;
333            data.extend_from_slice(&addr_bytes);
334        }
335    }
336    let connection_id = keccak256(&data);
337
338    // Step 2: hash the Agent struct
339    let agent_type_hash = keccak256(b"Agent(string source,bytes32 connectionId)");
340    let source_hash = keccak256(b"a"); // "a" = mainnet
341    let mut struct_data = [0u8; 96];
342    struct_data[..32].copy_from_slice(&agent_type_hash);
343    struct_data[32..64].copy_from_slice(&source_hash);
344    struct_data[64..96].copy_from_slice(&connection_id);
345    let struct_hash = keccak256(&struct_data);
346
347    // Step 3: EIP-712 final hash
348    let domain_sep = hyperliquid_domain_separator();
349    let mut final_data = Vec::with_capacity(66);
350    final_data.extend_from_slice(b"\x19\x01");
351    final_data.extend_from_slice(&domain_sep);
352    final_data.extend_from_slice(&struct_hash);
353    let final_hash = keccak256(&final_data);
354
355    // Step 4: sign with secp256k1
356    let key_bytes = hex::decode(private_key.trim_start_matches("0x"))
357        .map_err(|e| format!("invalid private key: {}", e))?;
358    let signing_key = SigningKey::from_bytes(key_bytes.as_slice().into())
359        .map_err(|e| e.to_string())?;
360    let (sig, recovery_id) = signing_key.sign_prehash_recoverable(&final_hash)
361        .map_err(|e| e.to_string())?;
362
363    let sig_bytes = sig.to_bytes();
364    let r = format!("0x{}", hex::encode(&sig_bytes[..32]));
365    let s = format!("0x{}", hex::encode(&sig_bytes[32..64]));
366    let v = 27u8 + recovery_id.to_byte();
367
368    Ok((r, s, v))
369}
370
371// --- Trait implementations ---
372
373#[allow(async_fn_in_trait)]
374impl guilder_abstraction::TestServer for HyperliquidClient {
375    /// Sends a lightweight allMids request; returns true if the server responds 200 OK.
376    async fn ping(&self) -> Result<bool, String> {
377        self.client
378            .post(HYPERLIQUID_INFO_URL)
379            .json(&serde_json::json!({"type": "allMids"}))
380            .send()
381            .await
382            .map(|r| r.status().is_success())
383            .map_err(|e| e.to_string())
384    }
385
386    /// Hyperliquid has no dedicated server-time endpoint; returns local UTC ms.
387    async fn get_server_time(&self) -> Result<i64, String> {
388        Ok(std::time::SystemTime::now()
389            .duration_since(std::time::UNIX_EPOCH)
390            .map(|d| d.as_millis() as i64)
391            .unwrap_or(0))
392    }
393}
394
395#[allow(async_fn_in_trait)]
396impl guilder_abstraction::GetMarketData for HyperliquidClient {
397    /// Returns all perpetual asset names from Hyperliquid's meta endpoint.
398    async fn get_symbol(&self) -> Result<Vec<String>, String> {
399        let resp = self.client
400            .post(HYPERLIQUID_INFO_URL)
401            .json(&serde_json::json!({"type": "meta"}))
402            .send()
403            .await
404            .map_err(|e| e.to_string())?;
405        parse_response::<MetaResponse>(resp).await
406            .map(|r| r.universe.into_iter().map(|a| a.name).collect())
407    }
408
409    /// Returns the current open interest for `symbol` from metaAndAssetCtxs.
410    async fn get_open_interest(&self, symbol: String) -> Result<Decimal, String> {
411        let resp = self.client
412            .post(HYPERLIQUID_INFO_URL)
413            .json(&serde_json::json!({"type": "metaAndAssetCtxs"}))
414            .send()
415            .await
416            .map_err(|e| e.to_string())?;
417        let (meta, ctxs) = parse_response::<Option<MetaAndAssetCtxsResponse>>(resp).await?
418            .ok_or_else(|| "metaAndAssetCtxs returned null".to_string())?;
419        meta.universe.iter()
420            .position(|a| a.name == symbol)
421            .and_then(|i| ctxs.get(i))
422            .and_then(|ctx| parse_decimal(&ctx.open_interest))
423            .ok_or_else(|| format!("symbol {} not found", symbol))
424    }
425
426    /// Returns a full AssetContext snapshot for `symbol` from metaAndAssetCtxs.
427    async fn get_asset_context(&self, symbol: String) -> Result<AssetContext, String> {
428        let resp = self.client
429            .post(HYPERLIQUID_INFO_URL)
430            .json(&serde_json::json!({"type": "metaAndAssetCtxs"}))
431            .send()
432            .await
433            .map_err(|e| e.to_string())?;
434        let (meta, ctxs) = parse_response::<Option<MetaAndAssetCtxsResponse>>(resp).await?
435            .ok_or_else(|| "metaAndAssetCtxs returned null".to_string())?;
436        let idx = meta.universe.iter()
437            .position(|a| a.name == symbol)
438            .ok_or_else(|| format!("symbol {} not found", symbol))?;
439        let ctx = ctxs.get(idx).ok_or_else(|| format!("symbol {} not found", symbol))?;
440        Ok(AssetContext {
441            symbol,
442            open_interest: parse_decimal(&ctx.open_interest).ok_or("invalid open_interest")?,
443            funding_rate: parse_decimal(&ctx.funding).ok_or("invalid funding")?,
444            mark_price: parse_decimal(&ctx.mark_px).ok_or("invalid mark_px")?,
445            day_volume: parse_decimal(&ctx.day_ntl_vlm).ok_or("invalid day_ntl_vlm")?,
446            mid_price: ctx.mid_px.as_deref().and_then(parse_decimal),
447            oracle_price: ctx.oracle_px.as_deref().and_then(parse_decimal),
448            premium: ctx.premium.as_deref().and_then(parse_decimal),
449            prev_day_price: ctx.prev_day_px.as_deref().and_then(parse_decimal),
450        })
451    }
452
453    /// Returns a full L2 orderbook snapshot for `symbol` from the l2Book REST endpoint.
454    /// Levels are returned as individual `L2Update` items; all share the same `sequence` (timestamp).
455    async fn get_l2_orderbook(&self, symbol: String) -> Result<Vec<L2Update>, String> {
456        let resp = self.client
457            .post(HYPERLIQUID_INFO_URL)
458            .json(&serde_json::json!({"type": "l2Book", "coin": symbol}))
459            .send()
460            .await
461            .map_err(|e| e.to_string())?;
462        let book: WsBook = parse_response(resp).await?;
463        let mut levels = Vec::new();
464        for level in book.levels.first().into_iter().flatten() {
465            if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
466                levels.push(L2Update { symbol: book.coin.clone(), price, volume, side: Side::Ask, sequence: book.time });
467            }
468        }
469        for level in book.levels.get(1).into_iter().flatten() {
470            if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
471                levels.push(L2Update { symbol: book.coin.clone(), price, volume, side: Side::Bid, sequence: book.time });
472            }
473        }
474        Ok(levels)
475    }
476
477    /// Returns the mid-price of `symbol` (e.g. "BTC") from allMids.
478    async fn get_price(&self, symbol: String) -> Result<Decimal, String> {
479        let resp = self.client
480            .post(HYPERLIQUID_INFO_URL)
481            .json(&serde_json::json!({"type": "allMids"}))
482            .send()
483            .await
484            .map_err(|e| e.to_string())?;
485        parse_response::<HashMap<String, String>>(resp).await?
486            .get(&symbol)
487            .and_then(|s| parse_decimal(s))
488            .ok_or_else(|| format!("symbol {} not found", symbol))
489    }
490
491    /// Returns predicted funding rates for all symbols across all venues.
492    /// Null venue entries (unsupported coins) are silently skipped.
493    async fn get_predicted_fundings(&self) -> Result<Vec<PredictedFunding>, String> {
494        let resp = self.client
495            .post(HYPERLIQUID_INFO_URL)
496            .json(&serde_json::json!({"type": "predictedFundings"}))
497            .send()
498            .await
499            .map_err(|e| e.to_string())?;
500        let data: PredictedFundingsResponse = parse_response(resp).await?;
501        let mut result = Vec::new();
502        for (symbol, venues) in data {
503            for (venue, entry) in venues {
504                let Some(entry) = entry else { continue };
505                if let Some(funding_rate) = parse_decimal(&entry.funding_rate) {
506                    result.push(PredictedFunding {
507                        symbol: symbol.clone(),
508                        venue,
509                        funding_rate,
510                        next_funding_time_ms: entry.next_funding_time,
511                    });
512                }
513            }
514        }
515        Ok(result)
516    }
517}
518
519#[allow(async_fn_in_trait)]
520impl guilder_abstraction::ManageOrder for HyperliquidClient {
521    /// Places an order on Hyperliquid. Requires `with_auth`. Returns an `OrderPlacement` with
522    /// the exchange-assigned order ID. Market orders are submitted as aggressive limit orders (IOC).
523    async fn place_order(&self, symbol: String, side: OrderSide, price: Decimal, volume: Decimal, order_type: OrderType, time_in_force: TimeInForce) -> Result<OrderPlacement, String> {
524        let asset_idx = self.get_asset_index(&symbol).await?;
525        let is_buy = matches!(side, OrderSide::Buy);
526
527        let tif_str = match time_in_force {
528            TimeInForce::Gtc => "Gtc",
529            TimeInForce::Ioc => "Ioc",
530            TimeInForce::Fok => "Fok",
531        };
532        // Market orders are IOC limit orders at a wide price
533        let order_type_val = match order_type {
534            OrderType::Limit => serde_json::json!({"limit": {"tif": tif_str}}),
535            OrderType::Market => serde_json::json!({"limit": {"tif": "Ioc"}}),
536        };
537
538        let action = serde_json::json!({
539            "type": "order",
540            "orders": [{
541                "a": asset_idx,
542                "b": is_buy,
543                "p": price.to_string(),
544                "s": volume.to_string(),
545                "r": false,
546                "t": order_type_val
547            }],
548            "grouping": "na"
549        });
550
551        let resp = self.submit_signed_action(action, None).await?;
552        let oid = resp["response"]["data"]["statuses"][0]["resting"]["oid"]
553            .as_i64()
554            .or_else(|| resp["response"]["data"]["statuses"][0]["filled"]["oid"].as_i64())
555            .ok_or_else(|| format!("unexpected response: {}", resp))?;
556
557        let timestamp_ms = std::time::SystemTime::now()
558            .duration_since(std::time::UNIX_EPOCH)
559            .unwrap()
560            .as_millis() as i64;
561
562        Ok(OrderPlacement { order_id: oid, symbol, side, price, quantity: volume, timestamp_ms })
563    }
564
565    /// Modifies price and size of an existing order by its order ID. Requires `with_auth`.
566    /// Fetches the order's current coin and side before submitting the modify action.
567    async fn change_order_by_cloid(&self, cloid: i64, price: Decimal, volume: Decimal) -> Result<i64, String> {
568        let user = self.require_user_address()?;
569
570        let resp = self.client
571            .post(HYPERLIQUID_INFO_URL)
572            .json(&serde_json::json!({"type": "openOrders", "user": user}))
573            .send()
574            .await
575            .map_err(|e| e.to_string())?;
576        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
577        let order = orders.iter()
578            .find(|o| o.oid == cloid)
579            .ok_or_else(|| format!("order {} not found", cloid))?;
580
581        let asset_idx = self.get_asset_index(&order.coin).await?;
582        let is_buy = order.side == "B";
583
584        let action = serde_json::json!({
585            "type": "batchModify",
586            "modifies": [{
587                "oid": cloid,
588                "order": {
589                    "a": asset_idx,
590                    "b": is_buy,
591                    "p": price.to_string(),
592                    "s": volume.to_string(),
593                    "r": false,
594                    "t": {"limit": {"tif": "Gtc"}}
595                }
596            }]
597        });
598
599        self.submit_signed_action(action, None).await?;
600        Ok(cloid)
601    }
602
603    /// Cancels a single order by its order ID. Requires `with_auth`.
604    /// Fetches open orders to resolve the coin/asset before cancelling.
605    async fn cancel_order(&self, cloid: i64) -> Result<i64, String> {
606        let user = self.require_user_address()?;
607
608        let resp = self.client
609            .post(HYPERLIQUID_INFO_URL)
610            .json(&serde_json::json!({"type": "openOrders", "user": user}))
611            .send()
612            .await
613            .map_err(|e| e.to_string())?;
614        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
615        let order = orders.iter()
616            .find(|o| o.oid == cloid)
617            .ok_or_else(|| format!("order {} not found", cloid))?;
618
619        let asset_idx = self.get_asset_index(&order.coin).await?;
620        let action = serde_json::json!({
621            "type": "cancel",
622            "cancels": [{"a": asset_idx, "o": cloid}]
623        });
624
625        self.submit_signed_action(action, None).await?;
626        Ok(cloid)
627    }
628
629    /// Cancels all open orders. Requires `with_auth`.
630    /// Fetches all open orders and submits a batch cancel in a single signed request.
631    async fn cancel_all_order(&self) -> Result<bool, String> {
632        let user = self.require_user_address()?;
633
634        let resp = self.client
635            .post(HYPERLIQUID_INFO_URL)
636            .json(&serde_json::json!({"type": "openOrders", "user": user}))
637            .send()
638            .await
639            .map_err(|e| e.to_string())?;
640        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
641        if orders.is_empty() {
642            return Ok(true);
643        }
644
645        let meta_resp = self.client
646            .post(HYPERLIQUID_INFO_URL)
647            .json(&serde_json::json!({"type": "meta"}))
648            .send()
649            .await
650            .map_err(|e| e.to_string())?;
651        let meta: MetaResponse = parse_response(meta_resp).await?;
652
653        let cancels: Vec<Value> = orders.iter()
654            .filter_map(|o| {
655                let asset_idx = meta.universe.iter().position(|a| a.name == o.coin)?;
656                Some(serde_json::json!({"a": asset_idx, "o": o.oid}))
657            })
658            .collect();
659
660        let action = serde_json::json!({"type": "cancel", "cancels": cancels});
661        self.submit_signed_action(action, None).await?;
662        Ok(true)
663    }
664}
665
666#[allow(async_fn_in_trait)]
667impl guilder_abstraction::SubscribeMarketData for HyperliquidClient {
668    /// Streams L2 orderbook updates for `symbol`. Each message from Hyperliquid is a
669    /// full-depth snapshot; every level is emitted as an individual `L2Update` event.
670    /// All levels in the same snapshot share the same `sequence` value.
671    fn subscribe_l2_update(&self, symbol: String) -> BoxStream<L2Update> {
672        Box::pin(async_stream::stream! {
673            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
674            let sub = serde_json::json!({
675                "method": "subscribe",
676                "subscription": {"type": "l2Book", "coin": symbol}
677            });
678            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
679
680            while let Some(Ok(Message::Text(text))) = ws.next().await {
681                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
682                if env.channel != "l2Book" { continue; }
683                let Ok(book) = serde_json::from_value::<WsBook>(env.data) else { continue; };
684
685                for level in book.levels.first().into_iter().flatten() {
686                    if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
687                        yield L2Update { symbol: book.coin.clone(), price, volume, side: Side::Ask, sequence: book.time };
688                    }
689                }
690                for level in book.levels.get(1).into_iter().flatten() {
691                    if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
692                        yield L2Update { symbol: book.coin.clone(), price, volume, side: Side::Bid, sequence: book.time };
693                    }
694                }
695            }
696        })
697    }
698
699    /// Streams asset context updates for `symbol` via Hyperliquid's `activeAssetCtx` subscription.
700    fn subscribe_asset_context(&self, symbol: String) -> BoxStream<AssetContext> {
701        Box::pin(async_stream::stream! {
702            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
703            let sub = serde_json::json!({
704                "method": "subscribe",
705                "subscription": {"type": "activeAssetCtx", "coin": symbol}
706            });
707            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
708
709            while let Some(Ok(Message::Text(text))) = ws.next().await {
710                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
711                if env.channel != "activeAssetCtx" { continue; }
712                let Ok(update) = serde_json::from_value::<WsAssetCtx>(env.data) else { continue; };
713                let ctx = &update.ctx;
714                if let (Some(open_interest), Some(funding_rate), Some(mark_price), Some(day_volume)) = (
715                    parse_decimal(&ctx.open_interest),
716                    parse_decimal(&ctx.funding),
717                    parse_decimal(&ctx.mark_px),
718                    parse_decimal(&ctx.day_ntl_vlm),
719                ) {
720                    yield AssetContext {
721                        symbol: update.coin,
722                        open_interest,
723                        funding_rate,
724                        mark_price,
725                        day_volume,
726                        mid_price: ctx.mid_px.as_deref().and_then(parse_decimal),
727                        oracle_price: ctx.oracle_px.as_deref().and_then(parse_decimal),
728                        premium: ctx.premium.as_deref().and_then(parse_decimal),
729                        prev_day_price: ctx.prev_day_px.as_deref().and_then(parse_decimal),
730                    };
731                }
732            }
733        })
734    }
735
736    /// Streams liquidation events for a user address via Hyperliquid's `userEvents` subscription.
737    /// Hyperliquid's liquidation event is account-level; `symbol` is empty and `side` is `Sell`.
738    fn subscribe_liquidation(&self, user: String) -> BoxStream<Liquidation> {
739        Box::pin(async_stream::stream! {
740            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
741            let sub = serde_json::json!({
742                "method": "subscribe",
743                "subscription": {"type": "userEvents", "user": user}
744            });
745            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
746
747            while let Some(Ok(Message::Text(text))) = ws.next().await {
748                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
749                if env.channel != "userEvents" { continue; }
750                let Ok(event) = serde_json::from_value::<WsUserEvent>(env.data) else { continue; };
751                let Some(liq) = event.liquidation else { continue; };
752                if let (Some(notional_position), Some(account_value)) = (
753                    parse_decimal(&liq.liquidated_ntl_pos),
754                    parse_decimal(&liq.liquidated_account_value),
755                ) {
756                    yield Liquidation {
757                        symbol: String::new(),
758                        side: OrderSide::Sell,
759                        liquidated_user: liq.liquidated_user,
760                        notional_position,
761                        account_value,
762                    };
763                }
764            }
765        })
766    }
767
768    /// Streams public trade fills for `symbol`. "B" (buyer aggressor) → Buy, otherwise → Sell.
769    fn subscribe_fill(&self, symbol: String) -> BoxStream<Fill> {
770        Box::pin(async_stream::stream! {
771            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
772            let sub = serde_json::json!({
773                "method": "subscribe",
774                "subscription": {"type": "trades", "coin": symbol}
775            });
776            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
777
778            while let Some(Ok(Message::Text(text))) = ws.next().await {
779                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
780                if env.channel != "trades" { continue; }
781                let Ok(trades) = serde_json::from_value::<Vec<WsTrade>>(env.data) else { continue; };
782
783                for trade in trades {
784                    let side = if trade.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
785                    if let (Some(price), Some(volume)) = (parse_decimal(&trade.px), parse_decimal(&trade.sz)) {
786                        yield Fill { symbol: trade.coin, price, volume, side, timestamp_ms: trade.time, trade_id: trade.tid };
787                    }
788                }
789            }
790        })
791    }
792}
793
794#[allow(async_fn_in_trait)]
795impl guilder_abstraction::GetAccountSnapshot for HyperliquidClient {
796    /// Returns open positions from `clearinghouseState`. Requires `with_auth`.
797    /// Zero-size positions are filtered out. Positive `szi` = long, negative = short.
798    async fn get_positions(&self) -> Result<Vec<Position>, String> {
799        let user = self.require_user_address()?;
800        let resp = self.client
801            .post(HYPERLIQUID_INFO_URL)
802            .json(&serde_json::json!({"type": "clearinghouseState", "user": user}))
803            .send()
804            .await
805            .map_err(|e| e.to_string())?;
806        let state: ClearinghouseStateResponse = parse_response(resp).await?;
807
808        Ok(state.asset_positions.into_iter()
809            .filter_map(|ap| {
810                let p = ap.position;
811                let size = parse_decimal(&p.szi)?;
812                if size.is_zero() { return None; }
813                let entry_price = p.entry_px.as_deref().and_then(parse_decimal).unwrap_or_default();
814                let side = if size > Decimal::ZERO { OrderSide::Buy } else { OrderSide::Sell };
815                Some(Position { symbol: p.coin, side, size: size.abs(), entry_price })
816            })
817            .collect())
818    }
819
820    /// Returns resting orders from Hyperliquid's `openOrders` endpoint. Requires `with_auth`.
821    /// `filled_quantity` is derived as `origSz - sz` (original size minus remaining size).
822    async fn get_open_orders(&self) -> Result<Vec<OpenOrder>, String> {
823        let user = self.require_user_address()?;
824        let resp = self.client
825            .post(HYPERLIQUID_INFO_URL)
826            .json(&serde_json::json!({"type": "openOrders", "user": user}))
827            .send()
828            .await
829            .map_err(|e| e.to_string())?;
830        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
831
832        Ok(orders.into_iter()
833            .filter_map(|o| {
834                let price = parse_decimal(&o.limit_px)?;
835                let quantity = parse_decimal(&o.orig_sz)?;
836                let remaining = parse_decimal(&o.sz)?;
837                let filled_quantity = quantity - remaining;
838                let side = if o.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
839                Some(OpenOrder { order_id: o.oid, symbol: o.coin, side, price, quantity, filled_quantity })
840            })
841            .collect())
842    }
843
844    /// Returns total account value (collateral) from `clearinghouseState`. Requires `with_auth`.
845    async fn get_collateral(&self) -> Result<Decimal, String> {
846        let user = self.require_user_address()?;
847        let resp = self.client
848            .post(HYPERLIQUID_INFO_URL)
849            .json(&serde_json::json!({"type": "clearinghouseState", "user": user}))
850            .send()
851            .await
852            .map_err(|e| e.to_string())?;
853        let state: ClearinghouseStateResponse = parse_response(resp).await?;
854        parse_decimal(&state.margin_summary.account_value)
855            .ok_or_else(|| "invalid account value".to_string())
856    }
857}
858
859#[allow(async_fn_in_trait)]
860impl guilder_abstraction::SubscribeUserEvents for HyperliquidClient {
861    /// Streams the user's own order executions via the `userEvents` WS subscription.
862    /// Requires `with_auth` (streams are empty if no user address is set).
863    fn subscribe_user_fills(&self) -> BoxStream<UserFill> {
864        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
865        let user = format!("{:#x}", addr);
866        Box::pin(async_stream::stream! {
867            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
868            let sub = serde_json::json!({
869                "method": "subscribe",
870                "subscription": {"type": "userEvents", "user": user}
871            });
872            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
873
874            while let Some(Ok(Message::Text(text))) = ws.next().await {
875                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
876                if env.channel != "userEvents" { continue; }
877                let Ok(event) = serde_json::from_value::<WsUserEvent>(env.data) else { continue; };
878                for fill in event.fills.unwrap_or_default() {
879                    let side = if fill.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
880                    if let (Some(price), Some(quantity), Some(fee_usd)) = (
881                        parse_decimal(&fill.px),
882                        parse_decimal(&fill.sz),
883                        parse_decimal(&fill.fee),
884                    ) {
885                        yield UserFill { order_id: fill.oid, symbol: fill.coin, side, price, quantity, fee_usd, timestamp_ms: fill.time };
886                    }
887                }
888            }
889        })
890    }
891
892    /// Streams order lifecycle events via the `orderUpdates` WS subscription.
893    /// Requires `with_auth`.
894    fn subscribe_order_updates(&self) -> BoxStream<OrderUpdate> {
895        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
896        let user = format!("{:#x}", addr);
897        Box::pin(async_stream::stream! {
898            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
899            let sub = serde_json::json!({
900                "method": "subscribe",
901                "subscription": {"type": "orderUpdates", "user": user}
902            });
903            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
904
905            while let Some(Ok(Message::Text(text))) = ws.next().await {
906                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
907                if env.channel != "orderUpdates" { continue; }
908                let Ok(updates) = serde_json::from_value::<Vec<WsOrderUpdate>>(env.data) else { continue; };
909                for upd in updates {
910                    let status = match upd.status.as_str() {
911                        "open" => OrderStatus::Placed,
912                        "filled" => OrderStatus::Filled,
913                        "canceled" | "cancelled" => OrderStatus::Cancelled,
914                        _ => OrderStatus::PartiallyFilled,
915                    };
916                    let side = if upd.order.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
917                    yield OrderUpdate {
918                        order_id: upd.order.oid,
919                        symbol: upd.order.coin,
920                        status,
921                        side: Some(side),
922                        price: parse_decimal(&upd.order.limit_px),
923                        quantity: parse_decimal(&upd.order.orig_sz),
924                        remaining_quantity: parse_decimal(&upd.order.sz),
925                        timestamp_ms: upd.status_timestamp,
926                    };
927                }
928            }
929        })
930    }
931
932    /// Streams funding payments applied to positions via the `userEvents` WS subscription.
933    /// Requires `with_auth`.
934    fn subscribe_funding_payments(&self) -> BoxStream<FundingPayment> {
935        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
936        let user = format!("{:#x}", addr);
937        Box::pin(async_stream::stream! {
938            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
939            let sub = serde_json::json!({
940                "method": "subscribe",
941                "subscription": {"type": "userEvents", "user": user}
942            });
943            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
944
945            while let Some(Ok(Message::Text(text))) = ws.next().await {
946                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
947                if env.channel != "userEvents" { continue; }
948                let Ok(event) = serde_json::from_value::<WsUserEvent>(env.data) else { continue; };
949                let Some(funding) = event.funding else { continue; };
950                if let Some(amount_usd) = parse_decimal(&funding.usdc) {
951                    yield FundingPayment { symbol: funding.coin, amount_usd, timestamp_ms: funding.time };
952                }
953            }
954        })
955    }
956
957    fn subscribe_deposits(&self) -> BoxStream<Deposit> {
958        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
959        let user = format!("{:#x}", addr);
960        Box::pin(async_stream::stream! {
961            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
962            let sub = serde_json::json!({
963                "method": "subscribe",
964                "subscription": {"type": "userNonFundingLedgerUpdates", "user": user}
965            });
966            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
967            while let Some(Ok(Message::Text(text))) = ws.next().await {
968                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
969                if env.channel != "userNonFundingLedgerUpdates" { continue; }
970                let Ok(ledger) = serde_json::from_value::<WsLedgerUpdates>(env.data) else { continue; };
971                for entry in ledger.updates {
972                    if entry.delta.kind == "deposit" {
973                        if let Some(amount_usd) = entry.delta.usdc.as_deref().and_then(parse_decimal) {
974                            yield Deposit { asset: "USDC".to_string(), amount_usd, timestamp_ms: entry.time };
975                        }
976                    }
977                }
978            }
979        })
980    }
981
982    fn subscribe_withdrawals(&self) -> BoxStream<Withdrawal> {
983        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
984        let user = format!("{:#x}", addr);
985        Box::pin(async_stream::stream! {
986            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
987            let sub = serde_json::json!({
988                "method": "subscribe",
989                "subscription": {"type": "userNonFundingLedgerUpdates", "user": user}
990            });
991            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
992            while let Some(Ok(Message::Text(text))) = ws.next().await {
993                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
994                if env.channel != "userNonFundingLedgerUpdates" { continue; }
995                let Ok(ledger) = serde_json::from_value::<WsLedgerUpdates>(env.data) else { continue; };
996                for entry in ledger.updates {
997                    if entry.delta.kind == "withdraw" {
998                        if let Some(amount_usd) = entry.delta.usdc.as_deref().and_then(parse_decimal) {
999                            yield Withdrawal { asset: "USDC".to_string(), amount_usd, timestamp_ms: entry.time };
1000                        }
1001                    }
1002                }
1003            }
1004        })
1005    }
1006}