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