1use std::{
2 collections::{BTreeSet, HashMap, HashSet},
3 str::FromStr,
4 sync::LazyLock,
5 time::SystemTime,
6};
7
8use alloy::primitives::{utils::keccak256, Address};
9use async_trait::async_trait;
10use futures::stream::BoxStream;
11use num_bigint::BigUint;
12use reqwest::Client;
13use serde::{Deserialize, Serialize};
14use tokio::time::{interval, timeout, Duration};
15use tracing::{error, info, warn};
16use tycho_common::{
17 models::{protocol::GetAmountOutParams, Chain},
18 simulation::indicatively_priced::SignedQuote,
19 Bytes,
20};
21
22use super::models::{NativeOrderbookEntry, NativeOrderbookSide, NativePriceData, NativePriceLevel};
23use crate::{
24 rfq::{
25 client::RFQClient,
26 errors::RFQError,
27 models::{ComponentLayout, QuoteRule, TimestampHeader},
28 protocols::{
29 component,
30 native::models::{
31 FirmQuoteRequest, FirmQuoteResponse, NativeApiErrorResponse, NativeSupportedChain,
32 },
33 utils::bytes_to_address,
34 },
35 },
36 tycho_client::feed::synchronizer::{ComponentWithState, StateSyncMessage},
37 tycho_common::models::protocol::{ProtocolComponent, ProtocolComponentState},
38};
39
40static NATIVE_HTTP_CLIENT: LazyLock<Client> = LazyLock::new(Client::new);
41const MAX_QUOTE_ATTEMPTS: u32 = 3;
42const TRANSIENT_RETRY_DELAY: Duration = Duration::from_millis(100);
43const NATIVE_API_RETRY_DELAY: Duration = Duration::from_secs(1);
44const TRADE_RFQT_SELECTOR: [u8; 4] = [0x70, 0x83, 0x52, 0x7c];
46const MIN_TRADE_RFQT_CALLDATA_LEN: usize = 4 + 3 * 32;
47const ACTUAL_SELLER_AMOUNT_OFFSET: usize = 4 + 32;
48const ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET: usize = 4 + 2 * 32;
49
50enum QuoteAttemptError {
51 Retry { error: RFQError, delay: Duration },
52 Fatal(RFQError),
53}
54
55impl QuoteAttemptError {
56 fn into_error(self) -> RFQError {
57 match self {
58 Self::Retry { error, .. } | Self::Fatal(error) => error,
59 }
60 }
61}
62
63#[derive(Default)]
64struct AggregatedLevels {
65 levels: Vec<NativePriceLevel>,
66 minimum: f64,
68}
69
70impl AggregatedLevels {
71 fn extend(&mut self, levels: Vec<NativePriceLevel>, minimum: f64) {
72 self.levels.extend(levels);
73 self.minimum = self.minimum.max(minimum);
74 }
75}
76
77#[derive(Clone, Debug, Serialize, Deserialize)]
78pub struct NativeClient {
79 chain: Chain,
80 endpoint: String,
81 #[serde(skip_serializing, default)]
82 api_key: String,
83 tokens: HashSet<Bytes>,
84 tvl: f64,
85 quote_tokens: HashSet<Bytes>,
86 poll_time: Duration,
87 quote_timeout: Duration,
88 #[serde(default)]
89 component_layout: ComponentLayout,
90}
91
92impl NativeClient {
93 pub const PROTOCOL_SYSTEM: &'static str = "rfq:native";
94 pub const DEFAULT_ENDPOINT: &'static str = "https://v2.api.native.org/swap-api-v2/v1";
95
96 fn classify_api_error(error: &NativeApiErrorResponse) -> QuoteAttemptError {
99 let message = format!("Native API error {}: {}", error.code, error.message);
100 match error.code {
101 301016 | 405030 => QuoteAttemptError::Retry {
103 error: RFQError::QuoteNotFound(message),
104 delay: NATIVE_API_RETRY_DELAY,
105 },
106 201005 => QuoteAttemptError::Retry {
107 error: RFQError::ConnectionError(message),
108 delay: NATIVE_API_RETRY_DELAY,
109 },
110 101010 | 171037 | 171011 | 171015 | 171055 | 101007 => {
114 QuoteAttemptError::Fatal(RFQError::QuoteNotFound(message))
115 }
116 131003 | 131004 | 131011 | 171018 | 171053 | 131005 => {
118 QuoteAttemptError::Fatal(RFQError::InvalidInput(message))
119 }
120 201001 => QuoteAttemptError::Fatal(RFQError::FatalError(message)),
121 _ => QuoteAttemptError::Fatal(RFQError::FatalError(format!(
122 "Unknown Native API error {}: {}",
123 error.code, error.message
124 ))),
125 }
126 }
127
128 pub fn new(
129 chain: Chain,
130 api_key: String,
131 tokens: HashSet<Bytes>,
132 tvl: f64,
133 quote_tokens: HashSet<Bytes>,
134 poll_time: Duration,
135 quote_timeout: Duration,
136 ) -> Result<Self, RFQError> {
137 NativeSupportedChain::try_from(chain).map_err(RFQError::InvalidInput)?;
138 if poll_time.is_zero() {
139 return Err(RFQError::InvalidInput(
140 "Native polling interval must be greater than zero".to_string(),
141 ))
142 }
143 Ok(Self {
144 chain,
145 endpoint: Self::DEFAULT_ENDPOINT.to_string(),
146 api_key,
147 tokens,
148 tvl,
149 quote_tokens,
150 poll_time,
151 quote_timeout,
152 component_layout: ComponentLayout::PerPair,
153 })
154 }
155
156 pub(crate) fn with_component_layout(mut self, component_layout: ComponentLayout) -> Self {
157 self.component_layout = component_layout;
158 self
159 }
160
161 fn stream_name(&self) -> &'static str {
164 match self.component_layout {
165 ComponentLayout::PerPair => "native",
166 ComponentLayout::AllPairs => "native_all_pairs",
167 }
168 }
169
170 fn select_tvl_conversion_book<'a>(
171 &self,
172 quote_address: &Bytes,
173 books: &'a HashMap<String, NativePriceData>,
174 ) -> Option<&'a NativePriceData> {
175 books
176 .values()
177 .filter(|candidate| {
178 candidate.base_address == *quote_address &&
181 self.quote_tokens
182 .contains(&candidate.quote_address)
183 })
184 .filter_map(|candidate| {
185 candidate
186 .calculate_tvl(None)
187 .map(|liquidity| (candidate, liquidity))
188 })
189 .max_by(|(candidate_a, liquidity_a), (candidate_b, liquidity_b)| {
190 liquidity_a
191 .total_cmp(liquidity_b)
192 .then_with(|| {
195 candidate_b
196 .quote_address
197 .as_ref()
198 .cmp(candidate_a.quote_address.as_ref())
199 })
200 })
201 .map(|(candidate, _)| candidate)
202 }
203
204 fn create_component_with_state(
205 &self,
206 component_id: String,
207 tokens: Vec<Bytes>,
208 book: NativePriceData,
209 tvl: f64,
210 ) -> ComponentWithState {
211 let protocol_component = ProtocolComponent {
212 id: component_id.clone(),
213 protocol_system: Self::PROTOCOL_SYSTEM.to_string(),
214 protocol_type_name: "native_relay_pool".to_string(),
215 chain: self.chain,
216 tokens,
217 contract_addresses: vec![],
218 static_attributes: Default::default(),
219 change: Default::default(),
220 creation_tx: Default::default(),
221 created_at: Default::default(),
222 };
223
224 let mut attributes = HashMap::new();
225
226 let book_json = serde_json::to_string(&book).unwrap_or_default();
227 attributes.insert("book".to_string(), book_json.as_bytes().to_vec().into());
228
229 ComponentWithState {
230 state: ProtocolComponentState::new(&component_id, attributes, HashMap::new()),
231 component: protocol_component,
232 component_tvl: Some(tvl),
233 entrypoints: vec![],
234 }
235 }
236
237 fn books_above_tvl_threshold<'a>(
240 &self,
241 books: &'a HashMap<String, NativePriceData>,
242 ) -> Vec<(&'a str, &'a NativePriceData, f64)> {
243 let mut kept = Vec::new();
244
245 for (component_id, book) in books {
246 if !self.tokens.contains(&book.base_address) ||
249 !self
250 .tokens
251 .contains(&book.quote_address)
252 {
253 continue;
254 }
255
256 let quote_price_data = if self
257 .quote_tokens
258 .contains(&book.quote_address)
259 {
260 None
261 } else {
262 self.select_tvl_conversion_book(&book.quote_address, books)
266 };
267
268 if !self
269 .quote_tokens
270 .contains(&book.quote_address) &&
271 quote_price_data.is_none()
272 {
273 continue;
274 }
275
276 let Some(incoming_tvl) = book.calculate_tvl(quote_price_data) else {
277 warn!("Skipping Native Relay market {component_id} because its TVL is unavailable or non-finite");
278 continue;
279 };
280
281 if incoming_tvl < self.tvl {
282 info!(
283 "Filtering out Native Relay market {} due to low TVL: {:.2} < {:.2}",
284 component_id, incoming_tvl, self.tvl
285 );
286 continue;
287 }
288
289 kept.push((component_id.as_str(), book, incoming_tvl));
290 }
291 kept
292 }
293
294 fn pair_components(
296 &self,
297 books: &HashMap<String, NativePriceData>,
298 ) -> HashMap<String, ComponentWithState> {
299 let mut new_components = HashMap::new();
300 for (component_id, book, tvl) in self.books_above_tvl_threshold(books) {
301 let tokens = vec![book.base_address.clone(), book.quote_address.clone()];
302 let component_with_state = self.create_component_with_state(
303 component_id.to_string(),
304 tokens,
305 book.clone(),
306 tvl,
307 );
308 new_components.insert(component_id.to_string(), component_with_state);
309 }
310 new_components
311 }
312
313 fn all_pairs_component(
317 &self,
318 grouped_books: &HashMap<String, NativePriceData>,
319 ) -> Result<Option<ComponentWithState>, RFQError> {
320 let mut books = Vec::new();
321 let mut tvl = 0.0;
322 for (_, book, book_tvl) in self.books_above_tvl_threshold(grouped_books) {
323 if book.bids.is_empty() && book.asks.is_empty() {
324 continue;
325 }
326 tvl += book_tvl;
327 books.push(book.clone());
328 }
329 if books.is_empty() {
330 return Ok(None);
331 }
332 books.sort_by(|a, b| {
333 (&a.base_address, &a.quote_address).cmp(&(&b.base_address, &b.quote_address))
334 });
335
336 let mut swap_directions = BTreeSet::new();
337 for book in &books {
338 if !book.bids.is_empty() {
339 swap_directions.insert((book.base_address.clone(), book.quote_address.clone()));
340 }
341 if !book.asks.is_empty() {
342 swap_directions.insert((book.quote_address.clone(), book.base_address.clone()));
343 }
344 }
345 let component = component::all_pairs_component(
346 Self::PROTOCOL_SYSTEM,
347 "native_relay_pool",
348 self.chain,
349 &swap_directions,
350 &books,
351 tvl,
352 QuoteRule::OncePerVenue,
353 )?;
354 Ok(Some(component))
355 }
356
357 async fn fetch_orderbook(&self) -> Result<Vec<NativeOrderbookEntry>, RFQError> {
358 let chain = NativeSupportedChain::try_from(self.chain).map_err(RFQError::InvalidInput)?;
359 let response = NATIVE_HTTP_CLIENT
360 .get(format!("{}/orderbook", self.endpoint))
361 .query(&[("chain", chain.as_str()), ("showNative", "0x0")])
364 .header("accept", "application/json")
365 .header("apikey", &self.api_key)
366 .send()
367 .await
368 .map_err(|e| RFQError::ConnectionError(e.to_string()))?;
369
370 let status = response.status();
371 let response_body = response
372 .bytes()
373 .await
374 .map_err(|e| RFQError::ConnectionError(e.to_string()))?;
375
376 if let Ok(api_error) = serde_json::from_slice::<NativeApiErrorResponse>(&response_body) {
378 return Err(Self::classify_api_error(&api_error).into_error());
379 }
380
381 if !status.is_success() {
382 return Err(RFQError::ConnectionError(format!(
383 "Native Relay orderbook HTTP error {}: {}",
384 status,
385 String::from_utf8_lossy(&response_body)
386 )));
387 }
388
389 serde_json::from_slice(&response_body).map_err(|e| {
390 RFQError::ParsingError(format!("Failed to parse Native Relay orderbook: {e}"))
391 })
392 }
393
394 fn group_orderbook(
395 &self,
396 entries: Vec<NativeOrderbookEntry>,
397 ) -> HashMap<String, NativePriceData> {
398 let mut entries_by_pair: HashMap<(Bytes, Bytes), Vec<NativeOrderbookEntry>> =
399 HashMap::new();
400
401 for entry in entries {
402 let pair = if entry.base_address.as_ref() <= entry.quote_address.as_ref() {
403 (entry.base_address.clone(), entry.quote_address.clone())
404 } else {
405 (entry.quote_address.clone(), entry.base_address.clone())
406 };
407 entries_by_pair
408 .entry(pair)
409 .or_default()
410 .push(entry);
411 }
412
413 let mut books = HashMap::new();
414 for ((token0, token1), entries) in entries_by_pair {
415 let token0_is_quote = self.quote_tokens.contains(&token0);
420 let token1_is_quote = self.quote_tokens.contains(&token1);
421 let (base_address, quote_address) = match (token0_is_quote, token1_is_quote) {
422 (true, false) => (token1.clone(), token0.clone()),
423 (false, true) => (token0.clone(), token1.clone()),
424 (true, true) | (false, false) => (token0.clone(), token1.clone()),
425 };
426 let mut direct_bids = AggregatedLevels::default();
427 let mut direct_asks = AggregatedLevels::default();
428 let mut mirrored_bids = AggregatedLevels::default();
429 let mut mirrored_asks = AggregatedLevels::default();
430
431 for entry in entries {
436 let levels: Vec<_> = entry
440 .levels
441 .into_iter()
442 .filter(|level| level.quantity != 0.0)
443 .collect();
444 if levels.is_empty() {
445 continue
446 }
447
448 let is_direct =
449 entry.base_address == base_address && entry.quote_address == quote_address;
450 if is_direct {
451 match entry.side {
452 NativeOrderbookSide::Bid => {
453 direct_bids.extend(levels, entry.minimum_in_base)
454 }
455 NativeOrderbookSide::Ask => {
456 direct_asks.extend(levels, entry.minimum_in_base)
457 }
458 }
459 } else {
460 let levels = NativePriceData::invert_price_levels(&levels);
461 match entry.side {
462 NativeOrderbookSide::Bid => {
463 mirrored_asks.extend(levels, entry.minimum_in_base)
464 }
465 NativeOrderbookSide::Ask => {
466 mirrored_bids.extend(levels, entry.minimum_in_base)
467 }
468 }
469 }
470 }
471
472 let (bids, minimum_in_base, minimum_out_quote) = if direct_bids.levels.is_empty() {
476 (mirrored_bids.levels, 0.0, mirrored_bids.minimum)
477 } else {
478 (direct_bids.levels, direct_bids.minimum, 0.0)
479 };
480 let (asks, minimum_in_quote, minimum_out_base) = if direct_asks.levels.is_empty() {
481 (mirrored_asks.levels, mirrored_asks.minimum, 0.0)
482 } else {
483 (direct_asks.levels, 0.0, direct_asks.minimum)
484 };
485 let pair = format!("native_{}/{}", hex::encode(&token0), hex::encode(&token1));
488 let component_id = keccak256(pair.as_bytes()).to_string();
489 books.insert(
490 component_id,
491 NativePriceData {
492 base_address,
493 quote_address,
494 minimum_in_base,
495 minimum_in_quote,
496 minimum_out_base,
497 minimum_out_quote,
498 bids,
499 asks,
500 },
501 );
502 }
503
504 books
505 }
506
507 fn process_quote_response(
508 quote_response: FirmQuoteResponse,
509 params: &GetAmountOutParams,
510 ) -> Result<SignedQuote, RFQError> {
511 if !quote_response.success {
513 return Err(RFQError::QuoteNotFound(format!(
514 "Native Relay quote request failed: {}",
515 quote_response.error_message
516 )));
517 }
518
519 if quote_response.router_version != "6" {
520 return Err(RFQError::ParsingError(format!(
521 "Unexpected Native router version: expected 6, got {}",
522 quote_response.router_version
523 )));
524 }
525
526 let order = quote_response
528 .orders
529 .first()
530 .ok_or_else(|| {
531 RFQError::QuoteNotFound(format!(
532 "No Native Relay orders for {} {} -> {}",
533 params.amount_in, params.token_in, params.token_out,
534 ))
535 })?;
536
537 let seller_token = bytes_to_address(¶ms.token_in)?;
539 let buyer_token = bytes_to_address(¶ms.token_out)?;
540 let order_seller_token = Address::from_str(&order.seller_token).map_err(|e| {
541 RFQError::ParsingError(format!(
542 "Invalid Native seller token {}: {e}",
543 order.seller_token
544 ))
545 })?;
546 let order_buyer_token = Address::from_str(&order.buyer_token).map_err(|e| {
547 RFQError::ParsingError(format!("Invalid Native buyer token {}: {e}", order.buyer_token))
548 })?;
549 if order_seller_token != seller_token || order_buyer_token != buyer_token {
550 return Err(RFQError::ParsingError(format!(
551 "Native Relay quote token mismatch: expected {}/{}, got {}/{}",
552 seller_token, buyer_token, order_seller_token, order_buyer_token
553 )));
554 }
555
556 let receiver = bytes_to_address(¶ms.receiver)?;
557 let order_recipient = Address::from_str(&order.recipient).map_err(|e| {
558 RFQError::ParsingError(format!(
559 "Invalid Native order recipient {}: {e}",
560 order.recipient
561 ))
562 })?;
563 if order_recipient != receiver {
564 return Err(RFQError::ParsingError(format!(
565 "Native Relay quote recipient mismatch: expected {receiver}, got {order_recipient}"
566 )));
567 }
568
569 let now = SystemTime::now()
571 .duration_since(SystemTime::UNIX_EPOCH)
572 .map_err(|_| RFQError::ParsingError("SystemTime before UNIX EPOCH!".to_string()))?
573 .as_secs();
574
575 if order.deadline_timestamp <= now {
576 return Err(RFQError::QuoteNotFound(format!(
577 "Native Relay quote already expired: deadline {} <= now {}",
578 order.deadline_timestamp, now
579 )));
580 }
581
582 let quoted_amount_in = BigUint::from_str("e_response.amount_in).map_err(|_| {
586 RFQError::ParsingError(format!(
587 "Failed to parse amount_in: {}",
588 quote_response.amount_in
589 ))
590 })?;
591 if quoted_amount_in != params.amount_in {
592 return Err(RFQError::ParsingError(format!(
593 "Native Relay quote input amount mismatch: expected {}, got {}",
594 params.amount_in, quoted_amount_in
595 )));
596 }
597
598 let signed_amount_in = BigUint::from_str(&order.seller_token_amount).map_err(|_| {
599 RFQError::ParsingError(format!(
600 "Failed to parse signed seller token amount: {}",
601 order.seller_token_amount
602 ))
603 })?;
604 if signed_amount_in != params.amount_in {
605 return Err(RFQError::ParsingError(format!(
606 "Native Relay signed input amount mismatch: expected {}, got {}",
607 params.amount_in, signed_amount_in
608 )));
609 }
610
611 let quoted_value = BigUint::from_str("e_response.tx_request.value).map_err(|_| {
618 RFQError::ParsingError(format!(
619 "Failed to parse Native txRequest.value: {}",
620 quote_response.tx_request.value
621 ))
622 })?;
623 let expected_value =
624 if seller_token == Address::ZERO { quoted_amount_in.clone() } else { BigUint::ZERO };
625 if quoted_value != expected_value {
626 return Err(RFQError::ParsingError(format!(
627 "Native Relay payable value mismatch: expected {}, got {}",
628 expected_value, quoted_value
629 )));
630 }
631
632 if quote_response
633 .tx_request
634 .calldata
635 .is_empty()
636 {
637 return Err(RFQError::QuoteNotFound(
638 "Native Relay quote did not include calldata".to_string(),
639 ));
640 }
641 let calldata = hex::decode(
643 quote_response
644 .tx_request
645 .calldata
646 .trim_start_matches("0x"),
647 )
648 .map_err(|e| RFQError::ParsingError(format!("Failed to decode calldata: {e}")))?;
649
650 if calldata.len() < MIN_TRADE_RFQT_CALLDATA_LEN {
651 return Err(RFQError::ParsingError(format!(
652 "Native tradeRFQT calldata too short: expected at least {} bytes, got {}",
653 MIN_TRADE_RFQT_CALLDATA_LEN,
654 calldata.len()
655 )));
656 }
657
658 if calldata[..TRADE_RFQT_SELECTOR.len()] != TRADE_RFQT_SELECTOR {
659 return Err(RFQError::ParsingError(format!(
660 "Unexpected Native V6 selector: expected 0x{}, got 0x{}",
661 hex::encode(TRADE_RFQT_SELECTOR),
662 hex::encode(&calldata[..TRADE_RFQT_SELECTOR.len()]),
663 )));
664 }
665
666 if quote_response.amount_in_offset as usize != ACTUAL_SELLER_AMOUNT_OFFSET ||
671 quote_response.amount_out_minimum_offset as usize != ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET
672 {
673 return Err(RFQError::ParsingError(format!(
674 "Unexpected Native V6 override offsets: expected {}/{} but got {}/{}",
675 ACTUAL_SELLER_AMOUNT_OFFSET,
676 ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET,
677 quote_response.amount_in_offset,
678 quote_response.amount_out_minimum_offset,
679 )));
680 }
681
682 if calldata[ACTUAL_SELLER_AMOUNT_OFFSET..ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET]
683 .iter()
684 .any(|byte| *byte != 0)
685 {
686 return Err(RFQError::ParsingError(
687 "Native actualSellerAmount override must be zero".to_string(),
688 ));
689 }
690 if calldata[ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET..MIN_TRADE_RFQT_CALLDATA_LEN]
691 .iter()
692 .any(|byte| *byte != 0)
693 {
694 return Err(RFQError::ParsingError(
695 "Native actualMinOutputAmount override must be zero".to_string(),
696 ));
697 }
698
699 let target = Bytes::from_str("e_response.tx_request.target).map_err(|_| {
700 RFQError::ParsingError(format!(
701 "Failed to parse router target address: {}",
702 quote_response.tx_request.target
703 ))
704 })?;
705
706 let mut quote_attributes: HashMap<String, Bytes> = HashMap::new();
707 quote_attributes.insert("target".to_string(), target);
708 quote_attributes.insert("calldata".to_string(), Bytes::from(calldata));
709 quote_attributes.insert(
710 "deadline_timestamp".to_string(),
711 Bytes::from(
712 order
713 .deadline_timestamp
714 .to_be_bytes()
715 .to_vec(),
716 ),
717 );
718
719 Ok(SignedQuote {
720 base_token: params.token_in.clone(),
721 quote_token: params.token_out.clone(),
722 amount_in: quoted_amount_in,
723 amount_out: BigUint::from_str("e_response.amount_out).map_err(|_| {
724 RFQError::ParsingError(format!(
725 "Failed to parse amount_out: {}",
726 quote_response.amount_out
727 ))
728 })?,
729 quote_attributes,
730 })
731 }
732
733 async fn try_quote(
734 &self,
735 request_data: &FirmQuoteRequest,
736 params: &GetAmountOutParams,
737 ) -> Result<SignedQuote, QuoteAttemptError> {
738 let response = NATIVE_HTTP_CLIENT
739 .get(format!("{}/firm-quote", self.endpoint))
740 .query(request_data)
741 .header("apikey", &self.api_key)
742 .send()
743 .await
744 .map_err(|e| QuoteAttemptError::Retry {
745 error: RFQError::ConnectionError(format!(
746 "Failed to make Native quote request: {e}"
747 )),
748 delay: TRANSIENT_RETRY_DELAY,
749 })?;
750
751 let status = response.status();
752 let response_body = response
753 .bytes()
754 .await
755 .map_err(|e| QuoteAttemptError::Retry {
756 error: RFQError::ConnectionError(format!(
757 "Failed to read Native quote response: {e}"
758 )),
759 delay: TRANSIENT_RETRY_DELAY,
760 })?;
761
762 if let Ok(api_error) = serde_json::from_slice::<NativeApiErrorResponse>(&response_body) {
764 return Err(Self::classify_api_error(&api_error));
765 }
766
767 if !status.is_success() {
768 let response_text = String::from_utf8_lossy(&response_body);
769 if status.is_server_error() {
770 return Err(QuoteAttemptError::Retry {
771 error: RFQError::ConnectionError(format!(
772 "Native quote server error ({status}): {response_text}"
773 )),
774 delay: TRANSIENT_RETRY_DELAY,
775 });
776 }
777
778 return Err(QuoteAttemptError::Fatal(RFQError::ConnectionError(format!(
779 "Unexpected Native quote HTTP response ({status}): {response_text}"
780 ))));
781 }
782
783 let quote_response =
784 serde_json::from_slice::<FirmQuoteResponse>(&response_body).map_err(|e| {
785 QuoteAttemptError::Retry {
786 error: RFQError::ParsingError(format!(
787 "Failed to parse Native quote response: {e}"
788 )),
789 delay: TRANSIENT_RETRY_DELAY,
790 }
791 })?;
792
793 Self::process_quote_response(quote_response, params).map_err(QuoteAttemptError::Fatal)
794 }
795}
796
797#[async_trait]
798impl RFQClient for NativeClient {
799 fn stream(
800 &self,
801 ) -> BoxStream<'static, Result<(String, StateSyncMessage<TimestampHeader>), RFQError>> {
802 let client = self.clone();
803
804 Box::pin(async_stream::stream! {
805 let mut current_components: HashMap<String, ComponentWithState> = HashMap::new();
806 let mut ticker = interval(client.poll_time);
807
808 loop {
809 ticker.tick().await;
810
811 let books = match client.fetch_orderbook().await {
815 Ok(entries) => client.group_orderbook(entries),
816 Err(e) => {
817 error!("Failed to fetch Native Relay orderbook: {}", e);
818 continue;
819 }
820 };
821
822 let components = match client.component_layout {
823 ComponentLayout::PerPair => client.pair_components(&books),
824 ComponentLayout::AllPairs => match client.all_pairs_component(&books) {
825 Ok(component) => component
826 .into_iter()
827 .map(|component| (component.component.id.clone(), component))
828 .collect(),
829 Err(e) => {
830 error!("Failed to build the Native Relay component: {}", e);
831 continue;
832 }
833 },
834 };
835 let timestamp = component::unix_timestamp().unwrap_or_default();
836 let msg = component::poll_message(&mut current_components, components, timestamp);
837 yield Ok((client.stream_name().to_string(), msg));
838 }
839 })
840 }
841
842 async fn request_binding_quote(
843 &self,
844 params: &GetAmountOutParams,
845 ) -> Result<SignedQuote, RFQError> {
846 let receiver = bytes_to_address(¶ms.receiver)?;
847 let token_in = bytes_to_address(¶ms.token_in)?;
848 let token_out = bytes_to_address(¶ms.token_out)?;
849
850 let chain = NativeSupportedChain::try_from(self.chain).map_err(RFQError::FatalError)?;
851
852 let request_data = FirmQuoteRequest {
853 src_chain: chain,
854 dst_chain: chain,
855 from_address: receiver.to_string(),
856 amount_wei: params.amount_in.to_string(),
857 token_in: token_in.to_string(),
858 token_out: token_out.to_string(),
859 version: 6,
860 allow_multihop: false,
861 };
862 let mut last_error = None;
863
864 let attempts = async {
865 for attempt in 1..=MAX_QUOTE_ATTEMPTS {
866 match self
867 .try_quote(&request_data, params)
868 .await
869 {
870 Ok(quote) => return Ok(quote),
871 Err(QuoteAttemptError::Fatal(error)) => return Err(error),
872 Err(QuoteAttemptError::Retry { error, delay }) => {
873 warn!(
874 "Native quote attempt {}/{} failed: {}",
875 attempt, MAX_QUOTE_ATTEMPTS, error
876 );
877 last_error = Some(error);
878
879 if attempt < MAX_QUOTE_ATTEMPTS {
880 tokio::time::sleep(delay).await;
881 }
882 }
883 }
884 }
885
886 Err(last_error.take().unwrap_or_else(|| {
887 RFQError::ConnectionError(
888 "Native quote request failed after all attempts".to_string(),
889 )
890 }))
891 };
892
893 let result = timeout(self.quote_timeout, attempts).await;
896 match result {
897 Ok(result) => result,
898 Err(_) => Err(last_error.unwrap_or_else(|| {
899 RFQError::ConnectionError(format!(
900 "Native quote request timed out after {:?}",
901 self.quote_timeout
902 ))
903 })),
904 }
905 }
906}
907
908#[cfg(test)]
909mod tests {
910 use std::{
911 collections::{HashMap, HashSet},
912 str::FromStr,
913 sync::{
914 atomic::{AtomicUsize, Ordering},
915 Arc,
916 },
917 };
918
919 use futures::StreamExt;
920 use rstest::rstest;
921 use tokio::{
922 io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
923 net::TcpListener,
924 };
925 use tycho_common::models::Chain;
926
927 use super::*;
928 use crate::rfq::protocols::{
929 component::{BOOKS_ATTRIBUTE, SWAP_DIRECTIONS_ATTRIBUTE},
930 native::client_builder::NativeClientBuilder,
931 };
932
933 fn successful_quote_json(amount_in: &str) -> serde_json::Value {
934 let calldata = format!("0x7083527c{:064x}{:064x}{:064x}", 0x60u8, 0u8, 0u8);
935 serde_json::json!({
936 "success": true,
937 "orders": [{
938 "pool": "0x1111111111111111111111111111111111111111",
939 "signer": "0x2222222222222222222222222222222222222222",
940 "recipient": "0x4444444444444444444444444444444444444444",
941 "sellerToken": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
942 "buyerToken": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
943 "effectiveSellerTokenAmount": amount_in,
944 "sellerTokenAmount": amount_in,
945 "buyerTokenAmount": "2",
946 "deadlineTimestamp": u64::MAX,
947 "nonce": 1,
948 "quoteId": "test-quote",
949 "multiHop": false,
950 "signature": "",
951 "externalSwapCalldata": "",
952 "amountOutMinimum": "2",
953 "widgetFee": {
954 "signer": "0x0000000000000000000000000000000000000000",
955 "feeRecipient": "0x0000000000000000000000000000000000000000",
956 "feeRate": 0.0
957 },
958 "widgetFeeSignature": ""
959 }],
960 "widgetFee": {
961 "signer": "0x0000000000000000000000000000000000000000",
962 "feeRecipient": "0x0000000000000000000000000000000000000000",
963 "feeRate": 0.0
964 },
965 "widgetFeeSignature": "",
966 "recipient": "0x4444444444444444444444444444444444444444",
967 "amountIn": amount_in,
968 "amountOut": "2",
969 "amountOutBeforeFee": "2",
970 "fallbackSwapDataArray": null,
971 "tokenTransferFeeOnPercent": 0.0,
972 "txRequest": {
973 "target": "0x4777A6B3A9A889ABfd4C7666Bdd2a7AB633293be",
974 "calldata": calldata,
975 "value": "0"
976 },
977 "source": [6],
978 "errorMessage": "",
979 "router_version": "6",
980 "toWrap": false,
981 "toUnwrap": false,
982 "amountInOffset": 36,
983 "amountOutMinimumOffset": 68
984 })
985 }
986
987 fn successful_quote_response(amount_in: &str) -> FirmQuoteResponse {
988 serde_json::from_value(successful_quote_json(amount_in)).unwrap()
989 }
990
991 fn conversion_book(
992 base_address: Bytes,
993 quote_address: Bytes,
994 quantity: f64,
995 price: f64,
996 ) -> NativePriceData {
997 NativePriceData {
998 base_address,
999 quote_address,
1000 minimum_in_base: 0.0,
1001 minimum_in_quote: 0.0,
1002 minimum_out_base: 0.0,
1003 minimum_out_quote: 0.0,
1004 bids: vec![NativePriceLevel { quantity, price }],
1005 asks: vec![],
1006 }
1007 }
1008
1009 #[test]
1010 fn test_native_client_serialization() {
1011 let mut tokens = HashSet::new();
1012 tokens.insert(Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap());
1013 tokens.insert(Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap());
1014
1015 let client = NativeClient::new(
1016 Chain::Ethereum,
1017 "test-api-key".to_string(),
1018 tokens,
1019 10.0,
1020 HashSet::new(),
1021 Duration::from_secs(1),
1022 Duration::from_secs(5),
1023 )
1024 .unwrap();
1025
1026 let serialized = serde_json::to_string(&client).unwrap();
1027 let deserialized: NativeClient = serde_json::from_str(&serialized).unwrap();
1028
1029 assert_eq!(deserialized.chain, client.chain);
1030 assert_eq!(deserialized.endpoint, client.endpoint);
1031 assert_eq!(deserialized.tokens, client.tokens);
1032 assert_eq!(deserialized.tvl, client.tvl);
1033 assert!(deserialized.api_key.is_empty());
1034 }
1035
1036 #[rstest]
1037 #[case::ethereum(Chain::Ethereum, "ethereum")]
1038 #[case::bsc(Chain::Bsc, "bsc")]
1039 #[case::arbitrum(Chain::Arbitrum, "arbitrum")]
1040 #[case::base(Chain::Base, "base")]
1041 #[case::robinhood(Chain::Robinhood, "robinhood")]
1042 fn accepts_every_chain_native_serves(#[case] chain: Chain, #[case] native_name: &str) {
1043 let client = NativeClient::new(
1044 chain,
1045 "test-api-key".to_string(),
1046 HashSet::new(),
1047 0.0,
1048 HashSet::new(),
1049 Duration::from_secs(1),
1050 Duration::from_secs(5),
1051 );
1052
1053 assert!(client.is_ok());
1054 assert_eq!(
1055 NativeSupportedChain::try_from(chain)
1056 .unwrap()
1057 .as_str(),
1058 native_name
1059 );
1060 }
1061
1062 #[test]
1063 fn rejects_unsupported_chain_at_construction() {
1064 let result = NativeClient::new(
1065 Chain::Polygon,
1066 "test-api-key".to_string(),
1067 HashSet::new(),
1068 0.0,
1069 HashSet::new(),
1070 Duration::from_secs(1),
1071 Duration::from_secs(5),
1072 );
1073
1074 assert!(matches!(result, Err(RFQError::InvalidInput(_))));
1075 }
1076
1077 #[test]
1078 fn builder_rejects_zero_poll_time() {
1079 let result = NativeClientBuilder::new(Chain::Ethereum, "test-api-key".to_string())
1080 .poll_time(Duration::ZERO)
1081 .build();
1082
1083 assert!(matches!(
1084 result,
1085 Err(RFQError::InvalidInput(message))
1086 if message == "Native polling interval must be greater than zero"
1087 ));
1088 }
1089
1090 #[test]
1091 fn selects_most_liquid_tvl_conversion_book() {
1092 let weth = Bytes::from_str("0x3333333333333333333333333333333333333333").unwrap();
1093 let usdc = Bytes::from_str("0x1111111111111111111111111111111111111111").unwrap();
1094 let usdt = Bytes::from_str("0x2222222222222222222222222222222222222222").unwrap();
1095 let wbtc = Bytes::from_str("0x4444444444444444444444444444444444444444").unwrap();
1096 let unapproved = Bytes::from_str("0x5555555555555555555555555555555555555555").unwrap();
1097 let client = NativeClient::new(
1098 Chain::Ethereum,
1099 "test-api-key".to_string(),
1100 HashSet::from([
1101 weth.clone(),
1102 usdc.clone(),
1103 usdt.clone(),
1104 wbtc.clone(),
1105 unapproved.clone(),
1106 ]),
1107 0.0,
1108 HashSet::from([usdc.clone(), usdt.clone()]),
1109 Duration::from_secs(1),
1110 Duration::from_secs(5),
1111 )
1112 .unwrap();
1113 let books = HashMap::from([
1114 ("usdc".to_string(), conversion_book(weth.clone(), usdc.clone(), 1.0, 100.0)),
1115 ("usdt".to_string(), conversion_book(weth.clone(), usdt.clone(), 2.0, 100.0)),
1116 ("unrelated".to_string(), conversion_book(wbtc, usdc, 1_000.0, 100.0)),
1117 ("unapproved".to_string(), conversion_book(weth.clone(), unapproved, 2_000.0, 100.0)),
1118 ]);
1119
1120 let selected = client
1121 .select_tvl_conversion_book(&weth, &books)
1122 .expect("one conversion book");
1123
1124 assert_eq!(selected.quote_address, usdt);
1125 }
1126
1127 #[test]
1128 fn selects_lower_quote_address_for_equal_tvl_conversion_liquidity() {
1129 let weth = Bytes::from_str("0x3333333333333333333333333333333333333333").unwrap();
1130 let lower_quote = Bytes::from_str("0x1111111111111111111111111111111111111111").unwrap();
1131 let higher_quote = Bytes::from_str("0x2222222222222222222222222222222222222222").unwrap();
1132 let client = NativeClient::new(
1133 Chain::Ethereum,
1134 "test-api-key".to_string(),
1135 HashSet::from([weth.clone(), lower_quote.clone(), higher_quote.clone()]),
1136 0.0,
1137 HashSet::from([lower_quote.clone(), higher_quote.clone()]),
1138 Duration::from_secs(1),
1139 Duration::from_secs(5),
1140 )
1141 .unwrap();
1142 let books = HashMap::from([
1143 ("higher".to_string(), conversion_book(weth.clone(), higher_quote, 2.0, 100.0)),
1144 ("lower".to_string(), conversion_book(weth.clone(), lower_quote.clone(), 1.0, 200.0)),
1145 ]);
1146
1147 let selected = client
1148 .select_tvl_conversion_book(&weth, &books)
1149 .expect("one conversion book");
1150
1151 assert_eq!(selected.quote_address, lower_quote);
1152 }
1153
1154 #[test]
1155 fn creates_per_pair_component_from_relay_orderbook() {
1156 let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
1157 let usdt = Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap();
1158 let client = NativeClient::new(
1159 Chain::Ethereum,
1160 "test-api-key".to_string(),
1161 HashSet::from([weth.clone(), usdt.clone()]),
1162 0.0,
1163 HashSet::from([usdt.clone()]),
1164 Duration::from_secs(1),
1165 Duration::from_secs(5),
1166 )
1167 .unwrap();
1168
1169 let books = client.group_orderbook(vec![
1170 NativeOrderbookEntry {
1171 base_address: weth.clone(),
1172 quote_address: usdt.clone(),
1173 minimum_in_base: 0.0,
1174 side: NativeOrderbookSide::Bid,
1175 levels: vec![NativePriceLevel { quantity: 0.0001, price: 3213.12345 }],
1176 },
1177 NativeOrderbookEntry {
1178 base_address: weth.clone(),
1179 quote_address: usdt.clone(),
1180 minimum_in_base: 0.0,
1181 side: NativeOrderbookSide::Ask,
1182 levels: vec![NativePriceLevel { quantity: 2.0, price: 3214.0 }],
1183 },
1184 NativeOrderbookEntry {
1185 base_address: usdt.clone(),
1186 quote_address: weth.clone(),
1187 minimum_in_base: 100.0,
1188 side: NativeOrderbookSide::Bid,
1189 levels: vec![NativePriceLevel { quantity: 6428.0, price: 1.0 / 3214.0 }],
1190 },
1191 NativeOrderbookEntry {
1192 base_address: usdt.clone(),
1193 quote_address: weth.clone(),
1194 minimum_in_base: 100.0,
1195 side: NativeOrderbookSide::Ask,
1196 levels: vec![NativePriceLevel { quantity: 0.321312345, price: 1.0 / 3213.12345 }],
1197 },
1198 ]);
1199
1200 let (component_id, book) = books
1201 .into_iter()
1202 .next()
1203 .expect("one grouped book");
1204 let component = client.create_component_with_state(
1205 component_id.clone(),
1206 vec![book.base_address.clone(), book.quote_address.clone()],
1207 book.clone(),
1208 book.calculate_tvl(None)
1209 .expect("TVL should be finite"),
1210 );
1211
1212 assert_eq!(component.component.id, component_id);
1213 assert_eq!(component.component.protocol_system, NativeClient::PROTOCOL_SYSTEM);
1214 assert_eq!(component.component.protocol_type_name, "native_relay_pool");
1215 assert_eq!(component.component.tokens, vec![weth, usdt]);
1216 assert_eq!(component.state.component_id, component_id);
1217
1218 let encoded_book = component
1219 .state
1220 .attributes
1221 .get("book")
1222 .expect("book attribute");
1223 let decoded_book: NativePriceData = serde_json::from_slice(encoded_book).unwrap();
1224 assert_eq!(decoded_book.bids.len(), 1);
1225 assert_eq!(decoded_book.asks.len(), 1);
1226 assert_eq!(decoded_book.bids[0].quantity, 0.0001);
1227 assert_eq!(decoded_book.bids[0].price, 3213.12345);
1228 }
1229
1230 #[test]
1231 fn creates_all_pairs_component_from_relay_orderbook() {
1232 let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
1233 let usdt = Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap();
1234 let client = NativeClient::new(
1235 Chain::Ethereum,
1236 "test-api-key".to_string(),
1237 HashSet::from([weth.clone(), usdt.clone()]),
1238 0.0,
1239 HashSet::from([usdt.clone()]),
1240 Duration::from_secs(1),
1241 Duration::from_secs(5),
1242 )
1243 .unwrap();
1244
1245 let books = client.group_orderbook(vec![
1246 NativeOrderbookEntry {
1247 base_address: weth.clone(),
1248 quote_address: usdt.clone(),
1249 minimum_in_base: 0.0,
1250 side: NativeOrderbookSide::Bid,
1251 levels: vec![NativePriceLevel { quantity: 0.0001, price: 3213.12345 }],
1252 },
1253 NativeOrderbookEntry {
1254 base_address: weth.clone(),
1255 quote_address: usdt.clone(),
1256 minimum_in_base: 0.0,
1257 side: NativeOrderbookSide::Ask,
1258 levels: vec![NativePriceLevel { quantity: 2.0, price: 3214.0 }],
1259 },
1260 NativeOrderbookEntry {
1261 base_address: usdt.clone(),
1262 quote_address: weth.clone(),
1263 minimum_in_base: 100.0,
1264 side: NativeOrderbookSide::Bid,
1265 levels: vec![NativePriceLevel { quantity: 6428.0, price: 1.0 / 3214.0 }],
1266 },
1267 NativeOrderbookEntry {
1268 base_address: usdt.clone(),
1269 quote_address: weth.clone(),
1270 minimum_in_base: 100.0,
1271 side: NativeOrderbookSide::Ask,
1272 levels: vec![NativePriceLevel { quantity: 0.321312345, price: 1.0 / 3213.12345 }],
1273 },
1274 ]);
1275
1276 let component = client
1277 .all_pairs_component(&books)
1278 .unwrap()
1279 .expect("the book clears the threshold");
1280
1281 assert_eq!(
1282 component.component.id,
1283 component::component_id(NativeClient::PROTOCOL_SYSTEM, client.chain)
1284 );
1285 assert_eq!(component.component.protocol_system, NativeClient::PROTOCOL_SYSTEM);
1286 assert_eq!(component.component.protocol_type_name, "native_relay_pool");
1287 let mut expected_tokens = vec![weth.clone(), usdt.clone()];
1288 expected_tokens.sort();
1289 assert_eq!(component.component.tokens, expected_tokens);
1290 assert_eq!(
1291 component.state.component_id,
1292 component::component_id(NativeClient::PROTOCOL_SYSTEM, client.chain)
1293 );
1294 assert_eq!(
1295 component.component.static_attributes[SWAP_DIRECTIONS_ATTRIBUTE].len(),
1296 80,
1297 "bids and asks"
1298 );
1299 assert_eq!(
1300 component.component.static_attributes[QuoteRule::ATTRIBUTE].as_ref(),
1301 b"once_per_venue"
1302 );
1303 let decoded_books: Vec<NativePriceData> =
1304 serde_json::from_slice(&component.state.attributes[BOOKS_ATTRIBUTE]).unwrap();
1305 assert_eq!(decoded_books.len(), 1);
1306 assert_eq!(decoded_books[0].bids.len(), 1);
1307 assert_eq!(decoded_books[0].asks.len(), 1);
1308 assert_eq!(decoded_books[0].bids[0].quantity, 0.0001);
1309 assert_eq!(decoded_books[0].bids[0].price, 3213.12345);
1310 }
1311
1312 #[test]
1313 fn uses_stable_component_id_and_direction_when_merging_mirrored_books() {
1314 let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
1315 let usdc = Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap();
1316 let client = NativeClient::new(
1317 Chain::Ethereum,
1318 "test-api-key".to_string(),
1319 HashSet::from([weth.clone(), usdc.clone()]),
1320 0.0,
1321 HashSet::from([usdc.clone()]),
1322 Duration::from_secs(1),
1323 Duration::from_secs(5),
1324 )
1325 .unwrap();
1326 let entries = vec![
1327 NativeOrderbookEntry {
1328 base_address: weth.clone(),
1329 quote_address: usdc.clone(),
1330 minimum_in_base: 100_000_000_000.0,
1331 side: NativeOrderbookSide::Bid,
1332 levels: vec![NativePriceLevel { quantity: 1.0, price: 2_000.0 }],
1333 },
1334 NativeOrderbookEntry {
1335 base_address: weth.clone(),
1336 quote_address: usdc.clone(),
1337 minimum_in_base: 300_000_000_000.0,
1338 side: NativeOrderbookSide::Ask,
1339 levels: vec![NativePriceLevel { quantity: 1.0, price: 2_100.0 }],
1340 },
1341 NativeOrderbookEntry {
1342 base_address: usdc.clone(),
1343 quote_address: weth.clone(),
1344 minimum_in_base: 100.0,
1345 side: NativeOrderbookSide::Bid,
1346 levels: vec![NativePriceLevel { quantity: 2_000.0, price: 0.0005 }],
1347 },
1348 NativeOrderbookEntry {
1349 base_address: usdc.clone(),
1350 quote_address: weth.clone(),
1351 minimum_in_base: 250.0,
1352 side: NativeOrderbookSide::Bid,
1353 levels: vec![NativePriceLevel { quantity: 2_000.0, price: 0.0005 }],
1354 },
1355 NativeOrderbookEntry {
1356 base_address: usdc.clone(),
1357 quote_address: weth.clone(),
1358 minimum_in_base: 400.0,
1359 side: NativeOrderbookSide::Ask,
1360 levels: vec![NativePriceLevel { quantity: 2.0, price: 0.5 }],
1361 },
1362 ];
1363
1364 let forward_only = client.group_orderbook(entries[..2].to_vec());
1365 let reverse_entries = entries[2..].to_vec();
1366 let reverse_only = client.group_orderbook(reverse_entries.clone());
1367 let reversed_reverse_only = client.group_orderbook(
1368 reverse_entries
1369 .into_iter()
1370 .rev()
1371 .collect(),
1372 );
1373 assert_eq!(reverse_only, reversed_reverse_only);
1374 let pair = format!("native_{}/{}", hex::encode(&usdc), hex::encode(&weth));
1375 let component_id = keccak256(pair.as_bytes()).to_string();
1376
1377 let forward_book = forward_only
1378 .get(&component_id)
1379 .expect("forward-only book uses the stable component ID");
1380 assert_eq!(forward_book.base_address, weth);
1381 assert_eq!(forward_book.quote_address, usdc);
1382 assert_eq!(forward_book.minimum_in_base, 100_000_000_000.0);
1383 assert_eq!(forward_book.minimum_in_quote, 0.0);
1384 assert_eq!(forward_book.minimum_out_base, 300_000_000_000.0);
1385 assert_eq!(forward_book.minimum_out_quote, 0.0);
1386
1387 let reverse_book = reverse_only
1388 .get(&component_id)
1389 .expect("reverse-only book uses the stable component ID");
1390 assert_eq!(reverse_book.base_address, weth);
1391 assert_eq!(reverse_book.quote_address, usdc);
1392 assert_eq!(reverse_book.minimum_in_base, 0.0);
1393 assert_eq!(reverse_book.minimum_in_quote, 250.0);
1394 assert_eq!(reverse_book.minimum_out_base, 0.0);
1395 assert_eq!(reverse_book.minimum_out_quote, 400.0);
1396 assert_eq!(reverse_book.bids, vec![NativePriceLevel { quantity: 1.0, price: 2.0 }]);
1397 assert_eq!(
1398 reverse_book.asks,
1399 vec![
1400 NativePriceLevel { quantity: 1.0, price: 2_000.0 },
1401 NativePriceLevel { quantity: 1.0, price: 2_000.0 },
1402 ]
1403 );
1404
1405 let mixed = client.group_orderbook(vec![entries[0].clone(), entries[2].clone()]);
1406 let mixed_book = mixed.get(&component_id).unwrap();
1407 assert_eq!(mixed_book.minimum_in_base, 100_000_000_000.0);
1408 assert_eq!(mixed_book.minimum_in_quote, 100.0);
1409 assert_eq!(mixed_book.minimum_out_base, 0.0);
1410 assert_eq!(mixed_book.minimum_out_quote, 0.0);
1411 assert_eq!(mixed_book.bids, vec![NativePriceLevel { quantity: 1.0, price: 2_000.0 }]);
1412 assert_eq!(mixed_book.asks, vec![NativePriceLevel { quantity: 1.0, price: 2_000.0 }]);
1413
1414 let books = client.group_orderbook(entries.clone());
1415 let reversed_books = client.group_orderbook(entries.into_iter().rev().collect());
1416
1417 assert_eq!(books, reversed_books);
1418 assert_eq!(books.len(), 1);
1419 let book = books.get(&component_id).unwrap();
1420 assert_eq!(book.base_address, weth);
1421 assert_eq!(book.quote_address, usdc);
1422 assert_eq!(book.minimum_in_base, 100_000_000_000.0);
1423 assert_eq!(book.minimum_in_quote, 0.0);
1424 assert_eq!(book.minimum_out_base, 300_000_000_000.0);
1425 assert_eq!(book.minimum_out_quote, 0.0);
1426 assert_eq!(book.bids, vec![NativePriceLevel { quantity: 1.0, price: 2_000.0 }]);
1427 assert_eq!(book.asks, vec![NativePriceLevel { quantity: 1.0, price: 2_100.0 }]);
1428 }
1429
1430 #[test]
1431 fn zero_only_direct_side_does_not_suppress_mirrored_liquidity() {
1432 let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
1433 let usdc = Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap();
1434 let client = NativeClient::new(
1435 Chain::Ethereum,
1436 "test-api-key".to_string(),
1437 HashSet::from([weth.clone(), usdc.clone()]),
1438 0.0,
1439 HashSet::from([usdc.clone()]),
1440 Duration::from_secs(1),
1441 Duration::from_secs(5),
1442 )
1443 .unwrap();
1444
1445 let books = client.group_orderbook(vec![
1446 NativeOrderbookEntry {
1447 base_address: weth.clone(),
1448 quote_address: usdc.clone(),
1449 minimum_in_base: 999.0,
1450 side: NativeOrderbookSide::Bid,
1451 levels: vec![NativePriceLevel { quantity: 0.0, price: 2_000.0 }],
1452 },
1453 NativeOrderbookEntry {
1454 base_address: usdc,
1455 quote_address: weth,
1456 minimum_in_base: 250.0,
1457 side: NativeOrderbookSide::Ask,
1458 levels: vec![NativePriceLevel { quantity: 2.0, price: 0.5 }],
1459 },
1460 ]);
1461
1462 let book = books
1463 .values()
1464 .next()
1465 .expect("one grouped book");
1466 assert_eq!(book.bids, vec![NativePriceLevel { quantity: 1.0, price: 2.0 }]);
1467 assert_eq!(book.minimum_in_base, 0.0);
1468 assert_eq!(book.minimum_out_quote, 250.0);
1469 }
1470
1471 #[rstest]
1472 #[case::token0_only(true, false, true)]
1473 #[case::token1_only(false, true, false)]
1474 #[case::both_tokens(true, true, false)]
1475 #[case::neither_token(false, false, false)]
1476 fn selects_stable_direction_for_quote_token_preferences(
1477 #[case] token0_is_quote: bool,
1478 #[case] token1_is_quote: bool,
1479 #[case] expected_quote_is_token0: bool,
1480 ) {
1481 let token0 = Bytes::from_str("0x1111111111111111111111111111111111111111").unwrap();
1482 let token1 = Bytes::from_str("0x2222222222222222222222222222222222222222").unwrap();
1483 assert!(token0.as_ref() < token1.as_ref());
1484
1485 let mut quote_tokens = HashSet::new();
1486 if token0_is_quote {
1487 quote_tokens.insert(token0.clone());
1488 }
1489 if token1_is_quote {
1490 quote_tokens.insert(token1.clone());
1491 }
1492 let client = NativeClient::new(
1493 Chain::Ethereum,
1494 "test-api-key".to_string(),
1495 HashSet::from([token0.clone(), token1.clone()]),
1496 0.0,
1497 quote_tokens,
1498 Duration::from_secs(1),
1499 Duration::from_secs(5),
1500 )
1501 .unwrap();
1502
1503 let books = client.group_orderbook(vec![NativeOrderbookEntry {
1505 base_address: token1.clone(),
1506 quote_address: token0.clone(),
1507 minimum_in_base: 0.0,
1508 side: NativeOrderbookSide::Bid,
1509 levels: vec![NativePriceLevel { quantity: 1.0, price: 1.0 }],
1510 }]);
1511
1512 let book = books
1513 .values()
1514 .next()
1515 .expect("one grouped book");
1516 let (expected_base, expected_quote) =
1517 if expected_quote_is_token0 { (token1, token0) } else { (token0, token1) };
1518 assert_eq!(book.base_address, expected_base);
1519 assert_eq!(book.quote_address, expected_quote);
1520 }
1521
1522 fn create_test_quote_params() -> GetAmountOutParams {
1523 GetAmountOutParams {
1524 amount_in: BigUint::from(1u64),
1525 token_in: Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
1526 token_out: Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(),
1527 sender: Bytes::from_str("0x3333333333333333333333333333333333333333").unwrap(),
1528 receiver: Bytes::from_str("0x4444444444444444444444444444444444444444").unwrap(),
1529 origin: None,
1530 }
1531 }
1532
1533 #[test]
1534 fn accepts_quote_with_requested_input_amount() {
1535 let params = create_test_quote_params();
1536 let response = successful_quote_response(¶ms.amount_in.to_string());
1537
1538 let quote = NativeClient::process_quote_response(response, ¶ms).unwrap();
1539
1540 assert_eq!(quote.amount_in, params.amount_in);
1541 assert_eq!(
1542 quote
1543 .quote_attributes
1544 .get("deadline_timestamp")
1545 .unwrap()
1546 .as_ref(),
1547 u64::MAX.to_be_bytes()
1548 );
1549 }
1550
1551 #[test]
1552 fn rejects_quote_with_mismatched_input_amount() {
1553 let params = create_test_quote_params();
1554 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1555 response.amount_in = "2".to_string();
1557
1558 let result = NativeClient::process_quote_response(response, ¶ms);
1559
1560 assert!(matches!(
1561 result,
1562 Err(RFQError::ParsingError(message)) if message.contains("Native Relay quote input amount mismatch")
1563 ));
1564 }
1565
1566 #[test]
1567 fn rejects_quote_with_mismatched_signed_input_amount() {
1568 let params = create_test_quote_params();
1569 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1570 response.orders[0].seller_token_amount = "2".to_string();
1571
1572 let result = NativeClient::process_quote_response(response, ¶ms);
1573
1574 assert!(matches!(
1575 result,
1576 Err(RFQError::ParsingError(message)) if message.contains("signed input amount mismatch")
1577 ));
1578 }
1579
1580 #[test]
1581 fn accepts_quote_with_different_effective_input_amount() {
1582 let mut params = create_test_quote_params();
1583 params.amount_in = BigUint::from(100u64);
1584 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1585 response.orders[0].effective_seller_token_amount = "99".to_string();
1586
1587 let quote = NativeClient::process_quote_response(response, ¶ms).unwrap();
1588
1589 assert_eq!(quote.amount_in, params.amount_in);
1590 }
1591
1592 #[rstest]
1593 #[case::seller_token(true)]
1594 #[case::buyer_token(false)]
1595 fn rejects_quote_with_mismatched_token(#[case] mutate_seller_token: bool) {
1596 let params = create_test_quote_params();
1597 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1598 let mismatched_token = "0x5555555555555555555555555555555555555555".to_string();
1599 if mutate_seller_token {
1600 response.orders[0].seller_token = mismatched_token;
1601 } else {
1602 response.orders[0].buyer_token = mismatched_token;
1603 }
1604
1605 let result = NativeClient::process_quote_response(response, ¶ms);
1606
1607 assert!(matches!(
1608 result,
1609 Err(RFQError::ParsingError(message)) if message.contains("quote token mismatch")
1610 ));
1611 }
1612
1613 #[test]
1614 fn rejects_quote_with_mismatched_recipient() {
1615 let params = create_test_quote_params();
1616 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1617 response.orders[0].recipient = "0x5555555555555555555555555555555555555555".to_string();
1618
1619 let result = NativeClient::process_quote_response(response, ¶ms);
1620
1621 assert!(matches!(
1622 result,
1623 Err(RFQError::ParsingError(message)) if message.contains("recipient mismatch")
1624 ));
1625 }
1626
1627 #[test]
1628 fn rejects_quote_without_calldata() {
1629 let params = create_test_quote_params();
1630 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1631 response.tx_request.calldata.clear();
1632
1633 let result = NativeClient::process_quote_response(response, ¶ms);
1634
1635 assert!(matches!(
1636 result,
1637 Err(RFQError::QuoteNotFound(message)) if message.contains("did not include calldata")
1638 ));
1639 }
1640
1641 #[test]
1642 fn rejects_truncated_trade_calldata() {
1643 let params = create_test_quote_params();
1644 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1645 response.tx_request.calldata = format!("0x7083527c{}", "00".repeat(95));
1646
1647 let result = NativeClient::process_quote_response(response, ¶ms);
1648
1649 assert!(matches!(
1650 result,
1651 Err(RFQError::ParsingError(message)) if message.contains("calldata too short")
1652 ));
1653 }
1654
1655 #[test]
1656 fn rejects_quote_with_wrong_trade_rfqt_selector() {
1657 let params = create_test_quote_params();
1658 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1659 let mut calldata = hex::decode(
1660 response
1661 .tx_request
1662 .calldata
1663 .trim_start_matches("0x"),
1664 )
1665 .unwrap();
1666 calldata[..4].copy_from_slice(&[0x09, 0x47, 0xc2, 0xd9]);
1668 response.tx_request.calldata = format!("0x{}", hex::encode(calldata));
1669
1670 let result = NativeClient::process_quote_response(response, ¶ms);
1671
1672 assert!(matches!(
1673 result,
1674 Err(RFQError::ParsingError(message)) if message.contains("selector")
1675 ));
1676 }
1677
1678 #[rstest]
1679 #[case::v4("4")]
1680 #[case::unknown("7")]
1681 fn rejects_quote_with_wrong_router_version(#[case] version: &str) {
1682 let params = create_test_quote_params();
1683 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1684 response.router_version = version.to_string();
1685
1686 assert!(matches!(
1687 NativeClient::process_quote_response(response, ¶ms),
1688 Err(RFQError::ParsingError(message)) if message.contains("Unexpected Native router version")
1689 ));
1690 }
1691
1692 #[rstest]
1693 #[case::seller_offset(68, 68)]
1694 #[case::minimum_offset(36, 36)]
1695 fn rejects_quote_with_noncanonical_override_offsets(
1696 #[case] amount_in_offset: u32,
1697 #[case] amount_out_minimum_offset: u32,
1698 ) {
1699 let params = create_test_quote_params();
1700 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1701 response.amount_in_offset = amount_in_offset;
1702 response.amount_out_minimum_offset = amount_out_minimum_offset;
1703
1704 let result = NativeClient::process_quote_response(response, ¶ms);
1705
1706 assert!(matches!(
1707 result,
1708 Err(RFQError::ParsingError(message)) if message.contains(
1709 "Unexpected Native V6 override offsets"
1710 )
1711 ));
1712 }
1713
1714 #[rstest]
1715 #[case::seller(ACTUAL_SELLER_AMOUNT_OFFSET, "actualSellerAmount")]
1716 #[case::minimum(ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET, "actualMinOutputAmount")]
1717 fn rejects_quote_with_preset_override(
1718 #[case] override_offset: usize,
1719 #[case] field_name: &str,
1720 ) {
1721 let params = create_test_quote_params();
1722 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1723 let mut calldata = hex::decode(
1724 response
1725 .tx_request
1726 .calldata
1727 .trim_start_matches("0x"),
1728 )
1729 .unwrap();
1730 calldata[override_offset + 31] = 1;
1731 response.tx_request.calldata = format!("0x{}", hex::encode(calldata));
1732
1733 let result = NativeClient::process_quote_response(response, ¶ms);
1734
1735 assert!(matches!(
1736 result,
1737 Err(RFQError::ParsingError(message)) if message.contains(field_name)
1738 ));
1739 }
1740
1741 #[test]
1742 fn accepts_native_eth_response_using_zero_address() {
1743 let mut params = create_test_quote_params();
1744 params.token_in = Bytes::zero(20);
1745 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1746 response.orders[0].seller_token = "0x0000000000000000000000000000000000000000".to_string();
1747 response.tx_request.value = params.amount_in.to_string();
1748
1749 let quote = NativeClient::process_quote_response(response, ¶ms).unwrap();
1750
1751 assert_eq!(quote.amount_in, params.amount_in);
1752 }
1753
1754 #[test]
1755 fn rejects_native_quote_with_mismatched_payable_value() {
1756 let mut params = create_test_quote_params();
1757 params.token_in = Bytes::zero(20);
1758 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1759 response.orders[0].seller_token = "0x0000000000000000000000000000000000000000".to_string();
1760 response.tx_request.value = "2".to_string();
1761
1762 let result = NativeClient::process_quote_response(response, ¶ms);
1763
1764 assert!(matches!(
1765 result,
1766 Err(RFQError::ParsingError(message)) if message.contains("payable value mismatch")
1767 ));
1768 }
1769
1770 #[test]
1771 fn rejects_malformed_payable_value() {
1772 let params = create_test_quote_params();
1773 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1774 response.tx_request.value = "not-a-number".to_string();
1775
1776 let result = NativeClient::process_quote_response(response, ¶ms);
1777
1778 assert!(matches!(
1779 result,
1780 Err(RFQError::ParsingError(message)) if message.contains("txRequest.value")
1781 ));
1782 }
1783
1784 #[test]
1785 fn rejects_erc20_quote_with_nonzero_payable_value() {
1786 let params = create_test_quote_params();
1787 let mut response = successful_quote_response(¶ms.amount_in.to_string());
1788 response.tx_request.value = "1".to_string();
1789
1790 let result = NativeClient::process_quote_response(response, ¶ms);
1791
1792 assert!(matches!(
1793 result,
1794 Err(RFQError::ParsingError(message)) if message.contains("payable value mismatch")
1795 ));
1796 }
1797
1798 #[test]
1799 fn accepts_native_eth_orderbook_using_zero_address() {
1800 let tycho_native_eth = Bytes::zero(20);
1801 let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
1802 let client = NativeClient::new(
1803 Chain::Ethereum,
1804 "test-api-key".to_string(),
1805 HashSet::from([tycho_native_eth.clone(), usdc.clone()]),
1806 0.0,
1807 HashSet::from([usdc.clone()]),
1808 Duration::from_secs(1),
1809 Duration::from_secs(5),
1810 )
1811 .unwrap();
1812
1813 let entry: NativeOrderbookEntry = serde_json::from_value(serde_json::json!({
1814 "base_address": tycho_native_eth.to_string(),
1815 "quote_address": usdc.to_string(),
1816 "minimum_in_base": 1.0,
1817 "side": "bid",
1818 "levels": [[1.0, 3_000.0]]
1819 }))
1820 .unwrap();
1821 let books = client.group_orderbook(vec![entry]);
1822
1823 let book = books.values().next().unwrap();
1824 assert_eq!(book.base_address, tycho_native_eth);
1825 }
1826
1827 fn create_test_client(endpoint: String) -> NativeClient {
1828 let mut client = NativeClient::new(
1829 Chain::Ethereum,
1830 "test-api-key".to_string(),
1831 HashSet::new(),
1832 0.0,
1833 HashSet::new(),
1834 Duration::from_secs(1),
1835 Duration::from_secs(5),
1836 )
1837 .unwrap();
1838 client.endpoint = endpoint;
1839 client
1840 }
1841
1842 #[tokio::test]
1843 async fn requests_v6_firm_quote() {
1844 let listener = TcpListener::bind("127.0.0.1:0")
1845 .await
1846 .unwrap();
1847 let address = listener.local_addr().unwrap();
1848 let server = tokio::spawn(async move {
1849 let (stream, _) = listener.accept().await.unwrap();
1850 let mut reader = BufReader::new(stream);
1851 let mut request_line = String::new();
1852 reader
1853 .read_line(&mut request_line)
1854 .await
1855 .unwrap();
1856 let body = successful_quote_json("1").to_string();
1857 let response = format!(
1858 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1859 body.len()
1860 );
1861 reader
1862 .into_inner()
1863 .write_all(response.as_bytes())
1864 .await
1865 .unwrap();
1866 request_line
1867 });
1868 let client = create_test_client(format!("http://{address}"));
1869 let params = create_test_quote_params();
1870
1871 let quote = client
1872 .request_binding_quote(¶ms)
1873 .await
1874 .unwrap();
1875 let request = server.await.unwrap();
1876 let url = reqwest::Url::parse(&format!(
1877 "http://{address}{}",
1878 request
1879 .split_whitespace()
1880 .nth(1)
1881 .unwrap()
1882 ))
1883 .unwrap();
1884 let query: HashMap<_, _> = url.query_pairs().into_owned().collect();
1885
1886 assert_eq!(url.path(), "/firm-quote");
1887 assert_eq!(query.get("version").map(String::as_str), Some("6"));
1888 assert_eq!(
1889 query
1890 .get("allow_multihop")
1891 .map(String::as_str),
1892 Some("false")
1893 );
1894 assert_eq!(quote.amount_in, params.amount_in);
1895 }
1896
1897 #[tokio::test]
1898 async fn requests_native_token_orderbooks() {
1899 let listener = TcpListener::bind("127.0.0.1:0")
1900 .await
1901 .unwrap();
1902 let address = listener.local_addr().unwrap();
1903 let server = tokio::spawn(async move {
1904 let (stream, _) = listener.accept().await.unwrap();
1905 let mut reader = BufReader::new(stream);
1906 let mut request_line = String::new();
1907 reader
1908 .read_line(&mut request_line)
1909 .await
1910 .unwrap();
1911 let mut stream = reader.into_inner();
1912 let response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n[]";
1913 stream
1914 .write_all(response.as_bytes())
1915 .await
1916 .unwrap();
1917 request_line
1918 });
1919 let client = create_test_client(format!("http://{address}"));
1920
1921 let orderbook = client.fetch_orderbook().await.unwrap();
1922 let request = server.await.unwrap();
1923
1924 assert!(orderbook.is_empty());
1925 assert!(request.starts_with("GET /orderbook?"));
1926 assert!(request.contains("chain=ethereum"));
1927 assert!(request.contains("showNative=0x0"));
1928 }
1929
1930 #[rstest]
1931 #[case::with_conversion_helper(true, 300.0, Some(400.0))]
1932 #[case::without_conversion_helper(false, 300.0, None)]
1933 #[case::below_normalized_tvl_threshold(true, 401.0, None)]
1934 #[tokio::test]
1935 async fn stream_uses_unrequested_books_only_for_tvl_conversion(
1936 #[case] include_helper: bool,
1937 #[case] tvl_threshold: f64,
1938 #[case] expected_tvl: Option<f64>,
1939 #[values(ComponentLayout::PerPair, ComponentLayout::AllPairs)] layout: ComponentLayout,
1940 ) {
1941 let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
1942 let usdt = Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap();
1943 let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
1944 let mut entries = vec![serde_json::json!({
1945 "base_address": weth.to_string(),
1946 "quote_address": usdt.to_string(),
1947 "minimum_in_base": 0.0,
1948 "side": "bid",
1949 "levels": [[2.0, 100.0]]
1950 })];
1951 if include_helper {
1952 entries.push(serde_json::json!({
1955 "base_address": usdc.to_string(),
1956 "quote_address": usdt.to_string(),
1957 "minimum_in_base": 0.0,
1958 "side": "bid",
1959 "levels": [[1_000.0, 0.5]]
1960 }));
1961 }
1962 let (address, _) =
1963 create_quote_server("200 OK", serde_json::to_string(&entries).unwrap()).await;
1964 let mut client =
1965 create_test_client(format!("http://{address}")).with_component_layout(layout);
1966 client.tokens = HashSet::from([weth.clone(), usdt.clone()]);
1967 client.quote_tokens = HashSet::from([usdc]);
1968 client.tvl = tvl_threshold;
1969
1970 let (_, update) = timeout(Duration::from_secs(5), client.stream().next())
1971 .await
1972 .expect("orderbook poll timed out")
1973 .expect("stream ended")
1974 .expect("orderbook poll failed");
1975
1976 if let Some(tvl) = expected_tvl {
1977 assert_eq!(update.snapshots.states.len(), 1, "helper must not be emitted");
1978 let component = update
1979 .snapshots
1980 .states
1981 .values()
1982 .next()
1983 .unwrap();
1984 assert_eq!(component.component.tokens, vec![weth, usdt]);
1985 assert_eq!(component.component_tvl, Some(tvl));
1986 } else {
1987 assert!(update.snapshots.states.is_empty());
1988 }
1989 }
1990
1991 async fn create_quote_server(
1992 final_status: impl Into<String>,
1993 final_body: impl Into<String>,
1994 ) -> (std::net::SocketAddr, Arc<AtomicUsize>) {
1995 let final_status = final_status.into();
1996 let final_body = final_body.into();
1997 let listener = TcpListener::bind("127.0.0.1:0")
1998 .await
1999 .unwrap();
2000 let address = listener.local_addr().unwrap();
2001 let request_count = Arc::new(AtomicUsize::new(0));
2002 let server_request_count = request_count.clone();
2003
2004 tokio::spawn(async move {
2005 while let Ok((mut stream, _)) = listener.accept().await {
2006 server_request_count.fetch_add(1, Ordering::SeqCst);
2007 let response = format!(
2008 "HTTP/1.1 {final_status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{final_body}",
2009 final_body.len()
2010 );
2011 let _ = stream
2012 .write_all(response.as_bytes())
2013 .await;
2014 let _ = stream.shutdown().await;
2015 }
2016 });
2017
2018 (address, request_count)
2019 }
2020
2021 async fn create_hanging_quote_server() -> std::net::SocketAddr {
2022 let listener = TcpListener::bind("127.0.0.1:0")
2023 .await
2024 .unwrap();
2025 let address = listener.local_addr().unwrap();
2026
2027 tokio::spawn(async move {
2028 let (_stream, _) = listener.accept().await.unwrap();
2029 std::future::pending::<()>().await;
2030 });
2031
2032 address
2033 }
2034
2035 #[tokio::test]
2036 async fn handles_orderbook_api_error_with_http_200() {
2037 let (address, request_count) = create_quote_server(
2038 "200 OK",
2039 r#"{"code":171015,"message":"quoted token not available"}"#,
2040 )
2041 .await;
2042 let client = create_test_client(format!("http://{address}"));
2043
2044 let result = client.fetch_orderbook().await;
2045
2046 assert!(matches!(
2047 result,
2048 Err(RFQError::QuoteNotFound(message)) if message.contains("171015")
2049 ));
2050 assert_eq!(request_count.load(Ordering::SeqCst), 1);
2051 }
2052
2053 #[tokio::test]
2054 async fn handles_documented_quote_error_without_retrying() {
2055 let (address, request_count) = create_quote_server(
2056 "200 OK",
2057 r#"{"code":171015,"message":"quoted token not available"}"#,
2058 )
2059 .await;
2060 let client = create_test_client(format!("http://{address}"));
2061
2062 let result = client
2063 .request_binding_quote(&create_test_quote_params())
2064 .await;
2065
2066 match result {
2067 Err(RFQError::QuoteNotFound(message)) => {
2068 assert!(message.contains("171015"));
2069 assert!(message.contains("quoted token not available"));
2070 }
2071 other => panic!("Expected Native API error, got {other:?}"),
2072 }
2073 assert_eq!(request_count.load(Ordering::SeqCst), 1);
2074 }
2075
2076 #[tokio::test]
2077 async fn handles_success_false_as_quote_not_found_without_retrying() {
2078 let mut response = successful_quote_json("1");
2079 response["success"] = serde_json::Value::Bool(false);
2080 response["errorMessage"] = serde_json::Value::String("quote unavailable".to_string());
2081 let (address, request_count) = create_quote_server("200 OK", response.to_string()).await;
2082 let client = create_test_client(format!("http://{address}"));
2083
2084 let result = client
2085 .request_binding_quote(&create_test_quote_params())
2086 .await;
2087
2088 assert!(matches!(
2089 result,
2090 Err(RFQError::QuoteNotFound(message)) if message.contains("quote unavailable")
2091 ));
2092 assert_eq!(request_count.load(Ordering::SeqCst), 1);
2093 }
2094
2095 #[tokio::test]
2096 async fn retries_documented_temporary_api_error() {
2097 let (address, request_count) = create_quote_server(
2098 "200 OK",
2099 r#"{"code":301016,"message":"quote invalid, risk management checks failed"}"#,
2100 )
2101 .await;
2102 let client = create_test_client(format!("http://{address}"));
2103
2104 let result = client
2105 .request_binding_quote(&create_test_quote_params())
2106 .await;
2107
2108 assert!(matches!(result, Err(RFQError::QuoteNotFound(_))));
2109 assert_eq!(request_count.load(Ordering::SeqCst), 3);
2110 }
2111
2112 #[tokio::test]
2113 async fn retries_server_error_without_native_error_envelope() {
2114 let (address, request_count) =
2115 create_quote_server("503 Service Unavailable", "<html>upstream unavailable</html>")
2116 .await;
2117 let client = create_test_client(format!("http://{address}"));
2118
2119 let result = client
2120 .request_binding_quote(&create_test_quote_params())
2121 .await;
2122
2123 assert!(matches!(
2124 result,
2125 Err(RFQError::ConnectionError(message)) if message.contains("503 Service Unavailable")
2126 ));
2127 assert_eq!(request_count.load(Ordering::SeqCst), 3);
2128 }
2129
2130 #[tokio::test]
2131 async fn retries_malformed_success_response() {
2132 let (address, request_count) =
2133 create_quote_server("200 OK", r#"{"unexpected":true}"#).await;
2134 let client = create_test_client(format!("http://{address}"));
2135
2136 let result = client
2137 .request_binding_quote(&create_test_quote_params())
2138 .await;
2139
2140 assert!(matches!(result, Err(RFQError::ParsingError(_))));
2141 assert_eq!(request_count.load(Ordering::SeqCst), 3);
2142 }
2143
2144 #[tokio::test]
2145 async fn times_out_when_quote_response_stalls() {
2146 let address = create_hanging_quote_server().await;
2147 let mut client = create_test_client(format!("http://{address}"));
2148 client.quote_timeout = Duration::from_millis(50);
2149
2150 let result = tokio::time::timeout(
2151 Duration::from_secs(1),
2152 client.request_binding_quote(&create_test_quote_params()),
2153 )
2154 .await
2155 .expect("Native quote timeout did not terminate the request");
2156
2157 assert!(matches!(
2158 result,
2159 Err(RFQError::ConnectionError(message)) if message.contains("timed out after 50ms")
2160 ));
2161 }
2162
2163 #[tokio::test]
2164 async fn shares_quote_timeout_across_retries() {
2165 let listener = TcpListener::bind("127.0.0.1:0")
2166 .await
2167 .unwrap();
2168 let address = listener.local_addr().unwrap();
2169 let request_count = Arc::new(AtomicUsize::new(0));
2170 let server_request_count = request_count.clone();
2171 let params = create_test_quote_params();
2172 let success_body = successful_quote_json(¶ms.amount_in.to_string()).to_string();
2173 let quote_timeout = NATIVE_API_RETRY_DELAY * 2;
2174
2175 tokio::spawn(async move {
2176 let retry_body =
2177 r#"{"code":301016,"message":"quote invalid, risk management checks failed"}"#
2178 .to_string();
2179 for body in [retry_body, success_body] {
2180 let (mut stream, _) = listener.accept().await.unwrap();
2181 let attempt = server_request_count.fetch_add(1, Ordering::SeqCst);
2182 if attempt == 1 {
2183 tokio::time::sleep(quote_timeout * 3 / 4).await;
2185 }
2186 let response = format!(
2187 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2188 body.len()
2189 );
2190 let _ = stream
2191 .write_all(response.as_bytes())
2192 .await;
2193 let _ = stream.shutdown().await;
2194 }
2195 });
2196
2197 let mut client = create_test_client(format!("http://{address}"));
2198 client.quote_timeout = quote_timeout;
2199
2200 let result = timeout(Duration::from_secs(5), client.request_binding_quote(¶ms))
2201 .await
2202 .expect("Native quote timeout did not terminate the retries");
2203
2204 assert!(matches!(
2205 result,
2206 Err(RFQError::QuoteNotFound(message)) if message.contains("301016")
2207 ));
2208 assert_eq!(request_count.load(Ordering::SeqCst), 2);
2209 }
2210
2211 #[tokio::test]
2212 async fn does_not_retry_documented_authentication_error() {
2213 let (address, request_count) = create_quote_server(
2214 "200 OK",
2215 r#"{"code":201001,"message":"auth get api key is invalid"}"#,
2216 )
2217 .await;
2218 let client = create_test_client(format!("http://{address}"));
2219
2220 let result = client
2221 .request_binding_quote(&create_test_quote_params())
2222 .await;
2223
2224 assert!(matches!(result, Err(RFQError::FatalError(_))));
2225 assert_eq!(request_count.load(Ordering::SeqCst), 1);
2226 }
2227}