Skip to main content

hypercall_client/
rfq_v2_recovery.rs

1//! Client-side recovery for RFQ v2: everything a client needs after a
2//! timeout, a lost WebSocket frame, a reconnect, or a process restart.
3//!
4//! The server's answer is always the outcome. These helpers never infer an
5//! outcome from silence: an ambiguous submission is resolved by resending the
6//! identical signed bytes under the original operation ID, a lost hint is
7//! recovered by re-reading the recipient change feed from the last applied
8//! cursor, an execution action is enabled only from fresh server reads, and a
9//! maker hold is released only on conclusive, identity-bound
10//! evidence. Every recovery state is serializable so a client can persist it
11//! and resume after a restart.
12//!
13//! Compiled with the `rfq-v2` cargo feature (on by default). See
14//! [`crate::rfq_v2`] for availability and the operation ID rules.
15
16use std::collections::{BTreeMap, BTreeSet};
17
18use reqwest::Method;
19use serde::{Deserialize, Serialize};
20use tokio::time::Duration;
21use uuid::Uuid;
22
23use hypercall_sdk_types::{
24    ws_protocol::WsRfqV2Changed, ListRfqV2ChangesQuery, ListRfqV2ChangesResponse,
25    ListRfqV2QuotesQuery, RfqV2AuthorizedTerms, RfqV2Digest, RfqV2ExecutionRequest,
26    RfqV2ExecutionResponse, RfqV2FirmQuoteTerms, RfqV2QuoteView, RfqV2Response, RfqV2SweepRequest,
27    WalletAddress,
28};
29
30use crate::{
31    rfq_v2::{
32        ambiguous_rfq_v2_submission, fill_policy_accepts, parent_auto_execution_limit,
33        parent_fill_policy, parent_legs, quote_within_auto_limit, quote_within_projection_range,
34        send_rfq_v2_bytes, RfqV2ParentUnitGrid, RfqV2ReadCredentials, RFQ_V2_ROUTE,
35    },
36    ClientError, HypercallClient, Result,
37};
38
39/// Largest page the change feed and quote list accept.
40const MAX_PAGE_LIMIT: usize = 100;
41
42mod json_u128 {
43    use serde::{de::Error as _, Deserialize, Deserializer, Serializer};
44
45    pub fn serialize<S: Serializer>(value: &u128, serializer: S) -> Result<S::Ok, S::Error> {
46        serializer.serialize_str(&value.to_string())
47    }
48
49    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u128, D::Error> {
50        String::deserialize(deserializer)?
51            .parse()
52            .map_err(D::Error::custom)
53    }
54}
55
56/// Bounds for reconciling an execution or sweep whose outcome is unknown.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct RfqV2ReconcilePolicy {
59    /// Delay before each identical resubmission.
60    pub retry_interval: Duration,
61    /// Identical resubmissions to send before reporting the outcome as still
62    /// ambiguous. Keep the total inside the signed request's expiry.
63    pub max_resubmissions: u32,
64}
65
66/// The definite result of a submission that was first ambiguous.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct RfqV2ReconciledExecution {
69    /// The server's result for the original operation ID.
70    pub response: RfqV2ExecutionResponse,
71    /// Identical resubmissions sent. Each carried the original operation ID
72    /// and the original signed bytes; none was a new operation.
73    pub resubmissions: u32,
74}
75
76impl HypercallClient {
77    /// Reconcile an execution after [`ClientError::RfqV2SubmissionAmbiguous`].
78    ///
79    /// A timeout is not an execution result: the request may still complete
80    /// later. This resends the identical signed request, byte for byte, under
81    /// its original operation ID. The server treats that as an exact retry,
82    /// so a completed operation returns its original result and is never
83    /// applied twice. It never signs, renumbers, or alters the
84    /// request. A definite rejection is returned as is; if every
85    /// resubmission is still ambiguous, the result stays ambiguous.
86    pub async fn reconcile_rfq_v2_execution(
87        &self,
88        rfq_id: Uuid,
89        request: &RfqV2ExecutionRequest,
90        policy: RfqV2ReconcilePolicy,
91    ) -> Result<RfqV2ReconciledExecution> {
92        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/executions");
93        let encoded = sonic_rs::to_vec(request)?;
94        self.reconcile_rfq_v2_submission(rfq_id, request.operation_id, &route, encoded, policy)
95            .await
96    }
97
98    /// Reconcile a sweep after [`ClientError::RfqV2SubmissionAmbiguous`],
99    /// with the same exact-retry rules as
100    /// [`HypercallClient::reconcile_rfq_v2_execution`].
101    pub async fn reconcile_rfq_v2_sweep(
102        &self,
103        rfq_id: Uuid,
104        request: &RfqV2SweepRequest,
105        policy: RfqV2ReconcilePolicy,
106    ) -> Result<RfqV2ReconciledExecution> {
107        let route = format!("{RFQ_V2_ROUTE}/{rfq_id}/sweeps");
108        let encoded = sonic_rs::to_vec(request)?;
109        self.reconcile_rfq_v2_submission(rfq_id, request.operation_id, &route, encoded, policy)
110            .await
111    }
112
113    async fn reconcile_rfq_v2_submission(
114        &self,
115        rfq_id: Uuid,
116        operation_id: Uuid,
117        route: &str,
118        encoded: Vec<u8>,
119        policy: RfqV2ReconcilePolicy,
120    ) -> Result<RfqV2ReconciledExecution> {
121        let mut last = None;
122        for resubmission in 1..=policy.max_resubmissions {
123            tokio::time::sleep(policy.retry_interval).await;
124            match send_rfq_v2_bytes(
125                self.request(Method::POST, route),
126                encoded.clone(),
127                "RFQ v2 reconciliation failed",
128            )
129            .await
130            {
131                Ok(response) => {
132                    return Ok(RfqV2ReconciledExecution {
133                        response,
134                        resubmissions: resubmission,
135                    })
136                }
137                Err(error) if ambiguous_rfq_v2_submission(&error) => last = Some(error),
138                Err(error) => return Err(error),
139            }
140        }
141        let source = last.unwrap_or_else(|| {
142            ClientError::InvalidInput("RFQ v2 reconcile policy allows no resubmission".to_string())
143        });
144        Err(ClientError::RfqV2SubmissionAmbiguous {
145            rfq_id: Some(rfq_id),
146            operation_id,
147            source: Box::new(source),
148        })
149    }
150}
151
152/// What a received change hint means for the local view.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum RfqV2HintDisposition {
155    /// At or below the applied cursor: a page already read covered it.
156    AlreadyApplied,
157    /// At or below a hint that is still waiting for a feed read. That read
158    /// starts from the applied cursor, so it covers this sequence too.
159    Duplicate,
160    /// New: read the change feed before treating the local view as current.
161    ReplayRequired,
162}
163
164/// Persistable recipient change-feed position with hint deduplication.
165///
166/// Global sequences have gaps for every change routed to another wallet, so
167/// a gap never proves a lost frame. Only reading the recipient feed from the
168/// last applied cursor does.
169///
170/// A hint carries no state and every feed read starts from the applied
171/// cursor, so the cursor keeps only the highest hint above it. Its size stays
172/// fixed however many hints arrive while the feed is unavailable or behind.
173#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
174#[serde(from = "ChangeCursorWire", into = "ChangeCursorWire")]
175pub struct RfqV2ChangeCursor {
176    last_applied_sequence: u64,
177    /// The highest hint sequence above the cursor that no page read has
178    /// covered.
179    pending_high_water: Option<u64>,
180}
181
182/// The persisted cursor shape. Earlier releases stored every pending hint
183/// sequence in `pending`; this one stores at most the highest. Either form
184/// reads back as the same high-water mark, and a cursor written now still
185/// reads in an earlier release.
186#[derive(Serialize, Deserialize)]
187struct ChangeCursorWire {
188    last_applied_sequence: u64,
189    #[serde(default)]
190    pending: BTreeSet<u64>,
191}
192
193impl From<ChangeCursorWire> for RfqV2ChangeCursor {
194    fn from(wire: ChangeCursorWire) -> Self {
195        Self {
196            last_applied_sequence: wire.last_applied_sequence,
197            pending_high_water: wire
198                .pending
199                .last()
200                .copied()
201                .filter(|sequence| *sequence > wire.last_applied_sequence),
202        }
203    }
204}
205
206impl From<RfqV2ChangeCursor> for ChangeCursorWire {
207    fn from(cursor: RfqV2ChangeCursor) -> Self {
208        Self {
209            last_applied_sequence: cursor.last_applied_sequence,
210            pending: cursor.pending_high_water.into_iter().collect(),
211        }
212    }
213}
214
215impl RfqV2ChangeCursor {
216    /// Resume from a persisted, fully applied sequence.
217    pub fn new(last_applied_sequence: u64) -> Self {
218        Self {
219            last_applied_sequence,
220            pending_high_water: None,
221        }
222    }
223
224    /// The last change-feed sequence whose reads were applied.
225    pub fn last_applied_sequence(&self) -> u64 {
226        self.last_applied_sequence
227    }
228
229    /// Hint sequences retained above the cursor: at most one, the highest,
230    /// because a feed read from the cursor covers every lower one.
231    pub fn pending_hints(&self) -> usize {
232        usize::from(self.pending_high_water.is_some())
233    }
234
235    /// The highest hint sequence above the cursor not yet covered by a feed
236    /// read, if any.
237    pub fn pending_high_water(&self) -> Option<u64> {
238        self.pending_high_water
239    }
240
241    /// Classify one hint sequence.
242    pub fn observe_hint(&mut self, sequence: u64) -> RfqV2HintDisposition {
243        if sequence <= self.last_applied_sequence {
244            RfqV2HintDisposition::AlreadyApplied
245        } else if self
246            .pending_high_water
247            .is_some_and(|pending| sequence <= pending)
248        {
249            RfqV2HintDisposition::Duplicate
250        } else {
251            self.pending_high_water = Some(sequence);
252            RfqV2HintDisposition::ReplayRequired
253        }
254    }
255
256    /// Move to `next_after_sequence` once a page's reads are applied.
257    fn commit(&mut self, next_after_sequence: u64) {
258        self.last_applied_sequence = next_after_sequence;
259        self.pending_high_water = self
260            .pending_high_water
261            .filter(|pending| *pending > next_after_sequence);
262    }
263}
264
265/// Reject a change page whose cursor does not progress, as the watcher does.
266#[expect(
267    clippy::result_large_err,
268    reason = "public client methods preserve the established unboxed ClientError contract"
269)]
270fn check_change_page(after_sequence: u64, page: &ListRfqV2ChangesResponse) -> Result<()> {
271    if page.next_after_sequence < after_sequence
272        || ((page.has_more || !page.changes.is_empty())
273            && page.next_after_sequence == after_sequence)
274    {
275        return Err(ClientError::RfqV2ChangeFeedCursor {
276            after_sequence,
277            next_after_sequence: page.next_after_sequence,
278            has_more: page.has_more,
279        });
280    }
281    Ok(())
282}
283
284/// Decode an RFQ v2 change hint from a raw [`crate::WsClient`] message.
285pub fn rfq_v2_change_hint(message: &sonic_rs::Value) -> Option<WsRfqV2Changed> {
286    use sonic_rs::JsonValueTrait as _;
287    if message.get("type").as_str() != Some("RfqV2Changed") {
288        return None;
289    }
290    sonic_rs::from_str(&sonic_rs::to_string(message).ok()?).ok()
291}
292
293/// Decode an `RfqV2Rfq` frame (an `rfq_v2` subscription with
294/// [`RfqV2View::Full`](hypercall_sdk_types::ws_protocol::RfqV2View::Full)):
295/// the change's `sequence` and the account's RFQ read, exactly the
296/// `GET /private/rfqs/{rfq_id}` body. Treat its `sequence` like a hint's for
297/// the change cursor.
298pub fn rfq_v2_full_read(
299    message: &sonic_rs::Value,
300) -> Option<hypercall_sdk_types::ws_protocol::WsRfqV2Rfq> {
301    use sonic_rs::JsonValueTrait as _;
302    if message.get("type").as_str() != Some("RfqV2Rfq") {
303        return None;
304    }
305    sonic_rs::from_str(&sonic_rs::to_string(message).ok()?).ok()
306}
307
308/// One object in a private mirror.
309#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
310pub enum RfqV2MirrorObject {
311    Parent { rfq_id: Uuid },
312    Quote { rfq_id: Uuid, quote_id: Uuid },
313}
314
315/// A lifecycle state the mirror applied from a server read.
316#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
317pub struct RfqV2MirrorTransition {
318    pub object: RfqV2MirrorObject,
319    pub status: String,
320    /// Remaining target for a parent, remaining capacity for a firm quote,
321    /// and zero for an indicative quote, which has no executable capacity.
322    #[serde(with = "json_u128")]
323    pub remaining: u128,
324}
325
326/// Counters a client can export to prove it recovered without duplication.
327#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
328pub struct RfqV2MirrorStats {
329    pub hints_received: u64,
330    pub duplicate_hints: u64,
331    pub already_applied_hints: u64,
332    pub pages_applied: u64,
333    pub rfq_refreshes: u64,
334    /// A lifecycle state applied again after the object had left it.
335    /// Lifecycle states only move forward, so this stays zero.
336    pub duplicate_transitions: u64,
337}
338
339/// A recipient's local view of its private RFQs, rebuilt only from
340/// authorized reads named by the change feed. WebSocket hints only decide
341/// when to read the feed; they never change the view themselves.
342#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
343pub struct RfqV2PrivateMirror {
344    cursor: RfqV2ChangeCursor,
345    parents: BTreeMap<Uuid, RfqV2Response>,
346    quotes: BTreeMap<Uuid, BTreeMap<Uuid, RfqV2QuoteView>>,
347    transitions: Vec<RfqV2MirrorTransition>,
348    stats: RfqV2MirrorStats,
349}
350
351impl RfqV2PrivateMirror {
352    /// An empty mirror that reads the change feed after `cursor`.
353    pub fn new(cursor: RfqV2ChangeCursor) -> Self {
354        Self {
355            cursor,
356            ..Self::default()
357        }
358    }
359
360    pub fn cursor(&self) -> &RfqV2ChangeCursor {
361        &self.cursor
362    }
363
364    pub fn stats(&self) -> RfqV2MirrorStats {
365        self.stats
366    }
367
368    /// Cached RFQs still live in the mirror (an open or partially filled
369    /// parent) whose parent, or one of whose live quotes, has a signed
370    /// deadline at or before `now_ms`. No change event announces an expiry,
371    /// so these need a reread.
372    fn live_rfqs_past_a_deadline(&self, now_ms: u64) -> Vec<Uuid> {
373        let live = |status: &str| matches!(status, "open" | "partially_filled");
374        self.parents
375            .iter()
376            .filter(|(_, parent)| live(&parent.status))
377            .filter(|(rfq_id, parent)| {
378                let parent_expiry = match &parent.parent {
379                    RfqV2AuthorizedTerms::Taker { terms } => terms.expires_at_ms,
380                    RfqV2AuthorizedTerms::Maker { terms } => terms.expires_at_ms,
381                };
382                parent_expiry <= now_ms
383                    || self.quotes.get(*rfq_id).is_some_and(|quotes| {
384                        quotes.values().any(|quote| match quote {
385                            RfqV2QuoteView::Firm { terms, status, .. } => {
386                                live(status) && terms.expires_at_ms <= now_ms
387                            }
388                            RfqV2QuoteView::Indicative { terms, status, .. } => {
389                                live(status) && terms.expires_at_ms <= now_ms
390                            }
391                        })
392                    })
393            })
394            .map(|(rfq_id, _)| *rfq_id)
395            .collect()
396    }
397
398    /// Every lifecycle state applied, in order.
399    pub fn transitions(&self) -> &[RfqV2MirrorTransition] {
400        &self.transitions
401    }
402
403    pub fn parent(&self, rfq_id: Uuid) -> Option<&RfqV2Response> {
404        self.parents.get(&rfq_id)
405    }
406
407    pub fn parents(&self) -> &BTreeMap<Uuid, RfqV2Response> {
408        &self.parents
409    }
410
411    /// The authorized quotes of one RFQ, by quote ID, terminal ones included.
412    pub fn quotes(&self, rfq_id: Uuid) -> Option<&BTreeMap<Uuid, RfqV2QuoteView>> {
413        self.quotes.get(&rfq_id)
414    }
415
416    pub fn all_quotes(&self) -> &BTreeMap<Uuid, BTreeMap<Uuid, RfqV2QuoteView>> {
417        &self.quotes
418    }
419
420    /// Record a WebSocket hint. Call
421    /// [`HypercallClient::sync_rfq_v2_mirror`] on `ReplayRequired`.
422    pub fn observe_hint(&mut self, hint: &WsRfqV2Changed) -> RfqV2HintDisposition {
423        self.stats.hints_received += 1;
424        let disposition = self.cursor.observe_hint(hint.sequence);
425        match disposition {
426            RfqV2HintDisposition::Duplicate => self.stats.duplicate_hints += 1,
427            RfqV2HintDisposition::AlreadyApplied => self.stats.already_applied_hints += 1,
428            RfqV2HintDisposition::ReplayRequired => {}
429        }
430        disposition
431    }
432
433    fn record(&mut self, object: RfqV2MirrorObject, status: &str, remaining: u128) {
434        let last = self
435            .transitions
436            .iter()
437            .rev()
438            .find(|transition| transition.object == object);
439        if last.is_some_and(|last| last.status == status && last.remaining == remaining) {
440            return;
441        }
442        let entered_before = self.transitions.iter().any(|transition| {
443            transition.object == object
444                && transition.status == status
445                && transition.remaining == remaining
446        });
447        if entered_before {
448            self.stats.duplicate_transitions += 1;
449        }
450        self.transitions.push(RfqV2MirrorTransition {
451            object,
452            status: status.to_string(),
453            remaining,
454        });
455    }
456
457    #[expect(
458        clippy::result_large_err,
459        reason = "public client methods preserve the established unboxed ClientError contract"
460    )]
461    fn apply_refresh(
462        &mut self,
463        parent: RfqV2Response,
464        quotes: BTreeMap<Uuid, RfqV2QuoteView>,
465    ) -> Result<()> {
466        let rfq_id = parent.rfq_id;
467        // Quote records are retained terminal history: a refresh that no
468        // longer lists a known quote is a broken read, not a deletion.
469        // Validate before recording anything, so a rejected read leaves the
470        // persisted mirror exactly as it was.
471        if let Some(known) = self.quotes.get(&rfq_id) {
472            if let Some(missing) = known.keys().find(|id| !quotes.contains_key(id)) {
473                return Err(ClientError::RfqV2ProtocolViolation(format!(
474                    "RFQ v2 quote {missing} vanished from the authorized history of RFQ {rfq_id}"
475                )));
476            }
477        }
478        self.record(
479            RfqV2MirrorObject::Parent { rfq_id },
480            &parent.status,
481            parent.remaining_target,
482        );
483        for (quote_id, quote) in &quotes {
484            let (status, remaining) = match quote {
485                RfqV2QuoteView::Indicative { status, .. } => (status, 0),
486                RfqV2QuoteView::Firm {
487                    status,
488                    remaining_capacity,
489                    ..
490                } => (status, *remaining_capacity),
491            };
492            self.record(
493                RfqV2MirrorObject::Quote {
494                    rfq_id,
495                    quote_id: *quote_id,
496                },
497                status,
498                remaining,
499            );
500        }
501        self.parents.insert(rfq_id, parent);
502        self.quotes.insert(rfq_id, quotes);
503        self.stats.rfq_refreshes += 1;
504        Ok(())
505    }
506}
507
508/// Persistable position in one RFQ's authorized quote list, with the quotes
509/// received so far. A client that disconnects mid-scan resumes from the
510/// stored cursor; after a complete scan it resumes after the scan's
511/// `as_of_sequence`, so later quotes arrive exactly once.
512#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
513pub struct RfqV2QuoteHistory {
514    rfq_id: Uuid,
515    page_limit: usize,
516    next_cursor: Option<String>,
517    after_sequence: u64,
518    quotes: BTreeMap<Uuid, RfqV2QuoteView>,
519    pages: u64,
520}
521
522impl RfqV2QuoteHistory {
523    /// Start a terminal-inclusive history scan of `rfq_id`.
524    #[expect(
525        clippy::result_large_err,
526        reason = "public client methods preserve the established unboxed ClientError contract"
527    )]
528    pub fn new(rfq_id: Uuid, page_limit: usize) -> Result<Self> {
529        if page_limit == 0 || page_limit > MAX_PAGE_LIMIT {
530            return Err(ClientError::InvalidInput(format!(
531                "RFQ v2 quote page limit must be 1..={MAX_PAGE_LIMIT}"
532            )));
533        }
534        Ok(Self {
535            rfq_id,
536            page_limit,
537            next_cursor: None,
538            after_sequence: 0,
539            quotes: BTreeMap::new(),
540            pages: 0,
541        })
542    }
543
544    pub fn rfq_id(&self) -> Uuid {
545        self.rfq_id
546    }
547
548    /// Quotes received so far, by quote ID.
549    pub fn quotes(&self) -> &BTreeMap<Uuid, RfqV2QuoteView> {
550        &self.quotes
551    }
552
553    /// Whether the last page ended the scan.
554    pub fn complete(&self) -> bool {
555        self.pages > 0 && self.next_cursor.is_none()
556    }
557
558    /// The change-feed sequence the last complete scan covered.
559    pub fn as_of_sequence(&self) -> u64 {
560        self.after_sequence
561    }
562
563    pub fn pages(&self) -> u64 {
564        self.pages
565    }
566}
567
568/// Lifecycle facts that keep an execution action disabled.
569#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
570#[serde(rename_all = "snake_case")]
571pub enum RfqV2ExecutionBlock {
572    /// Indicative quotes are never executable.
573    NotFirm,
574    /// The quote or parent belongs to a different RFQ or commitment.
575    IdentityMismatch,
576    ParentNotExecutable,
577    QuoteNotExecutable,
578    Expired,
579    InsufficientCapacity,
580    FillPolicy,
581    /// Some leg would be a fractional or out-of-range contract quantity at
582    /// this size, so the execution is refused.
583    UnrepresentableSize,
584    /// Some leg size, leg price, leg premium or the package premium at this
585    /// size is outside the engine's fill record range, so the execution is
586    /// refused.
587    OutsideRecordRange,
588    /// The quote's premium at this size is outside the parent's signed
589    /// auto-execution limit.
590    OutsideAutoLimit,
591}
592
593/// Whether a caller may offer one execution, decided from fresh reads.
594#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
595pub struct RfqV2ExecutionAction {
596    pub rfq_id: Uuid,
597    pub quote_id: Uuid,
598    pub enabled: bool,
599    pub block: Option<RfqV2ExecutionBlock>,
600    pub parent_status: String,
601    pub quote_status: String,
602    #[serde(with = "json_u128")]
603    pub remaining_target: u128,
604    #[serde(with = "json_u128")]
605    pub remaining_capacity: u128,
606    /// The caller's cached view disagreed with the server and was discarded.
607    pub observation_stale: bool,
608}
609
610/// Decide an execution action from a fresh parent and quote read.
611/// `observed` is the caller's cached quote, for example from an earlier
612/// event; it never enables anything and is only compared with the read.
613pub fn rfq_v2_execution_action(
614    parent: &RfqV2Response,
615    quote: &RfqV2QuoteView,
616    requested_units: u128,
617    now_ms: u64,
618    observed: Option<&RfqV2QuoteView>,
619) -> RfqV2ExecutionAction {
620    let observation_stale = observed.is_some_and(|observed| observed != quote);
621    let (quote_id, quote_status, remaining_capacity, block) = match quote {
622        RfqV2QuoteView::Indicative { terms, status, .. } => (
623            terms.id,
624            status.clone(),
625            0,
626            Some(RfqV2ExecutionBlock::NotFirm),
627        ),
628        RfqV2QuoteView::Firm {
629            terms,
630            status,
631            executable,
632            remaining_capacity,
633            ..
634        } => {
635            let block = if terms.rfq_id != parent.rfq_id
636                || terms.rfq_terms_commitment != parent.terms_commitment
637            {
638                Some(RfqV2ExecutionBlock::IdentityMismatch)
639            } else if !matches!(parent.status.as_str(), "open" | "partially_filled") {
640                Some(RfqV2ExecutionBlock::ParentNotExecutable)
641            } else if !executable || !matches!(status.as_str(), "open" | "partially_filled") {
642                Some(RfqV2ExecutionBlock::QuoteNotExecutable)
643            } else if terms.expires_at_ms <= now_ms {
644                Some(RfqV2ExecutionBlock::Expired)
645            } else if requested_units == 0
646                || requested_units > *remaining_capacity
647                || requested_units > parent.remaining_target
648            {
649                Some(RfqV2ExecutionBlock::InsufficientCapacity)
650            } else if !fill_policy_accepts(
651                terms.fill_policy,
652                terms.capacity,
653                *remaining_capacity,
654                requested_units,
655            ) || !fill_policy_accepts(
656                parent_fill_policy(parent),
657                parent.target,
658                parent.remaining_target,
659                requested_units,
660            ) {
661                // Every fill must satisfy the parent's signed policy as well
662                // as the quote's.
663                Some(RfqV2ExecutionBlock::FillPolicy)
664            } else if !RfqV2ParentUnitGrid::of(parent_legs(parent)).admits(requested_units) {
665                Some(RfqV2ExecutionBlock::UnrepresentableSize)
666            } else if !quote_within_projection_range(parent_legs(parent), terms, requested_units) {
667                Some(RfqV2ExecutionBlock::OutsideRecordRange)
668            } else if !quote_within_auto_limit(
669                parent_auto_execution_limit(parent),
670                terms,
671                requested_units,
672            ) {
673                Some(RfqV2ExecutionBlock::OutsideAutoLimit)
674            } else {
675                None
676            };
677            (terms.id, status.clone(), *remaining_capacity, block)
678        }
679    };
680    RfqV2ExecutionAction {
681        rfq_id: parent.rfq_id,
682        quote_id,
683        enabled: block.is_none(),
684        block,
685        parent_status: parent.status.clone(),
686        quote_status,
687        remaining_target: parent.remaining_target,
688        remaining_capacity,
689        observation_stale,
690    }
691}
692
693/// Why a maker hold may be released.
694#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
695#[serde(tag = "proof", rename_all = "snake_case")]
696pub enum RfqV2MakerHoldProof {
697    /// The maker's own quote filled; the hold becomes the fill.
698    OwnFill {
699        #[serde(with = "json_u128")]
700        filled_units: u128,
701    },
702    /// The parent was filled by other quotes while this one stayed unfilled.
703    CompetingWinner,
704    /// The quote or parent reached a terminal state with nothing filled.
705    TerminalUnfilled { status: String },
706}
707
708/// The persisted state of a maker hold.
709#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
710#[serde(tag = "state", rename_all = "snake_case")]
711pub enum RfqV2MakerHoldState {
712    Unresolved,
713    Released { proof: RfqV2MakerHoldProof },
714}
715
716/// What one round of server reads proved about a hold.
717#[derive(Debug, Clone, PartialEq, Eq)]
718pub enum RfqV2MakerHoldEvidence {
719    /// A status read was missing or 404. The outcome is unknown: missing
720    /// status never proves a loss or the absence of a fill.
721    Missing,
722    /// The reads describe a different RFQ, commitment, quote, or maker.
723    IdentityMismatch,
724    /// The quote can still execute, or nothing terminal was proved yet.
725    Inconclusive,
726    Conclusive(RfqV2MakerHoldProof),
727}
728
729/// A maker's local reservation for a published firm quote, kept until the
730/// RFQ outcome is conclusively known. Persist it with the change-feed cursor
731/// before relying on the quote, and restore it after a restart: the hold
732/// carries everything needed to decide the outcome again.
733#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
734pub struct RfqV2MakerHold {
735    pub rfq_id: Uuid,
736    /// The quote is the maker's operation: its ID is the idempotency key the
737    /// publication, any replacement, and every fill refer to.
738    pub quote_id: Uuid,
739    pub terms_commitment: RfqV2Digest,
740    pub maker_account: WalletAddress,
741    #[serde(with = "json_u128")]
742    pub capacity: u128,
743    /// The quote's signed expiry, which closes its response window.
744    pub response_window_ends_at_ms: u64,
745    /// Last applied recipient change-feed sequence.
746    pub last_cursor: u64,
747    pub state: RfqV2MakerHoldState,
748}
749
750impl RfqV2MakerHold {
751    /// Hold the full capacity of a firm quote the maker published.
752    pub fn for_firm_quote(terms: &RfqV2FirmQuoteTerms, last_cursor: u64) -> Self {
753        Self {
754            rfq_id: terms.rfq_id,
755            quote_id: terms.id,
756            terms_commitment: terms.rfq_terms_commitment,
757            maker_account: terms.maker_account,
758            capacity: terms.capacity,
759            response_window_ends_at_ms: terms.expires_at_ms,
760            last_cursor,
761            state: RfqV2MakerHoldState::Unresolved,
762        }
763    }
764
765    pub fn released(&self) -> bool {
766        matches!(self.state, RfqV2MakerHoldState::Released { .. })
767    }
768
769    /// Judge one round of reads. `None` is a missing or 404 read.
770    pub fn evaluate(
771        &self,
772        parent: Option<&RfqV2Response>,
773        quote: Option<&RfqV2QuoteView>,
774        now_ms: u64,
775    ) -> RfqV2MakerHoldEvidence {
776        let (Some(parent), Some(quote)) = (parent, quote) else {
777            return RfqV2MakerHoldEvidence::Missing;
778        };
779        let RfqV2QuoteView::Firm {
780            terms,
781            status,
782            executable,
783            remaining_capacity,
784            ..
785        } = quote
786        else {
787            return RfqV2MakerHoldEvidence::IdentityMismatch;
788        };
789        if parent.rfq_id != self.rfq_id
790            || parent.terms_commitment != self.terms_commitment
791            || terms.id != self.quote_id
792            || terms.rfq_id != self.rfq_id
793            || terms.rfq_terms_commitment != self.terms_commitment
794            || terms.maker_account != self.maker_account
795            || terms.capacity != self.capacity
796            || *remaining_capacity > self.capacity
797        {
798            return RfqV2MakerHoldEvidence::IdentityMismatch;
799        }
800        if *executable {
801            return RfqV2MakerHoldEvidence::Inconclusive;
802        }
803        let quote_terminal = matches!(
804            status.as_str(),
805            "filled" | "withdrawn" | "expired" | "replaced"
806        );
807        let parent_terminal = matches!(
808            parent.status.as_str(),
809            "filled" | "cancelled" | "expired" | "replaced"
810        );
811        let filled_units = self.capacity - remaining_capacity;
812        if !(quote_terminal || parent_terminal) {
813            // A used quote that can no longer execute (a spent one-shot
814            // policy, or a remainder below its minimum) never fills again,
815            // so its fill so far is final.
816            if filled_units > 0 {
817                return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::OwnFill {
818                    filled_units,
819                });
820            }
821            // Another quote filled part of the parent, and this unused quote
822            // can no longer execute: the parent's policy admits no further
823            // fill (a spent one-shot or a remainder below its minimum), and
824            // its remaining target only shrinks, so it never will.
825            if parent.status == "partially_filled" {
826                return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::CompetingWinner);
827            }
828            return RfqV2MakerHoldEvidence::Inconclusive;
829        }
830        if filled_units > 0 {
831            return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::OwnFill {
832                filled_units,
833            });
834        }
835        if parent.status == "filled" {
836            return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::CompetingWinner);
837        }
838        let terminal = if quote_terminal {
839            status
840        } else {
841            &parent.status
842        };
843        // Expiry is evidence only once this hold's own response window closed.
844        if terminal == "expired" && now_ms < self.response_window_ends_at_ms {
845            return RfqV2MakerHoldEvidence::Inconclusive;
846        }
847        RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::TerminalUnfilled {
848            status: terminal.clone(),
849        })
850    }
851
852    /// Release on conclusive evidence; anything else keeps the hold.
853    pub fn apply(&mut self, evidence: &RfqV2MakerHoldEvidence) {
854        if let (RfqV2MakerHoldState::Unresolved, RfqV2MakerHoldEvidence::Conclusive(proof)) =
855            (&self.state, evidence)
856        {
857            self.state = RfqV2MakerHoldState::Released {
858                proof: proof.clone(),
859            };
860        }
861    }
862}
863
864fn not_found(error: &ClientError) -> bool {
865    matches!(
866        error,
867        ClientError::Api { status: 404, .. } | ClientError::RfqV2Api { status: 404, .. }
868    )
869}
870
871#[expect(
872    clippy::result_large_err,
873    reason = "public client methods preserve the established unboxed ClientError contract"
874)]
875fn unix_now_ms() -> Result<u64> {
876    let elapsed = std::time::SystemTime::now()
877        .duration_since(std::time::UNIX_EPOCH)
878        .map_err(|error| {
879            ClientError::InvalidInput(format!("system clock before epoch: {error}"))
880        })?;
881    u64::try_from(elapsed.as_millis())
882        .map_err(|_| ClientError::InvalidInput("system clock overflows u64 ms".to_string()))
883}
884
885impl HypercallClient {
886    /// Fetch the next page of a quote history and merge it. A quote ID seen
887    /// on an earlier page is a protocol violation and fails the page.
888    pub async fn next_rfq_v2_quote_page(
889        &self,
890        history: &mut RfqV2QuoteHistory,
891        credentials: RfqV2ReadCredentials<'_>,
892    ) -> Result<()> {
893        let query = ListRfqV2QuotesQuery {
894            cursor: history.next_cursor.clone(),
895            limit: Some(history.page_limit),
896            after_sequence: (history.next_cursor.is_none() && history.after_sequence > 0)
897                .then_some(history.after_sequence),
898            include_terminal: Some(true),
899            ..ListRfqV2QuotesQuery::default()
900        };
901        let page = self
902            .list_rfq_v2_quotes(history.rfq_id, &query, credentials)
903            .await?;
904        let mut received = BTreeMap::new();
905        for quote in page.quotes {
906            let id = match &quote {
907                RfqV2QuoteView::Indicative { terms, .. } => terms.id,
908                RfqV2QuoteView::Firm { terms, .. } => terms.id,
909            };
910            if history.quotes.contains_key(&id) || received.insert(id, quote).is_some() {
911                return Err(ClientError::RfqV2ProtocolViolation(format!(
912                    "RFQ v2 quote {id} was delivered twice in the history of RFQ {}",
913                    history.rfq_id
914                )));
915            }
916        }
917        let next_cursor = if page.page.has_more {
918            Some(page.page.next_cursor.ok_or_else(|| {
919                ClientError::RfqV2ProtocolViolation(
920                    "RFQ v2 quote page has more results but no cursor".to_string(),
921                )
922            })?)
923        } else {
924            None
925        };
926        history.quotes.append(&mut received);
927        if next_cursor.is_none() {
928            history.after_sequence = page.as_of_sequence;
929        }
930        history.next_cursor = next_cursor;
931        history.pages += 1;
932        Ok(())
933    }
934
935    /// Page a quote history until the scan is complete.
936    pub async fn sync_rfq_v2_quote_history(
937        &self,
938        history: &mut RfqV2QuoteHistory,
939        credentials: RfqV2ReadCredentials<'_>,
940    ) -> Result<()> {
941        loop {
942            self.next_rfq_v2_quote_page(
943                history,
944                RfqV2ReadCredentials {
945                    bearer_token: credentials.bearer_token,
946                },
947            )
948            .await?;
949            if history.next_cursor.is_none() {
950                return Ok(());
951            }
952        }
953    }
954
955    /// Read the recipient change feed from the mirror's last applied cursor
956    /// and refresh each named RFQ from authorized reads. The cursor advances
957    /// page by page, only after that page's reads are applied, so an error
958    /// leaves a mirror that resumes safely. Call it after connecting, after
959    /// every reconnect, whenever a hint requires it, and periodically.
960    /// It only reads; it never resubmits an operation.
961    pub async fn sync_rfq_v2_mirror(
962        &self,
963        mirror: &mut RfqV2PrivateMirror,
964        credentials: RfqV2ReadCredentials<'_>,
965    ) -> Result<BTreeSet<Uuid>> {
966        let token = credentials.bearer_token;
967        let mut refreshed = BTreeSet::new();
968        loop {
969            let after_sequence = mirror.cursor.last_applied_sequence;
970            let query = ListRfqV2ChangesQuery {
971                after_sequence: Some(after_sequence),
972                limit: Some(MAX_PAGE_LIMIT as u32),
973            };
974            let page = self
975                .list_rfq_v2_changes(
976                    &query,
977                    RfqV2ReadCredentials {
978                        bearer_token: token,
979                    },
980                )
981                .await?;
982            check_change_page(after_sequence, &page)?;
983            let named: BTreeSet<Uuid> = page.changes.iter().map(|change| change.rfq_id).collect();
984            for rfq_id in named {
985                self.refresh_mirror_rfq(mirror, rfq_id, token).await?;
986                refreshed.insert(rfq_id);
987            }
988            mirror.cursor.commit(page.next_after_sequence);
989            mirror.stats.pages_applied += 1;
990            if !page.has_more {
991                break;
992            }
993        }
994        // Expiry is derived from the signed deadline, so no change event
995        // announces it: reread every cached RFQ that is still live but has a
996        // deadline the wall clock has passed.
997        for rfq_id in mirror.live_rfqs_past_a_deadline(unix_now_ms()?) {
998            if refreshed.insert(rfq_id) {
999                self.refresh_mirror_rfq(mirror, rfq_id, token).await?;
1000            }
1001        }
1002        Ok(refreshed)
1003    }
1004
1005    /// Reread one RFQ and its whole quote history into the mirror.
1006    async fn refresh_mirror_rfq(
1007        &self,
1008        mirror: &mut RfqV2PrivateMirror,
1009        rfq_id: Uuid,
1010        token: &str,
1011    ) -> Result<()> {
1012        let parent = self
1013            .get_rfq_v2(
1014                rfq_id,
1015                RfqV2ReadCredentials {
1016                    bearer_token: token,
1017                },
1018            )
1019            .await?;
1020        let mut history = RfqV2QuoteHistory::new(rfq_id, MAX_PAGE_LIMIT)?;
1021        self.sync_rfq_v2_quote_history(
1022            &mut history,
1023            RfqV2ReadCredentials {
1024                bearer_token: token,
1025            },
1026        )
1027        .await?;
1028        mirror.apply_refresh(parent, history.quotes)
1029    }
1030
1031    /// Decide whether to offer an execution from fresh server reads of the
1032    /// parent and quote. A cached or event-derived `observed` view is never
1033    /// trusted: a stale "capacity remains" event cannot enable a fill whose
1034    /// capacity is already used.
1035    pub async fn refresh_rfq_v2_execution_action(
1036        &self,
1037        rfq_id: Uuid,
1038        quote_id: Uuid,
1039        requested_units: u128,
1040        observed: Option<&RfqV2QuoteView>,
1041        credentials: RfqV2ReadCredentials<'_>,
1042    ) -> Result<RfqV2ExecutionAction> {
1043        let token = credentials.bearer_token;
1044        let parent = self
1045            .get_rfq_v2(
1046                rfq_id,
1047                RfqV2ReadCredentials {
1048                    bearer_token: token,
1049                },
1050            )
1051            .await?;
1052        let quote = self
1053            .get_rfq_v2_quote(
1054                rfq_id,
1055                quote_id,
1056                RfqV2ReadCredentials {
1057                    bearer_token: token,
1058                },
1059            )
1060            .await?;
1061        Ok(rfq_v2_execution_action(
1062            &parent,
1063            &quote,
1064            requested_units,
1065            unix_now_ms()?,
1066            observed,
1067        ))
1068    }
1069
1070    /// Re-decide a maker hold from server reads, then advance its
1071    /// change-feed cursor. A 404 or missing status leaves the hold
1072    /// unresolved; only identity-bound own-fill, competing-winner, or
1073    /// terminal evidence releases it. A released hold is final.
1074    pub async fn reconcile_rfq_v2_maker_hold(
1075        &self,
1076        hold: &mut RfqV2MakerHold,
1077        credentials: RfqV2ReadCredentials<'_>,
1078    ) -> Result<RfqV2MakerHoldEvidence> {
1079        if let RfqV2MakerHoldState::Released { proof } = &hold.state {
1080            return Ok(RfqV2MakerHoldEvidence::Conclusive(proof.clone()));
1081        }
1082        let token = credentials.bearer_token;
1083        // Read the feed position first: every change up to it happened
1084        // before the status reads below, so saving it afterwards can
1085        // never skip a change those reads did not observe.
1086        let mut cursor = hold.last_cursor;
1087        loop {
1088            let query = ListRfqV2ChangesQuery {
1089                after_sequence: Some(cursor),
1090                limit: Some(MAX_PAGE_LIMIT as u32),
1091            };
1092            let page = self
1093                .list_rfq_v2_changes(
1094                    &query,
1095                    RfqV2ReadCredentials {
1096                        bearer_token: token,
1097                    },
1098                )
1099                .await?;
1100            check_change_page(cursor, &page)?;
1101            cursor = page.next_after_sequence;
1102            if !page.has_more {
1103                break;
1104            }
1105        }
1106        let parent = match self
1107            .get_rfq_v2(
1108                hold.rfq_id,
1109                RfqV2ReadCredentials {
1110                    bearer_token: token,
1111                },
1112            )
1113            .await
1114        {
1115            Ok(parent) => Some(parent),
1116            Err(error) if not_found(&error) => None,
1117            Err(error) => return Err(error),
1118        };
1119        let quote = match self
1120            .get_rfq_v2_quote(
1121                hold.rfq_id,
1122                hold.quote_id,
1123                RfqV2ReadCredentials {
1124                    bearer_token: token,
1125                },
1126            )
1127            .await
1128        {
1129            Ok(quote) => Some(quote),
1130            Err(error) if not_found(&error) => None,
1131            Err(error) => return Err(error),
1132        };
1133        let evidence = hold.evaluate(parent.as_ref(), quote.as_ref(), unix_now_ms()?);
1134        hold.apply(&evidence);
1135        hold.last_cursor = cursor;
1136        Ok(evidence)
1137    }
1138}
1139
1140#[cfg(test)]
1141#[path = "rfq_v2_recovery_test.rs"]
1142mod tests;