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 require_positive_amount(amount_in: &BigUint) -> Result<(), SimulationError> {
174 if amount_in.is_zero() {
175 return Err(SimulationError::InvalidInput(
176 "Swap amount must be greater than zero".to_string(),
177 None,
178 ));
179 }
180 Ok(())
181}
182
183pub fn limits(
186 levels: &Levels,
187 in_decimals: u32,
188 out_decimals: u32,
189) -> Result<(BigUint, BigUint), SimulationError> {
190 let (total_in, total_out) = levels.totals();
191 Ok((to_atomic(total_in, in_decimals)?, to_atomic(total_out, out_decimals)?))
192}
193
194#[cfg(test)]
195mod tests {
196 use std::str::FromStr;
197
198 use rstest::rstest;
199 use tycho_common::models::Chain;
200
201 use super::*;
202 use crate::{book::levels::PriceLevel, evm::decoder::MockProtocolSim};
203
204 fn addr(last: u8) -> Bytes {
205 Bytes::from(vec![last; 20])
206 }
207
208 fn token(last: u8, decimals: u32) -> Token {
209 Token::new(&addr(last), &format!("T{last}"), decimals, 0, &[], Chain::Ethereum, 100)
210 }
211
212 #[test]
213 fn detects_both_directions_and_rejects_other_tokens() {
214 let (base, quote, other) = (token(1, 18), token(2, 6), addr(3));
215
216 assert_eq!(
217 SwapDirection::require(&base, "e, &base.address, "e.address).unwrap(),
218 SwapDirection::BaseToQuote
219 );
220 assert_eq!(
221 SwapDirection::require(&base, "e, "e.address, &base.address).unwrap(),
222 SwapDirection::QuoteToBase
223 );
224 assert!(matches!(
225 SwapDirection::require(&base, "e, &base.address, &other),
226 Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
227 ));
228 assert!(matches!(
229 SwapDirection::require_base_to_quote(&base, "e, "e.address, &base.address),
230 Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
231 ));
232 }
233
234 #[test]
235 fn the_direction_says_which_decimals_are_sold_and_bought() {
236 let (base, quote) = (token(1, 18), token(2, 6));
237
238 assert_eq!(SwapDirection::BaseToQuote.decimals(&base, "e), (18, 6));
239 assert_eq!(SwapDirection::QuoteToBase.decimals(&base, "e), (6, 18));
240 }
241
242 #[test]
243 fn converts_between_atomic_and_human_units() {
244 let atomic = BigUint::from_str("1500000").unwrap();
245
246 assert_eq!(to_human(&atomic, 6), 1.5);
247 assert_eq!(to_atomic(1.5, 6).unwrap(), atomic);
248 assert!(to_atomic(-1.0, 6).is_err());
249 assert!(to_atomic(f64::NAN, 6).is_err());
250 }
251
252 fn ladder() -> Levels {
255 Levels::new(vec![
256 PriceLevel { quantity: 1.0, price: 2_000.0 },
257 PriceLevel { quantity: 1.0, price: 2_000.0 },
258 ])
259 .unwrap()
260 }
261
262 fn new_state() -> Box<dyn ProtocolSim> {
263 let mut state = MockProtocolSim::new();
264 state
265 .expect_clone_box()
266 .returning(|| Box::new(MockProtocolSim::new()));
267 Box::new(state)
268 }
269
270 #[test]
271 fn fill_result_attaches_the_partial_result_when_the_ladder_runs_out() {
272 let ladder = ladder();
273
274 let state = new_state();
275 let complete = fill_result(ladder.fill(2.0), 2.0, 6, 100, state.as_ref()).unwrap();
276 assert_eq!(complete.amount, BigUint::from(4_000_000_000u64));
277 assert_eq!(complete.gas, BigUint::from(100u64));
278
279 let partial = fill_result(ladder.fill(3.0), 3.0, 6, 100, state.as_ref());
280 match partial {
281 Err(SimulationError::InvalidInput(message, Some(result))) => {
282 assert!(message.contains("consumed amount: 2"));
283 assert_eq!(result.amount, BigUint::from(4_000_000_000u64));
284 }
285 other => panic!("expected the partially filled result, got {other:?}"),
286 }
287 }
288
289 #[rstest]
296 #[case::eighteen_decimals(18, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
297 #[case::six_decimals(6, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
298 #[case::two_decimals(2, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
299 #[case::round_trip_overshoots(18, &[75559.18038262217])]
300 fn the_reported_limit_fills_completely(#[case] decimals: u32, #[case] quantities: &[f64]) {
301 let ladder = Levels::new(
302 quantities
303 .iter()
304 .map(|&quantity| PriceLevel { price: 1.5, quantity })
305 .collect(),
306 )
307 .unwrap();
308
309 let (sell_limit, _) = limits(&ladder, decimals, 6).unwrap();
310 let fill = ladder.fill(to_human(&sell_limit, decimals));
311
312 assert!(fill.is_complete(), "{decimals} decimals left {} unfilled", fill.remaining_in);
313 }
314
315 #[test]
316 fn limits_are_the_ladder_totals_in_atomic_units() {
317 let ladder = Levels::new(vec![
318 PriceLevel { price: 2.0, quantity: 1.5 },
319 PriceLevel { price: 3.0, quantity: 0.5 },
320 ])
321 .unwrap();
322
323 let (sell, buy) = limits(&ladder, 6, 2).unwrap();
324
325 assert_eq!(sell, BigUint::from(2_000_000u64));
326 assert_eq!(buy, BigUint::from(450u64));
327 }
328}