1use num_bigint::BigUint;
6use num_traits::{FromPrimitive, ToPrimitive, Zero};
7use tycho_common::{
8 models::token::Token,
9 simulation::{
10 errors::SimulationError,
11 protocol_sim::{GetAmountOutResult, ProtocolSim},
12 },
13 Bytes,
14};
15
16use crate::book::levels::{Fill, Levels};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum SwapDirection {
21 BaseToQuote,
23 QuoteToBase,
25}
26
27impl SwapDirection {
28 fn detect(base: &Bytes, quote: &Bytes, token_in: &Bytes, token_out: &Bytes) -> Option<Self> {
31 if token_in == base && token_out == quote {
32 Some(SwapDirection::BaseToQuote)
33 } else if token_in == quote && token_out == base {
34 Some(SwapDirection::QuoteToBase)
35 } else {
36 None
37 }
38 }
39
40 pub fn require(
42 base: &Token,
43 quote: &Token,
44 token_in: &Bytes,
45 token_out: &Bytes,
46 ) -> Result<Self, SimulationError> {
47 let (base, quote) = (&base.address, "e.address);
48 Self::detect(base, quote, token_in, token_out).ok_or_else(|| {
49 SimulationError::InvalidInput(
50 format!(
51 "Invalid token addresses. Got in={token_in}, out={token_out}, expected {base} / {quote}"
52 ),
53 None,
54 )
55 })
56 }
57
58 pub fn require_base_to_quote(
61 base: &Token,
62 quote: &Token,
63 token_in: &Bytes,
64 token_out: &Bytes,
65 ) -> Result<(), SimulationError> {
66 let (base, quote) = (&base.address, "e.address);
67 match Self::detect(base, quote, token_in, token_out) {
68 Some(SwapDirection::BaseToQuote) => Ok(()),
69 _ => Err(SimulationError::InvalidInput(
70 format!(
71 "Invalid token addresses. Got in={token_in}, out={token_out}, expected in={base}, out={quote}"
72 ),
73 None,
74 )),
75 }
76 }
77
78 pub fn decimals(self, base: &Token, quote: &Token) -> (u32, u32) {
81 match self {
82 SwapDirection::BaseToQuote => (base.decimals, quote.decimals),
83 SwapDirection::QuoteToBase => (quote.decimals, base.decimals),
84 }
85 }
86}
87
88pub fn quoting_client<'a, C>(
92 client: Option<&'a std::sync::Arc<C>>,
93 venue: &str,
94) -> Result<&'a C, SimulationError> {
95 client
96 .map(|client| client.as_ref())
97 .ok_or_else(|| {
98 SimulationError::FatalError(format!(
99 "This {venue} state carries no client, so it cannot request a quote"
100 ))
101 })
102}
103
104pub fn directions(base: &Token, quote: &Token, bids: bool, asks: bool) -> Vec<(Bytes, Bytes)> {
108 let mut directions = Vec::with_capacity(2);
109 if bids {
110 directions.push((base.address.clone(), quote.address.clone()));
111 }
112 if asks {
113 directions.push((quote.address.clone(), base.address.clone()));
114 }
115 directions
116}
117
118pub fn to_human(amount: &BigUint, decimals: u32) -> f64 {
122 let amount = amount
123 .to_f64()
124 .expect("BigUint::to_f64 saturates to infinity instead of failing");
125 amount / 10f64.powi(decimals as i32)
126}
127
128pub fn to_atomic(amount: f64, decimals: u32) -> Result<BigUint, SimulationError> {
131 BigUint::from_f64(amount * 10f64.powi(decimals as i32))
132 .ok_or_else(|| SimulationError::RecoverableError("Can't convert amount to BigUint".into()))
133}
134
135pub fn fill_result(
139 fill: Fill,
140 amount_in: f64,
141 out_decimals: u32,
142 gas: u64,
143 state: &dyn ProtocolSim,
144) -> Result<GetAmountOutResult, SimulationError> {
145 if fill.remaining_in == amount_in {
148 return Err(SimulationError::InvalidInput(
149 format!("Pool has no liquidity on this side, so {amount_in} cannot be filled"),
150 None,
151 ));
152 }
153 let result = GetAmountOutResult {
154 amount: to_atomic(fill.amount_out, out_decimals)?,
155 gas: BigUint::from(gas),
156 new_state: state.clone_box(),
157 };
158 if fill.is_complete() {
159 Ok(result)
160 } else {
161 Err(SimulationError::InvalidInput(
162 format!(
163 "Pool has not enough liquidity to support complete swap. Input amount: {amount_in}, consumed amount: {}",
164 amount_in - fill.remaining_in
165 ),
166 Some(result),
167 ))
168 }
169}
170
171pub fn marginal_price(
174 levels: &Levels,
175 filled: &BigUint,
176 in_decimals: u32,
177) -> Result<f64, SimulationError> {
178 levels
179 .marginal_price(to_human(filled, in_decimals))
180 .ok_or_else(|| SimulationError::RecoverableError("No liquidity".into()))
181}
182
183pub fn require_positive_amount(amount_in: &BigUint) -> Result<(), SimulationError> {
186 if amount_in.is_zero() {
187 return Err(SimulationError::InvalidInput(
188 "Swap amount must be greater than zero".to_string(),
189 None,
190 ));
191 }
192 Ok(())
193}
194
195pub fn limits(
198 levels: &Levels,
199 in_decimals: u32,
200 out_decimals: u32,
201) -> Result<(BigUint, BigUint), SimulationError> {
202 let (total_in, total_out) = levels.totals();
203 Ok((to_atomic(total_in, in_decimals)?, to_atomic(total_out, out_decimals)?))
204}
205
206#[cfg(test)]
207mod tests {
208 use std::str::FromStr;
209
210 use rstest::rstest;
211 use tycho_common::models::Chain;
212
213 use super::*;
214 use crate::{book::levels::PriceLevel, evm::decoder::MockProtocolSim};
215
216 fn addr(last: u8) -> Bytes {
217 Bytes::from(vec![last; 20])
218 }
219
220 fn token(last: u8, decimals: u32) -> Token {
221 Token::new(&addr(last), &format!("T{last}"), decimals, 0, &[], Chain::Ethereum, 100)
222 }
223
224 #[test]
225 fn detects_both_directions_and_rejects_other_tokens() {
226 let (base, quote, other) = (token(1, 18), token(2, 6), addr(3));
227
228 assert_eq!(
229 SwapDirection::require(&base, "e, &base.address, "e.address).unwrap(),
230 SwapDirection::BaseToQuote
231 );
232 assert_eq!(
233 SwapDirection::require(&base, "e, "e.address, &base.address).unwrap(),
234 SwapDirection::QuoteToBase
235 );
236 assert!(matches!(
237 SwapDirection::require(&base, "e, &base.address, &other),
238 Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
239 ));
240 assert!(matches!(
241 SwapDirection::require_base_to_quote(&base, "e, "e.address, &base.address),
242 Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
243 ));
244 }
245
246 #[test]
247 fn the_direction_says_which_decimals_are_sold_and_bought() {
248 let (base, quote) = (token(1, 18), token(2, 6));
249
250 assert_eq!(SwapDirection::BaseToQuote.decimals(&base, "e), (18, 6));
251 assert_eq!(SwapDirection::QuoteToBase.decimals(&base, "e), (6, 18));
252 }
253
254 #[test]
255 fn converts_between_atomic_and_human_units() {
256 let atomic = BigUint::from_str("1500000").unwrap();
257
258 assert_eq!(to_human(&atomic, 6), 1.5);
259 assert_eq!(to_atomic(1.5, 6).unwrap(), atomic);
260 assert!(to_atomic(-1.0, 6).is_err());
261 assert!(to_atomic(f64::NAN, 6).is_err());
262 }
263
264 fn ladder() -> Levels {
267 Levels::new(vec![
268 PriceLevel { quantity: 1.0, price: 2_000.0 },
269 PriceLevel { quantity: 1.0, price: 2_000.0 },
270 ])
271 .unwrap()
272 }
273
274 fn new_state() -> Box<dyn ProtocolSim> {
275 let mut state = MockProtocolSim::new();
276 state
277 .expect_clone_box()
278 .returning(|| Box::new(MockProtocolSim::new()));
279 Box::new(state)
280 }
281
282 #[test]
283 fn fill_result_attaches_the_partial_result_when_the_ladder_runs_out() {
284 let ladder = ladder();
285
286 let state = new_state();
287 let complete = fill_result(ladder.fill(2.0), 2.0, 6, 100, state.as_ref()).unwrap();
288 assert_eq!(complete.amount, BigUint::from(4_000_000_000u64));
289 assert_eq!(complete.gas, BigUint::from(100u64));
290
291 let partial = fill_result(ladder.fill(3.0), 3.0, 6, 100, state.as_ref());
292 match partial {
293 Err(SimulationError::InvalidInput(message, Some(result))) => {
294 assert!(message.contains("consumed amount: 2"));
295 assert_eq!(result.amount, BigUint::from(4_000_000_000u64));
296 }
297 other => panic!("expected the partially filled result, got {other:?}"),
298 }
299 }
300
301 #[rstest]
308 #[case::eighteen_decimals(18, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
309 #[case::six_decimals(6, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
310 #[case::two_decimals(2, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
311 #[case::round_trip_overshoots(18, &[75559.18038262217])]
312 fn the_reported_limit_fills_completely(#[case] decimals: u32, #[case] quantities: &[f64]) {
313 let ladder = Levels::new(
314 quantities
315 .iter()
316 .map(|&quantity| PriceLevel { price: 1.5, quantity })
317 .collect(),
318 )
319 .unwrap();
320
321 let (sell_limit, _) = limits(&ladder, decimals, 6).unwrap();
322 let fill = ladder.fill(to_human(&sell_limit, decimals));
323
324 assert!(fill.is_complete(), "{decimals} decimals left {} unfilled", fill.remaining_in);
325 }
326
327 #[test]
328 fn limits_are_the_ladder_totals_in_atomic_units() {
329 let ladder = Levels::new(vec![
330 PriceLevel { price: 2.0, quantity: 1.5 },
331 PriceLevel { price: 3.0, quantity: 0.5 },
332 ])
333 .unwrap();
334
335 let (sell, buy) = limits(&ladder, 6, 2).unwrap();
336
337 assert_eq!(sell, BigUint::from(2_000_000u64));
338 assert_eq!(buy, BigUint::from(450u64));
339 }
340}