Merge branch 'main' into router/hr/ENG-4237-refactor-usv3-callback
This commit is contained in:
15
CHANGELOG.md
15
CHANGELOG.md
@@ -1,3 +1,18 @@
|
||||
## [0.40.0](https://github.com/propeller-heads/tycho-execution/compare/0.39.0...0.40.0) (2025-02-18)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* (WIP) UniswapV4 encoding ([f32210b](https://github.com/propeller-heads/tycho-execution/commit/f32210bb1f6103a1775975604415295260de9107))
|
||||
* Generalize group_swaps method ([47b6180](https://github.com/propeller-heads/tycho-execution/commit/47b61802eef58068d1188c25db86974c7e03f3a8))
|
||||
* Merge USV4 strategy back into split strategy ([44aabf1](https://github.com/propeller-heads/tycho-execution/commit/44aabf17612994fa126cfdfa4ef7f043b825aeee))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Do not count intermediary tokens in indices ([e94154b](https://github.com/propeller-heads/tycho-execution/commit/e94154bc2d72c312d07eb1aa73a0fd96214ad288))
|
||||
* Do not group split swaps ([957bf89](https://github.com/propeller-heads/tycho-execution/commit/957bf898f28a23dd451d8a0ab07eb221dec1dc11))
|
||||
|
||||
## [0.39.0](https://github.com/propeller-heads/tycho-execution/compare/0.38.0...0.39.0) (2025-02-14)
|
||||
|
||||
|
||||
|
||||
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -4340,7 +4340,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tycho-execution"
|
||||
version = "0.39.0"
|
||||
version = "0.40.0"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"alloy-primitives",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tycho-execution"
|
||||
version = "0.39.0"
|
||||
version = "0.40.0"
|
||||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"ethereum": {
|
||||
"uniswap_v2": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
|
||||
"uniswap_v3": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
|
||||
"uniswap_v4": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
|
||||
"vm:balancer_v2": "0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,16 @@
|
||||
use std::{collections::HashSet, sync::LazyLock};
|
||||
|
||||
pub const DEFAULT_EXECUTORS_JSON: &str =
|
||||
include_str!("../../../src/encoding/config/executor_addresses.json");
|
||||
|
||||
/// These protocols support the optimization of grouping swaps.
|
||||
///
|
||||
/// This requires special encoding to send call data of multiple swaps to a single executor,
|
||||
/// as if it were a single swap. The protocol likely uses flash accounting to save gas on token
|
||||
/// transfers.
|
||||
pub static GROUPABLE_PROTOCOLS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
|
||||
let mut set = HashSet::new();
|
||||
set.insert("uniswap_v4");
|
||||
set.insert("balancer_v3");
|
||||
set
|
||||
});
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod strategy_encoder_registry;
|
||||
mod strategy_encoders;
|
||||
mod strategy_validators;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
552
src/encoding/evm/strategy_encoder/strategy_validators.rs
Normal file
552
src/encoding/evm/strategy_encoder/strategy_validators.rs
Normal file
@@ -0,0 +1,552 @@
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
use tycho_core::Bytes;
|
||||
|
||||
use crate::encoding::{
|
||||
errors::EncodingError,
|
||||
models::{NativeAction, Swap},
|
||||
};
|
||||
|
||||
/// Validates whether a sequence of split swaps represents a valid solution.
|
||||
#[derive(Clone)]
|
||||
pub struct SplitSwapValidator;
|
||||
|
||||
impl SplitSwapValidator {
|
||||
/// Raises an error if the split percentages are invalid.
|
||||
///
|
||||
/// Split percentages are considered valid if all the following conditions are met:
|
||||
/// * Each split amount is < 1 (100%)
|
||||
/// * There is exactly one 0% split for each token, and it's the last swap specified, signifying
|
||||
/// to the router to send the remainder of the token to the designated protocol
|
||||
/// * The sum of all non-remainder splits for each token is < 1 (100%)
|
||||
/// * There are no negative split amounts
|
||||
pub fn validate_split_percentages(&self, swaps: &[Swap]) -> Result<(), EncodingError> {
|
||||
let mut swaps_by_token: HashMap<Bytes, Vec<&Swap>> = HashMap::new();
|
||||
for swap in swaps {
|
||||
if swap.split >= 1.0 {
|
||||
return Err(EncodingError::InvalidInput(format!(
|
||||
"Split percentage must be less than 1 (100%), got {}",
|
||||
swap.split
|
||||
)));
|
||||
}
|
||||
swaps_by_token
|
||||
.entry(swap.token_in.clone())
|
||||
.or_default()
|
||||
.push(swap);
|
||||
}
|
||||
|
||||
for (token, token_swaps) in swaps_by_token {
|
||||
// Single swaps don't need remainder handling
|
||||
if token_swaps.len() == 1 {
|
||||
if token_swaps[0].split != 0.0 {
|
||||
return Err(EncodingError::InvalidInput(format!(
|
||||
"Single swap must have 0% split for token {:?}",
|
||||
token
|
||||
)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut found_zero_split = false;
|
||||
let mut total_percentage = 0.0;
|
||||
for (i, swap) in token_swaps.iter().enumerate() {
|
||||
match (swap.split == 0.0, i == token_swaps.len() - 1) {
|
||||
(true, false) => {
|
||||
return Err(EncodingError::InvalidInput(format!(
|
||||
"The 0% split for token {:?} must be the last swap",
|
||||
token
|
||||
)))
|
||||
}
|
||||
(true, true) => found_zero_split = true,
|
||||
(false, _) => {
|
||||
if swap.split < 0.0 {
|
||||
return Err(EncodingError::InvalidInput(format!(
|
||||
"All splits must be >= 0% for token {:?}",
|
||||
token
|
||||
)));
|
||||
}
|
||||
total_percentage += swap.split;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !found_zero_split {
|
||||
return Err(EncodingError::InvalidInput(format!(
|
||||
"Token {:?} must have exactly one 0% split for remainder handling",
|
||||
token
|
||||
)));
|
||||
}
|
||||
|
||||
// Total must be <100% to leave room for remainder
|
||||
if total_percentage >= 1.0 {
|
||||
return Err(EncodingError::InvalidInput(format!(
|
||||
"Total of non-remainder splits for token {:?} must be <100%, got {}%",
|
||||
token,
|
||||
total_percentage * 100.0
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Raises an error if swaps do not represent a valid path from the given token to the checked
|
||||
/// token.
|
||||
///
|
||||
/// A path is considered valid if all the following conditions are met:
|
||||
/// * The checked token is reachable from the given token through the swap path
|
||||
/// * There are no tokens which are unconnected from the main path
|
||||
///
|
||||
/// If the given token is the native token and the native action is WRAP, it will be converted
|
||||
/// to the wrapped token before validating the swap path. The same principle applies for the
|
||||
/// checked token and the UNWRAP action.
|
||||
pub fn validate_swap_path(
|
||||
&self,
|
||||
swaps: &[Swap],
|
||||
given_token: &Bytes,
|
||||
checked_token: &Bytes,
|
||||
native_action: &Option<NativeAction>,
|
||||
native_address: &Bytes,
|
||||
wrapped_address: &Bytes,
|
||||
) -> Result<(), EncodingError> {
|
||||
// Convert ETH to WETH only if there's a corresponding wrap/unwrap action
|
||||
let given_token = if *given_token == *native_address {
|
||||
match native_action {
|
||||
Some(NativeAction::Wrap) => wrapped_address,
|
||||
_ => given_token,
|
||||
}
|
||||
} else {
|
||||
given_token
|
||||
};
|
||||
|
||||
let checked_token = if *checked_token == *native_address {
|
||||
match native_action {
|
||||
Some(NativeAction::Unwrap) => wrapped_address,
|
||||
_ => checked_token,
|
||||
}
|
||||
} else {
|
||||
checked_token
|
||||
};
|
||||
|
||||
// Build directed graph of token flows
|
||||
let mut graph: HashMap<&Bytes, HashSet<&Bytes>> = HashMap::new();
|
||||
for swap in swaps {
|
||||
graph
|
||||
.entry(&swap.token_in)
|
||||
.or_default()
|
||||
.insert(&swap.token_out);
|
||||
}
|
||||
|
||||
// BFS from validation_given
|
||||
let mut visited = HashSet::new();
|
||||
let mut queue = VecDeque::new();
|
||||
queue.push_back(given_token);
|
||||
|
||||
while let Some(token) = queue.pop_front() {
|
||||
if !visited.insert(token) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Early success check
|
||||
if token == checked_token && visited.len() == graph.len() + 1 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(next_tokens) = graph.get(token) {
|
||||
for &next_token in next_tokens {
|
||||
if !visited.contains(next_token) {
|
||||
queue.push_back(next_token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, either checked_token wasn't reached or not all tokens were visited
|
||||
if !visited.contains(checked_token) {
|
||||
Err(EncodingError::InvalidInput(
|
||||
"Checked token is not reachable through swap path".to_string(),
|
||||
))
|
||||
} else {
|
||||
Err(EncodingError::InvalidInput(
|
||||
"Some tokens are not connected to the main path".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::str::FromStr;
|
||||
|
||||
use tycho_core::{dto::ProtocolComponent, Bytes};
|
||||
|
||||
use super::*;
|
||||
use crate::encoding::models::Swap;
|
||||
|
||||
#[test]
|
||||
fn test_validate_path_single_swap() {
|
||||
let validator = SplitSwapValidator;
|
||||
let eth = Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap();
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
let swaps = vec![Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0f64,
|
||||
}];
|
||||
let result = validator.validate_swap_path(&swaps, &weth, &dai, &None, ð, &weth);
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_path_multiple_swaps() {
|
||||
let validator = SplitSwapValidator;
|
||||
let eth = Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap();
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
let swaps = vec![
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.5f64,
|
||||
},
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: dai.clone(),
|
||||
token_out: usdc.clone(),
|
||||
split: 0f64,
|
||||
},
|
||||
];
|
||||
let result = validator.validate_swap_path(&swaps, &weth, &usdc, &None, ð, &weth);
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_path_disconnected() {
|
||||
let validator = SplitSwapValidator;
|
||||
let eth = Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap();
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
let wbtc = Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599").unwrap();
|
||||
|
||||
let disconnected_swaps = vec![
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.5,
|
||||
},
|
||||
// This swap is disconnected from the WETH->DAI path
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool2".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: wbtc.clone(),
|
||||
token_out: usdc.clone(),
|
||||
split: 0.0,
|
||||
},
|
||||
];
|
||||
let result =
|
||||
validator.validate_swap_path(&disconnected_swaps, &weth, &usdc, &None, ð, &weth);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(EncodingError::InvalidInput(msg)) if msg.contains("not reachable through swap path")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_path_unreachable_checked_token() {
|
||||
let validator = SplitSwapValidator;
|
||||
let eth = Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap();
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
|
||||
let unreachable_swaps = vec![Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 1.0,
|
||||
}];
|
||||
let result =
|
||||
validator.validate_swap_path(&unreachable_swaps, &weth, &usdc, &None, ð, &weth);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(EncodingError::InvalidInput(msg)) if msg.contains("not reachable through swap path")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_path_empty_swaps() {
|
||||
let validator = SplitSwapValidator;
|
||||
let eth = Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap();
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
|
||||
let empty_swaps: Vec<Swap> = vec![];
|
||||
let result = validator.validate_swap_path(&empty_swaps, &weth, &usdc, &None, ð, &weth);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(EncodingError::InvalidInput(msg)) if msg.contains("not reachable through swap path")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_swap_single() {
|
||||
let validator = SplitSwapValidator;
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
let swaps = vec![Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0f64,
|
||||
}];
|
||||
let result = validator.validate_split_percentages(&swaps);
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_swaps_multiple() {
|
||||
let validator = SplitSwapValidator;
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
|
||||
// Valid case: Multiple swaps with proper splits (50%, 30%, remainder)
|
||||
let valid_swaps = vec![
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.5,
|
||||
},
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool2".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.3,
|
||||
},
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool3".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.0, // Remainder (20%)
|
||||
},
|
||||
];
|
||||
assert!(validator
|
||||
.validate_split_percentages(&valid_swaps)
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_swaps_no_remainder_split() {
|
||||
let validator = SplitSwapValidator;
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
|
||||
let invalid_total_swaps = vec![
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.7,
|
||||
},
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool2".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.3,
|
||||
},
|
||||
];
|
||||
assert!(matches!(
|
||||
validator.validate_split_percentages(&invalid_total_swaps),
|
||||
Err(EncodingError::InvalidInput(msg)) if msg.contains("must have exactly one 0% split")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_swaps_zero_split_not_at_end() {
|
||||
let validator = SplitSwapValidator;
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
|
||||
let invalid_zero_position_swaps = vec![
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.0,
|
||||
},
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool2".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.5,
|
||||
},
|
||||
];
|
||||
assert!(matches!(
|
||||
validator.validate_split_percentages(&invalid_zero_position_swaps),
|
||||
Err(EncodingError::InvalidInput(msg)) if msg.contains("must be the last swap")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_swaps_splits_exceed_hundred_percent() {
|
||||
let validator = SplitSwapValidator;
|
||||
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
|
||||
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
|
||||
|
||||
let invalid_overflow_swaps = vec![
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.6,
|
||||
},
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool2".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.5,
|
||||
},
|
||||
Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool3".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: dai.clone(),
|
||||
split: 0.0,
|
||||
},
|
||||
];
|
||||
assert!(matches!(
|
||||
validator.validate_split_percentages(&invalid_overflow_swaps),
|
||||
Err(EncodingError::InvalidInput(msg)) if msg.contains("must be <100%")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_path_wrap_eth_given_token() {
|
||||
let validator = SplitSwapValidator;
|
||||
let eth = Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap();
|
||||
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
|
||||
|
||||
let swaps = vec![Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: weth.clone(),
|
||||
token_out: usdc.clone(),
|
||||
split: 0f64,
|
||||
}];
|
||||
|
||||
let result = validator.validate_swap_path(
|
||||
&swaps,
|
||||
ð,
|
||||
&usdc,
|
||||
&Some(NativeAction::Wrap),
|
||||
ð,
|
||||
&weth,
|
||||
);
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_token_path_connectivity_wrap_eth_checked_token() {
|
||||
let validator = SplitSwapValidator;
|
||||
let eth = Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap();
|
||||
let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
|
||||
|
||||
let swaps = vec![Swap {
|
||||
component: ProtocolComponent {
|
||||
id: "pool1".to_string(),
|
||||
protocol_system: "uniswap_v2".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
token_in: usdc.clone(),
|
||||
token_out: weth.clone(),
|
||||
split: 0f64,
|
||||
}];
|
||||
|
||||
let result = validator.validate_swap_path(
|
||||
&swaps,
|
||||
&usdc,
|
||||
ð,
|
||||
&Some(NativeAction::Unwrap),
|
||||
ð,
|
||||
&weth,
|
||||
);
|
||||
assert_eq!(result, Ok(()));
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@ impl SwapEncoderBuilder {
|
||||
"uniswap_v2" => Ok(Box::new(UniswapV2SwapEncoder::new(self.executor_address))),
|
||||
"vm:balancer_v2" => Ok(Box::new(BalancerV2SwapEncoder::new(self.executor_address))),
|
||||
"uniswap_v3" => Ok(Box::new(UniswapV3SwapEncoder::new(self.executor_address))),
|
||||
// TODO replace this with V4 encoder once implemented
|
||||
"uniswap_v4" => Ok(Box::new(UniswapV2SwapEncoder::new(self.executor_address))),
|
||||
_ => Err(EncodingError::FatalError(format!(
|
||||
"Unknown protocol system: {}",
|
||||
self.protocol_system
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use alloy_primitives::{aliases::U24, Address, Keccak256, U256};
|
||||
use std::cmp::max;
|
||||
|
||||
use alloy_primitives::{aliases::U24, Address, Keccak256, U256, U8};
|
||||
use num_bigint::BigUint;
|
||||
use tycho_core::Bytes;
|
||||
|
||||
use crate::encoding::errors::EncodingError;
|
||||
use crate::encoding::{errors::EncodingError, models::Solution};
|
||||
|
||||
/// Safely converts a `Bytes` object to an `Address` object.
|
||||
///
|
||||
@@ -52,3 +54,40 @@ pub fn percentage_to_uint24(decimal: f64) -> U24 {
|
||||
let scaled = (decimal / 1.0) * (MAX_UINT24 as f64);
|
||||
U24::from(scaled.round())
|
||||
}
|
||||
|
||||
/// Gets the minimum amount out for a solution to pass when executed on-chain.
|
||||
///
|
||||
/// The minimum amount is calculated based on the expected amount and the slippage percentage, if
|
||||
/// passed. If this information is not passed, the user-passed checked amount will be used.
|
||||
/// If both the slippage and minimum user-passed checked amount are passed, the maximum of the two
|
||||
/// will be used.
|
||||
/// If neither are passed, the minimum amount will be zero.
|
||||
pub fn get_min_amount_for_solution(solution: Solution) -> BigUint {
|
||||
let mut min_amount_out = solution
|
||||
.checked_amount
|
||||
.unwrap_or(BigUint::ZERO);
|
||||
|
||||
if let (Some(expected_amount), Some(slippage)) =
|
||||
(solution.expected_amount.as_ref(), solution.slippage)
|
||||
{
|
||||
let one_hundred = BigUint::from(100u32);
|
||||
let slippage_percent = BigUint::from((slippage * 100.0) as u32);
|
||||
let multiplier = &one_hundred - slippage_percent;
|
||||
let expected_amount_with_slippage = (expected_amount * &multiplier) / &one_hundred;
|
||||
min_amount_out = max(min_amount_out, expected_amount_with_slippage);
|
||||
}
|
||||
min_amount_out
|
||||
}
|
||||
|
||||
/// Gets the position of a token in a list of tokens.
|
||||
pub fn get_token_position(tokens: Vec<Bytes>, token: Bytes) -> Result<U8, EncodingError> {
|
||||
let position = U8::from(
|
||||
tokens
|
||||
.iter()
|
||||
.position(|t| *t == token)
|
||||
.ok_or_else(|| {
|
||||
EncodingError::InvalidInput(format!("Token {:?} not found in tokens array", token))
|
||||
})?,
|
||||
);
|
||||
Ok(position)
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ pub enum NativeAction {
|
||||
}
|
||||
|
||||
/// Represents a swap operation to be performed on a pool.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub struct Swap {
|
||||
/// Protocol component from tycho indexer
|
||||
pub component: ProtocolComponent,
|
||||
@@ -111,6 +111,7 @@ pub struct Transaction {
|
||||
/// * `receiver`: Address of the receiver of the out token after the swaps are completed.
|
||||
/// * `exact_out`: true if the solution is a buy order, false if it is a sell order.
|
||||
/// * `router_address`: Address of the router contract to be used for the swaps.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EncodingContext {
|
||||
pub receiver: Bytes,
|
||||
pub exact_out: bool,
|
||||
|
||||
Reference in New Issue
Block a user