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::<MetaAndAssetCtxsResponse>(resp).await?;
418        meta.universe.iter()
419            .position(|a| a.name == symbol)
420            .and_then(|i| ctxs.get(i))
421            .and_then(|ctx| parse_decimal(&ctx.open_interest))
422            .ok_or_else(|| format!("symbol {} not found", symbol))
423    }
424
425    /// Returns a full AssetContext snapshot for `symbol` from metaAndAssetCtxs.
426    async fn get_asset_context(&self, symbol: String) -> Result<AssetContext, String> {
427        let resp = self.client
428            .post(HYPERLIQUID_INFO_URL)
429            .json(&serde_json::json!({"type": "metaAndAssetCtxs"}))
430            .send()
431            .await
432            .map_err(|e| e.to_string())?;
433        let (meta, ctxs) = parse_response::<MetaAndAssetCtxsResponse>(resp).await?;
434        let idx = meta.universe.iter()
435            .position(|a| a.name == symbol)
436            .ok_or_else(|| format!("symbol {} not found", symbol))?;
437        let ctx = ctxs.get(idx).ok_or_else(|| format!("symbol {} not found", symbol))?;
438        Ok(AssetContext {
439            symbol,
440            open_interest: parse_decimal(&ctx.open_interest).ok_or("invalid open_interest")?,
441            funding_rate: parse_decimal(&ctx.funding).ok_or("invalid funding")?,
442            mark_price: parse_decimal(&ctx.mark_px).ok_or("invalid mark_px")?,
443            day_volume: parse_decimal(&ctx.day_ntl_vlm).ok_or("invalid day_ntl_vlm")?,
444            mid_price: ctx.mid_px.as_deref().and_then(parse_decimal),
445            oracle_price: ctx.oracle_px.as_deref().and_then(parse_decimal),
446            premium: ctx.premium.as_deref().and_then(parse_decimal),
447            prev_day_price: ctx.prev_day_px.as_deref().and_then(parse_decimal),
448        })
449    }
450
451    /// Returns a full L2 orderbook snapshot for `symbol` from the l2Book REST endpoint.
452    /// Levels are returned as individual `L2Update` items; all share the same `sequence` (timestamp).
453    async fn get_l2_orderbook(&self, symbol: String) -> Result<Vec<L2Update>, String> {
454        let resp = self.client
455            .post(HYPERLIQUID_INFO_URL)
456            .json(&serde_json::json!({"type": "l2Book", "coin": symbol}))
457            .send()
458            .await
459            .map_err(|e| e.to_string())?;
460        let book: WsBook = parse_response(resp).await?;
461        let mut levels = Vec::new();
462        for level in book.levels.first().into_iter().flatten() {
463            if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
464                levels.push(L2Update { symbol: book.coin.clone(), price, volume, side: Side::Ask, sequence: book.time });
465            }
466        }
467        for level in book.levels.get(1).into_iter().flatten() {
468            if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
469                levels.push(L2Update { symbol: book.coin.clone(), price, volume, side: Side::Bid, sequence: book.time });
470            }
471        }
472        Ok(levels)
473    }
474
475    /// Returns the mid-price of `symbol` (e.g. "BTC") from allMids.
476    async fn get_price(&self, symbol: String) -> Result<Decimal, String> {
477        let resp = self.client
478            .post(HYPERLIQUID_INFO_URL)
479            .json(&serde_json::json!({"type": "allMids"}))
480            .send()
481            .await
482            .map_err(|e| e.to_string())?;
483        parse_response::<HashMap<String, String>>(resp).await?
484            .get(&symbol)
485            .and_then(|s| parse_decimal(s))
486            .ok_or_else(|| format!("symbol {} not found", symbol))
487    }
488
489    /// Returns predicted funding rates for all symbols across all venues.
490    /// Null venue entries (unsupported coins) are silently skipped.
491    async fn get_predicted_fundings(&self) -> Result<Vec<PredictedFunding>, String> {
492        let resp = self.client
493            .post(HYPERLIQUID_INFO_URL)
494            .json(&serde_json::json!({"type": "predictedFundings"}))
495            .send()
496            .await
497            .map_err(|e| e.to_string())?;
498        let data: PredictedFundingsResponse = parse_response(resp).await?;
499        let mut result = Vec::new();
500        for (symbol, venues) in data {
501            for (venue, entry) in venues {
502                let Some(entry) = entry else { continue };
503                if let Some(funding_rate) = parse_decimal(&entry.funding_rate) {
504                    result.push(PredictedFunding {
505                        symbol: symbol.clone(),
506                        venue,
507                        funding_rate,
508                        next_funding_time_ms: entry.next_funding_time,
509                    });
510                }
511            }
512        }
513        Ok(result)
514    }
515}
516
517#[allow(async_fn_in_trait)]
518impl guilder_abstraction::ManageOrder for HyperliquidClient {
519    /// Places an order on Hyperliquid. Requires `with_auth`. Returns an `OrderPlacement` with
520    /// the exchange-assigned order ID. Market orders are submitted as aggressive limit orders (IOC).
521    async fn place_order(&self, symbol: String, side: OrderSide, price: Decimal, volume: Decimal, order_type: OrderType, time_in_force: TimeInForce) -> Result<OrderPlacement, String> {
522        let asset_idx = self.get_asset_index(&symbol).await?;
523        let is_buy = matches!(side, OrderSide::Buy);
524
525        let tif_str = match time_in_force {
526            TimeInForce::Gtc => "Gtc",
527            TimeInForce::Ioc => "Ioc",
528            TimeInForce::Fok => "Fok",
529        };
530        // Market orders are IOC limit orders at a wide price
531        let order_type_val = match order_type {
532            OrderType::Limit => serde_json::json!({"limit": {"tif": tif_str}}),
533            OrderType::Market => serde_json::json!({"limit": {"tif": "Ioc"}}),
534        };
535
536        let action = serde_json::json!({
537            "type": "order",
538            "orders": [{
539                "a": asset_idx,
540                "b": is_buy,
541                "p": price.to_string(),
542                "s": volume.to_string(),
543                "r": false,
544                "t": order_type_val
545            }],
546            "grouping": "na"
547        });
548
549        let resp = self.submit_signed_action(action, None).await?;
550        let oid = resp["response"]["data"]["statuses"][0]["resting"]["oid"]
551            .as_i64()
552            .or_else(|| resp["response"]["data"]["statuses"][0]["filled"]["oid"].as_i64())
553            .ok_or_else(|| format!("unexpected response: {}", resp))?;
554
555        let timestamp_ms = std::time::SystemTime::now()
556            .duration_since(std::time::UNIX_EPOCH)
557            .unwrap()
558            .as_millis() as i64;
559
560        Ok(OrderPlacement { order_id: oid, symbol, side, price, quantity: volume, timestamp_ms })
561    }
562
563    /// Modifies price and size of an existing order by its order ID. Requires `with_auth`.
564    /// Fetches the order's current coin and side before submitting the modify action.
565    async fn change_order_by_cloid(&self, cloid: i64, price: Decimal, volume: Decimal) -> Result<i64, String> {
566        let user = self.require_user_address()?;
567
568        let resp = self.client
569            .post(HYPERLIQUID_INFO_URL)
570            .json(&serde_json::json!({"type": "openOrders", "user": user}))
571            .send()
572            .await
573            .map_err(|e| e.to_string())?;
574        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
575        let order = orders.iter()
576            .find(|o| o.oid == cloid)
577            .ok_or_else(|| format!("order {} not found", cloid))?;
578
579        let asset_idx = self.get_asset_index(&order.coin).await?;
580        let is_buy = order.side == "B";
581
582        let action = serde_json::json!({
583            "type": "batchModify",
584            "modifies": [{
585                "oid": cloid,
586                "order": {
587                    "a": asset_idx,
588                    "b": is_buy,
589                    "p": price.to_string(),
590                    "s": volume.to_string(),
591                    "r": false,
592                    "t": {"limit": {"tif": "Gtc"}}
593                }
594            }]
595        });
596
597        self.submit_signed_action(action, None).await?;
598        Ok(cloid)
599    }
600
601    /// Cancels a single order by its order ID. Requires `with_auth`.
602    /// Fetches open orders to resolve the coin/asset before cancelling.
603    async fn cancel_order(&self, cloid: i64) -> Result<i64, String> {
604        let user = self.require_user_address()?;
605
606        let resp = self.client
607            .post(HYPERLIQUID_INFO_URL)
608            .json(&serde_json::json!({"type": "openOrders", "user": user}))
609            .send()
610            .await
611            .map_err(|e| e.to_string())?;
612        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
613        let order = orders.iter()
614            .find(|o| o.oid == cloid)
615            .ok_or_else(|| format!("order {} not found", cloid))?;
616
617        let asset_idx = self.get_asset_index(&order.coin).await?;
618        let action = serde_json::json!({
619            "type": "cancel",
620            "cancels": [{"a": asset_idx, "o": cloid}]
621        });
622
623        self.submit_signed_action(action, None).await?;
624        Ok(cloid)
625    }
626
627    /// Cancels all open orders. Requires `with_auth`.
628    /// Fetches all open orders and submits a batch cancel in a single signed request.
629    async fn cancel_all_order(&self) -> Result<bool, String> {
630        let user = self.require_user_address()?;
631
632        let resp = self.client
633            .post(HYPERLIQUID_INFO_URL)
634            .json(&serde_json::json!({"type": "openOrders", "user": user}))
635            .send()
636            .await
637            .map_err(|e| e.to_string())?;
638        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
639        if orders.is_empty() {
640            return Ok(true);
641        }
642
643        let meta_resp = self.client
644            .post(HYPERLIQUID_INFO_URL)
645            .json(&serde_json::json!({"type": "meta"}))
646            .send()
647            .await
648            .map_err(|e| e.to_string())?;
649        let meta: MetaResponse = parse_response(meta_resp).await?;
650
651        let cancels: Vec<Value> = orders.iter()
652            .filter_map(|o| {
653                let asset_idx = meta.universe.iter().position(|a| a.name == o.coin)?;
654                Some(serde_json::json!({"a": asset_idx, "o": o.oid}))
655            })
656            .collect();
657
658        let action = serde_json::json!({"type": "cancel", "cancels": cancels});
659        self.submit_signed_action(action, None).await?;
660        Ok(true)
661    }
662}
663
664#[allow(async_fn_in_trait)]
665impl guilder_abstraction::SubscribeMarketData for HyperliquidClient {
666    /// Streams L2 orderbook updates for `symbol`. Each message from Hyperliquid is a
667    /// full-depth snapshot; every level is emitted as an individual `L2Update` event.
668    /// All levels in the same snapshot share the same `sequence` value.
669    fn subscribe_l2_update(&self, symbol: String) -> BoxStream<L2Update> {
670        Box::pin(async_stream::stream! {
671            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
672            let sub = serde_json::json!({
673                "method": "subscribe",
674                "subscription": {"type": "l2Book", "coin": symbol}
675            });
676            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
677
678            while let Some(Ok(Message::Text(text))) = ws.next().await {
679                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
680                if env.channel != "l2Book" { continue; }
681                let Ok(book) = serde_json::from_value::<WsBook>(env.data) else { continue; };
682
683                for level in book.levels.first().into_iter().flatten() {
684                    if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
685                        yield L2Update { symbol: book.coin.clone(), price, volume, side: Side::Ask, sequence: book.time };
686                    }
687                }
688                for level in book.levels.get(1).into_iter().flatten() {
689                    if let (Some(price), Some(volume)) = (parse_decimal(&level.px), parse_decimal(&level.sz)) {
690                        yield L2Update { symbol: book.coin.clone(), price, volume, side: Side::Bid, sequence: book.time };
691                    }
692                }
693            }
694        })
695    }
696
697    /// Streams asset context updates for `symbol` via Hyperliquid's `activeAssetCtx` subscription.
698    fn subscribe_asset_context(&self, symbol: String) -> BoxStream<AssetContext> {
699        Box::pin(async_stream::stream! {
700            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
701            let sub = serde_json::json!({
702                "method": "subscribe",
703                "subscription": {"type": "activeAssetCtx", "coin": symbol}
704            });
705            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
706
707            while let Some(Ok(Message::Text(text))) = ws.next().await {
708                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
709                if env.channel != "activeAssetCtx" { continue; }
710                let Ok(update) = serde_json::from_value::<WsAssetCtx>(env.data) else { continue; };
711                let ctx = &update.ctx;
712                if let (Some(open_interest), Some(funding_rate), Some(mark_price), Some(day_volume)) = (
713                    parse_decimal(&ctx.open_interest),
714                    parse_decimal(&ctx.funding),
715                    parse_decimal(&ctx.mark_px),
716                    parse_decimal(&ctx.day_ntl_vlm),
717                ) {
718                    yield AssetContext {
719                        symbol: update.coin,
720                        open_interest,
721                        funding_rate,
722                        mark_price,
723                        day_volume,
724                        mid_price: ctx.mid_px.as_deref().and_then(parse_decimal),
725                        oracle_price: ctx.oracle_px.as_deref().and_then(parse_decimal),
726                        premium: ctx.premium.as_deref().and_then(parse_decimal),
727                        prev_day_price: ctx.prev_day_px.as_deref().and_then(parse_decimal),
728                    };
729                }
730            }
731        })
732    }
733
734    /// Streams liquidation events for a user address via Hyperliquid's `userEvents` subscription.
735    /// Hyperliquid's liquidation event is account-level; `symbol` is empty and `side` is `Sell`.
736    fn subscribe_liquidation(&self, user: String) -> BoxStream<Liquidation> {
737        Box::pin(async_stream::stream! {
738            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
739            let sub = serde_json::json!({
740                "method": "subscribe",
741                "subscription": {"type": "userEvents", "user": user}
742            });
743            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
744
745            while let Some(Ok(Message::Text(text))) = ws.next().await {
746                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
747                if env.channel != "userEvents" { continue; }
748                let Ok(event) = serde_json::from_value::<WsUserEvent>(env.data) else { continue; };
749                let Some(liq) = event.liquidation else { continue; };
750                if let (Some(notional_position), Some(account_value)) = (
751                    parse_decimal(&liq.liquidated_ntl_pos),
752                    parse_decimal(&liq.liquidated_account_value),
753                ) {
754                    yield Liquidation {
755                        symbol: String::new(),
756                        side: OrderSide::Sell,
757                        liquidated_user: liq.liquidated_user,
758                        notional_position,
759                        account_value,
760                    };
761                }
762            }
763        })
764    }
765
766    /// Streams public trade fills for `symbol`. "B" (buyer aggressor) → Buy, otherwise → Sell.
767    fn subscribe_fill(&self, symbol: String) -> BoxStream<Fill> {
768        Box::pin(async_stream::stream! {
769            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
770            let sub = serde_json::json!({
771                "method": "subscribe",
772                "subscription": {"type": "trades", "coin": symbol}
773            });
774            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
775
776            while let Some(Ok(Message::Text(text))) = ws.next().await {
777                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
778                if env.channel != "trades" { continue; }
779                let Ok(trades) = serde_json::from_value::<Vec<WsTrade>>(env.data) else { continue; };
780
781                for trade in trades {
782                    let side = if trade.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
783                    if let (Some(price), Some(volume)) = (parse_decimal(&trade.px), parse_decimal(&trade.sz)) {
784                        yield Fill { symbol: trade.coin, price, volume, side, timestamp_ms: trade.time, trade_id: trade.tid };
785                    }
786                }
787            }
788        })
789    }
790}
791
792#[allow(async_fn_in_trait)]
793impl guilder_abstraction::GetAccountSnapshot for HyperliquidClient {
794    /// Returns open positions from `clearinghouseState`. Requires `with_auth`.
795    /// Zero-size positions are filtered out. Positive `szi` = long, negative = short.
796    async fn get_positions(&self) -> Result<Vec<Position>, String> {
797        let user = self.require_user_address()?;
798        let resp = self.client
799            .post(HYPERLIQUID_INFO_URL)
800            .json(&serde_json::json!({"type": "clearinghouseState", "user": user}))
801            .send()
802            .await
803            .map_err(|e| e.to_string())?;
804        let state: ClearinghouseStateResponse = parse_response(resp).await?;
805
806        Ok(state.asset_positions.into_iter()
807            .filter_map(|ap| {
808                let p = ap.position;
809                let size = parse_decimal(&p.szi)?;
810                if size.is_zero() { return None; }
811                let entry_price = p.entry_px.as_deref().and_then(parse_decimal).unwrap_or_default();
812                let side = if size > Decimal::ZERO { OrderSide::Buy } else { OrderSide::Sell };
813                Some(Position { symbol: p.coin, side, size: size.abs(), entry_price })
814            })
815            .collect())
816    }
817
818    /// Returns resting orders from Hyperliquid's `openOrders` endpoint. Requires `with_auth`.
819    /// `filled_quantity` is derived as `origSz - sz` (original size minus remaining size).
820    async fn get_open_orders(&self) -> Result<Vec<OpenOrder>, String> {
821        let user = self.require_user_address()?;
822        let resp = self.client
823            .post(HYPERLIQUID_INFO_URL)
824            .json(&serde_json::json!({"type": "openOrders", "user": user}))
825            .send()
826            .await
827            .map_err(|e| e.to_string())?;
828        let orders: Vec<RestOpenOrder> = parse_response(resp).await?;
829
830        Ok(orders.into_iter()
831            .filter_map(|o| {
832                let price = parse_decimal(&o.limit_px)?;
833                let quantity = parse_decimal(&o.orig_sz)?;
834                let remaining = parse_decimal(&o.sz)?;
835                let filled_quantity = quantity - remaining;
836                let side = if o.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
837                Some(OpenOrder { order_id: o.oid, symbol: o.coin, side, price, quantity, filled_quantity })
838            })
839            .collect())
840    }
841
842    /// Returns total account value (collateral) from `clearinghouseState`. Requires `with_auth`.
843    async fn get_collateral(&self) -> Result<Decimal, String> {
844        let user = self.require_user_address()?;
845        let resp = self.client
846            .post(HYPERLIQUID_INFO_URL)
847            .json(&serde_json::json!({"type": "clearinghouseState", "user": user}))
848            .send()
849            .await
850            .map_err(|e| e.to_string())?;
851        let state: ClearinghouseStateResponse = parse_response(resp).await?;
852        parse_decimal(&state.margin_summary.account_value)
853            .ok_or_else(|| "invalid account value".to_string())
854    }
855}
856
857#[allow(async_fn_in_trait)]
858impl guilder_abstraction::SubscribeUserEvents for HyperliquidClient {
859    /// Streams the user's own order executions via the `userEvents` WS subscription.
860    /// Requires `with_auth` (streams are empty if no user address is set).
861    fn subscribe_user_fills(&self) -> BoxStream<UserFill> {
862        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
863        let user = format!("{:#x}", addr);
864        Box::pin(async_stream::stream! {
865            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
866            let sub = serde_json::json!({
867                "method": "subscribe",
868                "subscription": {"type": "userEvents", "user": user}
869            });
870            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
871
872            while let Some(Ok(Message::Text(text))) = ws.next().await {
873                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
874                if env.channel != "userEvents" { continue; }
875                let Ok(event) = serde_json::from_value::<WsUserEvent>(env.data) else { continue; };
876                for fill in event.fills.unwrap_or_default() {
877                    let side = if fill.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
878                    if let (Some(price), Some(quantity), Some(fee_usd)) = (
879                        parse_decimal(&fill.px),
880                        parse_decimal(&fill.sz),
881                        parse_decimal(&fill.fee),
882                    ) {
883                        yield UserFill { order_id: fill.oid, symbol: fill.coin, side, price, quantity, fee_usd, timestamp_ms: fill.time };
884                    }
885                }
886            }
887        })
888    }
889
890    /// Streams order lifecycle events via the `orderUpdates` WS subscription.
891    /// Requires `with_auth`.
892    fn subscribe_order_updates(&self) -> BoxStream<OrderUpdate> {
893        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
894        let user = format!("{:#x}", addr);
895        Box::pin(async_stream::stream! {
896            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
897            let sub = serde_json::json!({
898                "method": "subscribe",
899                "subscription": {"type": "orderUpdates", "user": user}
900            });
901            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
902
903            while let Some(Ok(Message::Text(text))) = ws.next().await {
904                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
905                if env.channel != "orderUpdates" { continue; }
906                let Ok(updates) = serde_json::from_value::<Vec<WsOrderUpdate>>(env.data) else { continue; };
907                for upd in updates {
908                    let status = match upd.status.as_str() {
909                        "open" => OrderStatus::Placed,
910                        "filled" => OrderStatus::Filled,
911                        "canceled" | "cancelled" => OrderStatus::Cancelled,
912                        _ => OrderStatus::PartiallyFilled,
913                    };
914                    let side = if upd.order.side == "B" { OrderSide::Buy } else { OrderSide::Sell };
915                    yield OrderUpdate {
916                        order_id: upd.order.oid,
917                        symbol: upd.order.coin,
918                        status,
919                        side: Some(side),
920                        price: parse_decimal(&upd.order.limit_px),
921                        quantity: parse_decimal(&upd.order.orig_sz),
922                        remaining_quantity: parse_decimal(&upd.order.sz),
923                        timestamp_ms: upd.status_timestamp,
924                    };
925                }
926            }
927        })
928    }
929
930    /// Streams funding payments applied to positions via the `userEvents` WS subscription.
931    /// Requires `with_auth`.
932    fn subscribe_funding_payments(&self) -> BoxStream<FundingPayment> {
933        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
934        let user = format!("{:#x}", addr);
935        Box::pin(async_stream::stream! {
936            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
937            let sub = serde_json::json!({
938                "method": "subscribe",
939                "subscription": {"type": "userEvents", "user": user}
940            });
941            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
942
943            while let Some(Ok(Message::Text(text))) = ws.next().await {
944                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
945                if env.channel != "userEvents" { continue; }
946                let Ok(event) = serde_json::from_value::<WsUserEvent>(env.data) else { continue; };
947                let Some(funding) = event.funding else { continue; };
948                if let Some(amount_usd) = parse_decimal(&funding.usdc) {
949                    yield FundingPayment { symbol: funding.coin, amount_usd, timestamp_ms: funding.time };
950                }
951            }
952        })
953    }
954
955    fn subscribe_deposits(&self) -> BoxStream<Deposit> {
956        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
957        let user = format!("{:#x}", addr);
958        Box::pin(async_stream::stream! {
959            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
960            let sub = serde_json::json!({
961                "method": "subscribe",
962                "subscription": {"type": "userNonFundingLedgerUpdates", "user": user}
963            });
964            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
965            while let Some(Ok(Message::Text(text))) = ws.next().await {
966                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
967                if env.channel != "userNonFundingLedgerUpdates" { continue; }
968                let Ok(ledger) = serde_json::from_value::<WsLedgerUpdates>(env.data) else { continue; };
969                for entry in ledger.updates {
970                    if entry.delta.kind == "deposit" {
971                        if let Some(amount_usd) = entry.delta.usdc.as_deref().and_then(parse_decimal) {
972                            yield Deposit { asset: "USDC".to_string(), amount_usd, timestamp_ms: entry.time };
973                        }
974                    }
975                }
976            }
977        })
978    }
979
980    fn subscribe_withdrawals(&self) -> BoxStream<Withdrawal> {
981        let Some(addr) = self.user_address else { return Box::pin(stream::empty()); };
982        let user = format!("{:#x}", addr);
983        Box::pin(async_stream::stream! {
984            let Ok((mut ws, _)) = connect_async(HYPERLIQUID_WS_URL).await else { return; };
985            let sub = serde_json::json!({
986                "method": "subscribe",
987                "subscription": {"type": "userNonFundingLedgerUpdates", "user": user}
988            });
989            if ws.send(Message::Text(sub.to_string().into())).await.is_err() { return; }
990            while let Some(Ok(Message::Text(text))) = ws.next().await {
991                let Ok(env) = serde_json::from_str::<WsEnvelope>(&text) else { continue; };
992                if env.channel != "userNonFundingLedgerUpdates" { continue; }
993                let Ok(ledger) = serde_json::from_value::<WsLedgerUpdates>(env.data) else { continue; };
994                for entry in ledger.updates {
995                    if entry.delta.kind == "withdraw" {
996                        if let Some(amount_usd) = entry.delta.usdc.as_deref().and_then(parse_decimal) {
997                            yield Withdrawal { asset: "USDC".to_string(), amount_usd, timestamp_ms: entry.time };
998                        }
999                    }
1000                }
1001            }
1002        })
1003    }
1004}