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/// One object in a private mirror.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
295pub enum RfqV2MirrorObject {
296    Parent { rfq_id: Uuid },
297    Quote { rfq_id: Uuid, quote_id: Uuid },
298}
299
300/// A lifecycle state the mirror applied from a server read.
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302pub struct RfqV2MirrorTransition {
303    pub object: RfqV2MirrorObject,
304    pub status: String,
305    /// Remaining target for a parent, remaining capacity for a firm quote,
306    /// and zero for an indicative quote, which has no executable capacity.
307    #[serde(with = "json_u128")]
308    pub remaining: u128,
309}
310
311/// Counters a client can export to prove it recovered without duplication.
312#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
313pub struct RfqV2MirrorStats {
314    pub hints_received: u64,
315    pub duplicate_hints: u64,
316    pub already_applied_hints: u64,
317    pub pages_applied: u64,
318    pub rfq_refreshes: u64,
319    /// A lifecycle state applied again after the object had left it.
320    /// Lifecycle states only move forward, so this stays zero.
321    pub duplicate_transitions: u64,
322}
323
324/// A recipient's local view of its private RFQs, rebuilt only from
325/// authorized reads named by the change feed. WebSocket hints only decide
326/// when to read the feed; they never change the view themselves.
327#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
328pub struct RfqV2PrivateMirror {
329    cursor: RfqV2ChangeCursor,
330    parents: BTreeMap<Uuid, RfqV2Response>,
331    quotes: BTreeMap<Uuid, BTreeMap<Uuid, RfqV2QuoteView>>,
332    transitions: Vec<RfqV2MirrorTransition>,
333    stats: RfqV2MirrorStats,
334}
335
336impl RfqV2PrivateMirror {
337    /// An empty mirror that reads the change feed after `cursor`.
338    pub fn new(cursor: RfqV2ChangeCursor) -> Self {
339        Self {
340            cursor,
341            ..Self::default()
342        }
343    }
344
345    pub fn cursor(&self) -> &RfqV2ChangeCursor {
346        &self.cursor
347    }
348
349    pub fn stats(&self) -> RfqV2MirrorStats {
350        self.stats
351    }
352
353    /// Cached RFQs still live in the mirror (an open or partially filled
354    /// parent) whose parent, or one of whose live quotes, has a signed
355    /// deadline at or before `now_ms`. No change event announces an expiry,
356    /// so these need a reread.
357    fn live_rfqs_past_a_deadline(&self, now_ms: u64) -> Vec<Uuid> {
358        let live = |status: &str| matches!(status, "open" | "partially_filled");
359        self.parents
360            .iter()
361            .filter(|(_, parent)| live(&parent.status))
362            .filter(|(rfq_id, parent)| {
363                let parent_expiry = match &parent.parent {
364                    RfqV2AuthorizedTerms::Taker { terms } => terms.expires_at_ms,
365                    RfqV2AuthorizedTerms::Maker { terms } => terms.expires_at_ms,
366                };
367                parent_expiry <= now_ms
368                    || self.quotes.get(*rfq_id).is_some_and(|quotes| {
369                        quotes.values().any(|quote| match quote {
370                            RfqV2QuoteView::Firm { terms, status, .. } => {
371                                live(status) && terms.expires_at_ms <= now_ms
372                            }
373                            RfqV2QuoteView::Indicative { terms, status, .. } => {
374                                live(status) && terms.expires_at_ms <= now_ms
375                            }
376                        })
377                    })
378            })
379            .map(|(rfq_id, _)| *rfq_id)
380            .collect()
381    }
382
383    /// Every lifecycle state applied, in order.
384    pub fn transitions(&self) -> &[RfqV2MirrorTransition] {
385        &self.transitions
386    }
387
388    pub fn parent(&self, rfq_id: Uuid) -> Option<&RfqV2Response> {
389        self.parents.get(&rfq_id)
390    }
391
392    pub fn parents(&self) -> &BTreeMap<Uuid, RfqV2Response> {
393        &self.parents
394    }
395
396    /// The authorized quotes of one RFQ, by quote ID, terminal ones included.
397    pub fn quotes(&self, rfq_id: Uuid) -> Option<&BTreeMap<Uuid, RfqV2QuoteView>> {
398        self.quotes.get(&rfq_id)
399    }
400
401    pub fn all_quotes(&self) -> &BTreeMap<Uuid, BTreeMap<Uuid, RfqV2QuoteView>> {
402        &self.quotes
403    }
404
405    /// Record a WebSocket hint. Call
406    /// [`HypercallClient::sync_rfq_v2_mirror`] on `ReplayRequired`.
407    pub fn observe_hint(&mut self, hint: &WsRfqV2Changed) -> RfqV2HintDisposition {
408        self.stats.hints_received += 1;
409        let disposition = self.cursor.observe_hint(hint.sequence);
410        match disposition {
411            RfqV2HintDisposition::Duplicate => self.stats.duplicate_hints += 1,
412            RfqV2HintDisposition::AlreadyApplied => self.stats.already_applied_hints += 1,
413            RfqV2HintDisposition::ReplayRequired => {}
414        }
415        disposition
416    }
417
418    fn record(&mut self, object: RfqV2MirrorObject, status: &str, remaining: u128) {
419        let last = self
420            .transitions
421            .iter()
422            .rev()
423            .find(|transition| transition.object == object);
424        if last.is_some_and(|last| last.status == status && last.remaining == remaining) {
425            return;
426        }
427        let entered_before = self.transitions.iter().any(|transition| {
428            transition.object == object
429                && transition.status == status
430                && transition.remaining == remaining
431        });
432        if entered_before {
433            self.stats.duplicate_transitions += 1;
434        }
435        self.transitions.push(RfqV2MirrorTransition {
436            object,
437            status: status.to_string(),
438            remaining,
439        });
440    }
441
442    #[expect(
443        clippy::result_large_err,
444        reason = "public client methods preserve the established unboxed ClientError contract"
445    )]
446    fn apply_refresh(
447        &mut self,
448        parent: RfqV2Response,
449        quotes: BTreeMap<Uuid, RfqV2QuoteView>,
450    ) -> Result<()> {
451        let rfq_id = parent.rfq_id;
452        // Quote records are retained terminal history: a refresh that no
453        // longer lists a known quote is a broken read, not a deletion.
454        // Validate before recording anything, so a rejected read leaves the
455        // persisted mirror exactly as it was.
456        if let Some(known) = self.quotes.get(&rfq_id) {
457            if let Some(missing) = known.keys().find(|id| !quotes.contains_key(id)) {
458                return Err(ClientError::RfqV2ProtocolViolation(format!(
459                    "RFQ v2 quote {missing} vanished from the authorized history of RFQ {rfq_id}"
460                )));
461            }
462        }
463        self.record(
464            RfqV2MirrorObject::Parent { rfq_id },
465            &parent.status,
466            parent.remaining_target,
467        );
468        for (quote_id, quote) in &quotes {
469            let (status, remaining) = match quote {
470                RfqV2QuoteView::Indicative { status, .. } => (status, 0),
471                RfqV2QuoteView::Firm {
472                    status,
473                    remaining_capacity,
474                    ..
475                } => (status, *remaining_capacity),
476            };
477            self.record(
478                RfqV2MirrorObject::Quote {
479                    rfq_id,
480                    quote_id: *quote_id,
481                },
482                status,
483                remaining,
484            );
485        }
486        self.parents.insert(rfq_id, parent);
487        self.quotes.insert(rfq_id, quotes);
488        self.stats.rfq_refreshes += 1;
489        Ok(())
490    }
491}
492
493/// Persistable position in one RFQ's authorized quote list, with the quotes
494/// received so far. A client that disconnects mid-scan resumes from the
495/// stored cursor; after a complete scan it resumes after the scan's
496/// `as_of_sequence`, so later quotes arrive exactly once.
497#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
498pub struct RfqV2QuoteHistory {
499    rfq_id: Uuid,
500    page_limit: usize,
501    next_cursor: Option<String>,
502    after_sequence: u64,
503    quotes: BTreeMap<Uuid, RfqV2QuoteView>,
504    pages: u64,
505}
506
507impl RfqV2QuoteHistory {
508    /// Start a terminal-inclusive history scan of `rfq_id`.
509    #[expect(
510        clippy::result_large_err,
511        reason = "public client methods preserve the established unboxed ClientError contract"
512    )]
513    pub fn new(rfq_id: Uuid, page_limit: usize) -> Result<Self> {
514        if page_limit == 0 || page_limit > MAX_PAGE_LIMIT {
515            return Err(ClientError::InvalidInput(format!(
516                "RFQ v2 quote page limit must be 1..={MAX_PAGE_LIMIT}"
517            )));
518        }
519        Ok(Self {
520            rfq_id,
521            page_limit,
522            next_cursor: None,
523            after_sequence: 0,
524            quotes: BTreeMap::new(),
525            pages: 0,
526        })
527    }
528
529    pub fn rfq_id(&self) -> Uuid {
530        self.rfq_id
531    }
532
533    /// Quotes received so far, by quote ID.
534    pub fn quotes(&self) -> &BTreeMap<Uuid, RfqV2QuoteView> {
535        &self.quotes
536    }
537
538    /// Whether the last page ended the scan.
539    pub fn complete(&self) -> bool {
540        self.pages > 0 && self.next_cursor.is_none()
541    }
542
543    /// The change-feed sequence the last complete scan covered.
544    pub fn as_of_sequence(&self) -> u64 {
545        self.after_sequence
546    }
547
548    pub fn pages(&self) -> u64 {
549        self.pages
550    }
551}
552
553/// Lifecycle facts that keep an execution action disabled.
554#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
555#[serde(rename_all = "snake_case")]
556pub enum RfqV2ExecutionBlock {
557    /// Indicative quotes are never executable.
558    NotFirm,
559    /// The quote or parent belongs to a different RFQ or commitment.
560    IdentityMismatch,
561    ParentNotExecutable,
562    QuoteNotExecutable,
563    Expired,
564    InsufficientCapacity,
565    FillPolicy,
566    /// Some leg would be a fractional or out-of-range contract quantity at
567    /// this size, so the execution is refused.
568    UnrepresentableSize,
569    /// Some leg size, leg price, leg premium or the package premium at this
570    /// size is outside the engine's fill record range, so the execution is
571    /// refused.
572    OutsideRecordRange,
573    /// The quote's premium at this size is outside the parent's signed
574    /// auto-execution limit.
575    OutsideAutoLimit,
576}
577
578/// Whether a caller may offer one execution, decided from fresh reads.
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
580pub struct RfqV2ExecutionAction {
581    pub rfq_id: Uuid,
582    pub quote_id: Uuid,
583    pub enabled: bool,
584    pub block: Option<RfqV2ExecutionBlock>,
585    pub parent_status: String,
586    pub quote_status: String,
587    #[serde(with = "json_u128")]
588    pub remaining_target: u128,
589    #[serde(with = "json_u128")]
590    pub remaining_capacity: u128,
591    /// The caller's cached view disagreed with the server and was discarded.
592    pub observation_stale: bool,
593}
594
595/// Decide an execution action from a fresh parent and quote read.
596/// `observed` is the caller's cached quote, for example from an earlier
597/// event; it never enables anything and is only compared with the read.
598pub fn rfq_v2_execution_action(
599    parent: &RfqV2Response,
600    quote: &RfqV2QuoteView,
601    requested_units: u128,
602    now_ms: u64,
603    observed: Option<&RfqV2QuoteView>,
604) -> RfqV2ExecutionAction {
605    let observation_stale = observed.is_some_and(|observed| observed != quote);
606    let (quote_id, quote_status, remaining_capacity, block) = match quote {
607        RfqV2QuoteView::Indicative { terms, status, .. } => (
608            terms.id,
609            status.clone(),
610            0,
611            Some(RfqV2ExecutionBlock::NotFirm),
612        ),
613        RfqV2QuoteView::Firm {
614            terms,
615            status,
616            executable,
617            remaining_capacity,
618            ..
619        } => {
620            let block = if terms.rfq_id != parent.rfq_id
621                || terms.rfq_terms_commitment != parent.terms_commitment
622            {
623                Some(RfqV2ExecutionBlock::IdentityMismatch)
624            } else if !matches!(parent.status.as_str(), "open" | "partially_filled") {
625                Some(RfqV2ExecutionBlock::ParentNotExecutable)
626            } else if !executable || !matches!(status.as_str(), "open" | "partially_filled") {
627                Some(RfqV2ExecutionBlock::QuoteNotExecutable)
628            } else if terms.expires_at_ms <= now_ms {
629                Some(RfqV2ExecutionBlock::Expired)
630            } else if requested_units == 0
631                || requested_units > *remaining_capacity
632                || requested_units > parent.remaining_target
633            {
634                Some(RfqV2ExecutionBlock::InsufficientCapacity)
635            } else if !fill_policy_accepts(
636                terms.fill_policy,
637                terms.capacity,
638                *remaining_capacity,
639                requested_units,
640            ) || !fill_policy_accepts(
641                parent_fill_policy(parent),
642                parent.target,
643                parent.remaining_target,
644                requested_units,
645            ) {
646                // Every fill must satisfy the parent's signed policy as well
647                // as the quote's.
648                Some(RfqV2ExecutionBlock::FillPolicy)
649            } else if !RfqV2ParentUnitGrid::of(parent_legs(parent)).admits(requested_units) {
650                Some(RfqV2ExecutionBlock::UnrepresentableSize)
651            } else if !quote_within_projection_range(parent_legs(parent), terms, requested_units) {
652                Some(RfqV2ExecutionBlock::OutsideRecordRange)
653            } else if !quote_within_auto_limit(
654                parent_auto_execution_limit(parent),
655                terms,
656                requested_units,
657            ) {
658                Some(RfqV2ExecutionBlock::OutsideAutoLimit)
659            } else {
660                None
661            };
662            (terms.id, status.clone(), *remaining_capacity, block)
663        }
664    };
665    RfqV2ExecutionAction {
666        rfq_id: parent.rfq_id,
667        quote_id,
668        enabled: block.is_none(),
669        block,
670        parent_status: parent.status.clone(),
671        quote_status,
672        remaining_target: parent.remaining_target,
673        remaining_capacity,
674        observation_stale,
675    }
676}
677
678/// Why a maker hold may be released.
679#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
680#[serde(tag = "proof", rename_all = "snake_case")]
681pub enum RfqV2MakerHoldProof {
682    /// The maker's own quote filled; the hold becomes the fill.
683    OwnFill {
684        #[serde(with = "json_u128")]
685        filled_units: u128,
686    },
687    /// The parent was filled by other quotes while this one stayed unfilled.
688    CompetingWinner,
689    /// The quote or parent reached a terminal state with nothing filled.
690    TerminalUnfilled { status: String },
691}
692
693/// The persisted state of a maker hold.
694#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
695#[serde(tag = "state", rename_all = "snake_case")]
696pub enum RfqV2MakerHoldState {
697    Unresolved,
698    Released { proof: RfqV2MakerHoldProof },
699}
700
701/// What one round of server reads proved about a hold.
702#[derive(Debug, Clone, PartialEq, Eq)]
703pub enum RfqV2MakerHoldEvidence {
704    /// A status read was missing or 404. The outcome is unknown: missing
705    /// status never proves a loss or the absence of a fill.
706    Missing,
707    /// The reads describe a different RFQ, commitment, quote, or maker.
708    IdentityMismatch,
709    /// The quote can still execute, or nothing terminal was proved yet.
710    Inconclusive,
711    Conclusive(RfqV2MakerHoldProof),
712}
713
714/// A maker's local reservation for a published firm quote, kept until the
715/// RFQ outcome is conclusively known. Persist it with the change-feed cursor
716/// before relying on the quote, and restore it after a restart: the hold
717/// carries everything needed to decide the outcome again.
718#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
719pub struct RfqV2MakerHold {
720    pub rfq_id: Uuid,
721    /// The quote is the maker's operation: its ID is the idempotency key the
722    /// publication, any replacement, and every fill refer to.
723    pub quote_id: Uuid,
724    pub terms_commitment: RfqV2Digest,
725    pub maker_account: WalletAddress,
726    #[serde(with = "json_u128")]
727    pub capacity: u128,
728    /// The quote's signed expiry, which closes its response window.
729    pub response_window_ends_at_ms: u64,
730    /// Last applied recipient change-feed sequence.
731    pub last_cursor: u64,
732    pub state: RfqV2MakerHoldState,
733}
734
735impl RfqV2MakerHold {
736    /// Hold the full capacity of a firm quote the maker published.
737    pub fn for_firm_quote(terms: &RfqV2FirmQuoteTerms, last_cursor: u64) -> Self {
738        Self {
739            rfq_id: terms.rfq_id,
740            quote_id: terms.id,
741            terms_commitment: terms.rfq_terms_commitment,
742            maker_account: terms.maker_account,
743            capacity: terms.capacity,
744            response_window_ends_at_ms: terms.expires_at_ms,
745            last_cursor,
746            state: RfqV2MakerHoldState::Unresolved,
747        }
748    }
749
750    pub fn released(&self) -> bool {
751        matches!(self.state, RfqV2MakerHoldState::Released { .. })
752    }
753
754    /// Judge one round of reads. `None` is a missing or 404 read.
755    pub fn evaluate(
756        &self,
757        parent: Option<&RfqV2Response>,
758        quote: Option<&RfqV2QuoteView>,
759        now_ms: u64,
760    ) -> RfqV2MakerHoldEvidence {
761        let (Some(parent), Some(quote)) = (parent, quote) else {
762            return RfqV2MakerHoldEvidence::Missing;
763        };
764        let RfqV2QuoteView::Firm {
765            terms,
766            status,
767            executable,
768            remaining_capacity,
769            ..
770        } = quote
771        else {
772            return RfqV2MakerHoldEvidence::IdentityMismatch;
773        };
774        if parent.rfq_id != self.rfq_id
775            || parent.terms_commitment != self.terms_commitment
776            || terms.id != self.quote_id
777            || terms.rfq_id != self.rfq_id
778            || terms.rfq_terms_commitment != self.terms_commitment
779            || terms.maker_account != self.maker_account
780            || terms.capacity != self.capacity
781            || *remaining_capacity > self.capacity
782        {
783            return RfqV2MakerHoldEvidence::IdentityMismatch;
784        }
785        if *executable {
786            return RfqV2MakerHoldEvidence::Inconclusive;
787        }
788        let quote_terminal = matches!(
789            status.as_str(),
790            "filled" | "withdrawn" | "expired" | "replaced"
791        );
792        let parent_terminal = matches!(
793            parent.status.as_str(),
794            "filled" | "cancelled" | "expired" | "replaced"
795        );
796        let filled_units = self.capacity - remaining_capacity;
797        if !(quote_terminal || parent_terminal) {
798            // A used quote that can no longer execute (a spent one-shot
799            // policy, or a remainder below its minimum) never fills again,
800            // so its fill so far is final.
801            if filled_units > 0 {
802                return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::OwnFill {
803                    filled_units,
804                });
805            }
806            // Another quote filled part of the parent, and this unused quote
807            // can no longer execute: the parent's policy admits no further
808            // fill (a spent one-shot or a remainder below its minimum), and
809            // its remaining target only shrinks, so it never will.
810            if parent.status == "partially_filled" {
811                return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::CompetingWinner);
812            }
813            return RfqV2MakerHoldEvidence::Inconclusive;
814        }
815        if filled_units > 0 {
816            return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::OwnFill {
817                filled_units,
818            });
819        }
820        if parent.status == "filled" {
821            return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::CompetingWinner);
822        }
823        let terminal = if quote_terminal {
824            status
825        } else {
826            &parent.status
827        };
828        // Expiry is evidence only once this hold's own response window closed.
829        if terminal == "expired" && now_ms < self.response_window_ends_at_ms {
830            return RfqV2MakerHoldEvidence::Inconclusive;
831        }
832        RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::TerminalUnfilled {
833            status: terminal.clone(),
834        })
835    }
836
837    /// Release on conclusive evidence; anything else keeps the hold.
838    pub fn apply(&mut self, evidence: &RfqV2MakerHoldEvidence) {
839        if let (RfqV2MakerHoldState::Unresolved, RfqV2MakerHoldEvidence::Conclusive(proof)) =
840            (&self.state, evidence)
841        {
842            self.state = RfqV2MakerHoldState::Released {
843                proof: proof.clone(),
844            };
845        }
846    }
847}
848
849fn not_found(error: &ClientError) -> bool {
850    matches!(
851        error,
852        ClientError::Api { status: 404, .. } | ClientError::RfqV2Api { status: 404, .. }
853    )
854}
855
856#[expect(
857    clippy::result_large_err,
858    reason = "public client methods preserve the established unboxed ClientError contract"
859)]
860fn unix_now_ms() -> Result<u64> {
861    let elapsed = std::time::SystemTime::now()
862        .duration_since(std::time::UNIX_EPOCH)
863        .map_err(|error| {
864            ClientError::InvalidInput(format!("system clock before epoch: {error}"))
865        })?;
866    u64::try_from(elapsed.as_millis())
867        .map_err(|_| ClientError::InvalidInput("system clock overflows u64 ms".to_string()))
868}
869
870impl HypercallClient {
871    /// Fetch the next page of a quote history and merge it. A quote ID seen
872    /// on an earlier page is a protocol violation and fails the page.
873    pub async fn next_rfq_v2_quote_page(
874        &self,
875        history: &mut RfqV2QuoteHistory,
876        credentials: RfqV2ReadCredentials<'_>,
877    ) -> Result<()> {
878        let query = ListRfqV2QuotesQuery {
879            cursor: history.next_cursor.clone(),
880            limit: Some(history.page_limit),
881            after_sequence: (history.next_cursor.is_none() && history.after_sequence > 0)
882                .then_some(history.after_sequence),
883            include_terminal: Some(true),
884            ..ListRfqV2QuotesQuery::default()
885        };
886        let page = self
887            .list_rfq_v2_quotes(history.rfq_id, &query, credentials)
888            .await?;
889        let mut received = BTreeMap::new();
890        for quote in page.quotes {
891            let id = match &quote {
892                RfqV2QuoteView::Indicative { terms, .. } => terms.id,
893                RfqV2QuoteView::Firm { terms, .. } => terms.id,
894            };
895            if history.quotes.contains_key(&id) || received.insert(id, quote).is_some() {
896                return Err(ClientError::RfqV2ProtocolViolation(format!(
897                    "RFQ v2 quote {id} was delivered twice in the history of RFQ {}",
898                    history.rfq_id
899                )));
900            }
901        }
902        let next_cursor = if page.page.has_more {
903            Some(page.page.next_cursor.ok_or_else(|| {
904                ClientError::RfqV2ProtocolViolation(
905                    "RFQ v2 quote page has more results but no cursor".to_string(),
906                )
907            })?)
908        } else {
909            None
910        };
911        history.quotes.append(&mut received);
912        if next_cursor.is_none() {
913            history.after_sequence = page.as_of_sequence;
914        }
915        history.next_cursor = next_cursor;
916        history.pages += 1;
917        Ok(())
918    }
919
920    /// Page a quote history until the scan is complete.
921    pub async fn sync_rfq_v2_quote_history(
922        &self,
923        history: &mut RfqV2QuoteHistory,
924        credentials: RfqV2ReadCredentials<'_>,
925    ) -> Result<()> {
926        loop {
927            self.next_rfq_v2_quote_page(
928                history,
929                RfqV2ReadCredentials {
930                    bearer_token: credentials.bearer_token,
931                },
932            )
933            .await?;
934            if history.next_cursor.is_none() {
935                return Ok(());
936            }
937        }
938    }
939
940    /// Read the recipient change feed from the mirror's last applied cursor
941    /// and refresh each named RFQ from authorized reads. The cursor advances
942    /// page by page, only after that page's reads are applied, so an error
943    /// leaves a mirror that resumes safely. Call it after connecting, after
944    /// every reconnect, whenever a hint requires it, and periodically.
945    /// It only reads; it never resubmits an operation.
946    pub async fn sync_rfq_v2_mirror(
947        &self,
948        mirror: &mut RfqV2PrivateMirror,
949        credentials: RfqV2ReadCredentials<'_>,
950    ) -> Result<BTreeSet<Uuid>> {
951        let token = credentials.bearer_token;
952        let mut refreshed = BTreeSet::new();
953        loop {
954            let after_sequence = mirror.cursor.last_applied_sequence;
955            let query = ListRfqV2ChangesQuery {
956                after_sequence: Some(after_sequence),
957                limit: Some(MAX_PAGE_LIMIT as u32),
958            };
959            let page = self
960                .list_rfq_v2_changes(
961                    &query,
962                    RfqV2ReadCredentials {
963                        bearer_token: token,
964                    },
965                )
966                .await?;
967            check_change_page(after_sequence, &page)?;
968            let named: BTreeSet<Uuid> = page.changes.iter().map(|change| change.rfq_id).collect();
969            for rfq_id in named {
970                self.refresh_mirror_rfq(mirror, rfq_id, token).await?;
971                refreshed.insert(rfq_id);
972            }
973            mirror.cursor.commit(page.next_after_sequence);
974            mirror.stats.pages_applied += 1;
975            if !page.has_more {
976                break;
977            }
978        }
979        // Expiry is derived from the signed deadline, so no change event
980        // announces it: reread every cached RFQ that is still live but has a
981        // deadline the wall clock has passed.
982        for rfq_id in mirror.live_rfqs_past_a_deadline(unix_now_ms()?) {
983            if refreshed.insert(rfq_id) {
984                self.refresh_mirror_rfq(mirror, rfq_id, token).await?;
985            }
986        }
987        Ok(refreshed)
988    }
989
990    /// Reread one RFQ and its whole quote history into the mirror.
991    async fn refresh_mirror_rfq(
992        &self,
993        mirror: &mut RfqV2PrivateMirror,
994        rfq_id: Uuid,
995        token: &str,
996    ) -> Result<()> {
997        let parent = self
998            .get_rfq_v2(
999                rfq_id,
1000                RfqV2ReadCredentials {
1001                    bearer_token: token,
1002                },
1003            )
1004            .await?;
1005        let mut history = RfqV2QuoteHistory::new(rfq_id, MAX_PAGE_LIMIT)?;
1006        self.sync_rfq_v2_quote_history(
1007            &mut history,
1008            RfqV2ReadCredentials {
1009                bearer_token: token,
1010            },
1011        )
1012        .await?;
1013        mirror.apply_refresh(parent, history.quotes)
1014    }
1015
1016    /// Decide whether to offer an execution from fresh server reads of the
1017    /// parent and quote. A cached or event-derived `observed` view is never
1018    /// trusted: a stale "capacity remains" event cannot enable a fill whose
1019    /// capacity is already used.
1020    pub async fn refresh_rfq_v2_execution_action(
1021        &self,
1022        rfq_id: Uuid,
1023        quote_id: Uuid,
1024        requested_units: u128,
1025        observed: Option<&RfqV2QuoteView>,
1026        credentials: RfqV2ReadCredentials<'_>,
1027    ) -> Result<RfqV2ExecutionAction> {
1028        let token = credentials.bearer_token;
1029        let parent = self
1030            .get_rfq_v2(
1031                rfq_id,
1032                RfqV2ReadCredentials {
1033                    bearer_token: token,
1034                },
1035            )
1036            .await?;
1037        let quote = self
1038            .get_rfq_v2_quote(
1039                rfq_id,
1040                quote_id,
1041                RfqV2ReadCredentials {
1042                    bearer_token: token,
1043                },
1044            )
1045            .await?;
1046        Ok(rfq_v2_execution_action(
1047            &parent,
1048            &quote,
1049            requested_units,
1050            unix_now_ms()?,
1051            observed,
1052        ))
1053    }
1054
1055    /// Re-decide a maker hold from server reads, then advance its
1056    /// change-feed cursor. A 404 or missing status leaves the hold
1057    /// unresolved; only identity-bound own-fill, competing-winner, or
1058    /// terminal evidence releases it. A released hold is final.
1059    pub async fn reconcile_rfq_v2_maker_hold(
1060        &self,
1061        hold: &mut RfqV2MakerHold,
1062        credentials: RfqV2ReadCredentials<'_>,
1063    ) -> Result<RfqV2MakerHoldEvidence> {
1064        if let RfqV2MakerHoldState::Released { proof } = &hold.state {
1065            return Ok(RfqV2MakerHoldEvidence::Conclusive(proof.clone()));
1066        }
1067        let token = credentials.bearer_token;
1068        // Read the feed position first: every change up to it happened
1069        // before the status reads below, so saving it afterwards can
1070        // never skip a change those reads did not observe.
1071        let mut cursor = hold.last_cursor;
1072        loop {
1073            let query = ListRfqV2ChangesQuery {
1074                after_sequence: Some(cursor),
1075                limit: Some(MAX_PAGE_LIMIT as u32),
1076            };
1077            let page = self
1078                .list_rfq_v2_changes(
1079                    &query,
1080                    RfqV2ReadCredentials {
1081                        bearer_token: token,
1082                    },
1083                )
1084                .await?;
1085            check_change_page(cursor, &page)?;
1086            cursor = page.next_after_sequence;
1087            if !page.has_more {
1088                break;
1089            }
1090        }
1091        let parent = match self
1092            .get_rfq_v2(
1093                hold.rfq_id,
1094                RfqV2ReadCredentials {
1095                    bearer_token: token,
1096                },
1097            )
1098            .await
1099        {
1100            Ok(parent) => Some(parent),
1101            Err(error) if not_found(&error) => None,
1102            Err(error) => return Err(error),
1103        };
1104        let quote = match self
1105            .get_rfq_v2_quote(
1106                hold.rfq_id,
1107                hold.quote_id,
1108                RfqV2ReadCredentials {
1109                    bearer_token: token,
1110                },
1111            )
1112            .await
1113        {
1114            Ok(quote) => Some(quote),
1115            Err(error) if not_found(&error) => None,
1116            Err(error) => return Err(error),
1117        };
1118        let evidence = hold.evaluate(parent.as_ref(), quote.as_ref(), unix_now_ms()?);
1119        hold.apply(&evidence);
1120        hold.last_cursor = cursor;
1121        Ok(evidence)
1122    }
1123}
1124
1125#[cfg(test)]
1126#[path = "rfq_v2_recovery_test.rs"]
1127mod tests;