hypersdk 0.2.8

Rust SDK for Hyperliquid
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! WebSocket client for real-time HyperCore market data.
//!
//! This module provides a persistent WebSocket connection that automatically
//! reconnects on failure and manages subscriptions across reconnections.
//!
//! # Connection Status
//!
//! The connection yields [`Event`] which wraps connection state and data messages:
//!
//! - [`Event::Connected`] - Connection established (including after reconnection)
//! - [`Event::Disconnected`] - Connection lost (will auto-reconnect)
//! - [`Event::Message`] - Contains an [`Incoming`] data message
//!
//! You can also check the current connection status using [`Connection::is_connected()`].
//!
//! # Examples
//!
//! ## Handle Connection Status
//!
//! ```no_run
//! use hypersdk::hypercore::{self, ws::Event, types::*};
//! use futures::StreamExt;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let mut ws = hypercore::mainnet_ws();
//! ws.subscribe(Subscription::Trades { coin: "BTC".into() });
//!
//! while let Some(event) = ws.next().await {
//!     match event {
//!         Event::Connected => {
//!             println!("Connected to WebSocket");
//!         }
//!         Event::Disconnected => {
//!             println!("Disconnected");
//!         }
//!         Event::Message(msg) => match msg {
//!             Incoming::Trades(trades) => {
//!                 for trade in trades {
//!                     println!("Trade: {} {} @ {}", trade.side, trade.sz, trade.px);
//!                 }
//!             }
//!             _ => {}
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Subscribe to Market Data
//!
//! ```no_run
//! use hypersdk::hypercore::{self, ws::Event, types::*};
//! use futures::StreamExt;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let mut ws = hypercore::mainnet_ws();
//!
//! // Subscribe to trades and orderbook
//! ws.subscribe(Subscription::Trades { coin: "BTC".into() });
//! ws.subscribe(Subscription::L2Book { coin: "BTC".into() });
//!
//! while let Some(event) = ws.next().await {
//!     let Event::Message(msg) = event else { continue };
//!     match msg {
//!         Incoming::Trades(trades) => {
//!             for trade in trades {
//!                 println!("Trade: {} {} @ {}", trade.side, trade.sz, trade.px);
//!             }
//!         }
//!         Incoming::L2Book(book) => {
//!             println!("Book update: {} levels", book.levels[0].len() + book.levels[1].len());
//!         }
//!         _ => {}
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Subscribe to User Events
//!
//! ```no_run
//! use hypersdk::hypercore::{self, ws::Event, types::*};
//! use hypersdk::Address;
//! use futures::StreamExt;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let mut ws = hypercore::mainnet_ws();
//! let user: Address = "0x...".parse()?;
//!
//! // Subscribe to order updates and fills
//! ws.subscribe(Subscription::OrderUpdates { user });
//! ws.subscribe(Subscription::UserFills { user });
//!
//! while let Some(event) = ws.next().await {
//!     let Event::Message(msg) = event else { continue };
//!     match msg {
//!         Incoming::OrderUpdates(updates) => {
//!             for update in updates {
//!                 println!("Order {}: {:?}", update.order.oid, update.status);
//!             }
//!         }
//!         Incoming::UserFills { fills, .. } => {
//!             for fill in fills {
//!                 println!("Fill: {} @ {}", fill.sz, fill.px);
//!             }
//!         }
//!         _ => {}
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use std::{
    collections::HashSet,
    pin::Pin,
    task::{Context, Poll, ready},
    time::Duration,
};

use anyhow::Result;
use futures::{SinkExt, StreamExt};
use tokio::{
    sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel},
    time::{interval, sleep, timeout},
};
use url::Url;
use yawc::{Frame, OpCode, Options, TcpWebSocket};

use crate::hypercore::types::{Incoming, Outgoing, Subscription};

struct Stream {
    stream: TcpWebSocket,
}

impl Stream {
    /// Establish a WebSocket connection.
    async fn connect(url: Url) -> Result<Self> {
        let stream = yawc::WebSocket::connect(url)
            .with_options(
                Options::default()
                    .with_no_delay()
                    .with_balanced_compression()
                    .with_utf8(),
            )
            .await?;

        Ok(Self { stream })
    }

    /// Subscribes to a topic.
    async fn subscribe(&mut self, subscription: Subscription) -> anyhow::Result<()> {
        let text = serde_json::to_string(&Outgoing::Subscribe { subscription })?;
        self.stream.send(Frame::text(text)).await?;
        Ok(())
    }

    /// Unsubscribes from a topic.
    async fn unsubscribe(&mut self, subscription: Subscription) -> anyhow::Result<()> {
        let text = serde_json::to_string(&Outgoing::Unsubscribe { subscription })?;
        self.stream.send(Frame::text(text)).await?;
        Ok(())
    }

    /// Send a ping
    async fn ping(&mut self) -> anyhow::Result<()> {
        let text = serde_json::to_string(&Outgoing::Ping)?;
        self.stream.send(Frame::text(text)).await?;
        Ok(())
    }

    /// Send a pong
    async fn pong(&mut self) -> anyhow::Result<()> {
        let text = serde_json::to_string(&Outgoing::Pong)?;
        self.stream.send(Frame::text(text)).await?;
        Ok(())
    }
}

impl futures::Stream for Stream {
    type Item = Incoming;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        while let Some(frame) = ready!(this.stream.poll_next_unpin(cx)) {
            if frame.opcode() == OpCode::Text {
                match serde_json::from_slice(frame.payload()) {
                    Ok(ok) => {
                        return Poll::Ready(Some(ok));
                    }
                    Err(err) => {
                        log::warn!("unable to parse: {}: {:?}", frame.as_str(), err);
                    }
                }
            } else {
                log::warn!(
                    "Hyperliquid sent a binary msg? {data:?}",
                    data = frame.payload()
                );
            }
        }

        Poll::Ready(None)
    }
}

type SubChannelData = (bool, Subscription);

/// WebSocket event representing either a connection state change or a data message.
///
/// This enum cleanly separates connection lifecycle events from actual data messages,
/// allowing you to handle each appropriately.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, ws::Event, types::*};
/// use futures::StreamExt;
///
/// # async fn example() {
/// let mut ws = hypercore::mainnet_ws();
/// ws.subscribe(Subscription::Trades { coin: "BTC".into() });
///
/// while let Some(event) = ws.next().await {
///     match event {
///         Event::Connected => println!("Connected!"),
///         Event::Disconnected => println!("Disconnected"),
///         Event::Message(msg) => {
///             // Handle data messages
///         }
///     }
/// }
/// # }
/// ```
#[derive(Clone, Debug)]
pub enum Event {
    /// WebSocket connection established.
    ///
    /// Sent when a connection is successfully established, including after reconnection.
    /// Subscriptions are automatically restored after reconnection.
    Connected,
    /// WebSocket connection lost.
    ///
    /// Sent when the connection is unexpectedly closed. The connection will
    /// automatically attempt to reconnect.
    Disconnected,
    /// A data message received from the WebSocket.
    Message(Incoming),
}

/// Persistent WebSocket connection with automatic reconnection.
///
/// This connection automatically handles:
/// - Reconnection on connection failure
/// - Re-subscription after reconnection
/// - Periodic ping/pong to keep the connection alive
/// - Connection status notifications via [`Event`]
///
/// The connection implements `futures::Stream`, yielding [`Event`] items that
/// wrap both connection state changes and data messages.
///
/// # Connection Status
///
/// The connection emits status events through the stream:
/// - [`Event::Connected`] - Connection established (including after reconnection)
/// - [`Event::Disconnected`] - Connection lost
/// - [`Event::Message`] - Contains an [`Incoming`] data message
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, ws::Event, types::*};
/// use futures::StreamExt;
///
/// # async fn example() {
/// let mut ws = hypercore::mainnet_ws();
/// ws.subscribe(Subscription::Trades { coin: "BTC".into() });
///
/// while let Some(event) = ws.next().await {
///     match event {
///         Event::Connected => {
///             println!("Connected!");
///         }
///         Event::Disconnected => {
///             println!("Disconnected");
///         }
///         Event::Message(Incoming::Trades(trades)) => {
///             // Handle trades...
///         }
///         _ => {}
///     }
/// }
/// # }
/// ```
pub struct Connection {
    rx: UnboundedReceiver<Event>,
    tx: UnboundedSender<SubChannelData>,
}

/// A handle for managing subscriptions to a WebSocket connection.
///
/// This handle is obtained by calling [`Connection::split()`] and allows for
/// subscribing and unsubscribing to channels independently of where the
/// event stream is being processed. It's useful for scenarios where you
/// want to manage subscriptions from a separate task or context.
///
/// The subscriptions managed by this handle persist across automatic
/// reconnections.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, ws::Event, types::*};
/// use futures::StreamExt;
/// use tokio::spawn;
///
/// # async fn example() -> anyhow::Result<()> {
/// let ws = hypercore::mainnet_ws();
/// let (handle, mut stream) = ws.split();
///
/// // Manage subscriptions in a separate task
/// spawn(async move {
///     handle.subscribe(Subscription::Trades { coin: "BTC".into() });
///     handle.subscribe(Subscription::L2Book { coin: "ETH".into() });
///
///     // Later, unsubscribe
///     tokio::time::sleep(std::time::Duration::from_secs(60)).await;
///     handle.unsubscribe(Subscription::Trades { coin: "BTC".into() });
/// });
///
/// // Process events in the current task
/// while let Some(event) = stream.next().await {
///     match event {
///         Event::Message(Incoming::Trades(trades)) => {
///             println!("Received {} trades", trades.len());
///         }
///         _ => {}
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct ConnectionHandle {
    tx: UnboundedSender<SubChannelData>,
}

/// A stream of events from a WebSocket connection.
///
/// This stream is obtained by calling [`Connection::split()`] and yields
/// [`Event`] items, which represent connection status changes or incoming
/// data messages.
///
/// It implements `futures::Stream`, allowing you to easily process events
/// using methods like `next().await` or `for_each()`.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hypercore::{self, ws::Event, types::*};
/// use futures::StreamExt;
///
/// # async fn example() -> anyhow::Result<()> {
/// let ws = hypercore::mainnet_ws();
/// let (_handle, mut stream) = ws.split();
///
/// while let Some(event) = stream.next().await {
///     match event {
///         Event::Connected => println!("Stream connected!"),
///         Event::Disconnected => println!("Stream disconnected"),
///         Event::Message(Incoming::Trades(trades)) => {
///             println!("Received {} trades", trades.len());
///         }
///         _ => {}
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ConnectionStream {
    rx: UnboundedReceiver<Event>,
}

impl Connection {
    /// Creates a new WebSocket connection to the specified URL.
    ///
    /// The connection starts immediately and runs in the background,
    /// automatically reconnecting on failures. Connection status events
    /// ([`Event::Connected`], [`Event::Disconnected`]) will be emitted through
    /// the stream.
    ///
    /// # Example
    ///
    /// Create a new WebSocket connection:
    /// `WebSocket::new(hypercore::mainnet_websocket_url())`
    pub fn new(url: Url) -> Self {
        let (tx, rx) = unbounded_channel();
        let (stx, srx) = unbounded_channel();
        tokio::spawn(connection(url, tx, srx));
        Self { rx, tx: stx }
    }

    /// Subscribes to a WebSocket channel.
    ///
    /// The subscription will persist across reconnections. If you're already
    /// subscribed to this channel, this is a no-op.
    ///
    /// # Example
    ///
    /// Subscribe to market data:
    /// - `ws.subscribe(Subscription::Trades { coin: "BTC".into() })`
    /// - `ws.subscribe(Subscription::L2Book { coin: "ETH".into() })`
    pub fn subscribe(&self, subscription: Subscription) {
        let _ = self.tx.send((true, subscription));
    }

    /// Unsubscribes from a WebSocket channel.
    ///
    /// Stops receiving updates for this subscription. Does nothing if you're
    /// not currently subscribed to this channel.
    ///
    /// # Example
    ///
    /// Unsubscribe from a channel:
    /// `ws.unsubscribe(Subscription::Trades { coin: "BTC".into() })`
    pub fn unsubscribe(&self, subscription: Subscription) {
        let _ = self.tx.send((false, subscription));
    }

    /// Closes the WebSocket connection.
    ///
    /// After calling this, the connection will no longer receive messages
    /// and cannot be reused.
    ///
    /// # Example
    ///
    /// Close the connection when done: `ws.close()`
    pub fn close(self) {
        drop(self);
    }

    /// Splits the connection into a subscription handle and an event stream.
    ///
    /// This is useful when you want to drive the stream in one task and
    /// manage subscriptions from another.
    pub fn split(self) -> (ConnectionHandle, ConnectionStream) {
        (
            ConnectionHandle { tx: self.tx },
            ConnectionStream { rx: self.rx },
        )
    }
}

impl futures::Stream for Connection {
    type Item = Event;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        this.rx.poll_recv(cx)
    }
}

impl ConnectionHandle {
    /// Subscribes to a WebSocket channel.
    ///
    /// The subscription will persist across reconnections. If you're already
    /// subscribed to this channel, this is a no-op.
    ///
    /// # Example
    ///
    /// Subscribe to market data:
    /// - `ws.subscribe(Subscription::Trades { coin: "BTC".into() })`
    /// - `ws.subscribe(Subscription::L2Book { coin: "ETH".into() })`
    pub fn subscribe(&self, subscription: Subscription) {
        let _ = self.tx.send((true, subscription));
    }

    /// Unsubscribes from a WebSocket channel.
    ///
    /// Stops receiving updates for this subscription. Does nothing if you're
    /// not currently subscribed to this channel.
    ///
    /// # Example
    ///
    /// Unsubscribe from a channel:
    /// `ws.unsubscribe(Subscription::Trades { coin: "BTC".into() })`
    pub fn unsubscribe(&self, subscription: Subscription) {
        let _ = self.tx.send((false, subscription));
    }

    /// Closes the WebSocket connection.
    ///
    /// After calling this, the connection will no longer receive messages
    /// and cannot be reused.
    ///
    /// # Example
    ///
    /// Close the connection when done: `ws.close()`
    pub fn close(self) {
        drop(self);
    }
}

impl futures::Stream for ConnectionStream {
    type Item = Event;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        this.rx.poll_recv(cx)
    }
}

async fn connection(
    url: Url,
    tx: UnboundedSender<Event>,
    mut srx: UnboundedReceiver<SubChannelData>,
) {
    const MAX_MISSED_PONGS: u8 = 2;
    const MAX_RECONNECT_DELAY_MS: u64 = 5_000; // 5 seconds max
    const INITIAL_RECONNECT_DELAY_MS: u64 = 500;

    let mut subs: HashSet<Subscription> = HashSet::new();
    let mut reconnect_attempts = 0u32;

    loop {
        let mut stream = match timeout(Duration::from_secs(10), Stream::connect(url.clone())).await
        {
            Ok(ok) => match ok {
                Ok(ok) => ok,
                Err(err) => {
                    log::error!("Unable to connect to {url}: {err:?}");

                    // Exponential backoff: 500ms, 1s, 2s, 4s, 5s (capped)
                    let delay_ms = (INITIAL_RECONNECT_DELAY_MS * (1u64 << reconnect_attempts))
                        .min(MAX_RECONNECT_DELAY_MS);
                    reconnect_attempts = reconnect_attempts.saturating_add(1);

                    log::debug!(
                        "Reconnecting in {}ms (attempt {})",
                        delay_ms,
                        reconnect_attempts
                    );
                    sleep(Duration::from_millis(delay_ms)).await;

                    continue;
                }
            },
            Err(err) => {
                log::error!("Connection timeout to {url}: {err:?}");

                let delay_ms = (INITIAL_RECONNECT_DELAY_MS * (1u64 << reconnect_attempts))
                    .min(MAX_RECONNECT_DELAY_MS);
                reconnect_attempts = reconnect_attempts.saturating_add(1);

                log::debug!(
                    "Reconnecting in {}ms (attempt {})",
                    delay_ms,
                    reconnect_attempts
                );
                sleep(Duration::from_millis(delay_ms)).await;

                continue;
            }
        };

        log::debug!("Connected to {url}");
        reconnect_attempts = 0; // Reset on successful connection
        let _ = tx.send(Event::Connected);

        // Re-subscribe to all active subscriptions after reconnection
        if !subs.is_empty() {
            log::debug!("Re-subscribing to {} channels", subs.len());
            for sub in subs.iter() {
                log::debug!("Re-subscribing to {sub}");
                if let Err(err) = stream.subscribe(sub.clone()).await {
                    log::error!("Failed to re-subscribe to {sub}: {err:?}");
                }
            }
        }

        let mut ping_interval = interval(Duration::from_secs(5));
        let mut missed_pongs: u8 = 0;

        loop {
            tokio::select! {
                _ = ping_interval.tick() => {
                    if missed_pongs >= MAX_MISSED_PONGS {
                        log::warn!("Missed {missed_pongs} pongs, reconnecting...");
                        break;
                    }

                    if stream.ping().await.is_ok() {
                        missed_pongs += 1;
                    }
                }
                maybe_item = stream.next() => {
                    let Some(item) = maybe_item else { break; };
                    match item {
                        Incoming::Pong => {
                            missed_pongs = 0;
                        }
                        Incoming::Ping => {
                            let _ = stream.pong().await;
                        }
                        _ => {
                            let _ = tx.send(Event::Message(item));
                        }
                    }
                }
                item = srx.recv() => {
                    let Some((is_sub, sub)) = item else { return };
                    if is_sub {
                        if !subs.insert(sub.clone()) {
                            log::debug!("Already subscribed to {sub:?}");
                            continue;
                        }

                        if let Err(err) = stream.subscribe(sub).await {
                            log::error!("Subscribing: {err:?}");
                            break;
                        }
                    } else if subs.remove(&sub) {
                        if let Err(err) = stream.unsubscribe(sub).await {
                            log::error!("Unsubscribing: {err:?}");
                            break;
                        }
                    }
                }
            }
        }

        log::warn!("Disconnected from {url}, attempting to reconnect...");
        let _ = tx.send(Event::Disconnected);
    }
}