Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 0 additions & 33 deletions crates/configs/src/price_estimation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,6 @@ use {
url::Url,
};

/// Controls which level of quote verification gets applied.
#[derive(Copy, Clone, Debug, Default, serde::Deserialize)]
#[cfg_attr(any(test, feature = "test-util"), derive(serde::Serialize))]
#[serde(rename_all = "kebab-case")]
pub enum QuoteVerificationMode {
/// Quotes do not get verified.
#[default]
Unverified,
/// Quotes get verified whenever possible and verified
/// quotes are preferred over unverified ones.
Prefer,
}

const fn default_quote_timeout() -> Duration {
Duration::from_secs(5)
}
Expand Down Expand Up @@ -56,10 +43,6 @@ pub struct PriceEstimation {
#[serde(default = "default_quote_inaccuracy_limit")]
pub quote_inaccuracy_limit: BigDecimal,

/// How strict quote verification should be.
#[serde(default)]
pub quote_verification: QuoteVerificationMode,

/// Default timeout for quote requests.
#[serde(with = "humantime_serde", default = "default_quote_timeout")]
pub quote_timeout: Duration,
Expand Down Expand Up @@ -134,7 +117,6 @@ impl Default for PriceEstimation {
one_inch: Default::default(),
coin_gecko: Default::default(),
quote_inaccuracy_limit: default_quote_inaccuracy_limit(),
quote_verification: Default::default(),
quote_timeout: default_quote_timeout(),
max_quote_timeout: default_max_quote_timeout(),
balance_overrides: Default::default(),
Expand All @@ -154,7 +136,6 @@ impl crate::test_util::TestDefault for PriceEstimation {
1_000_000_000_000_000_000u64,
)),
quote_timeout: Duration::from_secs(10),
quote_verification: QuoteVerificationMode::Prefer,
..Default::default()
}
}
Expand Down Expand Up @@ -317,10 +298,6 @@ mod tests {
assert!(config.one_inch.is_none());
assert!(config.coin_gecko.is_none());
assert_eq!(config.quote_inaccuracy_limit, BigDecimal::from(1));
assert!(matches!(
config.quote_verification,
QuoteVerificationMode::Unverified
));
assert_eq!(config.quote_timeout, Duration::from_secs(5));
assert_eq!(config.balance_overrides.probing_depth, 60);
assert_eq!(config.balance_overrides.cache_size, 1000);
Expand All @@ -333,7 +310,6 @@ mod tests {
fn deserialize_full() {
let toml = r#"
quote-inaccuracy-limit = "0.01"
quote-verification = "prefer"
quote-timeout = "10s"
max-quote-timeout = "20s"
tokens-without-verification = ["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"]
Expand Down Expand Up @@ -391,10 +367,6 @@ mod tests {
assert_eq!(buffered.debouncing_time, Duration::from_millis(500));
assert_eq!(buffered.broadcast_channel_capacity, 100);
assert_eq!(config.quote_inaccuracy_limit.to_string(), "0.01");
assert!(matches!(
config.quote_verification,
QuoteVerificationMode::Prefer
));
assert_eq!(config.quote_timeout, Duration::from_secs(10));
assert_eq!(config.max_quote_timeout, Duration::from_secs(20));
assert_eq!(config.balance_overrides.probing_depth, 30);
Expand All @@ -408,16 +380,11 @@ mod tests {
fn roundtrip_serialization() {
let config = PriceEstimation {
quote_timeout: Duration::from_secs(10),
quote_verification: QuoteVerificationMode::Prefer,
..Default::default()
};
let serialized = toml::to_string_pretty(&config).unwrap();
let deserialized: PriceEstimation = toml::from_str(&serialized).unwrap();
assert_eq!(config.quote_timeout, deserialized.quote_timeout);
assert!(matches!(
deserialized.quote_verification,
QuoteVerificationMode::Prefer
));
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion crates/e2e/tests/e2e/replace_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ async fn single_replace_order_test(web3: Web3) {
// orders we override the quote verification to prefer mode.
let orderbook_config = configs::orderbook::Configuration {
price_estimation: configs::price_estimation::PriceEstimation {
quote_verification: configs::price_estimation::QuoteVerificationMode::Prefer,
quote_verification: Default::default(),
..configs::orderbook::Configuration::test_default().price_estimation
},
..configs::orderbook::Configuration::test_default()
Expand Down
24 changes: 3 additions & 21 deletions crates/price-estimation/src/competition/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use {
super::{QuoteVerificationMode, native::NativePriceEstimating},
super::{native::NativePriceEstimating},
crate::PriceEstimationError,
futures::{
future::{BoxFuture, FutureExt},
Expand Down Expand Up @@ -38,7 +38,6 @@ pub struct CompetitionEstimator<T> {
stages: Vec<PriceEstimationStage<T>>,
usable_results_for_early_return: NonZeroUsize,
ranking: PriceRanking,
verification_mode: QuoteVerificationMode,
}

impl<T: Send + Sync + 'static> CompetitionEstimator<T> {
Expand All @@ -49,17 +48,6 @@ impl<T: Send + Sync + 'static> CompetitionEstimator<T> {
stages,
usable_results_for_early_return: NonZeroUsize::MAX,
ranking,
verification_mode: QuoteVerificationMode::Unverified,
}
}

/// Configures if verified price estimates should be ranked higher than
/// unverified ones even if the price is worse.
/// Per default verified quotes do not get preferred.
pub fn with_verification(self, mode: QuoteVerificationMode) -> Self {
Self {
verification_mode: mode,
..self
}
}

Expand Down Expand Up @@ -628,7 +616,6 @@ mod tests {
],
usable_results_for_early_return: NonZeroUsize::new(2).unwrap(),
ranking: PriceRanking::MaxOutAmount,
verification_mode: QuoteVerificationMode::Unverified,
};

let result = racing.estimates(query).await.unwrap().into_vec();
Expand Down Expand Up @@ -836,11 +823,7 @@ mod tests {
assert!(matches!(results[0], Err(PriceEstimationError::RateLimited)));
}

/// Best-so-far under `QuoteVerificationMode::Prefer`: a quote is forwarded
/// only when it ranks better than the best already sent. Errors are dropped
/// mid-stream, and because a verified quote outranks an unverified one
/// regardless of `out_amount` (same as the one-shot competition), a later
/// verified quote supersedes an earlier, higher unverified one.
/// Best-so-far: a quote is forwarded only when it ranks better than the best already sent.
#[tokio::test]
async fn estimate_stream_only_forwards_improving_quotes() {
// Staggered delays make the arrival order deterministic.
Expand Down Expand Up @@ -883,8 +866,7 @@ mod tests {
("verified-worse".to_owned(), quote(30, 150, true)),
]],
PriceRanking::MaxOutAmount,
)
.with_verification(QuoteVerificationMode::Prefer);
);

let results: Vec<_> = estimator.estimate_stream(make_query()).collect().await;

Expand Down
61 changes: 14 additions & 47 deletions crates/price-estimation/src/competition/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use {
PriceEstimating,
PriceEstimationError,
Query,
QuoteVerificationMode,
RankedEstimates,
StreamingPriceEstimating,
},
Expand Down Expand Up @@ -75,7 +74,7 @@ impl CompetitionPriceEstimating for CompetitionEstimator<Arc<dyn PriceEstimating
// Rank all estimates from best to worst so callers can inspect the
// full ordering (e.g. the reference score of the winner).
results.sort_by(|(_, a), (_, b)| {
compare_quote_result(&query, a, b, &context, self.verification_mode).reverse()
compare_quote_result(&query, a, b, &context).reverse()
});

let mut results = results.into_iter();
Expand Down Expand Up @@ -174,7 +173,6 @@ impl StreamingPriceEstimating for CompetitionEstimator<Arc<dyn PriceEstimating>>
&result,
&Ok(best.clone()),
&context,
self.verification_mode,
)
.is_gt()
});
Expand All @@ -197,7 +195,7 @@ impl StreamingPriceEstimating for CompetitionEstimator<Arc<dyn PriceEstimating>>
let terminal = results
.into_iter()
.max_by(|(_, a), (_, b)| {
compare_quote_result(&query, a, b, &context, self.verification_mode)
compare_quote_result(&query, a, b, &context)
});

if let Some((name, result)) = terminal {
Expand Down Expand Up @@ -229,17 +227,17 @@ fn compare_quote_result(
a: &PriceEstimateResult,
b: &PriceEstimateResult,
context: &RankingContext,
verification_mode: QuoteVerificationMode,
) -> Ordering {
let prefer_verified = !matches!(verification_mode, QuoteVerificationMode::Unverified);
match (a, b) {
(Ok(a), Ok(b)) => {
match (prefer_verified, a.verified, b.verified) {
// prefer verified over unverified quotes
(true, true, false) => Ordering::Greater,
(true, false, true) => Ordering::Less,
_ => compare_quote(query, a, b, context),
// Always prefer verified over unverified quotes
if a.verified && !b.verified {
return Ordering::Greater;
}
if !a.verified && b.verified {
return Ordering::Less;
}
compare_quote(query, a, b, context)
}
(Ok(_), Err(_)) => Ordering::Greater,
(Err(_), Ok(_)) => Ordering::Less,
Expand Down Expand Up @@ -397,7 +395,6 @@ mod tests {
CompetitionPriceEstimating,
Estimate,
MockPriceEstimating,
QuoteVerificationMode,
native::MockNativePriceEstimating,
},
alloy::{eips::eip1559::Eip1559Estimation, primitives::U256},
Expand Down Expand Up @@ -451,7 +448,6 @@ mod tests {
kind: OrderKind,
in_amount: u128,
estimates: Vec<PriceEstimateResult>,
verification: QuoteVerificationMode,
) -> Result<Vec<Estimate>, PriceEstimationError> {
fn estimator(estimate: PriceEstimateResult) -> Arc<dyn PriceEstimating> {
let mut estimator = MockPriceEstimating::new();
Expand All @@ -471,8 +467,7 @@ mod tests {
.collect(),
],
ranking.clone(),
)
.with_verification(verification);
);

priority
.estimates(Arc::new(Query {
Expand Down Expand Up @@ -506,7 +501,6 @@ mod tests {
// buy_token => effective receive 99_359.
price(107_999, 2_000),
],
QuoteVerificationMode::Unverified,
)
.await
.unwrap();
Expand All @@ -528,7 +522,6 @@ mod tests {
// User effectively pays `100_002` `sell_token`.
price(92_002, 2_000),
],
QuoteVerificationMode::Unverified,
)
.await
.unwrap();
Expand Down Expand Up @@ -556,7 +549,6 @@ mod tests {
// Would win on raw out_amount, but discarded because gas=0.
price(104_000, 0),
],
QuoteVerificationMode::Unverified,
)
.await
.unwrap();
Expand All @@ -580,7 +572,6 @@ mod tests {
// Would win on raw out_amount, but discarded because gas=0.
price(99_000, 0),
],
QuoteVerificationMode::Unverified,
)
.await
.unwrap();
Expand All @@ -602,7 +593,6 @@ mod tests {
error(PriceEstimationError::RateLimited),
error(PriceEstimationError::ProtocolInternal(anyhow::anyhow!("!"))),
],
QuoteVerificationMode::Unverified,
)
.await
.unwrap_err();
Expand All @@ -621,7 +611,6 @@ mod tests {
price(1, 1_000_000),
error(PriceEstimationError::RateLimited),
],
QuoteVerificationMode::Unverified,
)
.await
.unwrap();
Expand All @@ -643,29 +632,8 @@ mod tests {
..Default::default()
});

// With Prefer: verified quote leads even though price is worse.
let quotes = competition_results(
PriceRanking::MaxOutAmount,
OrderKind::Sell,
1,
vec![
better_unverified_quote.clone(),
worse_verified_quote.clone(),
],
QuoteVerificationMode::Prefer,
)
.await
.unwrap();
assert_eq!(
quotes,
vec![
worse_verified_quote.clone().unwrap(),
better_unverified_quote.clone().unwrap(),
]
);

// Without verification preference: better price leads regardless of
// verification status.
// Verified quotes are always preferred over unverified ones, regardless
// of price. This is unconditional behavior now (no config flag).
let quotes = competition_results(
PriceRanking::MaxOutAmount,
OrderKind::Sell,
Expand All @@ -674,15 +642,14 @@ mod tests {
better_unverified_quote.clone(),
worse_verified_quote.clone(),
],
QuoteVerificationMode::Unverified,
)
.await
.unwrap();
assert_eq!(
quotes,
vec![
better_unverified_quote.clone().unwrap(),
worse_verified_quote.clone().unwrap(),
worse_verified_quote.unwrap(),
better_unverified_quote.unwrap(),
]
);
}
Expand Down
9 changes: 4 additions & 5 deletions crates/price-estimation/src/factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,10 +396,10 @@ impl<'a> PriceEstimatorFactory<'a> {
gas: Arc<dyn GasPriceEstimating>,
) -> Result<Arc<CompetitionEstimator<Arc<dyn PriceEstimating>>>> {
let estimators = self.get_estimators(solvers, |entry| &entry.verified)?;
Ok(Arc::new(
self.sanitized_competition(estimators, PriceRanking::BestBangForBuck { native, gas })
.with_verification(self.args.quote_verification),
))
Ok(Arc::new(self.sanitized_competition(
estimators,
PriceRanking::BestBangForBuck { native, gas },
)))
}

/// Like [`Self::price_estimator`] but without quote verification: all
Expand Down Expand Up @@ -451,7 +451,6 @@ impl<'a> PriceEstimatorFactory<'a> {

let competition_estimator =
CompetitionEstimator::new(estimators, PriceRanking::MaxOutAmount)
.with_verification(self.args.quote_verification)
.with_early_return(results_required);
Ok(Box::new(competition_estimator))
}
Expand Down
1 change: 0 additions & 1 deletion crates/price-estimation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
pub use configs::{
native_price_estimators::{ExternalSolver, NativePriceEstimator, NativePriceEstimators},
price_estimation::QuoteVerificationMode,
};
use {
crate::trade_finding::QuoteExecution,
Expand Down
Loading