1use 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
39const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct RfqV2ReconcilePolicy {
59 pub retry_interval: Duration,
61 pub max_resubmissions: u32,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct RfqV2ReconciledExecution {
69 pub response: RfqV2ExecutionResponse,
71 pub resubmissions: u32,
74}
75
76impl HypercallClient {
77 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum RfqV2HintDisposition {
155 AlreadyApplied,
157 Duplicate,
160 ReplayRequired,
162}
163
164#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
174#[serde(from = "ChangeCursorWire", into = "ChangeCursorWire")]
175pub struct RfqV2ChangeCursor {
176 last_applied_sequence: u64,
177 pending_high_water: Option<u64>,
180}
181
182#[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 pub fn new(last_applied_sequence: u64) -> Self {
218 Self {
219 last_applied_sequence,
220 pending_high_water: None,
221 }
222 }
223
224 pub fn last_applied_sequence(&self) -> u64 {
226 self.last_applied_sequence
227 }
228
229 pub fn pending_hints(&self) -> usize {
232 usize::from(self.pending_high_water.is_some())
233 }
234
235 pub fn pending_high_water(&self) -> Option<u64> {
238 self.pending_high_water
239 }
240
241 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 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#[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
284pub 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
293pub 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
317pub struct RfqV2MirrorTransition {
318 pub object: RfqV2MirrorObject,
319 pub status: String,
320 #[serde(with = "json_u128")]
323 pub remaining: u128,
324}
325
326#[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 pub duplicate_transitions: u64,
337}
338
339#[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 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 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 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 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 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 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 "es {
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#[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 #[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 pub fn quotes(&self) -> &BTreeMap<Uuid, RfqV2QuoteView> {
550 &self.quotes
551 }
552
553 pub fn complete(&self) -> bool {
555 self.pages > 0 && self.next_cursor.is_none()
556 }
557
558 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
570#[serde(rename_all = "snake_case")]
571pub enum RfqV2ExecutionBlock {
572 NotFirm,
574 IdentityMismatch,
576 ParentNotExecutable,
577 QuoteNotExecutable,
578 Expired,
579 InsufficientCapacity,
580 FillPolicy,
581 UnrepresentableSize,
584 OutsideRecordRange,
588 OutsideAutoLimit,
591}
592
593#[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 pub observation_stale: bool,
608}
609
610pub 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
695#[serde(tag = "proof", rename_all = "snake_case")]
696pub enum RfqV2MakerHoldProof {
697 OwnFill {
699 #[serde(with = "json_u128")]
700 filled_units: u128,
701 },
702 CompetingWinner,
704 TerminalUnfilled { status: String },
706}
707
708#[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#[derive(Debug, Clone, PartialEq, Eq)]
718pub enum RfqV2MakerHoldEvidence {
719 Missing,
722 IdentityMismatch,
724 Inconclusive,
726 Conclusive(RfqV2MakerHoldProof),
727}
728
729#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
734pub struct RfqV2MakerHold {
735 pub rfq_id: Uuid,
736 pub quote_id: Uuid,
739 pub terms_commitment: RfqV2Digest,
740 pub maker_account: WalletAddress,
741 #[serde(with = "json_u128")]
742 pub capacity: u128,
743 pub response_window_ends_at_ms: u64,
745 pub last_cursor: u64,
747 pub state: RfqV2MakerHoldState,
748}
749
750impl RfqV2MakerHold {
751 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 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 if filled_units > 0 {
817 return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::OwnFill {
818 filled_units,
819 });
820 }
821 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 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 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 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 "e {
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 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 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 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 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 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 "e,
1064 requested_units,
1065 unix_now_ms()?,
1066 observed,
1067 ))
1068 }
1069
1070 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 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;