use std::time::{SystemTime, UNIX_EPOCH};
use alloy::{
primitives::{address, Address, U256},
sol,
sol_types::SolCall,
};
use num_bigint::BigUint;
use num_traits::Zero;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DisplayFromStr};
use tracing::debug;
use tycho_common::{
models::{protocol::GetAmountOutParams, Chain},
Bytes,
};
use crate::{
book::{
levels::{InvalidLevel, Levels, PriceLevel},
wire::{EntryReader, SkipInvalidEntries},
},
evm::protocol::u256_num::u256_to_biguint,
rfq::errors::RFQError,
snapshot_feed::errors::FeedError,
};
sol! {
struct OrderRFQ {
uint256 info;
address makerAsset;
address takerAsset;
address maker;
address allowedSender;
uint256 makingAmount;
uint256 takingAmount;
}
function fillOrderRFQTo(OrderRFQ order, bytes signature, uint256 flagsAndAmount, address target);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EuclidSupportedChain {
Ethereum,
}
impl EuclidSupportedChain {
pub fn id(self) -> u64 {
match self {
EuclidSupportedChain::Ethereum => 1,
}
}
pub fn settlement_router(self) -> Address {
match self {
EuclidSupportedChain::Ethereum => address!("1111111254EEB25477B68fb85Ed929f73A960582"),
}
}
}
impl TryFrom<Chain> for EuclidSupportedChain {
type Error = String;
#[expect(
clippy::wildcard_enum_match_arm,
reason = "Euclid serves one chain; every other, present or future, is refused"
)]
fn try_from(chain: Chain) -> Result<Self, Self::Error> {
match chain {
Chain::Ethereum => Ok(EuclidSupportedChain::Ethereum),
other => Err(format!("Euclid does not serve {other}")),
}
}
}
#[serde_as]
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidLevelsFrame {
pub chain_id: u64,
#[serde_as(deserialize_as = "SkipInvalidEntries")]
pub pairs: Vec<EuclidPairLevels>,
}
#[serde_as]
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidPairLevels {
pub base_address: Bytes,
pub quote_address: Bytes,
#[serde_as(as = "Vec<(DisplayFromStr, DisplayFromStr)>")]
pub bids: Vec<(f64, f64)>,
#[serde_as(as = "Vec<(DisplayFromStr, DisplayFromStr)>")]
pub asks: Vec<(f64, f64)>,
pub timestamp: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EuclidBook {
pub base: Bytes,
pub quote: Bytes,
pub updated_at_ms: u64,
pub bids: Levels,
pub asks: Levels,
}
impl TryFrom<EuclidPairLevels> for EuclidBook {
type Error = InvalidLevel;
fn try_from(pair: EuclidPairLevels) -> Result<Self, InvalidLevel> {
let ladder = |side: Vec<(f64, f64)>| {
Levels::new(
side.into_iter()
.map(|(price, quantity)| PriceLevel { price, quantity })
.collect(),
)
};
Ok(EuclidBook {
bids: ladder(pair.bids)?,
asks: ladder(pair.asks)?,
base: pair.base_address,
quote: pair.quote_address,
updated_at_ms: pair.timestamp,
})
}
}
impl EuclidBook {
pub fn notional_tvl(&self) -> f64 {
(self.bids.notional() + self.asks.notional()) / 2.0
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EuclidPrices {
pub chain_id: u64,
pub pairs: Vec<EuclidBook>,
}
impl EuclidPrices {
pub(super) fn from_frame(frame: EuclidLevelsFrame) -> Result<Self, FeedError> {
let mut reader = EntryReader::new();
let pairs = reader.read(frame.pairs, EuclidBook::try_from);
reader
.finish()
.map_err(|reason| FeedError::Parsing(format!("Euclid levels frame: {reason}")))?;
debug!(pairs = pairs.len(), "decoded levels frame");
Ok(EuclidPrices { chain_id: frame.chain_id, pairs })
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum EuclidFirmResponse {
Quote(EuclidFirmQuote),
Declined(EuclidDeclined),
}
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidFirmQuote {
pub tx_to: Bytes,
pub calldata: Bytes,
pub order_hash: Bytes,
}
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidDeclined {
pub error: String,
}
impl EuclidFirmQuote {
pub fn amount_out(
&self,
chain: EuclidSupportedChain,
params: &GetAmountOutParams,
) -> Result<BigUint, RFQError> {
if self.tx_to.as_ref() != chain.settlement_router().as_slice() {
return Err(RFQError::FatalError(format!(
"Euclid order settles through {}, not the 1inch Aggregation Router v5",
self.tx_to
)));
}
let call = fillOrderRFQToCall::abi_decode(self.calldata.as_ref()).map_err(|e| {
RFQError::FatalError(format!("Euclid calldata is not a fillOrderRFQTo call: {e}"))
})?;
let order = &call.order;
if order.makerAsset.as_slice() != params.token_out.as_ref() {
return Err(RFQError::FatalError(format!(
"Euclid order pays {}, requested {}",
order.makerAsset, params.token_out
)));
}
if order.takerAsset.as_slice() != params.token_in.as_ref() {
return Err(RFQError::FatalError(format!(
"Euclid order takes {}, requested {}",
order.takerAsset, params.token_in
)));
}
let fill = u256_to_biguint(call.flagsAndAmount);
if fill != params.amount_in {
return Err(RFQError::FatalError(format!(
"Euclid calldata fills {fill}, requested {}",
params.amount_in
)));
}
let taking_amount = u256_to_biguint(order.takingAmount);
if fill.is_zero() || fill > taking_amount {
return Err(RFQError::FatalError(format!(
"Euclid calldata fills {fill} of an order taking {taking_amount}"
)));
}
if call.target.as_slice() != params.receiver.as_ref() {
return Err(RFQError::FatalError(format!(
"Euclid order delivers to {}, requested {}",
call.target, params.receiver
)));
}
if order.allowedSender.as_slice() != params.sender.as_ref() {
return Err(RFQError::FatalError(format!(
"Euclid order admits {} as its filler, requested sender {}",
order.allowedSender, params.sender
)));
}
let expiry = ((order.info >> 64usize) & U256::from(u64::MAX)).to::<u64>();
if expiry != 0 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_before_epoch| {
RFQError::FatalError("system clock is before the epoch".to_string())
})?
.as_secs();
if expiry <= now {
return Err(RFQError::QuoteNotFound(format!(
"Euclid order expired at {expiry}, now {now}"
)));
}
}
let amount_out = u256_to_biguint(order.makingAmount) * fill / taking_amount;
if amount_out.is_zero() {
return Err(RFQError::QuoteNotFound(format!(
"Euclid order pays nothing for a fill of {}",
params.amount_in
)));
}
Ok(amount_out)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rstest::rstest;
use super::*;
use crate::rfq::protocols::euclid::test_support::{
bytes, quote_with, recorded_params, LEVELS_FRAME, RECORDED_AMOUNT_OUT, USDC, WETH,
};
#[test]
fn a_recorded_frame_parses_into_validated_books() {
let frame: EuclidLevelsFrame = serde_json::from_str(LEVELS_FRAME).unwrap();
assert_eq!(frame.chain_id, 1);
assert_eq!(frame.pairs.len(), 1);
let book = EuclidBook::try_from(frame.pairs[0].clone()).unwrap();
assert_eq!(book.base, bytes(WETH));
assert_eq!(book.quote, bytes(USDC));
assert_eq!(book.updated_at_ms, 1_794_312_452_328);
let level = |price, quantity| PriceLevel { price, quantity };
assert_eq!(
book.bids[..],
[level(2074.90778485, 0.00096390), level(2074.90778485, 0.00534533)]
);
assert_eq!(
book.asks[..],
[level(2103.07940882, 0.00095099), level(2103.07940882, 0.00152401)]
);
}
#[test]
fn a_pair_that_does_not_parse_is_dropped_and_the_rest_kept() {
let frame = format!(
r#"{{"chain_id":1,"pairs":[
{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["not a price","1"]],"asks":[],"timestamp":1}},
{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","1"]],"asks":[["3001","1"]],"timestamp":2}}
]}}"#
);
let frame: EuclidLevelsFrame = serde_json::from_str(&frame).unwrap();
assert_eq!(frame.pairs.len(), 1);
assert_eq!(frame.pairs[0].timestamp, 2);
}
#[test]
fn a_frame_whose_every_pair_fails_to_parse_is_an_error() {
let frame = format!(
r#"{{"chain_id":1,"pairs":[{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["x","1"]],"asks":[],"timestamp":1}}]}}"#
);
assert!(serde_json::from_str::<EuclidLevelsFrame>(&frame).is_err());
}
#[test]
fn a_frame_with_no_pairs_parses_as_empty() {
let frame: EuclidLevelsFrame =
serde_json::from_str(r#"{"chain_id":1,"timestamp":0,"pairs":[]}"#).unwrap();
assert!(frame.pairs.is_empty());
}
#[rstest]
#[case::negative_size("3000", "-1", InvalidLevel::Quantity(-1.0))]
#[case::zero_price("0", "1", InvalidLevel::Price(0.0))]
fn an_invalid_level_rejects_the_book(
#[case] price: &str,
#[case] size: &str,
#[case] expected: InvalidLevel,
) {
let pair: EuclidPairLevels = serde_json::from_str(&format!(
r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["{price}","{size}"]],"asks":[],"timestamp":1}}"#
))
.unwrap();
assert_eq!(EuclidBook::try_from(pair).unwrap_err(), expected);
}
#[test]
fn prices_keep_the_valid_pairs_of_a_frame() {
let frame = |pairs: &str| -> EuclidLevelsFrame {
serde_json::from_str(&format!(r#"{{"chain_id":1,"pairs":[{pairs}]}}"#)).unwrap()
};
let valid = format!(
r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","1"]],"asks":[["3001","1"]],"timestamp":2}}"#
);
let invalid = format!(
r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","-1"]],"asks":[],"timestamp":1}}"#
);
let prices = EuclidPrices::from_frame(frame(&format!("{invalid},{valid}"))).unwrap();
assert_eq!(prices.chain_id, 1);
assert_eq!(prices.pairs.len(), 1);
assert_eq!(prices.pairs[0].updated_at_ms, 2);
assert!(matches!(EuclidPrices::from_frame(frame(&invalid)), Err(FeedError::Parsing(_))));
assert!(EuclidPrices::from_frame(frame(""))
.unwrap()
.pairs
.is_empty());
}
#[test]
fn prices_survive_a_serde_round_trip() {
let frame: EuclidLevelsFrame = serde_json::from_str(LEVELS_FRAME).unwrap();
let prices = EuclidPrices::from_frame(frame).unwrap();
let sent = serde_json::to_string(&prices).unwrap();
let received: EuclidPrices = serde_json::from_str(&sent).unwrap();
assert_eq!(received, prices);
}
#[test]
fn notional_tvl_is_the_mean_of_both_sides() {
let pair: EuclidPairLevels = serde_json::from_str(&format!(
r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","2"]],"asks":[["3002","1"]],"timestamp":1}}"#
))
.unwrap();
assert_eq!(
EuclidBook::try_from(pair)
.unwrap()
.notional_tvl(),
4501.0
);
}
#[test]
fn a_decline_parses_as_one() {
let response: EuclidFirmResponse =
serde_json::from_str(r#"{"error":"insufficient_liquidity"}"#).unwrap();
assert!(
matches!(response, EuclidFirmResponse::Declined(d) if d.error == "insufficient_liquidity")
);
}
#[test]
fn the_recorded_quote_pays_what_its_order_signs() {
let amount_out = quote_with(|_| {})
.amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
.unwrap();
assert_eq!(amount_out, BigUint::from_str(RECORDED_AMOUNT_OUT).unwrap());
}
#[rstest]
#[case::half(1_500_000_000_000_000, 3_120_846)]
#[case::a_third_and_a_wei(1_000_000_000_000_001, 2_080_564)]
fn a_partial_fill_pays_pro_rata_rounded_down(#[case] fill: u64, #[case] expected: u64) {
let quote = quote_with(|call| call.flagsAndAmount = U256::from(fill));
let params = GetAmountOutParams { amount_in: BigUint::from(fill), ..recorded_params() };
assert_eq!(
quote
.amount_out(EuclidSupportedChain::Ethereum, ¶ms)
.unwrap(),
BigUint::from(expected)
);
}
#[rstest]
#[case::fill_word(
|_: &mut GetAmountOutParams, c: &mut fillOrderRFQToCall| c.flagsAndAmount = U256::from(1u8),
"calldata fills 1, requested 3000000000000000"
)]
#[case::token_in(
|p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.token_in = bytes(USDC),
"order takes"
)]
#[case::token_out(
|p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.token_out = bytes(WETH),
"order pays"
)]
#[case::receiver(
|p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.receiver = bytes(USDC),
"delivers to"
)]
#[case::sender(
|p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.sender = bytes(USDC),
"admits"
)]
fn a_quote_that_disagrees_with_the_request_fails(
#[case] tamper: fn(&mut GetAmountOutParams, &mut fillOrderRFQToCall),
#[case] reason: &str,
) {
let mut params = recorded_params();
let quote = quote_with(|call| tamper(&mut params, call));
let error = quote
.amount_out(EuclidSupportedChain::Ethereum, ¶ms)
.unwrap_err();
assert!(
matches!(&error, RFQError::FatalError(message) if message.contains(reason)),
"expected a failure about {reason:?}, got {error:?}"
);
}
#[test]
fn an_expired_order_is_no_quote() {
let quote = quote_with(|call| {
call.order.info = call.order.info & U256::from(u64::MAX) | (U256::from(1u8) << 64usize);
});
let error = quote
.amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
.unwrap_err();
assert!(
matches!(&error, RFQError::QuoteNotFound(message) if message.contains("expired at 1,")),
"{error:?}"
);
}
#[test]
fn an_order_without_an_expiry_is_quoted() {
let quote = quote_with(|call| call.order.info &= U256::from(u64::MAX));
let amount_out = quote
.amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
.unwrap();
assert_eq!(amount_out, BigUint::from(6_241_692u64));
}
#[test]
fn a_fill_that_pays_nothing_is_no_quote() {
let quote = quote_with(|call| call.flagsAndAmount = U256::from(1u8));
let params = GetAmountOutParams { amount_in: BigUint::from(1u8), ..recorded_params() };
let error = quote
.amount_out(EuclidSupportedChain::Ethereum, ¶ms)
.unwrap_err();
assert!(
matches!(&error, RFQError::QuoteNotFound(message) if message.contains("pays nothing")),
"{error:?}"
);
}
#[rstest]
#[case::over_the_order(|taking: U256| taking + U256::from(1u8))]
#[case::nothing(|_: U256| U256::ZERO)]
fn a_fill_the_order_does_not_cover_fails(#[case] fill: fn(U256) -> U256) {
let mut params = recorded_params();
let quote = quote_with(|call| {
call.flagsAndAmount = fill(call.order.takingAmount);
params.amount_in = u256_to_biguint(call.flagsAndAmount);
});
let error = quote
.amount_out(EuclidSupportedChain::Ethereum, ¶ms)
.unwrap_err();
assert!(
matches!(&error, RFQError::FatalError(message) if message.contains("of an order taking")),
"{error:?}"
);
}
#[rstest]
#[case::selector(|q: &mut EuclidFirmQuote| {
let mut calldata = q.calldata.to_vec();
calldata[0] ^= 0xff;
q.calldata = calldata.into();
}, "not a fillOrderRFQTo call")]
#[case::truncated(|q: &mut EuclidFirmQuote| {
q.calldata = q.calldata[..4 + 9 * 32].to_vec().into();
}, "not a fillOrderRFQTo call")]
#[case::tx_to(|q: &mut EuclidFirmQuote| q.tx_to = bytes(USDC), "settles through")]
fn a_quote_that_is_not_a_router_fill_fails(
#[case] tamper: fn(&mut EuclidFirmQuote),
#[case] reason: &str,
) {
let mut quote = quote_with(|_| {});
tamper(&mut quote);
let error = quote
.amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
.unwrap_err();
assert!(
matches!(&error, RFQError::FatalError(message) if message.contains(reason)),
"expected a failure about {reason:?}, got {error:?}"
);
}
#[test]
fn only_ethereum_is_served() {
assert_eq!(
EuclidSupportedChain::try_from(Chain::Ethereum),
Ok(EuclidSupportedChain::Ethereum)
);
assert!(EuclidSupportedChain::try_from(Chain::Base).is_err());
assert_eq!(EuclidSupportedChain::Ethereum.id(), 1);
}
}