1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::U256;
4use num_bigint::BigUint;
5use num_traits::ToPrimitive;
6use serde::{Deserialize, Serialize};
7use tycho_common::{
8 dto::ProtocolStateDelta,
9 models::token::Token,
10 simulation::{
11 errors::{SimulationError, TransitionError},
12 protocol_sim::{
13 Balances, GetAmountOutResult, PoolSwap, Price, ProtocolSim, QueryPoolSwapParams,
14 SwapConstraint,
15 },
16 },
17 Bytes,
18};
19
20use crate::{
21 evm::{
22 protocol::{
23 safe_math::{safe_add_u256, safe_div_u256, safe_mul_u256, safe_sub_u256},
24 u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
25 },
26 query_pool_swap::is_within_tolerance,
27 },
28 utils::decimals_i32,
29};
30
31const WAD: u128 = 1_000_000_000_000_000_000;
32const HALTED: U256 = U256::MAX;
34
35const PSM_SWAP_GAS: u64 = 120_000;
36const WRAPPER_SWAP_GAS: u64 = 220_000;
37const CONVERTER_SWAP_GAS: u64 = 100_000;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
42pub enum SkyComponentKind {
43 Psm,
45 PsmWrapper,
47 Converter,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
55pub struct JoinEscrows {
56 pub dai: U256,
57 pub usds: U256,
58}
59
60#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69#[expect(
70 clippy::partial_pub_fields,
71 reason = "public API; making `component_id` and `kind` private or the rest public is a breaking change"
72)]
73pub struct SkyState {
74 pub component_id: String,
75 pub kind: SkyComponentKind,
76 stable: Token,
78 gem: Token,
81 tin: U256,
83 tout: U256,
85 stable_balance: U256,
86 gem_balance: U256,
87 escrows: Option<JoinEscrows>,
89}
90
91impl SkyState {
92 #[expect(
93 clippy::too_many_arguments,
94 reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
95 )]
96 pub fn new(
97 component_id: String,
98 kind: SkyComponentKind,
99 stable: Token,
100 gem: Token,
101 tin: U256,
102 tout: U256,
103 stable_balance: U256,
104 gem_balance: U256,
105 escrows: Option<JoinEscrows>,
106 ) -> Self {
107 Self { component_id, kind, stable, gem, tin, tout, stable_balance, gem_balance, escrows }
108 }
109
110 fn conversion_factor(&self) -> U256 {
114 U256::from(10).pow(U256::from(self.stable.decimals - self.gem.decimals))
115 }
116
117 fn swap_gas(&self) -> u64 {
118 match self.kind {
119 SkyComponentKind::Psm => PSM_SWAP_GAS,
120 SkyComponentKind::PsmWrapper => WRAPPER_SWAP_GAS,
121 SkyComponentKind::Converter => CONVERTER_SWAP_GAS,
122 }
123 }
124
125 fn is_gem_to_stable(
126 &self,
127 token_in: &Bytes,
128 token_out: &Bytes,
129 ) -> Result<bool, SimulationError> {
130 if *token_in == self.gem.address && *token_out == self.stable.address {
131 Ok(true)
132 } else if *token_in == self.stable.address && *token_out == self.gem.address {
133 Ok(false)
134 } else {
135 Err(SimulationError::InvalidInput(
136 format!("invalid token pair: {token_in}, {token_out}"),
137 None,
138 ))
139 }
140 }
141
142 fn stable_out(&self, gem_in: U256) -> Result<U256, SimulationError> {
144 if self.tin == HALTED {
145 return Err(SimulationError::RecoverableError("sell gem is halted".to_string()));
146 }
147 let stable_wad = safe_mul_u256(gem_in, self.conversion_factor())?;
148 let fee = safe_mul_u256(stable_wad, self.tin)? / U256::from(WAD);
149 safe_sub_u256(stable_wad, fee)
150 }
151
152 fn gem_out(&self, stable_in: U256) -> Result<U256, SimulationError> {
155 if self.tout == HALTED {
156 return Err(SimulationError::RecoverableError("buy gem is halted".to_string()));
157 }
158 let wad = U256::from(WAD);
159 Ok(safe_mul_u256(stable_in, wad)? /
161 safe_mul_u256(self.conversion_factor(), safe_add_u256(wad, self.tout)?)?)
162 }
163
164 fn apply_component_balance_updates(&mut self, balances: &Balances) {
165 let Some(component_balances) = balances
166 .component_balances
167 .get(&self.component_id)
168 else {
169 return;
170 };
171 if let Some(balance) = component_balances.get(&self.stable.address) {
172 self.stable_balance = U256::from_be_slice(balance);
173 }
174 if let Some(balance) = component_balances.get(&self.gem.address) {
175 self.gem_balance = U256::from_be_slice(balance);
176 }
177 }
178
179 fn fee_f64(fee: U256) -> f64 {
180 if fee == HALTED {
181 return 1.0;
182 }
183 u256_to_f64(fee).unwrap_or(f64::MAX) / WAD as f64
184 }
185}
186
187#[typetag::serde]
188impl ProtocolSim for SkyState {
189 fn fee(&self) -> f64 {
190 f64::max(Self::fee_f64(self.tin), Self::fee_f64(self.tout))
191 }
192
193 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
197 if self.is_gem_to_stable(&base.address, "e.address)? {
198 if self.tout == HALTED {
199 return Err(SimulationError::RecoverableError("buy gem is halted".to_string()));
200 }
201 Ok(1.0 + Self::fee_f64(self.tout))
202 } else {
203 if self.tin == HALTED {
204 return Err(SimulationError::RecoverableError("sell gem is halted".to_string()));
205 }
206 Ok(1.0 / (1.0 - Self::fee_f64(self.tin)))
207 }
208 }
209
210 fn get_amount_out(
211 &self,
212 amount_in: BigUint,
213 token_in: &Token,
214 token_out: &Token,
215 ) -> Result<GetAmountOutResult, SimulationError> {
216 let amount_in = biguint_to_u256(&amount_in);
217 let mut new_state = self.clone();
218 let gem_to_stable = self.is_gem_to_stable(&token_in.address, &token_out.address)?;
219
220 let amount_out = if self.kind == SkyComponentKind::Converter {
226 let (sell_escrow, out) = if gem_to_stable {
227 (self.gem_balance, self.stable_out(amount_in)?)
228 } else {
229 (self.stable_balance, self.gem_out(amount_in)?)
230 };
231 if amount_in > sell_escrow {
232 return Err(SimulationError::RecoverableError(format!(
233 "amount in {amount_in} exceeds sell token escrow {sell_escrow}"
234 )));
235 }
236 if gem_to_stable {
237 new_state.gem_balance -= amount_in;
238 new_state.stable_balance += out;
239 } else {
240 new_state.stable_balance -= amount_in;
241 new_state.gem_balance += out;
242 }
243 out
244 } else if gem_to_stable {
245 let out = self.stable_out(amount_in)?;
246 if out > self.stable_balance {
247 return Err(SimulationError::RecoverableError(format!(
248 "amount out {out} exceeds stable inventory {}",
249 self.stable_balance
250 )));
251 }
252 if let Some(escrows) = &mut new_state.escrows {
256 if out > escrows.dai {
257 return Err(SimulationError::RecoverableError(format!(
258 "amount out {out} exceeds DAI join escrow {}",
259 escrows.dai
260 )));
261 }
262 escrows.dai -= out;
263 escrows.usds += out;
264 }
265 new_state.stable_balance -= out;
266 new_state.gem_balance += amount_in;
267 out
268 } else {
269 let out = self.gem_out(amount_in)?;
270 if out > self.gem_balance {
271 return Err(SimulationError::RecoverableError(format!(
272 "amount out {out} exceeds gem inventory {}",
273 self.gem_balance
274 )));
275 }
276 if let Some(escrows) = &mut new_state.escrows {
279 if amount_in > escrows.usds {
280 return Err(SimulationError::RecoverableError(format!(
281 "amount in {amount_in} exceeds USDS join escrow {}",
282 escrows.usds
283 )));
284 }
285 escrows.usds -= amount_in;
286 escrows.dai += amount_in;
287 }
288 new_state.gem_balance -= out;
289 new_state.stable_balance += amount_in;
290 out
291 };
292
293 Ok(GetAmountOutResult {
294 amount: u256_to_biguint(amount_out),
295 gas: BigUint::from(self.swap_gas()),
296 new_state: Box::new(new_state),
297 })
298 }
299
300 fn get_limits(
301 &self,
302 sell_token: Bytes,
303 buy_token: Bytes,
304 ) -> Result<(BigUint, BigUint), SimulationError> {
305 let wad = U256::from(WAD);
306 if self.is_gem_to_stable(&sell_token, &buy_token)? {
307 if self.tin == HALTED {
310 return Ok((BigUint::ZERO, BigUint::ZERO));
311 }
312 if self.kind == SkyComponentKind::Converter {
313 return Ok((u256_to_biguint(self.gem_balance), u256_to_biguint(self.gem_balance)));
314 }
315 let max_out = match &self.escrows {
318 Some(escrows) => self.stable_balance.min(escrows.dai),
319 None => self.stable_balance,
320 };
321 let max_in = safe_div_u256(
322 safe_mul_u256(max_out, wad)?,
323 safe_mul_u256(self.conversion_factor(), safe_sub_u256(wad, self.tin)?)?,
324 )?;
325 Ok((u256_to_biguint(max_in), u256_to_biguint(self.stable_out(max_in)?)))
326 } else {
327 if self.tout == HALTED {
328 return Ok((BigUint::ZERO, BigUint::ZERO));
329 }
330 if self.kind == SkyComponentKind::Converter {
331 return Ok((
332 u256_to_biguint(self.stable_balance),
333 u256_to_biguint(self.stable_balance),
334 ));
335 }
336 let max_out = self.gem_balance;
339 let max_in = safe_mul_u256(
340 safe_mul_u256(max_out, self.conversion_factor())?,
341 safe_add_u256(wad, self.tout)?,
342 )? / wad;
343 if let Some(escrows) = &self.escrows {
344 if escrows.usds < max_in {
345 return Ok((
346 u256_to_biguint(escrows.usds),
347 u256_to_biguint(self.gem_out(escrows.usds)?),
348 ));
349 }
350 }
351 Ok((u256_to_biguint(max_in), u256_to_biguint(max_out)))
352 }
353 }
354
355 fn delta_transition(
356 &mut self,
357 delta: ProtocolStateDelta,
358 _tokens: &HashMap<Bytes, Token>,
359 balances: &Balances,
360 ) -> Result<(), TransitionError> {
361 if let Some(tin) = delta.updated_attributes.get("tin") {
362 self.tin = U256::from_be_slice(tin);
363 }
364 if let Some(tout) = delta.updated_attributes.get("tout") {
365 self.tout = U256::from_be_slice(tout);
366 }
367 if let Some(escrows) = &mut self.escrows {
368 if let Some(dai) = delta
369 .updated_attributes
370 .get("dai_escrow")
371 {
372 escrows.dai = U256::from_be_slice(dai);
373 }
374 if let Some(usds) = delta
375 .updated_attributes
376 .get("usds_escrow")
377 {
378 escrows.usds = U256::from_be_slice(usds);
379 }
380 }
381 self.apply_component_balance_updates(balances);
382 Ok(())
383 }
384
385 fn clone_box(&self) -> Box<dyn ProtocolSim> {
386 Box::new(self.clone())
387 }
388
389 fn as_any(&self) -> &dyn Any {
390 self
391 }
392
393 fn as_any_mut(&mut self) -> &mut dyn Any {
394 self
395 }
396
397 fn eq(&self, other: &dyn ProtocolSim) -> bool {
398 if let Some(other_state) = other
399 .as_any()
400 .downcast_ref::<SkyState>()
401 {
402 self == other_state
403 } else {
404 false
405 }
406 }
407
408 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
420 let token_in = params.token_in();
421 let token_out = params.token_out();
422 let zero_swap =
423 || PoolSwap::new(BigUint::from(0u8), BigUint::from(0u8), self.clone_box(), None);
424
425 match params.swap_constraint() {
426 SwapConstraint::TradeLimitPrice { limit, .. } => {
427 let (max_in, _) =
429 self.get_limits(token_in.address.clone(), token_out.address.clone())?;
430 if max_in == BigUint::from(0u8) {
431 return Ok(zero_swap());
432 }
433 let execution = if self.is_gem_to_stable(&token_in.address, &token_out.address)? {
437 1.0 - Self::fee_f64(self.tin)
438 } else {
439 1.0 / (1.0 + Self::fee_f64(self.tout))
440 };
441 let limit = price_f64(limit, token_in.decimals, token_out.decimals)?;
442 if execution < limit {
443 return Ok(zero_swap());
444 }
445 let result = self.get_amount_out(max_in.clone(), token_in, token_out)?;
448 Ok(PoolSwap::new(max_in, result.amount, result.new_state, None))
449 }
450 SwapConstraint::PoolTargetPrice { target, tolerance, .. } => {
451 let target = price_f64(target, token_in.decimals, token_out.decimals)?;
452 let spot = self.spot_price(token_in, token_out)?;
453 if is_within_tolerance(spot, target, *tolerance) {
454 return Ok(zero_swap());
455 }
456 Err(SimulationError::InvalidInput(
457 format!("spot price {spot} is size-independent; cannot reach target {target}"),
458 None,
459 ))
460 }
461 }
462 }
463}
464
465fn price_f64(price: &Price, in_decimals: u32, out_decimals: u32) -> Result<f64, SimulationError> {
467 Ok(to_f64(&price.numerator, out_decimals)? / to_f64(&price.denominator, in_decimals)?)
468}
469
470fn to_f64(amount: &BigUint, decimals: u32) -> Result<f64, SimulationError> {
471 Ok(amount.to_f64().unwrap_or(f64::MAX) / 10f64.powi(decimals_i32(decimals)?))
472}
473
474#[cfg(test)]
475mod tests {
476 use std::str::FromStr;
477
478 use rstest::rstest;
479 use tycho_common::models::Chain;
480
481 use super::*;
482
483 fn dai() -> Token {
484 Token::new(
485 &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
486 "DAI",
487 18,
488 0,
489 &[Some(50_000)],
490 Chain::Ethereum,
491 100,
492 )
493 }
494
495 fn usdc() -> Token {
496 Token::new(
497 &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
498 "USDC",
499 6,
500 0,
501 &[Some(50_000)],
502 Chain::Ethereum,
503 100,
504 )
505 }
506
507 fn usds() -> Token {
508 Token::new(
509 &Bytes::from_str("0xdc035d45d973e3ec169d2276ddab16f1e407384f").unwrap(),
510 "USDS",
511 18,
512 0,
513 &[Some(50_000)],
514 Chain::Ethereum,
515 100,
516 )
517 }
518
519 fn wad(amount: u64) -> U256 {
520 U256::from(amount) * U256::from(WAD)
521 }
522
523 fn psm_state(tin: U256, tout: U256) -> SkyState {
524 SkyState::new(
525 "0xf6e72db5454dd049d0788e411b06cfaf16853042".to_string(),
526 SkyComponentKind::Psm,
527 dai(),
528 usdc(),
529 tin,
530 tout,
531 wad(1_000_000), U256::from(2_000_000_000_000u64), None,
534 )
535 }
536
537 fn wrapper_state(escrows: JoinEscrows) -> SkyState {
538 SkyState::new(
539 "0xa188eec8f81263234da3622a406892f3d630f98c".to_string(),
540 SkyComponentKind::PsmWrapper,
541 usds(),
542 usdc(),
543 U256::ZERO,
544 U256::ZERO,
545 wad(1_000_000), U256::from(2_000_000_000_000u64), Some(escrows),
548 )
549 }
550
551 fn converter_state() -> SkyState {
552 SkyState::new(
553 "0x3225737a9bbb6473cb4a45b7244aca2befdb276a".to_string(),
554 SkyComponentKind::Converter,
555 dai(),
556 usds(),
557 U256::ZERO,
558 U256::ZERO,
559 wad(3_000_000), wad(9_000_000), None,
562 )
563 }
564
565 #[test]
566 fn sell_gem_fee_free_rescales_decimals() {
567 let state = psm_state(U256::ZERO, U256::ZERO);
568 let res = state
569 .get_amount_out(BigUint::from(1_000_000u64), &usdc(), &dai())
570 .unwrap();
571 assert_eq!(res.amount, BigUint::from(WAD));
573 }
574
575 #[test]
576 fn buy_gem_fee_free_rescales_decimals() {
577 let state = psm_state(U256::ZERO, U256::ZERO);
578 let res = state
579 .get_amount_out(BigUint::from(WAD), &dai(), &usdc())
580 .unwrap();
581 assert_eq!(res.amount, BigUint::from(1_000_000u64));
583 }
584
585 #[test]
586 fn sell_gem_applies_tin() {
587 let state = psm_state(U256::from(WAD / 1000), U256::ZERO);
589 let res = state
590 .get_amount_out(BigUint::from(1_000_000u64), &usdc(), &dai())
591 .unwrap();
592 assert_eq!(res.amount, BigUint::from(WAD - WAD / 1000));
593 }
594
595 #[test]
596 fn buy_gem_applies_tout_and_rounds_down() {
597 let state = psm_state(U256::ZERO, U256::from(WAD / 1000));
599 let res = state
600 .get_amount_out(BigUint::from(WAD), &dai(), &usdc())
601 .unwrap();
602 assert_eq!(res.amount, BigUint::from(999_000u64));
603 let cost = U256::from(999_000u64) * U256::from(1_000_000_000_000u64) * (U256::from(WAD) + U256::from(WAD / 1000)) /
606 U256::from(WAD);
607 assert!(cost <= wad(1));
608 }
609
610 #[test]
611 fn swap_updates_inventory_in_new_state() {
612 let state = psm_state(U256::ZERO, U256::ZERO);
613 let res = state
614 .get_amount_out(BigUint::from(1_000_000u64), &usdc(), &dai())
615 .unwrap();
616 let new_state = res
617 .new_state
618 .as_any()
619 .downcast_ref::<SkyState>()
620 .unwrap()
621 .clone();
622 assert_eq!(new_state.stable_balance, state.stable_balance - U256::from(WAD));
623 assert_eq!(new_state.gem_balance, state.gem_balance + U256::from(1_000_000u64));
624 }
625
626 #[test]
627 fn sell_gem_bounded_by_stable_inventory() {
628 let state = psm_state(U256::ZERO, U256::ZERO);
629 let res = state.get_amount_out(BigUint::from(2_000_000_000_000u64), &usdc(), &dai());
631 assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
632 }
633
634 #[rstest]
635 #[case::sell_gem_halted(HALTED, U256::ZERO, true)]
636 #[case::buy_gem_halted(U256::ZERO, HALTED, false)]
637 fn halted_direction_has_zero_limits(
638 #[case] tin: U256,
639 #[case] tout: U256,
640 #[case] gem_to_stable: bool,
641 ) {
642 let state = psm_state(tin, tout);
643 let (sell, buy) = if gem_to_stable {
644 state
645 .get_limits(usdc().address, dai().address)
646 .unwrap()
647 } else {
648 state
649 .get_limits(dai().address, usdc().address)
650 .unwrap()
651 };
652 assert_eq!(sell, BigUint::ZERO);
653 assert_eq!(buy, BigUint::ZERO);
654 }
655
656 #[test]
657 fn limits_match_inventory() {
658 let state = psm_state(U256::ZERO, U256::ZERO);
659 let (max_in, max_out) = state
660 .get_limits(usdc().address, dai().address)
661 .unwrap();
662 assert_eq!(max_out, u256_to_biguint(wad(1_000_000)));
664 assert_eq!(max_in, BigUint::from(1_000_000_000_000u64));
665
666 let (max_in, max_out) = state
667 .get_limits(dai().address, usdc().address)
668 .unwrap();
669 assert_eq!(max_out, BigUint::from(2_000_000_000_000u64));
671 assert_eq!(max_in, u256_to_biguint(wad(2_000_000)));
672 }
673
674 #[test]
675 fn spot_prices_include_fees_and_round_trip() {
676 let tin = U256::from(WAD / 1000);
677 let tout = U256::from(2 * (WAD / 1000));
678 let state = psm_state(tin, tout);
679 let usdc_in_dai = state
680 .spot_price(&usdc(), &dai())
681 .unwrap();
682 let dai_in_usdc = state
683 .spot_price(&dai(), &usdc())
684 .unwrap();
685 assert!((usdc_in_dai - 1.002).abs() < 1e-12);
688 assert!((dai_in_usdc - 1.0 / 0.999).abs() < 1e-12);
689 assert!(usdc_in_dai * dai_in_usdc >= 1.0);
690 }
691
692 #[test]
693 fn converter_is_symmetric_one_to_one() {
694 let state = converter_state();
695 let res = state
696 .get_amount_out(BigUint::from(WAD), &usds(), &dai())
697 .unwrap();
698 assert_eq!(res.amount, BigUint::from(WAD));
699 let res = state
700 .get_amount_out(BigUint::from(WAD), &dai(), &usds())
701 .unwrap();
702 assert_eq!(res.amount, BigUint::from(WAD));
703 assert_eq!(
704 state
705 .spot_price(&dai(), &usds())
706 .unwrap(),
707 1.0
708 );
709 }
710
711 #[test]
712 fn converter_mints_output_regardless_of_target_escrow() {
713 let state = SkyState::new(
716 "0x3225737a9bbb6473cb4a45b7244aca2befdb276a".to_string(),
717 SkyComponentKind::Converter,
718 dai(),
719 usds(),
720 U256::ZERO,
721 U256::ZERO,
722 wad(3_000_000),
723 U256::ZERO,
724 None,
725 );
726 let res = state
727 .get_amount_out(BigUint::from(WAD), &dai(), &usds())
728 .unwrap();
729 assert_eq!(res.amount, BigUint::from(WAD));
730 let new_state = res
731 .new_state
732 .as_any()
733 .downcast_ref::<SkyState>()
734 .unwrap();
735 assert_eq!(new_state.stable_balance, wad(3_000_000) - U256::from(WAD));
736 assert_eq!(new_state.gem_balance, U256::from(WAD));
737 }
738
739 #[test]
740 fn converter_burn_bounded_by_sell_escrow() {
741 let state = converter_state();
742 let res = state.get_amount_out(u256_to_biguint(wad(9_000_001)), &usds(), &dai());
744 assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
745 }
746
747 #[test]
748 fn converter_limits_use_sell_token_escrow() {
749 let state = converter_state();
750 let (max_in, _) = state
751 .get_limits(dai().address, usds().address)
752 .unwrap();
753 assert_eq!(max_in, u256_to_biguint(wad(3_000_000)));
754 let (max_in, _) = state
755 .get_limits(usds().address, dai().address)
756 .unwrap();
757 assert_eq!(max_in, u256_to_biguint(wad(9_000_000)));
758 }
759
760 #[test]
761 fn wrapper_stable_payout_bounded_by_dai_escrow() {
762 let state = wrapper_state(JoinEscrows { dai: wad(400_000), usds: wad(9_000_000) });
764 let (max_in, max_out) = state
765 .get_limits(usdc().address, usds().address)
766 .unwrap();
767 assert_eq!(max_out, u256_to_biguint(wad(400_000)));
768 assert_eq!(max_in, BigUint::from(400_000_000_000u64));
769
770 let res = state.get_amount_out(BigUint::from(500_000_000_000u64), &usdc(), &usds());
771 assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
772 }
773
774 #[test]
775 fn wrapper_stable_input_bounded_by_usds_escrow() {
776 let state = wrapper_state(JoinEscrows { dai: wad(3_000_000), usds: wad(500_000) });
778 let (max_in, max_out) = state
779 .get_limits(usds().address, usdc().address)
780 .unwrap();
781 assert_eq!(max_in, u256_to_biguint(wad(500_000)));
782 assert_eq!(max_out, BigUint::from(500_000_000_000u64));
783
784 let res = state.get_amount_out(u256_to_biguint(wad(500_001)), &usds(), &usdc());
785 assert!(matches!(res, Err(SimulationError::RecoverableError(_))));
786 }
787
788 #[test]
789 fn wrapper_unbinding_escrows_leave_mirror_limits() {
790 let state = wrapper_state(JoinEscrows { dai: wad(3_000_000), usds: wad(9_000_000) });
791 let (max_in, max_out) = state
792 .get_limits(usds().address, usdc().address)
793 .unwrap();
794 assert_eq!(max_out, BigUint::from(2_000_000_000_000u64));
796 assert_eq!(max_in, u256_to_biguint(wad(2_000_000)));
797 let (_, max_out) = state
798 .get_limits(usdc().address, usds().address)
799 .unwrap();
800 assert_eq!(max_out, u256_to_biguint(wad(1_000_000)));
802 }
803
804 #[test]
805 fn wrapper_zero_usds_escrow_zeroes_buy_gem_limits() {
806 let state = wrapper_state(JoinEscrows { dai: wad(3_000_000), usds: U256::ZERO });
808 let (max_in, max_out) = state
809 .get_limits(usds().address, usdc().address)
810 .unwrap();
811 assert_eq!(max_in, BigUint::ZERO);
812 assert_eq!(max_out, BigUint::ZERO);
813 }
814
815 #[test]
816 fn wrapper_swap_moves_escrows_in_new_state() {
817 let escrows = JoinEscrows { dai: wad(3_000_000), usds: wad(9_000_000) };
818 let state = wrapper_state(escrows);
819
820 let res = state
822 .get_amount_out(BigUint::from(1_000_000u64), &usdc(), &usds())
823 .unwrap();
824 let new_state = res
825 .new_state
826 .as_any()
827 .downcast_ref::<SkyState>()
828 .unwrap();
829 let new_escrows = new_state.escrows.unwrap();
830 assert_eq!(new_escrows.dai, escrows.dai - U256::from(WAD));
831 assert_eq!(new_escrows.usds, escrows.usds + U256::from(WAD));
832
833 let res = state
835 .get_amount_out(BigUint::from(WAD), &usds(), &usdc())
836 .unwrap();
837 let new_state = res
838 .new_state
839 .as_any()
840 .downcast_ref::<SkyState>()
841 .unwrap();
842 let new_escrows = new_state.escrows.unwrap();
843 assert_eq!(new_escrows.usds, escrows.usds - U256::from(WAD));
844 assert_eq!(new_escrows.dai, escrows.dai + U256::from(WAD));
845 }
846
847 #[test]
848 fn delta_transition_updates_escrows() {
849 let mut state = wrapper_state(JoinEscrows { dai: wad(3_000_000), usds: wad(9_000_000) });
850 let delta = ProtocolStateDelta {
851 component_id: state.component_id.clone(),
852 updated_attributes: HashMap::from([
853 ("dai_escrow".to_string(), Bytes::from(wad(5).to_be_bytes_vec())),
854 ("usds_escrow".to_string(), Bytes::from(wad(6).to_be_bytes_vec())),
855 ]),
856 deleted_attributes: Default::default(),
857 };
858 let balances =
859 Balances { component_balances: HashMap::new(), account_balances: HashMap::new() };
860 state
861 .delta_transition(delta, &HashMap::new(), &balances)
862 .unwrap();
863 assert_eq!(state.escrows.unwrap(), JoinEscrows { dai: wad(5), usds: wad(6) });
864 }
865
866 fn usdc_dai_price(dai_wei: u128) -> Price {
868 Price::new(BigUint::from(dai_wei), BigUint::from(1_000_000u32))
869 }
870
871 #[test]
872 fn query_pool_swap_trade_limit_is_all_or_nothing() {
873 let state = psm_state(U256::from(WAD / 1000), U256::ZERO);
875
876 let swap = state
878 .query_pool_swap(&QueryPoolSwapParams::new(
879 usdc(),
880 dai(),
881 SwapConstraint::TradeLimitPrice {
882 limit: usdc_dai_price(990_000_000_000_000_000), tolerance: 0.0,
884 min_amount_in: None,
885 max_amount_in: None,
886 },
887 ))
888 .unwrap();
889 let (max_in, max_out) = state
890 .get_limits(usdc().address, dai().address)
891 .unwrap();
892 assert_eq!(swap.amount_in(), &max_in);
893 assert_eq!(swap.amount_out(), &max_out);
894
895 let swap = state
897 .query_pool_swap(&QueryPoolSwapParams::new(
898 usdc(),
899 dai(),
900 SwapConstraint::TradeLimitPrice {
901 limit: usdc_dai_price(999_500_000_000_000_000), tolerance: 0.0001,
903 min_amount_in: None,
904 max_amount_in: None,
905 },
906 ))
907 .unwrap();
908 assert_eq!(swap.amount_in(), &BigUint::from(0u8));
909 assert_eq!(swap.amount_out(), &BigUint::from(0u8));
910
911 let swap = state
914 .query_pool_swap(&QueryPoolSwapParams::new(
915 usdc(),
916 dai(),
917 SwapConstraint::TradeLimitPrice {
918 limit: usdc_dai_price(999_500_000_000_000_000), tolerance: 0.01,
920 min_amount_in: None,
921 max_amount_in: None,
922 },
923 ))
924 .unwrap();
925 assert_eq!(swap.amount_in(), &BigUint::from(0u8));
926 assert_eq!(swap.amount_out(), &BigUint::from(0u8));
927 }
928
929 #[test]
930 fn query_pool_swap_target_price_only_satisfiable_at_spot() {
931 let state = psm_state(U256::ZERO, U256::from(2 * (WAD / 1000)));
933
934 let swap = state
935 .query_pool_swap(&QueryPoolSwapParams::new(
936 usdc(),
937 dai(),
938 SwapConstraint::PoolTargetPrice {
939 target: usdc_dai_price(1_002_000_000_000_000_000), tolerance: 1e-9,
941 min_amount_in: None,
942 max_amount_in: None,
943 },
944 ))
945 .unwrap();
946 assert_eq!(swap.amount_in(), &BigUint::from(0u8));
947
948 let res = state.query_pool_swap(&QueryPoolSwapParams::new(
949 usdc(),
950 dai(),
951 SwapConstraint::PoolTargetPrice {
952 target: usdc_dai_price(1_010_000_000_000_000_000), tolerance: 1e-9,
954 min_amount_in: None,
955 max_amount_in: None,
956 },
957 ));
958 assert!(matches!(res, Err(SimulationError::InvalidInput(_, _))));
959 }
960
961 #[test]
962 fn delta_transition_updates_fees_and_balances() {
963 let mut state = psm_state(U256::ZERO, U256::ZERO);
964 let delta = ProtocolStateDelta {
965 component_id: state.component_id.clone(),
966 updated_attributes: HashMap::from([(
967 "tin".to_string(),
968 Bytes::from(U256::from(WAD / 100).to_be_bytes_vec()),
969 )]),
970 deleted_attributes: Default::default(),
971 };
972 let balances = Balances {
973 component_balances: HashMap::from([(
974 state.component_id.clone(),
975 HashMap::from([(dai().address, Bytes::from(wad(500_000).to_be_bytes_vec()))]),
976 )]),
977 account_balances: HashMap::new(),
978 };
979 state
980 .delta_transition(delta, &HashMap::new(), &balances)
981 .unwrap();
982 assert_eq!(state.tin, U256::from(WAD / 100));
983 assert_eq!(state.stable_balance, wad(500_000));
984 }
985
986 #[test]
987 fn invalid_pair_errors() {
988 let state = psm_state(U256::ZERO, U256::ZERO);
989 assert!(state
990 .get_amount_out(BigUint::from(1u64), &usds(), &dai())
991 .is_err());
992 }
993}