Skip to main content

hypercall_client/
qp_client.rs

1//! Quote Provider (QP) WebSocket client for the `/ws/quotes` endpoint.
2//!
3//! Connects to the Hypercall API server as a registered Quote Provider,
4//! authenticates via EIP-712 signature, and runs a bidirectional message
5//! loop with auto-reconnect.
6//!
7//! # Usage
8//!
9//! ```rust,no_run
10//! use std::sync::Arc;
11//! use tokio::sync::mpsc;
12//! use hypercall_client::{HypercallWallet, qp_client};
13//!
14//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
15//! let wallet = Arc::new(HypercallWallet::from_private_key("0x...", 999)?);
16//! let (outbound_tx, outbound_rx) = mpsc::channel(256);
17//! let (inbound_tx, mut inbound_rx) = mpsc::channel(256);
18//!
19//! // Spawn the auto-reconnecting QP client
20//! let config = qp_client::QpClientConfig::new("https://api.hypercall.xyz".into());
21//! tokio::spawn(qp_client::run_qp_client(
22//!     config,
23//!     wallet,
24//!     outbound_rx,
25//!     inbound_tx,
26//!     Arc::new(qp_client::NoopCallbacks),
27//! ));
28//!
29//! // Handle inbound RFQ requests
30//! while let Some(msg) = inbound_rx.recv().await {
31//!     match msg {
32//!         qp_client::ServerInbound::RfqRequest { rfq_id, legs, .. } => {
33//!             println!("RFQ {rfq_id}: {} legs", legs.len());
34//!         }
35//!         _ => {}
36//!     }
37//! }
38//! # Ok(())
39//! # }
40//! ```
41
42use std::sync::Arc;
43use std::time::Duration;
44
45use futures::{SinkExt, StreamExt};
46use tokio::sync::mpsc::{self, error::TrySendError};
47use tokio::time::{sleep, timeout};
48use tokio_tungstenite::{connect_async, tungstenite::Message};
49use tracing::{error, info, warn};
50
51use crate::wallet::HypercallWallet;
52
53pub(crate) const INBOUND_CHANNEL_CLOSED: &str = "Inbound channel closed";
54pub(crate) const WS_WRITE_TIMEOUT: Duration = Duration::from_secs(5);
55
56/// Write half of an established QP WebSocket.
57pub(crate) type WsSink = futures::stream::SplitSink<
58    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
59    Message,
60>;
61/// Read half of an established QP WebSocket.
62pub(crate) type WsStream = futures::stream::SplitStream<
63    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
64>;
65
66pub use hypercall_ws_protocol::{
67    IndicativeQuote, QpClientMessage as ClientOutbound, QpResponseLeg as ResponseLeg,
68    QpRfqLeg as RfqLeg, QpServerMessage as ServerInbound,
69};
70
71/// High-level reason the QP client disconnected from the server.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum QpDisconnectReason {
74    Closed,
75    Error,
76    InboundChannelClosed,
77}
78
79impl QpDisconnectReason {
80    pub const fn as_str(self) -> &'static str {
81        match self {
82            Self::Closed => "closed",
83            Self::Error => "error",
84            Self::InboundChannelClosed => "inbound_closed",
85        }
86    }
87}
88
89impl std::fmt::Display for QpDisconnectReason {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.write_str(self.as_str())
92    }
93}
94
95/// WebSocket write operation that failed.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum QpWriteOperation {
98    Auth,
99    Heartbeat,
100    Outbound,
101    Pong,
102}
103
104impl QpWriteOperation {
105    pub const fn as_str(self) -> &'static str {
106        match self {
107            Self::Auth => "auth",
108            Self::Heartbeat => "heartbeat",
109            Self::Outbound => "outbound",
110            Self::Pong => "pong",
111        }
112    }
113}
114
115impl std::fmt::Display for QpWriteOperation {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        f.write_str(self.as_str())
118    }
119}
120
121/// Reason a WebSocket write failed.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum QpWriteFailure {
124    Timeout,
125    SendError,
126}
127
128impl QpWriteFailure {
129    pub const fn as_str(self) -> &'static str {
130        match self {
131            Self::Timeout => "timeout",
132            Self::SendError => "send_error",
133        }
134    }
135}
136
137impl std::fmt::Display for QpWriteFailure {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        f.write_str(self.as_str())
140    }
141}
142
143/// Why the scoped runtime dropped an RFQ response instead of sending it.
144/// Surfaced through [`QpClientCallbacks::on_rfq_response_dropped`] alongside
145/// the message itself, so the caller can attribute the loss to the `rfq_id`
146/// it belongs to.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum RfqDropReason {
149    /// The response's delivery deadline passed before it was written.
150    Expired,
151    /// The response was consumed for writing but the socket write failed.
152    WriteFailed,
153    /// The response was consumed for writing but the socket write timed out.
154    WriteTimeout,
155}
156
157impl RfqDropReason {
158    pub const fn as_str(self) -> &'static str {
159        match self {
160            Self::Expired => "expired",
161            Self::WriteFailed => "write_failed",
162            Self::WriteTimeout => "write_timeout",
163        }
164    }
165}
166
167impl std::fmt::Display for RfqDropReason {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        f.write_str(self.as_str())
170    }
171}
172
173/// Callbacks for observability hooks. Implement this to wire in your own
174/// metrics framework (Prometheus, StatsD, etc.). The default [`NoopCallbacks`]
175/// does nothing.
176pub trait QpClientCallbacks: Send + Sync + 'static {
177    fn on_connected(&self) {}
178    fn on_disconnected(&self, _reason: QpDisconnectReason) {}
179    /// A bulk count of outbound messages discarded rather than sent. Both
180    /// runtimes report through this: the legacy client counts its pre-reconnect
181    /// drain, and the scoped runtime counts superseded indicative frames AND
182    /// dropped RFQ responses. It carries no identity, so a firm quote that
183    /// died here cannot be traced back to its `rfq_id` -- use
184    /// [`Self::on_rfq_response_dropped`] for that. The scoped runtime reports
185    /// every RFQ drop through BOTH hooks, so existing consumers of this count
186    /// see unchanged totals.
187    fn on_stale_messages_drained(&self, _count: u64) {}
188    /// An RFQ response the scoped runtime could not deliver, with the message
189    /// itself so the loss can be attributed (its `rfq_id`, nonce, and legs
190    /// are all still present). A signed quote that never reaches the venue
191    /// usually needs a corrective audit event on the same `rfq_id`; the bare
192    /// count above cannot support that. Scoped runtime only -- the legacy
193    /// client has no per-message deadlines.
194    fn on_rfq_response_dropped(&self, _message: &ClientOutbound, _reason: RfqDropReason) {}
195    fn on_inbound_message_dropped(&self) {}
196    fn on_transport_activity(&self) {}
197    fn on_write_failed(&self, _operation: QpWriteOperation, _failure: QpWriteFailure) {}
198}
199
200pub struct NoopCallbacks;
201impl QpClientCallbacks for NoopCallbacks {}
202
203/// Configuration for the QP WebSocket client.
204pub struct QpClientConfig {
205    pub api_url: String,
206    pub reconnect_delay: Duration,
207    /// How often the scoped runtime ([`crate::qp_scoped`]) republishes
208    /// every live slot even without changes. The server TTL-evicts rows it
209    /// has not re-received within its TTL (60s in production), so this
210    /// must stay well inside that or quiet scopes silently vanish
211    /// server-side. `Duration::ZERO` disables the keepalive entirely.
212    /// Ignored by the legacy raw-channel client, whose callers send their
213    /// own periodic snapshots.
214    pub indicative_republish_interval: Duration,
215}
216
217impl QpClientConfig {
218    pub fn new(api_url: String) -> Self {
219        Self {
220            api_url,
221            reconnect_delay: Duration::from_secs(5),
222            indicative_republish_interval: Duration::from_secs(15),
223        }
224    }
225}
226
227/// Run the QP WebSocket client with auto-reconnect.
228///
229/// - `outbound_rx`: messages to send to the server (indicative updates, RFQ responses)
230/// - `inbound_tx`: received messages (RFQ requests) forwarded to the caller
231/// - `callbacks`: observability hooks for metrics/logging
232pub async fn run_qp_client(
233    config: QpClientConfig,
234    wallet: Arc<HypercallWallet>,
235    mut outbound_rx: mpsc::Receiver<ClientOutbound>,
236    inbound_tx: mpsc::Sender<ServerInbound>,
237    callbacks: Arc<dyn QpClientCallbacks>,
238) {
239    loop {
240        match connect_and_run(
241            &config.api_url,
242            &wallet,
243            &mut outbound_rx,
244            &inbound_tx,
245            callbacks.as_ref(),
246        )
247        .await
248        {
249            Ok(_) => {
250                warn!(
251                    "QP WebSocket closed, reconnecting in {:?}",
252                    config.reconnect_delay
253                );
254                callbacks.on_disconnected(QpDisconnectReason::Closed);
255            }
256            Err(e) => {
257                if e == INBOUND_CHANNEL_CLOSED {
258                    error!("QP inbound channel closed; stopping client task");
259                    callbacks.on_disconnected(QpDisconnectReason::InboundChannelClosed);
260                    break;
261                }
262                error!(
263                    "QP WebSocket error: {}, reconnecting in {:?}",
264                    e, config.reconnect_delay
265                );
266                callbacks.on_disconnected(QpDisconnectReason::Error);
267            }
268        }
269        let mut drained = 0u64;
270        while outbound_rx.try_recv().is_ok() {
271            drained += 1;
272        }
273        if drained > 0 {
274            info!(
275                "Drained {} stale outbound messages before reconnect",
276                drained
277            );
278            callbacks.on_stale_messages_drained(drained);
279        }
280        sleep(config.reconnect_delay).await;
281    }
282}
283
284pub(crate) fn forward_inbound_or_close(
285    inbound_tx: &mpsc::Sender<ServerInbound>,
286    msg: ServerInbound,
287    callbacks: &dyn QpClientCallbacks,
288) -> Result<(), String> {
289    match inbound_tx.try_send(msg) {
290        Ok(()) => Ok(()),
291        Err(TrySendError::Closed(_)) => Err(INBOUND_CHANNEL_CLOSED.to_string()),
292        Err(TrySendError::Full(msg)) => {
293            warn!(
294                message = ?msg,
295                "Inbound RFQ channel full, dropping server message to keep WebSocket writer responsive"
296            );
297            callbacks.on_inbound_message_dropped();
298            Ok(())
299        }
300    }
301}
302
303/// Connect, authenticate, and return the socket halves plus the server's
304/// advertised capabilities. Shared by the legacy raw-channel client and the
305/// scoped runtime in [`crate::qp_scoped`].
306pub(crate) async fn connect_and_auth(
307    api_url: &str,
308    wallet: &HypercallWallet,
309    callbacks: &dyn QpClientCallbacks,
310) -> Result<(WsSink, WsStream, Vec<String>), String> {
311    let ws_url = if api_url.starts_with("https") {
312        format!("{}/ws/quotes", api_url.replacen("https", "wss", 1))
313    } else {
314        format!("{}/ws/quotes", api_url.replacen("http", "ws", 1))
315    };
316
317    info!("Connecting to {}", ws_url);
318    let (ws_stream, _) = connect_async(&ws_url)
319        .await
320        .map_err(|e| format!("WebSocket connect failed: {e}"))?;
321    info!("WebSocket connected");
322    callbacks.on_connected();
323    callbacks.on_transport_activity();
324
325    let (mut ws_sender, mut ws_receiver) = ws_stream.split();
326
327    // Authenticate with EIP-712 signature
328    let now_ms = std::time::SystemTime::now()
329        .duration_since(std::time::UNIX_EPOCH)
330        .unwrap()
331        .as_millis() as u64;
332    let nonce = wallet.next_nonce();
333    let signature = wallet
334        .sign_connect_quote_provider(alloy::primitives::U256::from(now_ms), nonce)
335        .await
336        .map_err(|e| format!("Failed to sign auth: {e}"))?;
337
338    let auth_msg = ClientOutbound::ConnectQuoteProvider {
339        wallet: wallet.address.as_hex(),
340        timestamp: now_ms.to_string(),
341        nonce,
342        signature,
343    };
344    let json = serde_json::to_string(&auth_msg).map_err(|e| format!("JSON encode: {e}"))?;
345    match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Text(json))).await {
346        Ok(Ok(())) => {}
347        Ok(Err(e)) => {
348            callbacks.on_write_failed(QpWriteOperation::Auth, QpWriteFailure::SendError);
349            return Err(format!("Send auth failed: {e}"));
350        }
351        Err(_) => {
352            callbacks.on_write_failed(QpWriteOperation::Auth, QpWriteFailure::Timeout);
353            return Err("Send auth timed out".to_string());
354        }
355    }
356
357    // Wait for auth response
358    let auth_response = tokio::time::timeout(Duration::from_secs(10), ws_receiver.next())
359        .await
360        .map_err(|_| "Auth response timeout".to_string())?
361        .ok_or_else(|| "Connection closed before auth".to_string())?
362        .map_err(|e| format!("Auth frame error: {e}"))?;
363    callbacks.on_transport_activity();
364
365    let auth_text = match auth_response {
366        Message::Text(t) => t,
367        Message::Binary(b) => {
368            String::from_utf8(b.to_vec()).map_err(|_| "Invalid binary frame".to_string())?
369        }
370        Message::Ping(data) => {
371            match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Pong(data))).await {
372                Ok(Ok(())) => {}
373                Ok(Err(_)) => {
374                    callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::SendError);
375                }
376                Err(_) => {
377                    callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::Timeout);
378                }
379            }
380            callbacks.on_transport_activity();
381            return Err("Unexpected ping during auth".into());
382        }
383        Message::Pong(_) => return Err("Unexpected pong during auth".into()),
384        _ => return Err("Unexpected frame type during auth".into()),
385    };
386
387    let server_msg: ServerInbound =
388        serde_json::from_str(&auth_text).map_err(|e| format!("Auth parse: {e}"))?;
389    let capabilities = match server_msg {
390        ServerInbound::Authenticated {
391            wallet: w,
392            capabilities,
393        } => {
394            info!("Authenticated as QP: {}", w);
395            capabilities
396        }
397        ServerInbound::AuthFailed { reason } => {
398            return Err(format!("Authentication failed: {}", reason));
399        }
400        other => return Err(format!("Unexpected message during auth: {:?}", other)),
401    };
402
403    Ok((ws_sender, ws_receiver, capabilities))
404}
405
406async fn connect_and_run(
407    api_url: &str,
408    wallet: &HypercallWallet,
409    outbound_rx: &mut mpsc::Receiver<ClientOutbound>,
410    inbound_tx: &mpsc::Sender<ServerInbound>,
411    callbacks: &dyn QpClientCallbacks,
412) -> Result<(), String> {
413    let (mut ws_sender, mut ws_receiver, _capabilities) =
414        connect_and_auth(api_url, wallet, callbacks).await?;
415
416    // Message loop with heartbeat timeout
417    let mut heartbeat = tokio::time::interval(Duration::from_secs(30));
418    let mut last_activity = tokio::time::Instant::now();
419    let heartbeat_timeout = Duration::from_secs(90);
420
421    loop {
422        tokio::select! {
423            _ = heartbeat.tick() => {
424                if last_activity.elapsed() > heartbeat_timeout {
425                    warn!("QP WebSocket heartbeat timeout ({}s with no activity), reconnecting",
426                          last_activity.elapsed().as_secs());
427                    break;
428                }
429                match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Ping(vec![]))).await {
430                    Ok(Ok(())) => {}
431                    Ok(Err(e)) => {
432                        callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::SendError);
433                        return Err(format!("Send heartbeat failed: {e}"));
434                    }
435                    Err(_) => {
436                        callbacks.on_write_failed(QpWriteOperation::Heartbeat, QpWriteFailure::Timeout);
437                        return Err("Send heartbeat timed out".to_string());
438                    }
439                }
440                callbacks.on_transport_activity();
441            }
442            Some(msg) = outbound_rx.recv() => {
443                let json = serde_json::to_string(&msg).map_err(|e| format!("JSON encode: {e}"))?;
444                match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Text(json))).await {
445                    Ok(Ok(())) => {}
446                    Ok(Err(e)) => {
447                        callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::SendError);
448                        return Err(format!("Send outbound failed: {e}"));
449                    }
450                    Err(_) => {
451                        callbacks.on_write_failed(QpWriteOperation::Outbound, QpWriteFailure::Timeout);
452                        return Err("Send outbound timed out".to_string());
453                    }
454                }
455                callbacks.on_transport_activity();
456            }
457            Some(Ok(frame)) = ws_receiver.next() => {
458                last_activity = tokio::time::Instant::now();
459                callbacks.on_transport_activity();
460                match frame {
461                    Message::Text(text) => {
462                        match serde_json::from_str::<ServerInbound>(&text) {
463                            Ok(msg) => {
464                                forward_inbound_or_close(inbound_tx, msg, callbacks)?;
465                            }
466                            Err(e) => {
467                                warn!("Failed to parse server message: {}", e);
468                            }
469                        }
470                    }
471                    Message::Binary(bytes) => {
472                        if let Ok(text) = String::from_utf8(bytes.to_vec()) {
473                            if let Ok(msg) = serde_json::from_str::<ServerInbound>(&text) {
474                                forward_inbound_or_close(inbound_tx, msg, callbacks)?;
475                            }
476                        }
477                    }
478                    Message::Ping(data) => {
479                        match timeout(WS_WRITE_TIMEOUT, ws_sender.send(Message::Pong(data))).await {
480                            Ok(Ok(())) => {}
481                            Ok(Err(_)) => {
482                                callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::SendError);
483                            }
484                            Err(_) => {
485                                callbacks.on_write_failed(QpWriteOperation::Pong, QpWriteFailure::Timeout);
486                            }
487                        }
488                        callbacks.on_transport_activity();
489                    }
490                    Message::Pong(_) => {}
491                    Message::Close(_) => break,
492                    _ => {}
493                }
494            }
495            else => break,
496        }
497    }
498
499    Ok(())
500}
501
502#[cfg(test)]
503mod tests {
504    use super::*;
505    use std::sync::atomic::{AtomicUsize, Ordering};
506
507    use tokio::net::TcpListener;
508    use tokio_tungstenite::accept_async;
509
510    const TEST_PRIVATE_KEY: &str =
511        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
512
513    #[derive(Default)]
514    struct RecordingCallbacks {
515        connected: AtomicUsize,
516        transport_activity: AtomicUsize,
517    }
518
519    impl QpClientCallbacks for RecordingCallbacks {
520        fn on_connected(&self) {
521            self.connected.fetch_add(1, Ordering::Relaxed);
522        }
523
524        fn on_transport_activity(&self) {
525            self.transport_activity.fetch_add(1, Ordering::Relaxed);
526        }
527    }
528
529    #[tokio::test]
530    async fn connect_and_run_reports_transport_activity_for_ping_pong() {
531        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
532        let addr = listener.local_addr().unwrap();
533
534        let server = tokio::spawn(async move {
535            let (stream, _) = listener.accept().await.unwrap();
536            let mut ws = accept_async(stream).await.unwrap();
537
538            let auth = ws.next().await.unwrap().unwrap();
539            assert!(matches!(auth, Message::Text(_)));
540
541            let authenticated = ServerInbound::Authenticated {
542                wallet: "0x0000000000000000000000000000000000000000".to_string(),
543                capabilities: Vec::new(),
544            };
545            ws.send(Message::Text(
546                serde_json::to_string(&authenticated).unwrap(),
547            ))
548            .await
549            .unwrap();
550
551            ws.send(Message::Ping(vec![1, 2, 3])).await.unwrap();
552
553            while let Some(frame) = ws.next().await {
554                match frame.unwrap() {
555                    Message::Ping(data) => {
556                        ws.send(Message::Pong(data)).await.unwrap();
557                    }
558                    Message::Pong(data) if data == vec![1, 2, 3] => {
559                        ws.close(None).await.unwrap();
560                        break;
561                    }
562                    Message::Close(_) => break,
563                    _ => {}
564                }
565            }
566        });
567
568        let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
569        let (_outbound_tx, mut outbound_rx) = mpsc::channel(8);
570        let (inbound_tx, _inbound_rx) = mpsc::channel(8);
571        let callbacks = RecordingCallbacks::default();
572
573        let result = tokio::time::timeout(
574            Duration::from_secs(5),
575            connect_and_run(
576                &format!("http://{}", addr),
577                &wallet,
578                &mut outbound_rx,
579                &inbound_tx,
580                &callbacks,
581            ),
582        )
583        .await
584        .expect("QP client test timed out");
585
586        result.unwrap();
587        server.await.unwrap();
588
589        assert_eq!(callbacks.connected.load(Ordering::Relaxed), 1);
590        assert!(
591            callbacks.transport_activity.load(Ordering::Relaxed) >= 3,
592            "expected connect, auth, and ping/pong activity callbacks"
593        );
594    }
595}