Skip to main content

hypercall_ws_protocol/
qp.rs

1//! Quote Provider WebSocket protocol for `/ws/quotes`.
2
3use serde::{Deserialize, Serialize};
4use std::borrow::Cow;
5
6/// Capability string advertised in [`QpServerMessage::Authenticated`] when
7/// the server accepts [`QpClientMessage::ScopedIndicativeQuoteUpdate`].
8/// Clients must not send scoped updates without seeing this capability.
9pub const CAP_SCOPED_INDICATIVE: &str = "scoped_indicative";
10
11/// Opaque scope identifier for scoped indicative updates: exactly 16 bytes,
12/// contents client-defined. The server never interprets the contents; it
13/// only uses the id as a partition key for snapshot-omission eviction.
14///
15/// Wire form is a 32-character canonical lowercase hex JSON string. How a
16/// client derives the bytes is its own convention: a zero-padded ASCII
17/// label ([`ScopeId::from_label`]), raw UUID bytes (a UUID is already 128
18/// bits), or a stable 128-bit hash of a longer name. Collisions only
19/// matter within one wallet's scopes, so non-cryptographic derivations
20/// are fine.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct ScopeId(pub [u8; 16]);
23
24impl ScopeId {
25    /// Canonical wire form: 32 lowercase hex characters.
26    pub fn to_hex(self) -> String {
27        let mut out = String::with_capacity(32);
28        for b in self.0 {
29            use std::fmt::Write;
30            write!(out, "{b:02x}").expect("writing hex to String cannot fail");
31        }
32        out
33    }
34
35    /// Convenience derivation: an ASCII label of at most 16 bytes,
36    /// zero-padded. Returns `None` for longer labels rather than
37    /// truncating, because truncation would silently collide distinct
38    /// scopes.
39    pub fn from_label(label: &str) -> Option<Self> {
40        let bytes = label.as_bytes();
41        if bytes.is_empty() || bytes.len() > 16 {
42            return None;
43        }
44        let mut buf = [0u8; 16];
45        buf[..bytes.len()].copy_from_slice(bytes);
46        Some(Self(buf))
47    }
48}
49
50impl std::fmt::Display for ScopeId {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.write_str(&self.to_hex())
53    }
54}
55
56impl TryFrom<&str> for ScopeId {
57    type Error = ScopeIdParseError;
58
59    fn try_from(s: &str) -> Result<Self, Self::Error> {
60        let bytes = s.as_bytes();
61        if bytes.len() != 32 {
62            return Err(ScopeIdParseError::Length(bytes.len()));
63        }
64        let mut buf = [0u8; 16];
65        for (i, chunk) in bytes.chunks_exact(2).enumerate() {
66            let hi = hex_nibble(chunk[0]).ok_or(ScopeIdParseError::NotLowercaseHex)?;
67            let lo = hex_nibble(chunk[1]).ok_or(ScopeIdParseError::NotLowercaseHex)?;
68            buf[i] = (hi << 4) | lo;
69        }
70        Ok(Self(buf))
71    }
72}
73
74/// Canonical lowercase only: each scope has exactly one wire
75/// representation, so byte-level dedup/compare of frames stays valid.
76fn hex_nibble(c: u8) -> Option<u8> {
77    match c {
78        b'0'..=b'9' => Some(c - b'0'),
79        b'a'..=b'f' => Some(c - b'a' + 10),
80        _ => None,
81    }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
85#[displaystr::display]
86pub enum ScopeIdParseError {
87    /// Wire scope must be exactly 32 hex characters (16 bytes).
88    Length(usize) = "scope must be 32 lowercase hex chars, got length {_0}",
89    /// Wire scope must be canonical lowercase hex.
90    NotLowercaseHex = "scope must be canonical lowercase hex",
91}
92
93impl Serialize for ScopeId {
94    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
95        serializer.serialize_str(&self.to_hex())
96    }
97}
98
99impl<'de> Deserialize<'de> for ScopeId {
100    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
101        // Cow borrows when the deserializer can lend (in-memory JSON with
102        // no escapes, the hot server path) and owns otherwise (readers).
103        let s = std::borrow::Cow::<str>::deserialize(deserializer)?;
104        Self::try_from(s.as_ref()).map_err(serde::de::Error::custom)
105    }
106}
107
108/// Gateway-authenticated reconnect request for an already-authenticated QP.
109///
110/// Direct public QP connections use `ConnectQuoteProvider` and strict nonce
111/// checks.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113pub struct GatewayResumeQuoteProvider {
114    pub wallet: String,
115    pub timestamp: String,
116    pub nonce: u64,
117    pub signature: String,
118}
119
120/// Messages sent by a QP client.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(tag = "type", rename_all = "snake_case")]
123pub enum QpClientMessage {
124    /// First frame for direct QP connections.
125    ConnectQuoteProvider {
126        wallet: String,
127        timestamp: String,
128        nonce: u64,
129        signature: String,
130    },
131    /// First frame for gateway-managed reconnects.
132    ///
133    /// Public QP clients must not send it directly.
134    GatewayResumeQuoteProvider {
135        wallet: String,
136        timestamp: String,
137        nonce: u64,
138        signature: String,
139    },
140    /// Periodic indicative quote update: a full snapshot for the wallet.
141    /// Instruments this wallet previously quoted but omits here are
142    /// evicted server-side.
143    IndicativeQuoteUpdate { quotes: Vec<IndicativeQuote> },
144    /// Scoped indicative quote update: a full snapshot of one
145    /// client-defined scope (see [`ScopeId`]). Eviction-by-omission is
146    /// limited to instruments this wallet previously published under the
147    /// same scope; other scopes are untouched. Empty `quotes` explicitly
148    /// clears the scope.
149    ///
150    /// Clients must only send this after the server advertised
151    /// [`CAP_SCOPED_INDICATIVE`] in [`QpServerMessage::Authenticated`];
152    /// older servers reject the unknown message type.
153    ScopedIndicativeQuoteUpdate {
154        scope: ScopeId,
155        quotes: Vec<IndicativeQuote>,
156    },
157    /// Firm quote response to an RFQ.
158    RfqResponse {
159        rfq_id: String,
160        /// "quote" or "decline".
161        action: String,
162        #[serde(skip_serializing_if = "Option::is_none")]
163        legs: Option<Vec<QpResponseLeg>>,
164        #[serde(skip_serializing_if = "Option::is_none")]
165        net_premium: Option<String>,
166        #[serde(skip_serializing_if = "Option::is_none")]
167        valid_for_ms: Option<u64>,
168        #[serde(skip_serializing_if = "Option::is_none")]
169        signature: Option<String>,
170        #[serde(skip_serializing_if = "Option::is_none")]
171        nonce: Option<u64>,
172    },
173}
174
175/// Messages sent to a QP client.
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(tag = "type", rename_all = "snake_case")]
178pub enum QpServerMessage {
179    Authenticated {
180        wallet: String,
181        /// Optional protocol capabilities this server supports (e.g.
182        /// [`CAP_SCOPED_INDICATIVE`]). Absent/empty on older servers, and
183        /// omitted from the wire when empty so a server advertising
184        /// nothing is byte-identical to a pre-capability server. Clients
185        /// must treat unknown strings as inert.
186        #[serde(default, skip_serializing_if = "Vec::is_empty")]
187        capabilities: Vec<String>,
188    },
189    AuthFailed {
190        reason: String,
191    },
192    RfqRequest {
193        rfq_id: String,
194        legs: Vec<QpRfqLeg>,
195        taker_wallet: String,
196        request_timestamp: u64,
197        response_deadline_ms: u64,
198        #[serde(default, skip_serializing_if = "Option::is_none")]
199        auto_accept_limit: Option<String>,
200        #[serde(default)]
201        auto_execute: bool,
202        #[serde(default, skip_serializing_if = "Option::is_none")]
203        taker_limit_price: Option<String>,
204        #[serde(default, skip_serializing_if = "Option::is_none")]
205        reference_price: Option<String>,
206        #[serde(default, skip_serializing_if = "Option::is_none")]
207        min_improvement_tick: Option<String>,
208        #[serde(default, skip_serializing_if = "Option::is_none")]
209        auction_deadline_ms: Option<u64>,
210        #[serde(default)]
211        requires_price_improvement: bool,
212    },
213    QpMarginRejection {
214        rfq_id: String,
215        quote_id: String,
216        reason: String,
217    },
218    RfqAlreadyFilled {
219        rfq_id: String,
220        filled_by_quote_id: String,
221    },
222}
223
224/// Backwards-compatible names for API-side code.
225pub type QpInboundMessage = QpClientMessage;
226pub type QpOutboundMessage = QpServerMessage;
227
228/// A single indicative quote for an instrument.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct IndicativeQuote {
231    pub instrument: String,
232    pub bid_price: String,
233    pub ask_price: String,
234    pub max_bid_size: String,
235    pub max_ask_size: String,
236}
237
238/// Borrowing view of an indicative snapshot used by allocation-sensitive ingress.
239///
240/// Unescaped JSON strings point into the original WebSocket frame. Escaped strings
241/// fall back to an owned value so this remains wire-compatible with the ordinary
242/// [`QpClientMessage`] decoder.
243#[derive(Debug, PartialEq, Eq, Deserialize)]
244pub struct BorrowedIndicativeQuoteUpdate<'a> {
245    #[serde(rename = "type")]
246    _message_type: IndicativeQuoteUpdateType,
247    #[serde(borrow)]
248    pub quotes: Vec<BorrowedIndicativeQuote<'a>>,
249}
250
251#[derive(Debug, PartialEq, Eq, Deserialize)]
252#[serde(rename_all = "snake_case")]
253enum IndicativeQuoteUpdateType {
254    IndicativeQuoteUpdate,
255}
256
257/// One quote whose string fields borrow from the snapshot frame when possible.
258#[derive(Debug, PartialEq, Eq, Deserialize)]
259pub struct BorrowedIndicativeQuote<'a> {
260    #[serde(borrow)]
261    pub instrument: Cow<'a, str>,
262    #[serde(borrow)]
263    pub bid_price: Cow<'a, str>,
264    #[serde(borrow)]
265    pub ask_price: Cow<'a, str>,
266    #[serde(borrow)]
267    pub max_bid_size: Cow<'a, str>,
268    #[serde(borrow)]
269    pub max_ask_size: Cow<'a, str>,
270}
271
272/// Borrowing view of a SCOPED indicative snapshot, the scoped counterpart
273/// of [`BorrowedIndicativeQuoteUpdate`]. Same borrowing rules; the scope
274/// id is fixed-size and always owned.
275#[derive(Debug, PartialEq, Eq, Deserialize)]
276pub struct BorrowedScopedIndicativeQuoteUpdate<'a> {
277    #[serde(rename = "type")]
278    _message_type: ScopedIndicativeQuoteUpdateType,
279    pub scope: ScopeId,
280    #[serde(borrow)]
281    pub quotes: Vec<BorrowedIndicativeQuote<'a>>,
282}
283
284#[derive(Debug, PartialEq, Eq, Deserialize)]
285#[serde(rename_all = "snake_case")]
286enum ScopedIndicativeQuoteUpdateType {
287    ScopedIndicativeQuoteUpdate,
288}
289
290/// A leg in a QP's firm quote response.
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292pub struct QpResponseLeg {
293    pub instrument: String,
294    pub side: String,
295    pub price: String,
296    pub size: String,
297}
298
299/// A leg in an RFQ request sent to QPs.
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301pub struct QpRfqLeg {
302    pub instrument: String,
303    pub side: String,
304    pub size: String,
305}
306
307#[cfg(test)]
308#[path = "qp_test.rs"]
309mod tests;