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
293#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302pub struct RfqV2MirrorTransition {
303 pub object: RfqV2MirrorObject,
304 pub status: String,
305 #[serde(with = "json_u128")]
308 pub remaining: u128,
309}
310
311#[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 pub duplicate_transitions: u64,
322}
323
324#[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 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 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 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 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 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 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 "es {
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#[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 #[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 pub fn quotes(&self) -> &BTreeMap<Uuid, RfqV2QuoteView> {
535 &self.quotes
536 }
537
538 pub fn complete(&self) -> bool {
540 self.pages > 0 && self.next_cursor.is_none()
541 }
542
543 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
555#[serde(rename_all = "snake_case")]
556pub enum RfqV2ExecutionBlock {
557 NotFirm,
559 IdentityMismatch,
561 ParentNotExecutable,
562 QuoteNotExecutable,
563 Expired,
564 InsufficientCapacity,
565 FillPolicy,
566 UnrepresentableSize,
569 OutsideRecordRange,
573 OutsideAutoLimit,
576}
577
578#[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 pub observation_stale: bool,
593}
594
595pub 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
680#[serde(tag = "proof", rename_all = "snake_case")]
681pub enum RfqV2MakerHoldProof {
682 OwnFill {
684 #[serde(with = "json_u128")]
685 filled_units: u128,
686 },
687 CompetingWinner,
689 TerminalUnfilled { status: String },
691}
692
693#[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#[derive(Debug, Clone, PartialEq, Eq)]
703pub enum RfqV2MakerHoldEvidence {
704 Missing,
707 IdentityMismatch,
709 Inconclusive,
711 Conclusive(RfqV2MakerHoldProof),
712}
713
714#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
719pub struct RfqV2MakerHold {
720 pub rfq_id: Uuid,
721 pub quote_id: Uuid,
724 pub terms_commitment: RfqV2Digest,
725 pub maker_account: WalletAddress,
726 #[serde(with = "json_u128")]
727 pub capacity: u128,
728 pub response_window_ends_at_ms: u64,
730 pub last_cursor: u64,
732 pub state: RfqV2MakerHoldState,
733}
734
735impl RfqV2MakerHold {
736 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 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 if filled_units > 0 {
802 return RfqV2MakerHoldEvidence::Conclusive(RfqV2MakerHoldProof::OwnFill {
803 filled_units,
804 });
805 }
806 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 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 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 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 "e {
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 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 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 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 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 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 "e,
1049 requested_units,
1050 unix_now_ms()?,
1051 observed,
1052 ))
1053 }
1054
1055 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 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;