Skip to main content

hypercall_client/
rfq_v2.rs

1//! Typed low-level client for the RFQ V2 HTTP contract (`/private/rfqs*`).
2//!
3//! Callers supply complete signed payloads. [`crate::rfq_v2_signing`] builds
4//! and signs them with a [`crate::HypercallWallet`]; remote signers and
5//! non-Rust implementations sign the same EIP-712 messages and use the same
6//! transport.
7//!
8//! # Availability
9//!
10//! Compiled with the `rfq-v2` cargo feature, on by default since 0.3.0. RFQ V2
11//! is open to every account in production from October 16, 2026.
12//!
13//! A non-production environment can run RFQ V2 in two other modes. Disabled,
14//! it refuses every RFQ V2 request, including private reads and
15//! `AuthenticateRfqV2` socket authentication, with HTTP 403 and error code
16//! `rfq_v2_disabled`. Over HTTP that surfaces as [`ClientError::RfqV2Api`]
17//! with `status: 403` and that `code`; on the socket,
18//! [`crate::WsClient::connect_rfq_v2`] fails. Allowlist-only, it answers 403
19//! `rfq_v2_not_allowlisted` to accounts not on the list.
20//!
21//! # Operation IDs
22//!
23//! Every client-chosen operation ID must be a UUIDv7 whose embedded timestamp,
24//! measured against the server clock, is at most one hour old and at most 30
25//! seconds in the future. Any other ID is refused with HTTP 400
26//! `rfq_v2_invalid_operation_id`. Mint a fresh `Uuid::now_v7()` for each new
27//! operation, and reuse an ID only to retry the identical signed request while
28//! it is still inside that window.
29
30use std::cmp::Ordering;
31
32use alloy::primitives::aliases::U512;
33use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
34use displaystr::display;
35use reqwest::{Method, RequestBuilder};
36use serde::{de::DeserializeOwned, Serialize};
37use tokio::{sync::mpsc, time::Duration};
38use uuid::Uuid;
39
40use hypercall_sdk_types::{
41    CreateRfqV2Request, CreateRfqV2Response, DeclineRfqV2Request, ListRfqV2ChangesQuery,
42    ListRfqV2ChangesResponse, ListRfqV2Query, ListRfqV2QuotesQuery, ListRfqV2QuotesResponse,
43    ListRfqV2Response, PublishRfqV2FirmQuoteRequest, PublishRfqV2IndicativeQuoteRequest,
44    PublishRfqV2QuoteResponse, RequestRfqV2FirmQuoteRequest, RfqV2AuthorizedTerms,
45    RfqV2AutoExecutionLimit, RfqV2BulkWithdrawalRequest, RfqV2Digest, RfqV2ErrorResponse,
46    RfqV2ExecutionRequest, RfqV2ExecutionResponse, RfqV2FillPolicy, RfqV2InvalidationRequest,
47    RfqV2OperationResponse, RfqV2PackageLeg, RfqV2PreflightStatus, RfqV2QuoteReplacement,
48    RfqV2QuoteView, RfqV2ReadGrant, RfqV2ReplacementRequest, RfqV2Response,
49    RfqV2ScheduledQuoteCancelRequest, RfqV2ScheduledQuoteCancelResponse, RfqV2Side,
50    RfqV2SweepRequest,
51};
52
53use crate::{ClientError, HypercallClient, Result};
54
55pub(crate) const RFQ_V2_ROUTE: &str = "/private/rfqs";
56const RFQ_V2_BULK_WITHDRAWAL_ROUTE: &str = "/private/rfq-quote-withdrawals";
57const RFQ_V2_CANCEL_SCHEDULE_ROUTE: &str = "/private/rfq-quote-cancel-schedule";
58
59async fn send_rfq_v2_json<T: DeserializeOwned>(
60    request: RequestBuilder,
61    action: &'static str,
62) -> Result<T> {
63    let response = request.send().await?;
64    if !response.status().is_success() {
65        let status = response.status().as_u16();
66        // The status is already known, so a body that cannot be read keeps
67        // it: a 4xx stays a definite refusal.
68        let body = match response.text().await {
69            Ok(body) => body,
70            Err(error) => return Err(ClientError::api_source(status, error)),
71        };
72        if let Ok(error) = serde_json::from_str::<RfqV2ErrorResponse>(&body) {
73            return Err(ClientError::RfqV2Api {
74                status,
75                code: error.code,
76                message: error.message,
77            });
78        }
79        return Err(ClientError::Api {
80            status,
81            message: format!("{action}: {body}"),
82        });
83    }
84    Ok(response.json().await?)
85}
86
87async fn send_rfq_v2_body<T: DeserializeOwned, B: Serialize + ?Sized>(
88    request: RequestBuilder,
89    body: &B,
90    action: &'static str,
91) -> Result<T> {
92    // Encode locally before dispatch. A serialization failure is a definite
93    // client error, never an ambiguous submission.
94    let encoded = sonic_rs::to_vec(body)?;
95    send_rfq_v2_bytes(request, encoded, action).await
96}
97
98/// Send already-encoded JSON. Reconciliation resends these exact bytes.
99pub(crate) async fn send_rfq_v2_bytes<T: DeserializeOwned>(
100    request: RequestBuilder,
101    encoded: Vec<u8>,
102    action: &'static str,
103) -> Result<T> {
104    send_rfq_v2_json(
105        request
106            .header(reqwest::header::CONTENT_TYPE, "application/json")
107            .body(encoded),
108        action,
109    )
110    .await
111}
112
113/// Report a transport failure, timeout, or 5xx on a mutation as
114/// [`ClientError::RfqV2SubmissionAmbiguous`]: the server may have applied it.
115#[expect(
116    clippy::result_large_err,
117    reason = "passes through the established unboxed public ClientError contract"
118)]
119fn classify_rfq_v2_mutation<T>(
120    rfq_id: Option<Uuid>,
121    operation_id: Uuid,
122    result: Result<T>,
123) -> Result<T> {
124    match result {
125        Err(source) if ambiguous_rfq_v2_submission(&source) => {
126            Err(ClientError::RfqV2SubmissionAmbiguous {
127                rfq_id,
128                operation_id,
129                source: Box::new(source),
130            })
131        }
132        result => result,
133    }
134}
135
136/// Transport failures, timeouts and 5xx responses leave the outcome unknown.
137/// `501 Not Implemented` is the exception: the route was never served.
138pub(crate) fn ambiguous_rfq_v2_submission(error: &ClientError) -> bool {
139    match error {
140        // A builder error happens before any byte is sent.
141        ClientError::Http(error) => !error.is_builder(),
142        error => matches!(
143            error,
144            ClientError::Api {
145                status: 500 | 502..=599,
146                ..
147            } | ClientError::ApiSource {
148                status: 500 | 502..=599,
149                ..
150            } | ClientError::RfqV2Api {
151                status: 500 | 502..=599,
152                ..
153            }
154        ),
155    }
156}
157
158/// Caller-provided read session for role-filtered private RFQ data.
159///
160/// The token is borrowed for one request and is never stored on the client.
161/// A caller may encode a wallet-signed `RfqV2ReadGrant` with
162/// `encode_rfq_v2_read_grant` and reuse it until expiry.
163pub struct RfqV2ReadCredentials<'a> {
164    pub bearer_token: &'a str,
165}
166
167/// Encode a signed private-read grant as a bearer token. The grant must be
168/// EIP-712 signed for `AuthorizeRfqReadV2` under the Hypercall domain.
169#[expect(
170    clippy::result_large_err,
171    reason = "public client methods preserve the established unboxed ClientError contract"
172)]
173pub fn encode_rfq_v2_read_grant(grant: &RfqV2ReadGrant) -> Result<String> {
174    Ok(URL_SAFE_NO_PAD.encode(sonic_rs::to_vec(grant)?))
175}
176
177fn rfq_v2_grant_remaining(expires_at_ms: u64) -> std::time::Duration {
178    let Ok(elapsed) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) else {
179        return std::time::Duration::ZERO;
180    };
181    let now_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
182    std::time::Duration::from_millis(expires_at_ms.saturating_sub(now_ms))
183}
184
185impl HypercallClient {
186    /// Poll the signed recipient change feed even while its WebSocket remains
187    /// connected. A WebSocket hint is only a wake-up signal; it cannot prove
188    /// that no earlier hint was lost. The caller must refresh each returned
189    /// RFQ and persist `next_after_sequence` only after applying the page.
190    /// If applying a page fails, drop the receiver and restart from the last
191    /// persisted cursor. Dropping the receiver stops polling. Recreate it
192    /// with a fresh grant before the current one expires.
193    #[expect(
194        clippy::result_large_err,
195        reason = "public client methods preserve the established unboxed ClientError contract"
196    )]
197    pub fn watch_rfq_v2_changes(
198        &self,
199        grant: &RfqV2ReadGrant,
200        after_sequence: u64,
201        poll_interval: Duration,
202    ) -> Result<mpsc::Receiver<Result<ListRfqV2ChangesResponse>>> {
203        if poll_interval.is_zero() {
204            return Err(ClientError::InvalidInput(
205                "RFQ v2 change poll interval must be positive".to_string(),
206            ));
207        }
208        if rfq_v2_grant_remaining(grant.expires_at_ms).is_zero() {
209            return Err(ClientError::InvalidInput(
210                "RFQ v2 read grant expired".to_string(),
211            ));
212        }
213        let token = encode_rfq_v2_read_grant(grant)?;
214        let expires_at_ms = grant.expires_at_ms;
215        let client = self.clone();
216        let (sender, receiver) = mpsc::channel(1);
217        tokio::spawn(async move {
218            let mut cursor = after_sequence;
219            let mut interval = tokio::time::interval(poll_interval);
220            // A slow read must not trigger a burst of catch-up polls.
221            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
222            loop {
223                let remaining = rfq_v2_grant_remaining(expires_at_ms);
224                if remaining.is_zero() {
225                    break;
226                }
227                tokio::select! {
228                    _ = sender.closed() => break,
229                    _ = tokio::time::sleep(remaining) => break,
230                    _ = interval.tick() => {}
231                }
232                if rfq_v2_grant_remaining(expires_at_ms).is_zero() {
233                    break;
234                }
235                loop {
236                    let remaining = rfq_v2_grant_remaining(expires_at_ms);
237                    if remaining.is_zero() {
238                        return;
239                    }
240                    let query = ListRfqV2ChangesQuery {
241                        after_sequence: Some(cursor),
242                        limit: Some(100),
243                    };
244                    let read = client.list_rfq_v2_changes(
245                        &query,
246                        RfqV2ReadCredentials {
247                            bearer_token: &token,
248                        },
249                    );
250                    let result = tokio::select! {
251                        _ = sender.closed() => return,
252                        _ = tokio::time::sleep(remaining) => return,
253                        result = read => result,
254                    };
255                    let page = match result {
256                        Ok(page) => page,
257                        Err(error) => {
258                            let auth_failed = matches!(
259                                error,
260                                ClientError::Api {
261                                    status: 401 | 403,
262                                    ..
263                                } | ClientError::ApiSource {
264                                    status: 401 | 403,
265                                    ..
266                                } | ClientError::RfqV2Api {
267                                    status: 401 | 403,
268                                    ..
269                                }
270                            );
271                            let sent = tokio::select! {
272                                _ = sender.closed() => false,
273                                _ = tokio::time::sleep(remaining) => false,
274                                result = sender.send(Err(error)) => result.is_ok(),
275                            };
276                            if !sent || auth_failed {
277                                return;
278                            }
279                            break;
280                        }
281                    };
282                    if page.next_after_sequence < cursor
283                        || ((page.has_more || !page.changes.is_empty())
284                            && page.next_after_sequence == cursor)
285                    {
286                        let error = ClientError::RfqV2ChangeFeedCursor {
287                            after_sequence: cursor,
288                            next_after_sequence: page.next_after_sequence,
289                            has_more: page.has_more,
290                        };
291                        tokio::select! {
292                            _ = sender.closed() => {},
293                            _ = tokio::time::sleep(remaining) => {},
294                            _ = sender.send(Err(error)) => {},
295                        }
296                        return;
297                    }
298                    let has_more = page.has_more;
299                    let next_cursor = page.next_after_sequence;
300                    // A quiet recipient feed often returns the same global
301                    // cursor. Do not fill the one-page channel with no-op
302                    // polls and block discovery of a later change.
303                    if page.changes.is_empty() && next_cursor == cursor {
304                        break;
305                    }
306                    let sent = tokio::select! {
307                        _ = sender.closed() => false,
308                        _ = tokio::time::sleep(remaining) => false,
309                        result = sender.send(Ok(page)) => result.is_ok(),
310                    };
311                    if !sent {
312                        return;
313                    }
314                    cursor = next_cursor;
315                    if !has_more || rfq_v2_grant_remaining(expires_at_ms).is_zero() {
316                        break;
317                    }
318                }
319            }
320        });
321        Ok(receiver)
322    }
323}
324
325impl HypercallClient {
326    /// Set, renew, or remove a maker-wide V2 firm-quote cancel deadline.
327    pub async fn schedule_rfq_v2_quote_cancel(
328        &self,
329        request: &RfqV2ScheduledQuoteCancelRequest,
330    ) -> Result<RfqV2ScheduledQuoteCancelResponse> {
331        classify_rfq_v2_mutation(
332            None,
333            request.operation_id,
334            send_rfq_v2_body(
335                self.request(Method::POST, RFQ_V2_CANCEL_SCHEDULE_ROUTE),
336                request,
337                "RFQ v2 quote cancel schedule failed",
338            )
339            .await,
340        )
341    }
342
343    /// Relay a signed RFQ parent into the V2 delivery plane.
344    pub async fn create_rfq_v2(&self, request: &CreateRfqV2Request) -> Result<CreateRfqV2Response> {
345        classify_rfq_v2_mutation(
346            Some(request.terms.id),
347            request.terms.id,
348            send_rfq_v2_body(
349                self.request(Method::POST, RFQ_V2_ROUTE),
350                request,
351                "RFQ v2 create failed",
352            )
353            .await,
354        )
355    }
356
357    /// Publish a non-executable indicative quote.
358    pub async fn publish_rfq_v2_indicative_quote(
359        &self,
360        rfq_id: Uuid,
361        request: &PublishRfqV2IndicativeQuoteRequest,
362    ) -> Result<PublishRfqV2QuoteResponse> {
363        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/quotes/indicative");
364        classify_rfq_v2_mutation(
365            Some(rfq_id),
366            request.terms.id,
367            send_rfq_v2_body(
368                self.request(Method::POST, &route),
369                request,
370                "RFQ v2 indicative quote publication failed",
371            )
372            .await,
373        )
374    }
375
376    /// Publish an executable firm quote for best-effort preflight and relay.
377    pub async fn publish_rfq_v2_firm_quote(
378        &self,
379        rfq_id: Uuid,
380        request: &PublishRfqV2FirmQuoteRequest,
381    ) -> Result<PublishRfqV2QuoteResponse> {
382        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/quotes/firm");
383        classify_rfq_v2_mutation(
384            Some(rfq_id),
385            request.terms.id,
386            send_rfq_v2_body(
387                self.request(Method::POST, &route),
388                request,
389                "RFQ v2 firm quote publication failed",
390            )
391            .await,
392        )
393    }
394
395    /// Ask the maker of an indicative quote for a fresh firm authorization.
396    pub async fn request_rfq_v2_firm_quote(
397        &self,
398        rfq_id: Uuid,
399        indicative_quote_id: Uuid,
400        request: &RequestRfqV2FirmQuoteRequest,
401    ) -> Result<RfqV2OperationResponse> {
402        let route =
403            format!("{RFQ_V2_ROUTE}/{rfq_id}/quotes/{indicative_quote_id}/firm-up-requests");
404        classify_rfq_v2_mutation(
405            Some(rfq_id),
406            request.operation_id,
407            send_rfq_v2_body(
408                self.request(Method::POST, &route),
409                request,
410                "RFQ v2 firm-up request failed",
411            )
412            .await,
413        )
414    }
415
416    /// Decline an RFQ this maker was routed. Only the taker and this maker
417    /// can see the decline. It does not affect any quote or execution.
418    pub async fn decline_rfq_v2(
419        &self,
420        rfq_id: Uuid,
421        request: &DeclineRfqV2Request,
422    ) -> Result<RfqV2OperationResponse> {
423        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/declines");
424        classify_rfq_v2_mutation(
425            Some(rfq_id),
426            request.operation_id,
427            send_rfq_v2_body(
428                self.request(Method::POST, &route),
429                request,
430                "RFQ v2 decline failed",
431            )
432            .await,
433        )
434    }
435
436    /// Submit one signed firm-quote allocation for execution.
437    pub async fn execute_rfq_v2(
438        &self,
439        rfq_id: Uuid,
440        request: &RfqV2ExecutionRequest,
441    ) -> Result<RfqV2ExecutionResponse> {
442        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/executions");
443        classify_rfq_v2_mutation(
444            Some(rfq_id),
445            request.operation_id,
446            send_rfq_v2_body(
447                self.request(Method::POST, &route),
448                request,
449                "RFQ v2 execution failed",
450            )
451            .await,
452        )
453    }
454
455    /// Submit an exact, ordered, all-or-nothing multi-quote allocation.
456    pub async fn sweep_rfq_v2(
457        &self,
458        rfq_id: Uuid,
459        request: &RfqV2SweepRequest,
460    ) -> Result<RfqV2ExecutionResponse> {
461        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/sweeps");
462        classify_rfq_v2_mutation(
463            Some(rfq_id),
464            request.operation_id,
465            send_rfq_v2_body(
466                self.request(Method::POST, &route),
467                request,
468                "RFQ v2 sweep failed",
469            )
470            .await,
471        )
472    }
473
474    /// Make a signed parent RFQ terminal.
475    pub async fn cancel_rfq_v2(
476        &self,
477        rfq_id: Uuid,
478        request: &RfqV2InvalidationRequest,
479    ) -> Result<RfqV2OperationResponse> {
480        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/cancellations");
481        classify_rfq_v2_mutation(
482            Some(rfq_id),
483            request.operation_id,
484            send_rfq_v2_body(
485                self.request(Method::POST, &route),
486                request,
487                "RFQ v2 cancellation failed",
488            )
489            .await,
490        )
491    }
492
493    /// Make a signed quote terminal when its withdrawal policy permits it.
494    pub async fn withdraw_rfq_v2_quote(
495        &self,
496        rfq_id: Uuid,
497        quote_id: Uuid,
498        request: &RfqV2InvalidationRequest,
499    ) -> Result<RfqV2OperationResponse> {
500        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/quotes/{quote_id}/withdrawals");
501        classify_rfq_v2_mutation(
502            Some(rfq_id),
503            request.operation_id,
504            send_rfq_v2_body(
505                self.request(Method::POST, &route),
506                request,
507                "RFQ v2 quote withdrawal failed",
508            )
509            .await,
510        )
511    }
512
513    /// Atomically withdraw a signed maker-scoped set of open quotes.
514    pub async fn withdraw_rfq_v2_quotes(
515        &self,
516        request: &RfqV2BulkWithdrawalRequest,
517    ) -> Result<RfqV2OperationResponse> {
518        classify_rfq_v2_mutation(
519            None,
520            request.operation_id,
521            send_rfq_v2_body(
522                self.request(Method::POST, RFQ_V2_BULK_WITHDRAWAL_ROUTE),
523                request,
524                "RFQ v2 bulk quote withdrawal failed",
525            )
526            .await,
527        )
528    }
529
530    /// Retire a parent and publish a fresh signed replacement.
531    pub async fn replace_rfq_v2(
532        &self,
533        rfq_id: Uuid,
534        request: &RfqV2ReplacementRequest<CreateRfqV2Request>,
535    ) -> Result<CreateRfqV2Response> {
536        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/replacements");
537        classify_rfq_v2_mutation(
538            Some(rfq_id),
539            request.operation_id,
540            send_rfq_v2_body(
541                self.request(Method::POST, &route),
542                request,
543                "RFQ v2 replacement failed",
544            )
545            .await,
546        )
547    }
548
549    /// Retire a quote and publish a fresh signed replacement of the same kind.
550    pub async fn replace_rfq_v2_quote(
551        &self,
552        rfq_id: Uuid,
553        quote_id: Uuid,
554        request: &RfqV2ReplacementRequest<RfqV2QuoteReplacement>,
555    ) -> Result<PublishRfqV2QuoteResponse> {
556        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/quotes/{quote_id}/replacements");
557        classify_rfq_v2_mutation(
558            Some(rfq_id),
559            request.operation_id,
560            send_rfq_v2_body(
561                self.request(Method::POST, &route),
562                request,
563                "RFQ v2 quote replacement failed",
564            )
565            .await,
566        )
567    }
568
569    /// Read the authorization-aware RFQ view for the current caller.
570    pub async fn get_rfq_v2(
571        &self,
572        rfq_id: Uuid,
573        credentials: RfqV2ReadCredentials<'_>,
574    ) -> Result<RfqV2Response> {
575        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}?view=authorized");
576        send_rfq_v2_json(
577            self.request(Method::GET, &route)
578                .bearer_auth(credentials.bearer_token),
579            "RFQ v2 authorized read failed",
580        )
581        .await
582    }
583
584    /// List RFQs visible to the authorized caller, including terminal history.
585    pub async fn list_rfqs_v2(
586        &self,
587        query: &ListRfqV2Query,
588        credentials: RfqV2ReadCredentials<'_>,
589    ) -> Result<ListRfqV2Response> {
590        send_rfq_v2_json(
591            self.request(Method::GET, RFQ_V2_ROUTE)
592                .query(query)
593                .bearer_auth(credentials.bearer_token),
594            "RFQ v2 list failed",
595        )
596        .await
597    }
598
599    /// List the RFQ IDs that changed for this signed account after a global
600    /// sequence. Gaps in the sequence are expected.
601    pub async fn list_rfq_v2_changes(
602        &self,
603        query: &ListRfqV2ChangesQuery,
604        credentials: RfqV2ReadCredentials<'_>,
605    ) -> Result<ListRfqV2ChangesResponse> {
606        send_rfq_v2_json(
607            self.request(Method::GET, &format!("{RFQ_V2_ROUTE}/changes"))
608                .query(query)
609                .bearer_auth(credentials.bearer_token),
610            "RFQ v2 change feed failed",
611        )
612        .await
613    }
614
615    /// List quotes visible to the authorized caller for one RFQ.
616    pub async fn list_rfq_v2_quotes(
617        &self,
618        rfq_id: Uuid,
619        query: &ListRfqV2QuotesQuery,
620        credentials: RfqV2ReadCredentials<'_>,
621    ) -> Result<ListRfqV2QuotesResponse> {
622        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/quotes");
623        send_rfq_v2_json(
624            self.request(Method::GET, &route)
625                .query(query)
626                .bearer_auth(credentials.bearer_token),
627            "RFQ v2 quote list failed",
628        )
629        .await
630    }
631
632    /// Read one full quote visible to the authorized caller.
633    pub async fn get_rfq_v2_quote(
634        &self,
635        rfq_id: Uuid,
636        quote_id: Uuid,
637        credentials: RfqV2ReadCredentials<'_>,
638    ) -> Result<RfqV2QuoteView> {
639        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/quotes/{quote_id}");
640        send_rfq_v2_json(
641            self.request(Method::GET, &route)
642                .bearer_auth(credentials.bearer_token),
643            "RFQ v2 quote read failed",
644        )
645        .await
646    }
647}
648
649/// Exact parent and size constraints for deterministic local quote selection.
650#[derive(Debug, Clone, Copy, PartialEq, Eq)]
651pub struct RfqV2BestQuoteCriteria<'a> {
652    pub rfq_id: Uuid,
653    pub terms_commitment: RfqV2Digest,
654    pub requested_units: u128,
655    /// The parent's remaining target from a fresh read
656    /// ([`RfqV2Response::remaining_target`]). A quote's own capacity and
657    /// `executable` flag do not bound the size against fills by other quotes.
658    pub parent_remaining_target: u128,
659    /// The parent's signed target ([`RfqV2Response::target`]).
660    pub parent_target: u128,
661    /// The parent's signed fill policy. Every fill must satisfy it as well
662    /// as the quote's own policy.
663    pub parent_fill_policy: RfqV2FillPolicy,
664    /// The sizes at which every leg is a whole number of contract micro-units.
665    pub parent_unit_grid: RfqV2ParentUnitGrid,
666    /// The parent's signed legs, which with a quote's leg prices fix the
667    /// sizes and premiums the server bounds to its fill record range.
668    pub parent_legs: &'a [RfqV2PackageLeg],
669    pub now_ms: u64,
670    /// Signed parent limit, when the RFQ uses automatic execution.
671    /// [`Self::for_parent`] takes it from the signed parent terms; never set
672    /// it from any other source.
673    pub auto_execution_limit: Option<RfqV2AutoExecutionLimit>,
674}
675
676impl<'a> RfqV2BestQuoteCriteria<'a> {
677    /// Criteria bound to a fresh parent read: its identity,
678    /// remaining and signed target, signed fill policy, leg grid, and signed
679    /// auto-execution limit.
680    pub fn for_parent(parent: &'a RfqV2Response, requested_units: u128, now_ms: u64) -> Self {
681        Self {
682            rfq_id: parent.rfq_id,
683            terms_commitment: parent.terms_commitment,
684            requested_units,
685            parent_remaining_target: parent.remaining_target,
686            parent_target: parent.target,
687            parent_fill_policy: parent_fill_policy(parent),
688            parent_unit_grid: RfqV2ParentUnitGrid::of(parent_legs(parent)),
689            parent_legs: parent_legs(parent),
690            now_ms,
691            auto_execution_limit: parent_auto_execution_limit(parent),
692        }
693    }
694}
695
696/// Leg sizes are whole micro-units of a contract held in a `u64`. A fill of
697/// `units` package units is `units * quantity_micros_per_unit / 1e6` contract
698/// micro-units on each leg, and an execution is refused when any leg's
699/// quantity is fractional or exceeds `u64`.
700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
701pub struct RfqV2ParentUnitGrid {
702    /// Every admitted size is a multiple of this.
703    pub step: u128,
704    /// No admitted size exceeds this.
705    pub ceiling: u128,
706}
707
708const CONTRACT_UNIT_MICROS: u128 = 1_000_000;
709
710impl RfqV2ParentUnitGrid {
711    /// A grid that admits every size, for a parent without legs.
712    pub const UNBOUNDED: Self = Self {
713        step: 1,
714        ceiling: u128::MAX,
715    };
716
717    pub fn of(legs: &[RfqV2PackageLeg]) -> Self {
718        legs.iter().fold(Self::UNBOUNDED, |grid, leg| {
719            let quantity = leg.quantity_micros_per_unit;
720            if quantity == 0 {
721                // Admission refuses zero-quantity legs; never enable one.
722                return Self {
723                    step: 1,
724                    ceiling: 0,
725                };
726            }
727            // `quantity * units` is a multiple of 1e6 exactly when `units`
728            // is a multiple of 1e6 / gcd(quantity, 1e6). That divides 1e6,
729            // so the least common multiple stays a divisor of 1e6.
730            let leg_step = CONTRACT_UNIT_MICROS / gcd(quantity, CONTRACT_UNIT_MICROS);
731            let leg_ceiling = u128::from(u64::MAX) * CONTRACT_UNIT_MICROS / quantity;
732            Self {
733                step: grid.step / gcd(grid.step, leg_step) * leg_step,
734                ceiling: grid.ceiling.min(leg_ceiling),
735            }
736        })
737    }
738
739    pub fn admits(&self, units: u128) -> bool {
740        units <= self.ceiling && units.is_multiple_of(self.step)
741    }
742}
743
744fn gcd(mut a: u128, mut b: u128) -> u128 {
745    while b != 0 {
746        (a, b) = (b, a % b);
747    }
748    a
749}
750
751/// The taker's signed fill policy, from either role's parent view.
752pub(crate) fn parent_fill_policy(parent: &RfqV2Response) -> RfqV2FillPolicy {
753    match &parent.parent {
754        RfqV2AuthorizedTerms::Taker { terms } => terms.fill_policy,
755        RfqV2AuthorizedTerms::Maker { terms } => terms.fill_policy,
756    }
757}
758
759/// The parent's signed auto-execution limit, from either role's parent view.
760pub(crate) fn parent_auto_execution_limit(
761    parent: &RfqV2Response,
762) -> Option<RfqV2AutoExecutionLimit> {
763    match &parent.parent {
764        RfqV2AuthorizedTerms::Taker { terms } => terms.auto_execution_limit,
765        RfqV2AuthorizedTerms::Maker { terms } => terms.auto_execution_limit,
766    }
767}
768
769/// The parent's signed legs, from either role's parent view.
770pub(crate) fn parent_legs(parent: &RfqV2Response) -> &[RfqV2PackageLeg] {
771    match &parent.parent {
772        RfqV2AuthorizedTerms::Taker { terms } => &terms.legs,
773        RfqV2AuthorizedTerms::Maker { terms } => &terms.legs,
774    }
775}
776
777#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
778#[display]
779pub enum RfqV2BestQuoteError {
780    NoEligibleQuote = "no eligible firm quote covers the requested size",
781}
782
783/// The builder fee native RFQ execution charges per allocation. A quote's
784/// signed `fee_limits` are ceilings, not charges, so selection prices the fee
785/// actually charged; pricing the ceiling would reject executable quotes and
786/// rank worse quotes first.
787const CHARGED_EXECUTION_FEE_MICROS: u128 = 0;
788
789/// Select the best eligible firm quote. Selection is local and executes
790/// nothing.
791pub fn select_best_rfq_v2_quote<'q>(
792    quotes: &'q [RfqV2QuoteView],
793    criteria: RfqV2BestQuoteCriteria<'_>,
794) -> std::result::Result<&'q RfqV2QuoteView, RfqV2BestQuoteError> {
795    let mut best: Option<(&RfqV2QuoteView, bool, u128, u128, u128, Uuid)> = None;
796
797    for quote in quotes {
798        let RfqV2QuoteView::Firm {
799            terms,
800            status,
801            executable,
802            remaining_capacity,
803            preflight,
804            ..
805        } = quote
806        else {
807            continue;
808        };
809        if terms.rfq_id != criteria.rfq_id
810            || terms.rfq_terms_commitment != criteria.terms_commitment
811            || !executable
812            || !matches!(status.as_str(), "open" | "partially_filled")
813            || (status == "partially_filled"
814                && matches!(terms.fill_policy, RfqV2FillPolicy::OneSmallerPackage { .. }))
815            || terms.expires_at_ms <= criteria.now_ms
816            || terms.reference_quantity == 0
817            || criteria.requested_units == 0
818            || criteria.requested_units > *remaining_capacity
819            || criteria.requested_units > criteria.parent_remaining_target
820            || !fill_policy_accepts(
821                terms.fill_policy,
822                terms.capacity,
823                *remaining_capacity,
824                criteria.requested_units,
825            )
826            || !criteria.parent_unit_grid.admits(criteria.requested_units)
827            || !fill_policy_accepts(
828                criteria.parent_fill_policy,
829                criteria.parent_target,
830                criteria.parent_remaining_target,
831                criteria.requested_units,
832            )
833            || preflight
834                .as_ref()
835                .is_some_and(|result| result.status == RfqV2PreflightStatus::Rejected)
836            || !quote_within_projection_range(criteria.parent_legs, terms, criteria.requested_units)
837            || !quote_within_auto_limit(
838                criteria.auto_execution_limit,
839                terms,
840                criteria.requested_units,
841            )
842        {
843            continue;
844        }
845
846        let candidate = (
847            quote,
848            terms.maker_receives_reference_premium,
849            terms.reference_premium_micros,
850            terms.reference_quantity,
851            CHARGED_EXECUTION_FEE_MICROS,
852            terms.id,
853        );
854        let Some(current) = best else {
855            best = Some(candidate);
856            continue;
857        };
858        let units = U512::from(criteria.requested_units);
859        let candidate_quantity = U512::from(candidate.3);
860        let current_quantity = U512::from(current.3);
861        let candidate_fee = U512::from(candidate.4);
862        let current_fee = U512::from(current.4);
863        let candidate_premium = U512::from(candidate.2) * units;
864        let current_premium = U512::from(current.2) * units;
865        let candidate_debit = candidate_fee * candidate_quantity
866            + if candidate.1 {
867                candidate_premium
868            } else {
869                U512::ZERO
870            };
871        let current_debit = current_fee * current_quantity
872            + if current.1 {
873                current_premium
874            } else {
875                U512::ZERO
876            };
877        let candidate_credit = if candidate.1 {
878            U512::ZERO
879        } else {
880            candidate_premium
881        };
882        let current_credit = if current.1 {
883            U512::ZERO
884        } else {
885            current_premium
886        };
887        let economics = (candidate_debit * current_quantity + current_credit * candidate_quantity)
888            .cmp(&(current_debit * candidate_quantity + candidate_credit * current_quantity));
889        if economics == Ordering::Less
890            || (economics == Ordering::Equal && candidate.5.as_bytes() < current.5.as_bytes())
891        {
892            best = Some(candidate);
893        }
894    }
895
896    best.map(|selected| selected.0)
897        .ok_or(RfqV2BestQuoteError::NoEligibleQuote)
898}
899
900/// Exclusive magnitude bound the engine puts on every executed RFQ leg size,
901/// leg price, leg premium and package premium: twelve integer digits, the
902/// range of its `NUMERIC(20, 8)` fill and premium projections.
903const MAX_PROJECTED_AMOUNT_EXCLUSIVE: u128 = 1_000_000_000_000;
904
905/// Whether a fill of `requested_units` against this firm quote stays inside
906/// the engine's fill record range, which refuses it otherwise. Mirrors the
907/// engine's `within_projection_range` checks for one allocation, computed
908/// exactly: a leg's size is `quantity_micros_per_unit * units` at 1e-12, its
909/// price `price_micros` at 1e-6, and its premium their product at 1e-18,
910/// debited from the taker on a bought leg and credited on a sold one. The
911/// engine also bounds each option leg's underlying notional by the live
912/// spot, which the client cannot see, so passing here does not prove that
913/// check passes.
914pub(crate) fn quote_within_projection_range(
915    legs: &[RfqV2PackageLeg],
916    terms: &hypercall_sdk_types::RfqV2FirmQuoteTerms,
917    requested_units: u128,
918) -> bool {
919    let max = U512::from(MAX_PROJECTED_AMOUNT_EXCLUSIVE);
920    let micros = U512::from(1_000_000_u128);
921    let size_bound = max * micros * micros;
922    let price_bound = max * micros;
923    let premium_bound = size_bound * micros;
924    let units = U512::from(requested_units);
925    let (mut credit, mut debit) = (U512::ZERO, U512::ZERO);
926    for (leg, priced) in legs.iter().zip(&terms.priced_legs) {
927        let size = U512::from(leg.quantity_micros_per_unit) * units;
928        let price = U512::from(priced.price_micros);
929        let cash = price * size;
930        if size >= size_bound || price >= price_bound || cash >= premium_bound {
931            return false;
932        }
933        match leg.taker_side {
934            RfqV2Side::Buy => debit += cash,
935            RfqV2Side::Sell => credit += cash,
936        }
937    }
938    credit.abs_diff(debit) < premium_bound
939}
940
941/// Whether a fill of `requested_units` against this firm quote stays inside
942/// the parent's signed auto-execution premium bound. A manual parent has no
943/// bound.
944pub(crate) fn quote_within_auto_limit(
945    limit: Option<RfqV2AutoExecutionLimit>,
946    terms: &hypercall_sdk_types::RfqV2FirmQuoteTerms,
947    requested_units: u128,
948) -> bool {
949    limit.is_none_or(|limit| {
950        within_auto_limit(
951            limit,
952            terms.maker_receives_reference_premium,
953            terms.reference_premium_micros,
954            terms.reference_quantity,
955            CHARGED_EXECUTION_FEE_MICROS,
956            requested_units,
957        )
958    })
959}
960
961fn within_auto_limit(
962    limit: RfqV2AutoExecutionLimit,
963    maker_receives: bool,
964    premium_micros: u128,
965    reference_quantity: u128,
966    fee_micros: u128,
967    requested_units: u128,
968) -> bool {
969    let units = U512::from(requested_units);
970    let reference = U512::from(reference_quantity);
971    let scale = U512::from(1_000_000_u128);
972    let premium = U512::from(premium_micros) * units * scale;
973    let fee = U512::from(fee_micros) * reference * scale;
974    let bound = U512::from(limit.premium_micros) * units * reference;
975    match (limit.maker_receives_premium, maker_receives) {
976        (true, true) => premium + fee <= bound,
977        (true, false) => fee <= bound + premium,
978        (false, true) => false,
979        (false, false) => premium >= bound + fee,
980    }
981}
982
983/// The per-fill policy rule against one signed authorization (a
984/// parent's target or a quote's capacity) and its remaining amount: a
985/// full-size fill is the whole signed amount, and a one-shot policy admits
986/// nothing once the authorization has filled.
987pub(crate) fn fill_policy_accepts(
988    policy: RfqV2FillPolicy,
989    signed_capacity: u128,
990    remaining: u128,
991    requested_units: u128,
992) -> bool {
993    let unfilled = remaining == signed_capacity;
994    match policy {
995        RfqV2FillPolicy::FullSizeOnce => unfilled && requested_units == signed_capacity,
996        RfqV2FillPolicy::OneSmallerPackage { minimum, step } => {
997            unfilled
998                && requested_units >= minimum
999                && step != 0
1000                && requested_units.is_multiple_of(step)
1001        }
1002        RfqV2FillPolicy::RepeatedPartial { minimum, step } => {
1003            requested_units >= minimum && step != 0 && requested_units.is_multiple_of(step)
1004        }
1005    }
1006}
1007
1008#[cfg(test)]
1009#[path = "rfq_v2_test.rs"]
1010mod tests;