Skip to main content

hypercall_client/
rfq.rs

1//! High-level RFQ quote builder for Quote Providers.
2#![expect(
3    clippy::result_large_err,
4    reason = "the RFQ builder preserves the established unboxed public ClientError contract"
5)]
6//!
7//! Constructs valid, signed `RfqResponse` messages from an inbound
8//! `RfqRequest` and per-leg prices. The builder enforces the public RFQ
9//! response constraints so invalid quotes are caught client-side instead of
10//! being rejected later.
11//!
12//! # Example
13//!
14//! ```rust,no_run
15//! use hypercall_client::{HypercallWallet, rfq};
16//! use hypercall_client::qp_client::ServerInbound;
17//! use rust_decimal_macros::dec;
18//!
19//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
20//! let wallet = HypercallWallet::from_private_key("0x...", 999)?;
21//!
22//! // When you receive an RfqRequest from the server:
23//! // let msg: ServerInbound = ...;
24//! // if let ServerInbound::RfqRequest { rfq_id, legs, .. } = msg {
25//! //     let quote = rfq::build_rfq_quote(&rfq_id, &legs, &[dec!(0.05)], 3000, &wallet).await?;
26//! //     outbound_tx.send(quote).await?;
27//! // }
28//! # Ok(())
29//! # }
30//! ```
31
32use rust_decimal::prelude::ToPrimitive;
33use rust_decimal::Decimal;
34
35use crate::error::{ClientError, Result, RfqInputError};
36use crate::wallet::HypercallWallet;
37use hypercall_ws_protocol::{QpClientMessage, QpResponseLeg, QpRfqLeg};
38
39/// EIP-712 encodes `net_premium` as an integer number of micro-units (6
40/// decimal places). The signing conversion truncates any finer precision
41/// toward zero, so the signed value must bind exactly the premium emitted on
42/// the wire — sub-micro digits would let the signature diverge from what the
43/// server stores and charges.
44const NET_PREMIUM_MICRO_DECIMAL_PLACES: u32 = 6;
45
46/// Build a signed RFQ quote response from an inbound RFQ request.
47///
48/// Only per-leg prices come from the quote provider. Instrument, side, and
49/// size are echoed from the original request, preventing the class of bugs
50/// where a QP constructs a semantically invalid response that is rejected
51/// later.
52///
53/// # Net premium sign convention
54///
55/// - Taker **buy** legs contribute `-price * size` (debit to taker)
56/// - Taker **sell** legs contribute `+price * size` (credit to taker)
57///
58/// The net premium is the sum across all legs.
59pub async fn build_rfq_quote(
60    rfq_id: &str,
61    legs: &[QpRfqLeg],
62    leg_prices: &[Decimal],
63    valid_for_ms: u64,
64    wallet: &HypercallWallet,
65) -> Result<QpClientMessage> {
66    if legs.is_empty() {
67        return Err(ClientError::RfqInput(RfqInputError::NoLegs));
68    }
69    if legs.len() != leg_prices.len() {
70        return Err(ClientError::RfqInput(RfqInputError::LegCountMismatch {
71            request_count: legs.len(),
72            price_count: leg_prices.len(),
73        }));
74    }
75
76    let mut response_legs = Vec::with_capacity(legs.len());
77    let mut net_premium = Decimal::ZERO;
78
79    for (i, (leg, price)) in legs.iter().zip(leg_prices.iter()).enumerate() {
80        if *price <= Decimal::ZERO {
81            return Err(ClientError::RfqInput(RfqInputError::LegPriceNonPositive {
82                index: i,
83                price: *price,
84            }));
85        }
86
87        let size: Decimal = leg.size.parse().map_err(|source| {
88            ClientError::RfqInput(RfqInputError::InvalidLegSize {
89                label: "invalid",
90                value: leg.size.clone(),
91                source,
92            })
93        })?;
94        if size <= Decimal::ZERO {
95            return Err(ClientError::RfqInput(RfqInputError::LegSizeNonPositive {
96                index: i,
97                size,
98            }));
99        }
100
101        match leg.side.to_lowercase().as_str() {
102            "buy" => net_premium -= *price * size,
103            "sell" => net_premium += *price * size,
104            other => {
105                return Err(ClientError::RfqInput(RfqInputError::InvalidSide {
106                    index: i,
107                    side: other.to_owned(),
108                }));
109            }
110        }
111
112        response_legs.push(QpResponseLeg {
113            instrument: leg.instrument.clone(),
114            side: leg.side.clone(),
115            price: price.to_string(),
116            size: leg.size.clone(),
117        });
118    }
119
120    let legs_hash = compute_qp_legs_hash(legs)?;
121
122    // Reject sub-micro net_premium before the `* 1e6 -> to_i64()` conversion
123    // truncates it toward zero. Without this guard the signed integer would
124    // alias distinct premiums while `net_premium.to_string()` on the wire
125    // carries the full-precision value the server stores and charges.
126    if net_premium.normalize().scale() > NET_PREMIUM_MICRO_DECIMAL_PLACES {
127        return Err(ClientError::RfqInput(
128            RfqInputError::NetPremiumSubMicroPrecision { net_premium },
129        ));
130    }
131
132    let premium_scaled = net_premium * Decimal::new(1_000_000, 0);
133    let premium_micro = premium_scaled.to_i64().ok_or(ClientError::RfqInput(
134        RfqInputError::NetPremiumNotRepresentable { net_premium },
135    ))?;
136    let net_premium_i256 = alloy::primitives::I256::try_from(premium_micro).map_err(|source| {
137        ClientError::RfqInput(RfqInputError::NetPremiumConversion {
138            source: Box::new(source),
139        })
140    })?;
141    let valid_for_u256 = alloy::primitives::U256::from(valid_for_ms);
142
143    let rfq_uuid = uuid::Uuid::parse_str(rfq_id).map_err(|source| {
144        ClientError::RfqInput(RfqInputError::InvalidUuid {
145            label: "invalid rfq_id",
146            source,
147        })
148    })?;
149    let mut rfq_id_bytes = [0u8; 32];
150    rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
151
152    let nonce = wallet.next_nonce();
153    let signature = wallet
154        .sign_submit_rfq_response(
155            rfq_id_bytes,
156            legs_hash,
157            net_premium_i256,
158            valid_for_u256,
159            nonce,
160        )
161        .await?;
162
163    Ok(QpClientMessage::RfqResponse {
164        rfq_id: rfq_id.to_string(),
165        action: "quote".to_string(),
166        legs: Some(response_legs),
167        net_premium: Some(net_premium.to_string()),
168        valid_for_ms: Some(valid_for_ms),
169        signature: Some(signature),
170        nonce: Some(nonce),
171    })
172}
173
174/// Build a decline response for an RFQ.
175pub fn build_rfq_decline(rfq_id: &str) -> QpClientMessage {
176    QpClientMessage::RfqResponse {
177        rfq_id: rfq_id.to_string(),
178        action: "decline".to_string(),
179        legs: None,
180        net_premium: None,
181        valid_for_ms: None,
182        signature: None,
183        nonce: None,
184    }
185}
186
187fn compute_qp_legs_hash(legs: &[QpRfqLeg]) -> Result<[u8; 32]> {
188    use sha3::Digest;
189    let canonical = legs
190        .iter()
191        .map(|l| {
192            let size_canonical = l
193                .size
194                .parse::<Decimal>()
195                .map_err(|source| {
196                    ClientError::RfqInput(RfqInputError::InvalidLegSize {
197                        label: "invalid",
198                        value: l.size.clone(),
199                        source,
200                    })
201                })?
202                .to_string();
203            Ok(format!(
204                "{}|{}|{}",
205                l.instrument,
206                l.side.to_lowercase(),
207                size_canonical
208            ))
209        })
210        .collect::<Result<Vec<_>>>()?
211        .join(";");
212    let mut hasher = sha3::Keccak256::new();
213    hasher.update(canonical.as_bytes());
214    Ok(hasher.finalize().into())
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use crate::HypercallWallet;
221    use rust_decimal_macros::dec;
222
223    const TEST_KEY: &str = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
224
225    fn make_legs(specs: &[(&str, &str, &str)]) -> Vec<QpRfqLeg> {
226        specs
227            .iter()
228            .map(|(inst, side, size)| QpRfqLeg {
229                instrument: inst.to_string(),
230                side: side.to_string(),
231                size: size.to_string(),
232            })
233            .collect()
234    }
235
236    #[tokio::test]
237    async fn single_leg_buy_produces_negative_premium() {
238        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
239        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
240        let msg = build_rfq_quote(
241            "019060da-0000-7000-8000-000000000001",
242            &legs,
243            &[dec!(500)],
244            3000,
245            &wallet,
246        )
247        .await
248        .unwrap();
249
250        if let QpClientMessage::RfqResponse {
251            net_premium,
252            legs: resp_legs,
253            signature,
254            nonce,
255            action,
256            ..
257        } = msg
258        {
259            assert_eq!(action, "quote");
260            let premium: Decimal = net_premium.unwrap().parse().unwrap();
261            assert!(
262                premium < Decimal::ZERO,
263                "taker-buy should be negative premium"
264            );
265            assert_eq!(premium, dec!(-500));
266            assert!(signature.unwrap().starts_with("0x"));
267            assert!(nonce.is_some());
268            let resp = resp_legs.unwrap();
269            assert_eq!(resp.len(), 1);
270            assert_eq!(resp[0].instrument, "BTC-20260501-90000-C");
271            assert_eq!(resp[0].side, "buy");
272            assert_eq!(resp[0].size, "1");
273        } else {
274            panic!("expected RfqResponse");
275        }
276    }
277
278    #[tokio::test]
279    async fn single_leg_sell_produces_positive_premium() {
280        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
281        let legs = make_legs(&[("BTC-20260501-90000-C", "sell", "2")]);
282        let msg = build_rfq_quote(
283            "019060da-0000-7000-8000-000000000002",
284            &legs,
285            &[dec!(300)],
286            3000,
287            &wallet,
288        )
289        .await
290        .unwrap();
291
292        if let QpClientMessage::RfqResponse { net_premium, .. } = msg {
293            let premium: Decimal = net_premium.unwrap().parse().unwrap();
294            assert!(
295                premium > Decimal::ZERO,
296                "taker-sell should be positive premium"
297            );
298            assert_eq!(premium, dec!(600));
299        } else {
300            panic!("expected RfqResponse");
301        }
302    }
303
304    #[tokio::test]
305    async fn multi_leg_net_premium() {
306        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
307        let legs = make_legs(&[
308            ("BTC-20260501-90000-C", "buy", "1"),
309            ("BTC-20260501-100000-C", "sell", "1"),
310        ]);
311        let msg = build_rfq_quote(
312            "019060da-0000-7000-8000-000000000003",
313            &legs,
314            &[dec!(500), dec!(200)],
315            3000,
316            &wallet,
317        )
318        .await
319        .unwrap();
320
321        if let QpClientMessage::RfqResponse { net_premium, .. } = msg {
322            let premium: Decimal = net_premium.unwrap().parse().unwrap();
323            // buy leg: -500, sell leg: +200 = -300
324            assert_eq!(premium, dec!(-300));
325        } else {
326            panic!("expected RfqResponse");
327        }
328    }
329
330    #[tokio::test]
331    async fn rejects_zero_price() {
332        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
333        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
334        let err = build_rfq_quote(
335            "019060da-0000-7000-8000-000000000004",
336            &legs,
337            &[dec!(0)],
338            3000,
339            &wallet,
340        )
341        .await
342        .unwrap_err();
343        assert!(matches!(
344            &err,
345            ClientError::RfqInput(RfqInputError::LegPriceNonPositive { index: 0, price })
346                if *price == dec!(0)
347        ));
348        assert_eq!(
349            err.to_string(),
350            "API error (0): leg 0 price must be positive, got 0"
351        );
352    }
353
354    #[tokio::test]
355    async fn rejects_negative_price() {
356        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
357        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
358        let err = build_rfq_quote(
359            "019060da-0000-7000-8000-000000000005",
360            &legs,
361            &[dec!(-10)],
362            3000,
363            &wallet,
364        )
365        .await
366        .unwrap_err();
367        assert!(matches!(
368            &err,
369            ClientError::RfqInput(RfqInputError::LegPriceNonPositive { index: 0, price })
370                if *price == dec!(-10)
371        ));
372        assert_eq!(
373            err.to_string(),
374            "API error (0): leg 0 price must be positive, got -10"
375        );
376    }
377
378    #[tokio::test]
379    async fn rejects_leg_count_mismatch() {
380        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
381        let legs = make_legs(&[
382            ("BTC-20260501-90000-C", "buy", "1"),
383            ("BTC-20260501-100000-C", "sell", "1"),
384        ]);
385        let err = build_rfq_quote(
386            "019060da-0000-7000-8000-000000000006",
387            &legs,
388            &[dec!(500)],
389            3000,
390            &wallet,
391        )
392        .await
393        .unwrap_err();
394        assert!(matches!(
395            &err,
396            ClientError::RfqInput(RfqInputError::LegCountMismatch {
397                request_count: 2,
398                price_count: 1,
399            })
400        ));
401        assert_eq!(
402            err.to_string(),
403            "API error (0): leg count mismatch: request has 2 legs but 1 prices provided"
404        );
405    }
406
407    #[tokio::test]
408    async fn rejects_invalid_side() {
409        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
410        let legs = make_legs(&[("BTC-20260501-90000-C", "long", "1")]);
411        let err = build_rfq_quote(
412            "019060da-0000-7000-8000-000000000007",
413            &legs,
414            &[dec!(500)],
415            3000,
416            &wallet,
417        )
418        .await
419        .unwrap_err();
420        assert!(matches!(
421            &err,
422            ClientError::RfqInput(RfqInputError::InvalidSide { index: 0, side })
423                if side == "long"
424        ));
425        assert_eq!(
426            err.to_string(),
427            "API error (0): leg 0 has invalid side: \"long\""
428        );
429    }
430
431    #[tokio::test]
432    async fn decline_has_no_signature() {
433        let msg = build_rfq_decline("019060da-0000-7000-8000-000000000008");
434        if let QpClientMessage::RfqResponse {
435            action,
436            signature,
437            legs,
438            ..
439        } = msg
440        {
441            assert_eq!(action, "decline");
442            assert!(signature.is_none());
443            assert!(legs.is_none());
444        } else {
445            panic!("expected RfqResponse");
446        }
447    }
448
449    #[tokio::test]
450    async fn legs_hash_matches_server_canonicalization() {
451        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1.50")]);
452        let hash = compute_qp_legs_hash(&legs).unwrap();
453
454        use sha3::Digest;
455        let size_canonical = "1.50".parse::<Decimal>().unwrap().to_string();
456        let canonical = format!("BTC-20260501-90000-C|buy|{}", size_canonical);
457        let mut hasher = sha3::Keccak256::new();
458        hasher.update(canonical.as_bytes());
459        let expected: [u8; 32] = hasher.finalize().into();
460
461        assert_eq!(hash, expected);
462
463        // Different representation of same value produces same hash
464        let legs2 = make_legs(&[("BTC-20260501-90000-C", "buy", "01.50")]);
465        let hash2 = compute_qp_legs_hash(&legs2).unwrap();
466        assert_eq!(hash, hash2, "01.50 and 1.50 should produce same hash");
467    }
468
469    #[tokio::test]
470    async fn signature_includes_signed_quote_payload() {
471        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
472        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
473        let msg = build_rfq_quote(
474            "019060da-0000-7000-8000-000000000009",
475            &legs,
476            &[dec!(500)],
477            3000,
478            &wallet,
479        )
480        .await
481        .unwrap();
482
483        if let QpClientMessage::RfqResponse {
484            net_premium,
485            valid_for_ms,
486            signature,
487            nonce,
488            ..
489        } = msg
490        {
491            let premium: Decimal = net_premium.unwrap().parse().unwrap();
492            assert_eq!(premium, dec!(-500));
493            let valid_for_ms = valid_for_ms.unwrap();
494            assert_eq!(valid_for_ms, 3000);
495            let nonce = nonce.unwrap();
496            let signature = signature.unwrap();
497            assert!(signature.starts_with("0x"));
498
499            let rfq_uuid = uuid::Uuid::parse_str("019060da-0000-7000-8000-000000000009").unwrap();
500            let mut rfq_id_bytes = [0u8; 32];
501            rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
502            let legs_hash = compute_qp_legs_hash(&legs).unwrap();
503            let expected_signature = wallet
504                .sign_submit_rfq_response(
505                    rfq_id_bytes,
506                    legs_hash,
507                    alloy::primitives::I256::try_from(-500_000_000i64).unwrap(),
508                    alloy::primitives::U256::from(valid_for_ms),
509                    nonce,
510                )
511                .await
512                .unwrap();
513            assert_eq!(signature, expected_signature);
514        } else {
515            panic!("expected RfqResponse");
516        }
517    }
518
519    #[tokio::test]
520    async fn rejects_sub_micro_net_premium() {
521        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
522        let legs = make_legs(&[("BTC-20260501-90000-C", "sell", "1")]);
523        // sell leg: net_premium = price * size = 1.0000009 (7 decimal places).
524        let err = build_rfq_quote(
525            "019060da-0000-7000-8000-000000000010",
526            &legs,
527            &[dec!(1.0000009)],
528            3000,
529            &wallet,
530        )
531        .await
532        .unwrap_err();
533        assert!(matches!(
534            &err,
535            ClientError::RfqInput(RfqInputError::NetPremiumSubMicroPrecision { net_premium })
536                if *net_premium == dec!(1.0000009)
537        ));
538        assert!(
539            err.to_string().contains("sub-micro precision"),
540            "expected sub-micro precision message, got: {err}"
541        );
542    }
543
544    #[tokio::test]
545    async fn admits_exactly_six_decimal_places_net_premium() {
546        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
547        let legs = make_legs(&[("BTC-20260501-90000-C", "sell", "1")]);
548        let msg = build_rfq_quote(
549            "019060da-0000-7000-8000-000000000011",
550            &legs,
551            &[dec!(1.123456)],
552            3000,
553            &wallet,
554        )
555        .await
556        .unwrap();
557        if let QpClientMessage::RfqResponse { net_premium, .. } = msg {
558            let premium: Decimal = net_premium.unwrap().parse().unwrap();
559            assert_eq!(premium, dec!(1.123456));
560        } else {
561            panic!("expected RfqResponse");
562        }
563    }
564}