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