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                physical: None,
233            })
234            .collect()
235    }
236
237    #[tokio::test]
238    async fn single_leg_buy_produces_negative_premium() {
239        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
240        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
241        let msg = build_rfq_quote(
242            "019060da-0000-7000-8000-000000000001",
243            &legs,
244            &[dec!(500)],
245            3000,
246            &wallet,
247        )
248        .await
249        .unwrap();
250
251        if let QpClientMessage::RfqResponse {
252            net_premium,
253            legs: resp_legs,
254            signature,
255            nonce,
256            action,
257            ..
258        } = msg
259        {
260            assert_eq!(action, "quote");
261            let premium: Decimal = net_premium.unwrap().parse().unwrap();
262            assert!(
263                premium < Decimal::ZERO,
264                "taker-buy should be negative premium"
265            );
266            assert_eq!(premium, dec!(-500));
267            assert!(signature.unwrap().starts_with("0x"));
268            assert!(nonce.is_some());
269            let resp = resp_legs.unwrap();
270            assert_eq!(resp.len(), 1);
271            assert_eq!(resp[0].instrument, "BTC-20260501-90000-C");
272            assert_eq!(resp[0].side, "buy");
273            assert_eq!(resp[0].size, "1");
274        } else {
275            panic!("expected RfqResponse");
276        }
277    }
278
279    #[tokio::test]
280    async fn single_leg_sell_produces_positive_premium() {
281        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
282        let legs = make_legs(&[("BTC-20260501-90000-C", "sell", "2")]);
283        let msg = build_rfq_quote(
284            "019060da-0000-7000-8000-000000000002",
285            &legs,
286            &[dec!(300)],
287            3000,
288            &wallet,
289        )
290        .await
291        .unwrap();
292
293        if let QpClientMessage::RfqResponse { net_premium, .. } = msg {
294            let premium: Decimal = net_premium.unwrap().parse().unwrap();
295            assert!(
296                premium > Decimal::ZERO,
297                "taker-sell should be positive premium"
298            );
299            assert_eq!(premium, dec!(600));
300        } else {
301            panic!("expected RfqResponse");
302        }
303    }
304
305    #[tokio::test]
306    async fn multi_leg_net_premium() {
307        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
308        let legs = make_legs(&[
309            ("BTC-20260501-90000-C", "buy", "1"),
310            ("BTC-20260501-100000-C", "sell", "1"),
311        ]);
312        let msg = build_rfq_quote(
313            "019060da-0000-7000-8000-000000000003",
314            &legs,
315            &[dec!(500), dec!(200)],
316            3000,
317            &wallet,
318        )
319        .await
320        .unwrap();
321
322        if let QpClientMessage::RfqResponse { net_premium, .. } = msg {
323            let premium: Decimal = net_premium.unwrap().parse().unwrap();
324            // buy leg: -500, sell leg: +200 = -300
325            assert_eq!(premium, dec!(-300));
326        } else {
327            panic!("expected RfqResponse");
328        }
329    }
330
331    #[tokio::test]
332    async fn rejects_zero_price() {
333        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
334        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
335        let err = build_rfq_quote(
336            "019060da-0000-7000-8000-000000000004",
337            &legs,
338            &[dec!(0)],
339            3000,
340            &wallet,
341        )
342        .await
343        .unwrap_err();
344        assert!(matches!(
345            &err,
346            ClientError::RfqInput(RfqInputError::LegPriceNonPositive { index: 0, price })
347                if *price == dec!(0)
348        ));
349        assert_eq!(
350            err.to_string(),
351            "API error (0): leg 0 price must be positive, got 0"
352        );
353    }
354
355    #[tokio::test]
356    async fn rejects_negative_price() {
357        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
358        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
359        let err = build_rfq_quote(
360            "019060da-0000-7000-8000-000000000005",
361            &legs,
362            &[dec!(-10)],
363            3000,
364            &wallet,
365        )
366        .await
367        .unwrap_err();
368        assert!(matches!(
369            &err,
370            ClientError::RfqInput(RfqInputError::LegPriceNonPositive { index: 0, price })
371                if *price == dec!(-10)
372        ));
373        assert_eq!(
374            err.to_string(),
375            "API error (0): leg 0 price must be positive, got -10"
376        );
377    }
378
379    #[tokio::test]
380    async fn rejects_leg_count_mismatch() {
381        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
382        let legs = make_legs(&[
383            ("BTC-20260501-90000-C", "buy", "1"),
384            ("BTC-20260501-100000-C", "sell", "1"),
385        ]);
386        let err = build_rfq_quote(
387            "019060da-0000-7000-8000-000000000006",
388            &legs,
389            &[dec!(500)],
390            3000,
391            &wallet,
392        )
393        .await
394        .unwrap_err();
395        assert!(matches!(
396            &err,
397            ClientError::RfqInput(RfqInputError::LegCountMismatch {
398                request_count: 2,
399                price_count: 1,
400            })
401        ));
402        assert_eq!(
403            err.to_string(),
404            "API error (0): leg count mismatch: request has 2 legs but 1 prices provided"
405        );
406    }
407
408    #[tokio::test]
409    async fn rejects_invalid_side() {
410        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
411        let legs = make_legs(&[("BTC-20260501-90000-C", "long", "1")]);
412        let err = build_rfq_quote(
413            "019060da-0000-7000-8000-000000000007",
414            &legs,
415            &[dec!(500)],
416            3000,
417            &wallet,
418        )
419        .await
420        .unwrap_err();
421        assert!(matches!(
422            &err,
423            ClientError::RfqInput(RfqInputError::InvalidSide { index: 0, side })
424                if side == "long"
425        ));
426        assert_eq!(
427            err.to_string(),
428            "API error (0): leg 0 has invalid side: \"long\""
429        );
430    }
431
432    #[tokio::test]
433    async fn decline_has_no_signature() {
434        let msg = build_rfq_decline("019060da-0000-7000-8000-000000000008");
435        if let QpClientMessage::RfqResponse {
436            action,
437            signature,
438            legs,
439            ..
440        } = msg
441        {
442            assert_eq!(action, "decline");
443            assert!(signature.is_none());
444            assert!(legs.is_none());
445        } else {
446            panic!("expected RfqResponse");
447        }
448    }
449
450    #[tokio::test]
451    async fn legs_hash_matches_server_canonicalization() {
452        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1.50")]);
453        let hash = compute_qp_legs_hash(&legs).unwrap();
454
455        use sha3::Digest;
456        let size_canonical = "1.50".parse::<Decimal>().unwrap().to_string();
457        let canonical = format!("BTC-20260501-90000-C|buy|{}", size_canonical);
458        let mut hasher = sha3::Keccak256::new();
459        hasher.update(canonical.as_bytes());
460        let expected: [u8; 32] = hasher.finalize().into();
461
462        assert_eq!(hash, expected);
463
464        // Different representation of same value produces same hash
465        let legs2 = make_legs(&[("BTC-20260501-90000-C", "buy", "01.50")]);
466        let hash2 = compute_qp_legs_hash(&legs2).unwrap();
467        assert_eq!(hash, hash2, "01.50 and 1.50 should produce same hash");
468    }
469
470    #[tokio::test]
471    async fn signature_includes_signed_quote_payload() {
472        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
473        let legs = make_legs(&[("BTC-20260501-90000-C", "buy", "1")]);
474        let msg = build_rfq_quote(
475            "019060da-0000-7000-8000-000000000009",
476            &legs,
477            &[dec!(500)],
478            3000,
479            &wallet,
480        )
481        .await
482        .unwrap();
483
484        if let QpClientMessage::RfqResponse {
485            net_premium,
486            valid_for_ms,
487            signature,
488            nonce,
489            ..
490        } = msg
491        {
492            let premium: Decimal = net_premium.unwrap().parse().unwrap();
493            assert_eq!(premium, dec!(-500));
494            let valid_for_ms = valid_for_ms.unwrap();
495            assert_eq!(valid_for_ms, 3000);
496            let nonce = nonce.unwrap();
497            let signature = signature.unwrap();
498            assert!(signature.starts_with("0x"));
499
500            let rfq_uuid = uuid::Uuid::parse_str("019060da-0000-7000-8000-000000000009").unwrap();
501            let mut rfq_id_bytes = [0u8; 32];
502            rfq_id_bytes[16..].copy_from_slice(rfq_uuid.as_bytes());
503            let legs_hash = compute_qp_legs_hash(&legs).unwrap();
504            let expected_signature = wallet
505                .sign_submit_rfq_response(
506                    rfq_id_bytes,
507                    legs_hash,
508                    alloy::primitives::I256::try_from(-500_000_000i64).unwrap(),
509                    alloy::primitives::U256::from(valid_for_ms),
510                    nonce,
511                )
512                .await
513                .unwrap();
514            assert_eq!(signature, expected_signature);
515        } else {
516            panic!("expected RfqResponse");
517        }
518    }
519
520    #[tokio::test]
521    async fn rejects_sub_micro_net_premium() {
522        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
523        let legs = make_legs(&[("BTC-20260501-90000-C", "sell", "1")]);
524        // sell leg: net_premium = price * size = 1.0000009 (7 decimal places).
525        let err = build_rfq_quote(
526            "019060da-0000-7000-8000-000000000010",
527            &legs,
528            &[dec!(1.0000009)],
529            3000,
530            &wallet,
531        )
532        .await
533        .unwrap_err();
534        assert!(matches!(
535            &err,
536            ClientError::RfqInput(RfqInputError::NetPremiumSubMicroPrecision { net_premium })
537                if *net_premium == dec!(1.0000009)
538        ));
539        assert!(
540            err.to_string().contains("sub-micro precision"),
541            "expected sub-micro precision message, got: {err}"
542        );
543    }
544
545    #[tokio::test]
546    async fn admits_exactly_six_decimal_places_net_premium() {
547        let wallet = HypercallWallet::from_private_key(TEST_KEY, 998).unwrap();
548        let legs = make_legs(&[("BTC-20260501-90000-C", "sell", "1")]);
549        let msg = build_rfq_quote(
550            "019060da-0000-7000-8000-000000000011",
551            &legs,
552            &[dec!(1.123456)],
553            3000,
554            &wallet,
555        )
556        .await
557        .unwrap();
558        if let QpClientMessage::RfqResponse { net_premium, .. } = msg {
559            let premium: Decimal = net_premium.unwrap().parse().unwrap();
560            assert_eq!(premium, dec!(1.123456));
561        } else {
562            panic!("expected RfqResponse");
563        }
564    }
565}