use std::{collections::HashMap, str::FromStr};
use alloy::primitives::{Address, U256};
use num_bigint::BigUint;
use reqwest::Client;
use tokio::time::{timeout, Duration};
use tracing::{debug, instrument, warn};
use tycho_common::{
models::protocol::GetAmountOutParams, simulation::indicatively_priced::SignedQuote, Bytes,
};
use crate::{
evm::protocol::u256_num::biguint_to_u256,
rfq::{
errors::RFQError,
protocols::hashflow::models::{
HashflowChain, HashflowError, HashflowFailure, HashflowMarketMakerLevels,
HashflowMarketMakersResponse, HashflowPriceLevelsResponse, HashflowQuoteRequest,
HashflowQuoteResponse, HashflowRFQ, HashflowRFQOptions,
},
},
snapshot_feed::{errors::FeedError, http::fetch_json},
};
/// Whether Hashflow refused the request because it does not price the chain.
fn refuses_the_chain(body: &str) -> bool {
serde_json::from_str::<HashflowFailure>(body)
.is_ok_and(|failure| failure.error.refuses_the_chain())
}
/// Hashflow's public taker API, where a client talks unless it is given another.
const HASHFLOW_API_URL: &str = "https://api.hashflow.com";
/// Requests binding Hashflow quotes. One instance is shared (via `Arc`) by every state a
/// [`HashflowFeed`](super::feed::HashflowFeed) emits, so all of them reuse the same HTTP
/// connection pool.
#[derive(derive_more::Debug)]
pub struct HashflowClient {
chain_id: u64,
quote_endpoint: String,
#[debug(skip)]
source: String,
#[debug(skip)]
auth_key: String,
quote_timeout: Duration,
http: Client,
}
/// Reads the price levels Hashflow's market makers quote on one chain. It never requests a
/// quote, so it carries no quote timeout. `Debug` output omits the credentials.
#[derive(derive_more::Debug, Clone)]
pub struct HashflowLevelsClient {
chain_id: u64,
price_levels_endpoint: String,
market_makers_endpoint: String,
#[debug(skip)]
source: String,
#[debug(skip)]
auth_key: String,
http: Client,
}
/// The base of Hashflow's taker API endpoints on the deployment at `base_url`, or on the venue.
fn taker_url(base_url: Option<&str>) -> String {
format!(
"{}/taker/v3",
base_url
.unwrap_or(HASHFLOW_API_URL)
.trim_end_matches('/')
)
}
impl HashflowClient {
/// A client for Hashflow's taker API, whose rfq endpoint sits on the version's own path.
/// `base_url` points it somewhere else than the venue, which is how a test reaches a server
/// of its own.
pub fn new(
base_url: Option<&str>,
chain_id: u64,
source: String,
auth_key: String,
quote_timeout: Duration,
) -> Self {
HashflowClient {
chain_id,
quote_endpoint: format!("{}/rfq", taker_url(base_url)),
source,
auth_key,
quote_timeout,
http: Client::new(),
}
}
/// Sends this client's requests through `http`, so it can share a connection pool with
/// another client.
pub(super) fn with_http_client(mut self, http: Client) -> Self {
self.http = http;
self
}
/// Requests a signed quote from `market_maker` alone: the API does not fall back to another
/// maker when it declines, so a quote always comes from the maker whose levels priced it.
#[instrument(
name = "quote_request",
level = "error",
skip_all,
fields(token_in = %params.token_in, token_out = %params.token_out, amount_in = %params.amount_in, %market_maker)
)]
pub async fn request_binding_quote(
&self,
params: &GetAmountOutParams,
market_maker: String,
) -> Result<SignedQuote, RFQError> {
let hashflow_chain = HashflowChain::evm(self.chain_id);
// A fresh random address becomes the quote's effectiveTrader — the address Hashflow
// scopes its strictly increasing quote nonces to — so quotes never invalidate each
// other, at the cost of a cold nonce storage slot on Hashflow's router (~17k gas per
// swap). The receiver executes the trade on-chain, so it is Hashflow's trader.
let effective_trader = Bytes::from(Address::random().to_vec());
let quote_request = HashflowQuoteRequest {
source: self.source.clone(),
base_chain: hashflow_chain.clone(),
quote_chain: hashflow_chain,
rfqs: vec![HashflowRFQ {
base_token: params.token_in.to_string(),
quote_token: params.token_out.to_string(),
base_token_amount: Some(params.amount_in.to_string()),
quote_token_amount: None,
trader: params.receiver.to_string(),
effective_trader: Some(effective_trader.to_string()),
market_makers: vec![market_maker],
options: HashflowRFQOptions { do_not_retry_with_other_makers: true },
}],
calldata: false,
};
let url = self.quote_endpoint.clone();
let start_time = std::time::Instant::now();
const MAX_RETRIES: u32 = 3;
let mut last_error = None;
for attempt in 0..MAX_RETRIES {
// Check if we have time remaining for this attempt
let elapsed = start_time.elapsed();
if elapsed >= self.quote_timeout {
return Err(last_error.unwrap_or_else(|| {
RFQError::ConnectionError(format!(
"Hashflow quote request timed out after {:?}",
self.quote_timeout
))
}));
}
let remaining_time = self.quote_timeout - elapsed;
let request = self
.http
.post(&url)
.json("e_request)
.header("accept", "application/json")
.header("Authorization", &self.auth_key);
let response = match timeout(remaining_time, request.send()).await {
Ok(Ok(resp)) => resp,
Ok(Err(e)) => {
warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %e, "quote request failed");
last_error = Some(RFQError::ConnectionError(format!(
"Failed to send Hashflow quote request: {e}"
)));
if attempt < MAX_RETRIES - 1 {
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
} else {
return Err(last_error.unwrap());
}
}
Err(_) => {
return Err(RFQError::ConnectionError(format!(
"Hashflow quote request timed out after {:?}",
self.quote_timeout
)));
}
};
if response.status() != 200 {
let status = response.status();
let err_msg = match response.text().await {
Ok(text) => text,
Err(e) => {
warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %e, "error response parsing failed");
last_error = Some(RFQError::ParsingError(format!(
"Failed to read response text from Hashflow failed request: {e}"
)));
if attempt < MAX_RETRIES - 1 {
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
} else {
return Err(last_error.unwrap());
}
}
};
// The venue answering a quote request at all means the request reached it,
// so a status it refuses with is about this attempt: a rate limit, a gateway
// between us and it, or a key to be fixed at the venue while the feed runs on.
last_error = Some(RFQError::ConnectionError(format!(
"Hashflow quote request failed with {status}: {err_msg}",
)));
if attempt < MAX_RETRIES - 1 {
warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %err_msg, "returned non-200 status");
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
} else {
return Err(last_error.unwrap());
}
}
let quote_response = match response
.json::<HashflowQuoteResponse>()
.await
{
Ok(resp) => resp,
Err(e) => {
warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %e, "quote response parsing failed");
last_error = Some(RFQError::ParsingError(format!(
"Failed to parse Hashflow quote response: {e}"
)));
if attempt < MAX_RETRIES - 1 {
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
} else {
return Err(last_error.unwrap());
}
}
};
match quote_response.status.as_str() {
"success" => {
if let Some(quotes) = quote_response.quotes {
if quotes.is_empty() {
return Err(RFQError::QuoteNotFound(format!(
"Hashflow quote not found for {} {} ->{}",
params.amount_in, params.token_in, params.token_out,
)));
}
// We assume there will be only one quote request at a time
let quote = quotes[0].clone();
quote.validate(params, &effective_trader)?;
let mut quote_attributes: HashMap<String, Bytes> = HashMap::new();
quote_attributes.insert("pool".to_string(), quote.quote_data.pool);
if let Some(external_account) = quote.quote_data.external_account {
quote_attributes
.insert("external_account".to_string(), external_account);
} else {
quote_attributes.insert(
"external_account".to_string(),
Bytes::from_str(&Address::ZERO.to_string()).map_err(|_| {
RFQError::ParsingError(
"Failed to parse zero address".to_string(),
)
})?,
);
}
quote_attributes.insert("trader".to_string(), quote.quote_data.trader);
quote_attributes
.insert("effective_trader".to_string(), effective_trader.clone());
quote_attributes
.insert("base_token".to_string(), quote.quote_data.base_token);
quote_attributes
.insert("quote_token".to_string(), quote.quote_data.quote_token);
quote_attributes.insert(
"base_token_amount".to_string(),
Bytes::from(
biguint_to_u256(
&BigUint::from_str("e.quote_data.base_token_amount)
.map_err(|_| {
RFQError::ParsingError(format!(
"Failed to parse base token amount: {}",
quote.quote_data.base_token_amount
))
})?,
)
.to_be_bytes::<32>()
.to_vec(),
),
);
quote_attributes.insert(
"quote_token_amount".to_string(),
Bytes::from(
biguint_to_u256(
&BigUint::from_str("e.quote_data.quote_token_amount)
.map_err(|_| {
RFQError::ParsingError(format!(
"Failed to parse quote token amount: {}",
quote.quote_data.quote_token_amount
))
})?,
)
.to_be_bytes::<32>()
.to_vec(),
),
);
quote_attributes.insert(
"quote_expiry".to_string(),
Bytes::from(
U256::from(quote.quote_data.quote_expiry)
.to_be_bytes::<32>()
.to_vec(),
),
);
quote_attributes.insert(
"nonce".to_string(),
Bytes::from(
U256::from(quote.quote_data.nonce)
.to_be_bytes::<32>()
.to_vec(),
),
);
quote_attributes.insert("tx_id".to_string(), quote.quote_data.tx_id);
quote_attributes.insert("signature".to_string(), quote.signature);
let signed_quote = SignedQuote {
base_token: params.token_in.clone(),
quote_token: params.token_out.clone(),
amount_in: BigUint::from_str("e.quote_data.base_token_amount)
.map_err(|_| {
RFQError::ParsingError(format!(
"Failed to parse amount in string: {}",
quote.quote_data.base_token_amount
))
})?,
amount_out: BigUint::from_str("e.quote_data.quote_token_amount)
.map_err(|_| {
RFQError::ParsingError(format!(
"Failed to parse amount out string: {}",
quote.quote_data.quote_token_amount
))
})?,
quote_attributes,
};
return Ok(signed_quote);
} else {
return Err(RFQError::QuoteNotFound(format!(
"Hashflow quote not found for {} {} ->{}",
params.amount_in, params.token_in, params.token_out,
)));
}
}
"fail" => {
let Some(error) = quote_response.error else {
return Err(RFQError::FatalError(
"Hashflow API error: request failed without an error".to_string(),
));
};
// A declined trade leaves the route to be priced elsewhere; a code the
// venue has not been seen to decline with is taken to be the request itself
// being wrong.
return Err(if error.declines_the_trade() {
RFQError::QuoteNotFound(format!("Hashflow quote: {error}"))
} else {
RFQError::FatalError(format!("Hashflow API error: {error}"))
});
}
_ => {
return Err(RFQError::FatalError(
"Hashflow API error: Unknown status".to_string(),
));
}
}
}
Err(last_error.unwrap_or_else(|| {
RFQError::ConnectionError("Hashflow quote request failed after retries".to_string())
}))
}
}
impl HashflowLevelsClient {
/// A client for the market makers and price levels of Hashflow's taker API on `chain_id`.
/// `base_url` points it somewhere else than the venue, as for [`HashflowClient::new`].
pub fn new(base_url: Option<&str>, chain_id: u64, source: String, auth_key: String) -> Self {
let taker = taker_url(base_url);
HashflowLevelsClient {
chain_id,
price_levels_endpoint: format!("{taker}/price-levels"),
market_makers_endpoint: format!("{taker}/market-makers"),
source,
auth_key,
http: Client::new(),
}
}
/// Sends this client's requests through `http`, so it can share a connection pool with
/// another client.
pub(super) fn with_http_client(mut self, http: Client) -> Self {
self.http = http;
self
}
/// The query every book request carries: who is asking and about which chain.
fn chain_query(&self) -> Vec<(&'static str, String)> {
vec![
("source", self.source.clone()),
("baseChainType", "evm".to_string()),
("baseChainId", self.chain_id.to_string()),
]
}
/// The makers currently quoting on this chain.
pub async fn fetch_market_makers(&self) -> Result<Vec<String>, FeedError> {
let request = self
.http
.get(&self.market_makers_endpoint)
.query(&self.chain_query())
.header("accept", "application/json")
.header("Authorization", &self.auth_key);
let mm_response: HashflowMarketMakersResponse =
fetch_json(request, "Hashflow market makers", refuses_the_chain).await?;
debug!(
count = mm_response.market_makers.len(),
market_makers = ?mm_response.market_makers,
"fetched market makers"
);
Ok(mm_response.market_makers)
}
/// The price levels the given makers are quoting, keyed by maker name.
pub async fn fetch_price_levels(
&self,
market_makers: &[String],
) -> Result<HashMap<String, Vec<HashflowMarketMakerLevels>>, FeedError> {
let mut query_params = self.chain_query();
// Add market makers as array parameters
for mm in market_makers {
query_params.push(("marketMakers[]", mm.clone()));
}
let request = self
.http
.get(&self.price_levels_endpoint)
.query(&query_params)
.header("accept", "application/json")
.header("Authorization", &self.auth_key);
let price_response: HashflowPriceLevelsResponse =
fetch_json(request, "Hashflow price levels", refuses_the_chain).await?;
if price_response.status != "success" {
let refuses_the_chain = price_response
.error
.as_ref()
.is_some_and(HashflowError::refuses_the_chain);
let error = match price_response.error {
Some(error) => error.to_string(),
None => "no error details".to_string(),
};
let message = format!("API returned error status: {error}");
return Err(if refuses_the_chain {
FeedError::Fatal(message)
} else {
FeedError::Connection(message)
});
}
price_response
.levels
.ok_or_else(|| FeedError::Parsing("API response missing levels".to_string()))
}
}
#[cfg(test)]
mod tests {
use std::{
str::FromStr,
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex,
},
};
use dotenv::dotenv;
use rstest::rstest;
use tycho_common::models::Chain;
use super::*;
use crate::snapshot_feed::http::test_support::{
spawn_http_server, MockHttpServer, MockResponse,
};
/// Response template; the mock server replaces `{{EFFECTIVE_TRADER}}` with the address the
/// request carried, echoing it like the real API.
const QUOTE_RESPONSE: &str = r#"{"status":"success","error":null,"rfqId":"test-rfq-id","internalRfqIds":null,"quotes":[{"quoteData":{"pool":"0x71D9750ECF0c5081FAE4E3EDC4253E52024b0B59","externalAccount":null,"trader":"0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35","effectiveTrader":"{{EFFECTIVE_TRADER}}","baseToken":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","baseTokenAmount":"1000000000000000000","quoteToken":"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599","quoteTokenAmount":"3329502","quoteExpiry":1707847360,"nonce":1707844960943648659,"txid":"0x0000000000000000000000000000000000000000000000000000000000000001"},"signature":"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12"}]}"#;
const QUOTE_RESPONSE_WITHOUT_EFFECTIVE_TRADER: &str = r#"{"status":"success","error":null,"rfqId":"test-rfq-id","internalRfqIds":null,"quotes":[{"quoteData":{"pool":"0x71D9750ECF0c5081FAE4E3EDC4253E52024b0B59","externalAccount":null,"trader":"0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35","baseToken":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","baseTokenAmount":"1000000000000000000","quoteToken":"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599","quoteTokenAmount":"3329502","quoteExpiry":1707847360,"nonce":1707844960943648659,"txid":"0x0000000000000000000000000000000000000000000000000000000000000001"},"signature":"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12"}]}"#;
/// Extracts the effectiveTrader value from a request body.
fn effective_trader_of(request_body: &str) -> String {
let start = request_body
.find("\"effectiveTrader\":\"")
.expect("request carries no effectiveTrader") +
"\"effectiveTrader\":\"".len();
request_body[start..start + request_body[start..].find('"').unwrap()].to_string()
}
/// A server answering every quote request with `json_response`, after `delay`, with the
/// request's own `effectiveTrader` put where the response names one. The bodies it was
/// asked with are recorded in the returned log.
async fn quote_server(
delay: Duration,
json_response: &'static str,
) -> (MockHttpServer, Arc<Mutex<Vec<String>>>) {
let request_log: Arc<Mutex<Vec<String>>> = Arc::default();
let recorded = Arc::clone(&request_log);
let server = spawn_http_server(move |request| {
recorded
.lock()
.unwrap()
.push(request.body.clone());
Some(MockResponse {
status: "200 OK",
body: json_response
.replace("{{EFFECTIVE_TRADER}}", &effective_trader_of(&request.body)),
delay,
})
})
.await;
(server, request_log)
}
fn create_test_client(base_url: String, quote_timeout: Duration) -> HashflowClient {
HashflowClient::new(
Some(&base_url),
Chain::Ethereum.id(),
"test_user".to_string(),
"test_key".to_string(),
quote_timeout,
)
}
#[test]
fn debug_output_omits_credentials() {
let client =
create_test_client("https://hashflow.example".to_string(), Duration::from_secs(1));
let rendered = format!("{client:?}");
assert!(!rendered.contains("test_user"));
assert!(!rendered.contains("test_key"));
assert!(rendered.contains("hashflow.example"));
}
/// A status the venue refuses a quote with says the request reached it and this attempt
/// failed — a rate limit, a gateway in between, a key to be fixed at the venue — so the
/// state asks again instead of being retired.
#[tokio::test]
async fn a_refused_status_leaves_the_component_quotable() {
let server =
spawn_http_server(|_| Some(("429 Too Many Requests", "slow down".to_string()))).await;
let client = create_test_client(server.url(), Duration::from_secs(1));
let error = client
.request_binding_quote(&create_test_quote_params(), "mm1".to_string())
.await
.unwrap_err();
assert!(matches!(error, RFQError::ConnectionError(_)), "{error}");
assert!(error.to_string().contains("429"), "{error}");
}
/// Helper function to create test quote params
fn create_test_quote_params() -> GetAmountOutParams {
let token_in = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
let token_out = Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap();
let router = Bytes::from_str("0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35").unwrap();
GetAmountOutParams {
amount_in: BigUint::from(1_000000000000000000u64),
token_in,
token_out,
sender: router.clone(),
receiver: router,
origin: None,
}
}
#[tokio::test]
async fn request_binding_quote_without_effective_trader() {
// A response that drops the requested effectiveTrader would leave the quote in the
// trader's shared nonce scope, so the client rejects it.
let (server, _) =
quote_server(Duration::ZERO, QUOTE_RESPONSE_WITHOUT_EFFECTIVE_TRADER).await;
let client = create_test_client(server.url(), Duration::from_secs(1));
let params = create_test_quote_params();
let err = client
.request_binding_quote(¶ms, "mm1".to_string())
.await
.unwrap_err();
assert!(format!("{err:?}").contains("Effective trader mismatch"));
}
/// A maker declining arrives as `fail` inside an HTTP 200; the first two bodies are recorded
/// from the live API. Both say the trade is unavailable now, which leaves the route to be
/// priced elsewhere. The third carries the same envelope with the error the API answers an
/// unserved chain with, for what becomes of a code that is not a decline.
#[rstest]
#[case::no_maker_supports_the_request(
r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317477065b24ec0000","error":{"code":82,"message":"No maker supports this request"}}"#,
true,
"No maker supports this request (code 82)"
)]
#[case::below_minimum_amount(
r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317477065b24ec0000","error":{"code":79,"message":"Below minimum amount"}}"#,
true,
"Below minimum amount (code 79)"
)]
#[case::exceeds_supported_amounts(
r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317498228a10fe0000","error":{"code":76,"message":"Exceeds supported amounts"}}"#,
true,
"Exceeds supported amounts (code 76)"
)]
#[case::a_code_that_is_not_a_decline(
r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317477065b24ec0000","error":{"code":42,"message":"Invalid chainId: 130"}}"#,
false,
"Invalid chainId: 130 (code 42)"
)]
#[tokio::test]
async fn only_a_failure_that_is_not_a_decline_is_fatal(
#[case] body: &'static str,
#[case] declined: bool,
#[case] says: &str,
) {
let (server, _) = quote_server(Duration::ZERO, body).await;
let client = create_test_client(server.url(), Duration::from_secs(1));
let error = client
.request_binding_quote(&create_test_quote_params(), "mm1".to_string())
.await
.unwrap_err();
assert!(
if declined {
matches!(error, RFQError::QuoteNotFound(_))
} else {
matches!(error, RFQError::FatalError(_))
},
"{error}"
);
assert!(error.to_string().contains(says), "{error}");
}
#[tokio::test]
async fn request_binding_quote_field_mapping() {
// The wire request carries the receiver as Hashflow's trader, a fresh random address as
// the effectiveTrader — a new one per quote request — and the one maker it goes to.
let (server, request_log) = quote_server(Duration::ZERO, QUOTE_RESPONSE).await;
let client = create_test_client(server.url(), Duration::from_secs(1));
let params = create_test_quote_params();
let first_quote = client
.request_binding_quote(¶ms, "mm1".to_string())
.await
.unwrap();
client
.request_binding_quote(¶ms, "mm1".to_string())
.await
.unwrap();
let requests = request_log.lock().unwrap();
assert_eq!(requests.len(), 2);
for body in requests.iter() {
assert!(
body.contains(&format!("\"trader\":\"{}\"", params.receiver)),
"trader is not the receiver: {body}"
);
assert!(
body.contains(
r#""marketMakers":["mm1"],"options":{"doNotRetryWithOtherMakers":true}"#
),
"request is not pinned to the state's maker: {body}"
);
}
let first = effective_trader_of(&requests[0]);
let second = effective_trader_of(&requests[1]);
assert_eq!(first.len(), 42, "effective trader is not an address");
assert_ne!(first, second, "effective traders are not unique per quote");
assert_ne!(first, params.receiver.to_string(), "effective trader equals the trader");
assert_eq!(
first_quote
.quote_attributes
.get("effective_trader")
.unwrap()
.to_string(),
first,
"quote attributes do not carry the requested effective trader"
);
}
#[tokio::test]
async fn hashflow_quote_timeout() {
let (server, _) = quote_server(Duration::from_millis(500), QUOTE_RESPONSE).await;
// Test 1: Client with short timeout (200ms) - should timeout
let client_short_timeout = create_test_client(server.url(), Duration::from_millis(200));
let params = create_test_quote_params();
// This should timeout after 200ms
let start = std::time::Instant::now();
let result = client_short_timeout
.request_binding_quote(¶ms, "mm1".to_string())
.await;
let elapsed = start.elapsed();
// Verify that we got a timeout error
assert!(result.is_err());
let err = result.unwrap_err();
match err {
RFQError::ConnectionError(msg) => {
assert!(msg.contains("timed out"), "Expected timeout error, got: {}", msg);
}
_ => panic!("Expected ConnectionError, got: {:?}", err),
}
// Should have timed out around 200ms, definitely less than 400ms
assert!(
elapsed.as_millis() >= 200 && elapsed.as_millis() < 400,
"Expected timeout around 200ms, got: {:?}",
elapsed
);
// Test 2: Client with long timeout (1 second) - should wait and receive response
// Note: With retry logic, we may need multiple attempts if the response is malformed,
// so we need a longer timeout to account for retries
let client_long_timeout = create_test_client(server.url(), Duration::from_secs(1));
// This should wait for the response (500ms)
let result = client_long_timeout
.request_binding_quote(¶ms, "mm1".to_string())
.await;
// Should succeed - the server waits 500ms which is within the 1s timeout
assert!(result.is_ok(), "Expected success, got: {:?}", result);
}
#[tokio::test]
async fn hashflow_quote_retry_on_bad_response() {
// The venue answers the first two attempts with a server error and the third with a
// quote.
// The route counts its own attempts, so one test's retries never reach another's.
let attempts = Arc::new(AtomicUsize::new(0));
let server = spawn_http_server(move |request| {
Some(if attempts.fetch_add(1, Ordering::SeqCst) < 2 {
("500 Internal Server Error", "Internal Server Error".to_string())
} else {
(
"200 OK",
QUOTE_RESPONSE
.replace("{{EFFECTIVE_TRADER}}", &effective_trader_of(&request.body)),
)
})
})
.await;
let client = create_test_client(server.url(), Duration::from_secs(5));
let params = create_test_quote_params();
let result = client
.request_binding_quote(¶ms, "mm1".to_string())
.await;
assert!(result.is_ok(), "Expected success after retries, got: {:?}", result);
let quote = result.unwrap();
// Verify the quote is parsed as expected
assert_eq!(quote.amount_in, BigUint::from(1_000000000000000000u64));
assert_eq!(quote.amount_out, BigUint::from(3329502u64));
// Verify exactly 3 requests were made (2 failures + 1 success)
assert_eq!(server.request_count(), 3);
}
/// Both book endpoints ask about the chain under the parameter Hashflow reads it from.
#[tokio::test]
async fn the_book_requests_carry_the_chain_id() {
let targets = Arc::new(Mutex::new(Vec::new()));
let recorded = Arc::clone(&targets);
let server = spawn_http_server(move |request| {
recorded
.lock()
.unwrap()
.push(request.target.to_string());
if request
.target
.starts_with("/taker/v3/market-makers")
{
Some(("200 OK", r#"{"marketMakers":["mm1"]}"#.to_string()))
} else {
Some(("200 OK", r#"{"status":"success","levels":{"mm1":[]}}"#.to_string()))
}
})
.await;
let url = server.url();
let chain_id = Chain::Arbitrum.id();
let client = HashflowLevelsClient::new(
Some(&url),
chain_id,
"test_user".to_string(),
"test_key".to_string(),
);
let makers = client
.fetch_market_makers()
.await
.unwrap();
client
.fetch_price_levels(&makers)
.await
.unwrap();
let targets = targets.lock().unwrap();
assert_eq!(targets.len(), 2, "{targets:?}");
assert!(
targets
.iter()
.all(|target| target.contains(&format!("baseChainId={chain_id}"))),
"{targets:?}"
);
}
/// Unichain (130) is a chain Hashflow does not price, and the words it refuses one with are
/// what this client reads to stop the feed instead of polling on.
#[tokio::test]
#[ignore = "hits Hashflow's live API; requires HASHFLOW_USER and HASHFLOW_KEY"]
async fn live_hashflow_api_refuses_a_chain_it_does_not_price() {
dotenv().ok();
let source = std::env::var("HASHFLOW_USER").expect("HASHFLOW_USER not set");
let auth_key = std::env::var("HASHFLOW_KEY").expect("HASHFLOW_KEY not set");
let client = HashflowLevelsClient::new(None, Chain::Unichain.id(), source, auth_key);
let error = client
.fetch_market_makers()
.await
.unwrap_err();
assert!(error.is_fatal(), "{error}");
}
/// A bad request is ordinarily worth another poll — a maker can vanish between two calls —
/// so only the refusal that names the chain ends the feed.
#[rstest]
#[case::an_unserved_chain(
r#"{"status":"fail","error":{"code":42,"message":"Invalid chainId: 130"}}"#,
true
)]
#[case::an_unknown_market_maker(
r#"{"status":"fail","error":{"code":42,"message":"Unknown market maker: mm1"}}"#,
false
)]
#[tokio::test]
async fn only_the_refusal_naming_the_chain_is_fatal(
#[case] body: &'static str,
#[case] fatal: bool,
) {
let server = spawn_http_server(move |_| Some(("400 Bad Request", body.to_string()))).await;
let url = server.url();
let client = HashflowLevelsClient::new(
Some(&url),
Chain::Unichain.id(),
"test_user".to_string(),
"test_key".to_string(),
);
let error = client
.fetch_market_makers()
.await
.unwrap_err();
assert_eq!(error.is_fatal(), fatal, "{error}");
}
/// Hashflow also carries a failure in the body of a 200, where the same words mean the same
/// thing.
#[rstest]
#[case::an_unserved_chain(
r#"{"status":"fail","error":{"code":42,"message":"Invalid chainId: 130"}}"#,
true
)]
#[case::an_unknown_market_maker(
r#"{"status":"fail","error":{"code":42,"message":"Unknown market maker: mm1"}}"#,
false
)]
#[tokio::test]
async fn a_failure_inside_a_successful_response_is_judged_the_same_way(
#[case] body: &'static str,
#[case] fatal: bool,
) {
let server = spawn_http_server(move |_| Some(("200 OK", body.to_string()))).await;
let url = server.url();
let client = HashflowLevelsClient::new(
Some(&url),
Chain::Unichain.id(),
"test_user".to_string(),
"test_key".to_string(),
);
let error = client
.fetch_price_levels(&["mm1".to_string()])
.await
.unwrap_err();
assert_eq!(error.is_fatal(), fatal, "{error}");
}
}