Merge branch 'main' into feat/maverick-v2-executor

This commit is contained in:
Tamara
2025-04-29 12:01:20 -04:00
committed by GitHub
57 changed files with 9339 additions and 5667 deletions

View File

@@ -116,8 +116,7 @@ impl Permit2 {
Ok(allowance)
}
Err(err) => Err(EncodingError::RecoverableError(format!(
"Call to permit2 allowance method failed with error: {:?}",
err
"Call to permit2 allowance method failed with error: {err}"
))),
}
}
@@ -158,8 +157,7 @@ impl Permit2 {
.sign_hash_sync(&hash)
.map_err(|e| {
EncodingError::FatalError(format!(
"Failed to sign permit2 approval with error: {}",
e
"Failed to sign permit2 approval with error: {e}"
))
})?;
Ok((permit_single, signature))
@@ -172,7 +170,7 @@ mod tests {
use alloy_primitives::Uint;
use num_bigint::BigUint;
use tycho_common::models::Chain as TychoCoreChain;
use tycho_common::models::Chain as TychoCommonChain;
use super::*;
@@ -208,7 +206,7 @@ mod tests {
}
fn eth_chain() -> Chain {
TychoCoreChain::Ethereum.into()
TychoCommonChain::Ethereum.into()
}
#[test]

View File

@@ -64,8 +64,7 @@ impl ProtocolApprovalsManager {
Ok(allowance.is_zero())
}
Err(err) => Err(EncodingError::RecoverableError(format!(
"Allowance call failed with error: {:?}",
err
"Allowance call failed with error: {err}"
))),
}
}

View File

@@ -13,7 +13,36 @@ pub const PROTOCOL_SPECIFIC_CONFIG: &str =
pub static GROUPABLE_PROTOCOLS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
let mut set = HashSet::new();
set.insert("uniswap_v4");
set.insert("balancer_v3");
set.insert("vm:balancer_v3");
set.insert("ekubo_v2");
set
});
/// These protocols need an external in transfer to the pool. This transfer can be from the router,
/// from the user or from the previous pool. Any protocols that are not defined here expect funds to
/// be in the router at the time of swap and do the transfer themselves from msg.sender
pub static IN_TRANSFER_REQUIRED_PROTOCOLS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
let mut set = HashSet::new();
set.insert("uniswap_v2");
set.insert("sushiswap_v2");
set.insert("pancakeswap_v2");
set.insert("uniswap_v3");
set.insert("pancakeswap_v3");
set.insert("uniswap_v4");
set.insert("ekubo_v2");
set
});
// The protocols here are a subset of the ones defined in IN_TRANSFER_REQUIRED_PROTOCOLS. The tokens
// can not be sent directly from the previous pool into a pool of this protocol. The tokens need to
// be sent to the router and only then transferred into the pool. This is the case for uniswap v3
// because of the callback logic. The only way for this to work it would be to call the second swap
// during the callback of the first swap. This is currently not supported.
pub static CALLBACK_CONSTRAINED_PROTOCOLS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
let mut set = HashSet::new();
set.insert("uniswap_v3");
set.insert("pancakeswap_v3");
set.insert("uniswap_v4");
set.insert("ekubo_v2");
set
});

View File

@@ -1,150 +0,0 @@
use tycho_common::{models::Chain, Bytes};
use crate::encoding::{
errors::EncodingError,
evm::{
strategy_encoder::strategy_encoders::{ExecutorStrategyEncoder, SplitSwapStrategyEncoder},
swap_encoder::swap_encoder_registry::SwapEncoderRegistry,
tycho_encoder::EVMTychoEncoder,
},
strategy_encoder::StrategyEncoder,
};
/// Builder pattern for constructing an `EVMTychoEncoder` with customizable options.
///
/// This struct allows setting a chain and strategy encoder before building the final encoder.
pub struct EVMEncoderBuilder {
strategy: Option<Box<dyn StrategyEncoder>>,
chain: Option<Chain>,
executors_file_path: Option<String>,
router_address: Option<Bytes>,
}
impl Default for EVMEncoderBuilder {
fn default() -> Self {
Self::new()
}
}
impl EVMEncoderBuilder {
pub fn new() -> Self {
EVMEncoderBuilder {
chain: None,
strategy: None,
executors_file_path: None,
router_address: None,
}
}
pub fn chain(mut self, chain: Chain) -> Self {
self.chain = Some(chain);
self
}
/// Sets the `executors_file_path` manually.
/// If it's not set, the default path will be used (config/executor_addresses.json)
pub fn executors_file_path(mut self, executors_file_path: String) -> Self {
self.executors_file_path = Some(executors_file_path);
self
}
/// Sets the `router_address` manually.
/// If it's not set, the default router address will be used (config/router_addresses.json)
pub fn router_address(mut self, router_address: Bytes) -> Self {
self.router_address = Some(router_address);
self
}
/// Sets the `strategy_encoder` manually.
///
/// **Note**: This method should not be used in combination with `tycho_router` or
/// `direct_execution`.
pub fn strategy_encoder(mut self, strategy: Box<dyn StrategyEncoder>) -> Self {
self.strategy = Some(strategy);
self
}
/// Shortcut method to initialize a `SplitSwapStrategyEncoder` without any approval nor token in
/// transfer. **Note**: Should not be used at the same time as `strategy_encoder`.
pub fn initialize_tycho_router(self) -> Result<Self, EncodingError> {
if let Some(chain) = self.chain {
let swap_encoder_registry =
SwapEncoderRegistry::new(self.executors_file_path.clone(), chain)?;
let strategy = Box::new(SplitSwapStrategyEncoder::new(
chain,
swap_encoder_registry,
None,
self.router_address.clone(),
)?);
Ok(EVMEncoderBuilder {
chain: Some(chain),
strategy: Some(strategy),
executors_file_path: self.executors_file_path,
router_address: self.router_address,
})
} else {
Err(EncodingError::FatalError(
"Please set the chain before setting the tycho router".to_string(),
))
}
}
/// Shortcut method to initialize a `SplitSwapStrategyEncoder` with Permit2 approval and token
/// in transfer. **Note**: Should not be used at the same time as `strategy_encoder`.
pub fn initialize_tycho_router_with_permit2(
self,
swapper_pk: String,
) -> Result<Self, EncodingError> {
if let Some(chain) = self.chain {
let swap_encoder_registry =
SwapEncoderRegistry::new(self.executors_file_path.clone(), chain)?;
let strategy = Box::new(SplitSwapStrategyEncoder::new(
chain,
swap_encoder_registry,
Some(swapper_pk),
self.router_address.clone(),
)?);
Ok(EVMEncoderBuilder {
chain: Some(chain),
strategy: Some(strategy),
executors_file_path: self.executors_file_path,
router_address: self.router_address,
})
} else {
Err(EncodingError::FatalError(
"Please set the chain before setting the tycho router".to_string(),
))
}
}
/// Shortcut method to initialize an `ExecutorStrategyEncoder`.
/// **Note**: Should not be used at the same time as `strategy_encoder`.
pub fn initialize_direct_execution(self) -> Result<Self, EncodingError> {
if let Some(chain) = self.chain {
let swap_encoder_registry =
SwapEncoderRegistry::new(self.executors_file_path.clone(), chain)?;
let strategy = Box::new(ExecutorStrategyEncoder::new(swap_encoder_registry));
Ok(EVMEncoderBuilder {
chain: Some(chain),
strategy: Some(strategy),
executors_file_path: self.executors_file_path,
router_address: self.router_address,
})
} else {
Err(EncodingError::FatalError(
"Please set the chain before setting the strategy".to_string(),
))
}
}
/// Builds the `EVMTychoEncoder` instance using the configured chain and strategy.
/// Returns an error if either the chain or strategy has not been set.
pub fn build(self) -> Result<EVMTychoEncoder, EncodingError> {
if let (Some(chain), Some(strategy)) = (self.chain, self.strategy) {
EVMTychoEncoder::new(chain, strategy)
} else {
Err(EncodingError::FatalError(
"Please set the chain and strategy before building the encoder".to_string(),
))
}
}
}

View File

@@ -0,0 +1,155 @@
use std::collections::HashMap;
use tycho_common::{models::Chain as TychoCommonChain, Bytes};
use crate::encoding::{
errors::EncodingError,
evm::{
constants::DEFAULT_ROUTERS_JSON,
swap_encoder::swap_encoder_registry::SwapEncoderRegistry,
tycho_encoders::{TychoExecutorEncoder, TychoRouterEncoder},
},
models::Chain,
tycho_encoder::TychoEncoder,
};
/// Builder pattern for constructing a `TychoRouterEncoder` with customizable options.
///
/// This struct allows setting a chain and strategy encoder before building the final encoder.
pub struct TychoRouterEncoderBuilder {
swapper_pk: Option<String>,
chain: Option<Chain>,
executors_file_path: Option<String>,
router_address: Option<Bytes>,
token_in_already_in_router: Option<bool>,
}
impl Default for TychoRouterEncoderBuilder {
fn default() -> Self {
Self::new()
}
}
impl TychoRouterEncoderBuilder {
pub fn new() -> Self {
TychoRouterEncoderBuilder {
swapper_pk: None,
chain: None,
executors_file_path: None,
router_address: None,
token_in_already_in_router: None,
}
}
pub fn chain(mut self, chain: TychoCommonChain) -> Self {
self.chain = Some(chain.into());
self
}
/// Sets the `executors_file_path` manually.
/// If it's not set, the default path will be used (config/executor_addresses.json)
pub fn executors_file_path(mut self, executors_file_path: String) -> Self {
self.executors_file_path = Some(executors_file_path);
self
}
/// Sets the `router_address` manually.
/// If it's not set, the default router address will be used (config/router_addresses.json)
pub fn router_address(mut self, router_address: Bytes) -> Self {
self.router_address = Some(router_address);
self
}
pub fn swapper_pk(mut self, swapper_pk: String) -> Self {
self.swapper_pk = Some(swapper_pk);
self
}
// Sets the `token_in_already_in_router` flag.
// If set to true, the encoder will assume that the token in is already in the router.
// WARNING: this is an advanced feature and should be used with caution. Make sure you have
// checks to make sure that your tokens won't be lost. The Router is not considered safe to hold
// tokens, so if this is not done within the same transaction you will lose your tokens.
pub fn token_in_already_in_router(mut self, token_in_already_in_router: bool) -> Self {
self.token_in_already_in_router = Some(token_in_already_in_router);
self
}
/// Builds the `TychoRouterEncoder` instance using the configured chain.
/// Returns an error if either the chain has not been set.
pub fn build(self) -> Result<Box<dyn TychoEncoder>, EncodingError> {
if let Some(chain) = self.chain {
let tycho_router_address;
if let Some(address) = self.router_address {
tycho_router_address = address;
} else {
let default_routers: HashMap<String, Bytes> =
serde_json::from_str(DEFAULT_ROUTERS_JSON)?;
tycho_router_address = default_routers
.get(&chain.name)
.ok_or(EncodingError::FatalError(
"No default router address found for chain".to_string(),
))?
.to_owned();
}
let swap_encoder_registry =
SwapEncoderRegistry::new(self.executors_file_path.clone(), chain.clone())?;
Ok(Box::new(TychoRouterEncoder::new(
chain,
swap_encoder_registry,
self.swapper_pk,
tycho_router_address,
self.token_in_already_in_router
.unwrap_or(false),
)?))
} else {
Err(EncodingError::FatalError(
"Please set the chain and router address before building the encoder".to_string(),
))
}
}
}
/// Builder pattern for constructing a `TychoExecutorEncoder` with customizable options.
pub struct TychoExecutorEncoderBuilder {
chain: Option<Chain>,
executors_file_path: Option<String>,
}
impl Default for TychoExecutorEncoderBuilder {
fn default() -> Self {
Self::new()
}
}
impl TychoExecutorEncoderBuilder {
pub fn new() -> Self {
TychoExecutorEncoderBuilder { chain: None, executors_file_path: None }
}
pub fn chain(mut self, chain: TychoCommonChain) -> Self {
self.chain = Some(chain.into());
self
}
/// Sets the `executors_file_path` manually.
/// If it's not set, the default path will be used (config/executor_addresses.json)
pub fn executors_file_path(mut self, executors_file_path: String) -> Self {
self.executors_file_path = Some(executors_file_path);
self
}
/// Builds the `TychoExecutorEncoder` instance using the configured chain and strategy.
/// Returns an error if either the chain or strategy has not been set.
pub fn build(self) -> Result<Box<dyn TychoEncoder>, EncodingError> {
if let Some(chain) = self.chain {
let swap_encoder_registry =
SwapEncoderRegistry::new(self.executors_file_path.clone(), chain.clone())?;
Ok(Box::new(TychoExecutorEncoder::new(chain, swap_encoder_registry)?))
} else {
Err(EncodingError::FatalError(
"Please set the chain and strategy before building the encoder".to_string(),
))
}
}
}

View File

@@ -6,15 +6,15 @@ use crate::encoding::{evm::constants::GROUPABLE_PROTOCOLS, models::Swap};
/// optimization.
///
/// # Fields
/// * `input_token`: Bytes, the input token of the first swap
/// * `output_token`: Bytes, the output token of the final swap
/// * `token_in`: Bytes, the input token of the first swap
/// * `token_out`: Bytes, the output token of the final swap
/// * `protocol_system`: String, the protocol system of the swaps
/// * `swaps`: Vec<Swap>, the sequence of swaps to be executed as a group
/// * `split`: f64, the split percentage of the first swap in the group
#[derive(Clone, PartialEq, Debug)]
pub struct SwapGroup {
pub input_token: Bytes,
pub output_token: Bytes,
pub token_in: Bytes,
pub token_out: Bytes,
pub protocol_system: String,
pub swaps: Vec<Swap>,
pub split: f64,
@@ -44,7 +44,7 @@ pub fn group_swaps(swaps: Vec<Swap>) -> Vec<SwapGroup> {
if let Some(group) = current_group.as_mut() {
group.swaps.push(swap.clone());
// Update the output token of the current group.
group.output_token = swap.token_out.clone();
group.token_out = swap.token_out.clone();
}
} else {
// Not second or later USV4 pool. Push the current group (if it exists) and then
@@ -53,8 +53,8 @@ pub fn group_swaps(swaps: Vec<Swap>) -> Vec<SwapGroup> {
grouped_swaps.push(group.clone());
}
current_group = Some(SwapGroup {
input_token: swap.token_in.clone(),
output_token: swap.token_out.clone(),
token_in: swap.token_in.clone(),
token_out: swap.token_out.clone(),
protocol_system: current_swap_protocol.clone(),
swaps: vec![swap.clone()],
split: swap.split,
@@ -135,15 +135,15 @@ mod tests {
vec![
SwapGroup {
swaps: vec![swap_weth_wbtc, swap_wbtc_usdc],
input_token: weth,
output_token: usdc.clone(),
token_in: weth,
token_out: usdc.clone(),
protocol_system: "uniswap_v4".to_string(),
split: 0f64,
},
SwapGroup {
swaps: vec![swap_usdc_dai],
input_token: usdc,
output_token: dai,
token_in: usdc,
token_out: dai,
protocol_system: "uniswap_v2".to_string(),
split: 0f64,
}
@@ -216,22 +216,22 @@ mod tests {
vec![
SwapGroup {
swaps: vec![swap_wbtc_weth],
input_token: wbtc.clone(),
output_token: weth.clone(),
token_in: wbtc.clone(),
token_out: weth.clone(),
protocol_system: "uniswap_v4".to_string(),
split: 0f64,
},
SwapGroup {
swaps: vec![swap_weth_usdc],
input_token: weth.clone(),
output_token: usdc.clone(),
token_in: weth.clone(),
token_out: usdc.clone(),
protocol_system: "uniswap_v4".to_string(),
split: 0.5f64,
},
SwapGroup {
swaps: vec![swap_weth_dai, swap_dai_usdc],
input_token: weth,
output_token: usdc,
token_in: weth,
token_out: usdc,
protocol_system: "uniswap_v4".to_string(),
split: 0f64,
}
@@ -255,7 +255,7 @@ mod tests {
let swap_weth_wbtc = Swap {
component: ProtocolComponent {
protocol_system: "balancer_v3".to_string(),
protocol_system: "vm:balancer_v3".to_string(),
..Default::default()
},
token_in: weth.clone(),
@@ -264,7 +264,7 @@ mod tests {
};
let swap_wbtc_usdc = Swap {
component: ProtocolComponent {
protocol_system: "balancer_v3".to_string(),
protocol_system: "vm:balancer_v3".to_string(),
..Default::default()
},
token_in: wbtc.clone(),
@@ -304,15 +304,15 @@ mod tests {
vec![
SwapGroup {
swaps: vec![swap_weth_wbtc, swap_wbtc_usdc],
input_token: weth.clone(),
output_token: usdc.clone(),
protocol_system: "balancer_v3".to_string(),
token_in: weth.clone(),
token_out: usdc.clone(),
protocol_system: "vm:balancer_v3".to_string(),
split: 0.5f64,
},
SwapGroup {
swaps: vec![swap_weth_dai, swap_dai_usdc],
input_token: weth,
output_token: usdc,
token_in: weth,
token_out: usdc,
protocol_system: "uniswap_v4".to_string(),
split: 0f64,
}

View File

@@ -1,7 +1,8 @@
pub mod approvals;
mod constants;
pub mod encoder_builder;
pub mod encoder_builders;
mod group_swaps;
pub mod strategy_encoder;
mod swap_encoder;
pub mod tycho_encoder;
pub mod tycho_encoders;
pub mod utils;

View File

@@ -1,3 +1,4 @@
mod group_swaps;
pub mod strategy_encoders;
mod strategy_validators;
mod transfer_optimizations;

File diff suppressed because it is too large Load Diff

View File

@@ -7,92 +7,10 @@ use crate::encoding::{
models::{NativeAction, Solution, 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(())
}
pub trait SwapValidator {
/// Raises an error if the solution does not have checked amount set or slippage with checked
/// amount set.
pub fn validate_solution_min_amounts(&self, solution: &Solution) -> Result<(), EncodingError> {
fn validate_solution_min_amounts(&self, solution: &Solution) -> Result<(), EncodingError> {
if solution.checked_amount.is_none() &&
(solution.slippage.is_none() || solution.expected_amount.is_none())
{
@@ -113,7 +31,7 @@ impl SplitSwapValidator {
/// 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(
fn validate_swap_path(
&self,
swaps: &[Swap],
given_token: &Bytes,
@@ -197,6 +115,94 @@ impl SplitSwapValidator {
}
}
/// Validates whether a sequence of split swaps represents a valid solution.
#[derive(Clone)]
pub struct SplitSwapValidator;
impl SwapValidator for 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 {token} must be the last swap",
)))
}
(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 {token} must have exactly one 0% split for remainder handling"
)));
}
// 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(())
}
}
/// Validates whether a sequence of sequential swaps represents a valid solution.
#[derive(Clone)]
pub struct SequentialSwapValidator;
impl SwapValidator for SequentialSwapValidator {}
#[cfg(test)]
mod tests {
use std::str::FromStr;

View File

@@ -0,0 +1,352 @@
use std::str::FromStr;
use tycho_common::Bytes;
use crate::encoding::{
errors::EncodingError,
evm::{
constants::{CALLBACK_CONSTRAINED_PROTOCOLS, IN_TRANSFER_REQUIRED_PROTOCOLS},
group_swaps::SwapGroup,
},
models::TransferType,
};
/// A struct that defines how the tokens will be transferred into the given pool given the solution.
#[derive(Clone)]
pub struct TransferOptimization {
native_token: Bytes,
wrapped_token: Bytes,
permit2: bool,
token_in_already_in_router: bool,
router_address: Bytes,
}
impl TransferOptimization {
pub fn new(
native_token: Bytes,
wrapped_token: Bytes,
permit2: bool,
token_in_already_in_router: bool,
router_address: Bytes,
) -> Self {
TransferOptimization {
native_token,
wrapped_token,
permit2,
token_in_already_in_router,
router_address,
}
}
/// Returns the transfer method that should be used for the given swap and solution.
pub fn get_transfer_type(
&self,
swap: SwapGroup,
given_token: Bytes,
wrap: bool,
in_between_swap_optimization: bool,
) -> TransferType {
let in_transfer_required: bool =
IN_TRANSFER_REQUIRED_PROTOCOLS.contains(&swap.protocol_system.as_str());
let is_first_swap = swap.token_in == given_token;
if swap.token_in == self.native_token {
// Funds are already in router. All protocols currently take care of native transfers.
TransferType::None
} else if (swap.token_in == self.wrapped_token) && wrap {
// Wrapping already happened in the router so we can just use a normal transfer.
TransferType::TransferToProtocol
} else if is_first_swap {
if in_transfer_required {
if self.token_in_already_in_router {
// Transfer from router to pool.
TransferType::TransferToProtocol
} else if self.permit2 {
// Transfer from swapper to pool using permit2.
TransferType::TransferPermit2ToProtocol
} else {
// Transfer from swapper to pool.
TransferType::TransferFromToProtocol
}
// in transfer is not necessary for these protocols. Only make a transfer if the
// tokens are not already in the router
} else if !self.token_in_already_in_router {
if self.permit2 {
// Transfer from swapper to router using permit2.
TransferType::TransferPermit2ToRouter
} else {
// Transfer from swapper to router.
TransferType::TransferFromToRouter
}
} else {
TransferType::None
}
// all other swaps
} else if !in_transfer_required || in_between_swap_optimization {
// funds should already be in the router or in the next pool
TransferType::None
} else {
TransferType::TransferToProtocol
}
}
// Returns the optimized receiver of the swap. This is used to chain swaps together and avoid
// unnecessary token transfers.
// Returns the receiver address and a boolean indicating whether the receiver is optimized (this
// is necessary for the next swap transfer type decision).
pub fn get_receiver(
&self,
solution_receiver: Bytes,
next_swap: Option<&SwapGroup>,
) -> Result<(Bytes, bool), EncodingError> {
if let Some(next) = next_swap {
// if the protocol of the next swap supports transfer in optimization
if IN_TRANSFER_REQUIRED_PROTOCOLS.contains(&next.protocol_system.as_str()) {
// if the protocol does not allow for chained swaps, we can't optimize the
// receiver of this swap nor the transfer in of the next swap
if CALLBACK_CONSTRAINED_PROTOCOLS.contains(&next.protocol_system.as_str()) {
Ok((self.router_address.clone(), false))
} else {
Ok((
Bytes::from_str(&next.swaps[0].component.id.clone()).map_err(|_| {
EncodingError::FatalError("Invalid component id".to_string())
})?,
true,
))
}
} else {
// the protocol of the next swap does not support transfer in optimization
Ok((self.router_address.clone(), false))
}
} else {
// last swap - there is no next swap
Ok((solution_receiver, false))
}
}
}
#[cfg(test)]
mod tests {
use alloy_primitives::hex;
use rstest::rstest;
use tycho_common::models::protocol::ProtocolComponent;
use super::*;
use crate::encoding::models::Swap;
fn weth() -> Bytes {
Bytes::from(hex!("c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").to_vec())
}
fn eth() -> Bytes {
Bytes::from(hex!("0000000000000000000000000000000000000000").to_vec())
}
fn dai() -> Bytes {
Bytes::from(hex!("6b175474e89094c44da98b954eedeac495271d0f").to_vec())
}
fn usdc() -> Bytes {
Bytes::from(hex!("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").to_vec())
}
fn router_address() -> Bytes {
Bytes::from("0x5615deb798bb3e4dfa0139dfa1b3d433cc23b72f")
}
#[test]
fn test_first_swap_transfer_from_permit2() {
// The swap token is the same as the given token, which is not the native token
let swap = SwapGroup {
protocol_system: "uniswap_v2".to_string(),
token_in: weth(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), true, false, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), weth(), false, false);
assert_eq!(transfer_method, TransferType::TransferPermit2ToProtocol);
}
#[test]
fn test_first_swap_transfer_from() {
// The swap token is the same as the given token, which is not the native token
let swap = SwapGroup {
protocol_system: "uniswap_v2".to_string(),
token_in: weth(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, false, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), weth(), false, false);
assert_eq!(transfer_method, TransferType::TransferFromToProtocol);
}
#[test]
fn test_first_swap_native() {
// The swap token is the same as the given token, and it's the native token.
// No transfer action is needed.
let swap = SwapGroup {
protocol_system: "uniswap_v2".to_string(),
token_in: eth(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, false, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), eth(), false, false);
assert_eq!(transfer_method, TransferType::None);
}
#[test]
fn test_first_swap_wrapped() {
// The swap token is NOT the same as the given token, but we are wrapping.
// Since the swap's token in is the wrapped token - this is the first swap.
let swap = SwapGroup {
protocol_system: "uniswap_v2".to_string(),
token_in: weth(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, false, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), eth(), true, false);
assert_eq!(transfer_method, TransferType::TransferToProtocol);
}
#[test]
fn test_not_first_swap() {
// The swap token is NOT the same as the given token, and we are NOT wrapping.
// Thus, this is not the first swap.
let swap = SwapGroup {
protocol_system: "uniswap_v2".to_string(),
token_in: usdc(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, false, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), weth(), false, false);
assert_eq!(transfer_method, TransferType::TransferToProtocol);
}
#[test]
fn test_not_first_swap_funds_in_router() {
// Not the first swap and the protocol requires the funds to be in the router (which they
// already are, so the transfer type is None)
let swap = SwapGroup {
protocol_system: "vm:curve".to_string(),
token_in: usdc(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, false, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), weth(), false, false);
assert_eq!(transfer_method, TransferType::None);
}
#[test]
fn test_not_first_swap_in_between_swap_optimization() {
// Not the first swap and the in between swaps are optimized. The funds should already be in
// the next pool or in the router
let swap = SwapGroup {
protocol_system: "uniswap_v2".to_string(),
token_in: usdc(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, false, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), weth(), false, true);
assert_eq!(transfer_method, TransferType::None);
}
#[test]
fn test_first_swap_tokens_already_in_router_optimization() {
// It is the first swap, tokens are already in the router and the protocol requires the
// transfer in
let swap = SwapGroup {
protocol_system: "uniswap_v2".to_string(),
token_in: usdc(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, true, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), usdc(), false, false);
assert_eq!(transfer_method, TransferType::TransferToProtocol);
}
#[test]
fn test_first_swap_tokens_already_in_router_no_transfer_needed_optimization() {
// It is the first swap, tokens are already in the router and the protocol does not require
// the transfer in
let swap = SwapGroup {
protocol_system: "vm:curve".to_string(),
token_in: usdc(),
token_out: dai(),
split: 0f64,
swaps: vec![],
};
let optimization = TransferOptimization::new(eth(), weth(), false, true, router_address());
let transfer_method = optimization.get_transfer_type(swap.clone(), usdc(), false, false);
assert_eq!(transfer_method, TransferType::None);
}
fn receiver() -> Bytes {
Bytes::from("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2")
}
fn component_id() -> Bytes {
Bytes::from("0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11")
}
#[rstest]
// there is no next swap -> receiver is the solution receiver
#[case(None, receiver(), false)]
// protocol of next swap supports transfer in optimization
#[case(Some("uniswap_v2"), component_id(), true)]
// protocol of next swap supports transfer in optimization but is callback constrained
#[case(Some("uniswap_v3"), router_address(), false)]
// protocol of next swap does not support transfer in optimization
#[case(Some("vm:curve"), router_address(), false)]
fn test_get_receiver(
#[case] protocol: Option<&str>,
#[case] expected_receiver: Bytes,
#[case] expected_optimization: bool,
) {
let optimization = TransferOptimization::new(eth(), weth(), false, false, router_address());
let next_swap = if protocol.is_none() {
None
} else {
Some(SwapGroup {
protocol_system: protocol.unwrap().to_string(),
token_in: usdc(),
token_out: dai(),
split: 0f64,
swaps: vec![Swap {
component: ProtocolComponent {
protocol_system: protocol.unwrap().to_string(),
id: component_id().to_string(),
..Default::default()
},
token_in: usdc(),
token_out: dai(),
split: 0f64,
}],
})
};
let result = optimization.get_receiver(receiver(), next_swap.as_ref());
assert!(result.is_ok());
let (actual_receiver, optimization_flag) = result.unwrap();
assert_eq!(actual_receiver, expected_receiver);
assert_eq!(optimization_flag, expected_optimization);
}
}

View File

@@ -20,16 +20,11 @@ pub struct SwapEncoderRegistry {
impl SwapEncoderRegistry {
/// Populates the registry with the `SwapEncoders` for the given blockchain by parsing the
/// executors' addresses in the file at the given path.
pub fn new(
executors_file_path: Option<String>,
blockchain: tycho_common::models::Chain,
) -> Result<Self, EncodingError> {
let chain = Chain::from(blockchain);
pub fn new(executors_file_path: Option<String>, chain: Chain) -> Result<Self, EncodingError> {
let config_str = if let Some(ref path) = executors_file_path {
fs::read_to_string(path).map_err(|e| {
EncodingError::FatalError(format!(
"Error reading executors file from {:?}: {}",
executors_file_path, e
"Error reading executors file from {executors_file_path:?}: {e}",
))
})?
} else {

File diff suppressed because it is too large Load Diff

View File

@@ -1,720 +0,0 @@
use std::collections::HashSet;
use num_bigint::BigUint;
use tycho_common::Bytes;
use crate::encoding::{
errors::EncodingError,
models::{Chain, NativeAction, Solution, Transaction},
strategy_encoder::StrategyEncoder,
tycho_encoder::TychoEncoder,
};
/// Represents an encoder for a swap using any strategy supported by the strategy registry.
///
/// # Fields
/// * `strategy_encoder`: Strategy encoder to follow for encoding the solution
/// * `native_address`: Address of the chain's native token
/// * `wrapped_address`: Address of the chain's wrapped native token
pub struct EVMTychoEncoder {
strategy_encoder: Box<dyn StrategyEncoder>,
native_address: Bytes,
wrapped_address: Bytes,
}
impl Clone for EVMTychoEncoder {
fn clone(&self) -> Self {
Self {
strategy_encoder: self.strategy_encoder.clone_box(),
native_address: self.native_address.clone(),
wrapped_address: self.wrapped_address.clone(),
}
}
}
impl EVMTychoEncoder {
pub fn new(
chain: tycho_common::models::Chain,
strategy_encoder: Box<dyn StrategyEncoder>,
) -> Result<Self, EncodingError> {
let chain: Chain = Chain::from(chain);
let native_address = chain.native_token()?;
let wrapped_address = chain.wrapped_token()?;
Ok(EVMTychoEncoder { strategy_encoder, native_address, wrapped_address })
}
}
impl EVMTychoEncoder {
/// Raises an `EncodingError` if the solution is not considered valid.
///
/// A solution is considered valid if all the following conditions are met:
/// * The solution is not exact out.
/// * The solution has at least one swap.
/// * If the solution is wrapping, the given token is the chain's native token and the first
/// swap's input is the chain's wrapped token.
/// * If the solution is unwrapping, the checked token is the chain's native token and the last
/// swap's output is the chain's wrapped token.
/// * The token cannot appear more than once in the solution unless it is the first and last
/// token (i.e. a true cyclical swap).
fn validate_solution(&self, solution: &Solution) -> Result<(), EncodingError> {
if solution.exact_out {
return Err(EncodingError::FatalError(
"Currently only exact input solutions are supported".to_string(),
));
}
if solution.swaps.is_empty() {
return Err(EncodingError::FatalError("No swaps found in solution".to_string()));
}
if let Some(native_action) = solution.clone().native_action {
if native_action == NativeAction::Wrap {
if solution.given_token != self.native_address {
return Err(EncodingError::FatalError(
"Native token must be the input token in order to wrap".to_string(),
));
}
if let Some(first_swap) = solution.swaps.first() {
if first_swap.token_in != self.wrapped_address {
return Err(EncodingError::FatalError(
"Wrapped token must be the first swap's input in order to wrap"
.to_string(),
));
}
}
} else if native_action == NativeAction::Unwrap {
if solution.checked_token != self.native_address {
return Err(EncodingError::FatalError(
"Native token must be the output token in order to unwrap".to_string(),
));
}
if let Some(last_swap) = solution.swaps.last() {
if last_swap.token_out != self.wrapped_address {
return Err(EncodingError::FatalError(
"Wrapped token must be the last swap's output in order to unwrap"
.to_string(),
));
}
}
}
}
let mut solution_tokens = vec![];
let mut split_tokens_already_considered = HashSet::new();
for (i, swap) in solution.swaps.iter().enumerate() {
// so we don't count the split tokens more than once
if swap.split != 0.0 {
if !split_tokens_already_considered.contains(&swap.token_in) {
solution_tokens.push(swap.token_in.clone());
split_tokens_already_considered.insert(swap.token_in.clone());
}
} else {
// it might be the last swap of the split or a regular swap
if !split_tokens_already_considered.contains(&swap.token_in) {
solution_tokens.push(swap.token_in.clone());
}
}
if i == solution.swaps.len() - 1 {
solution_tokens.push(swap.token_out.clone());
}
}
if solution_tokens.len() !=
solution_tokens
.iter()
.cloned()
.collect::<HashSet<Bytes>>()
.len()
{
if let Some(last_swap) = solution.swaps.last() {
if solution.swaps[0].token_in != last_swap.token_out {
return Err(EncodingError::FatalError(
"Cyclical swaps are only allowed if they are the first and last token of a solution".to_string(),
));
} else {
// it is a valid cyclical swap
// we don't support any wrapping or unwrapping in this case
if let Some(_native_action) = solution.clone().native_action {
return Err(EncodingError::FatalError(
"Wrapping/Unwrapping is not available in cyclical swaps".to_string(),
));
}
}
}
}
Ok(())
}
}
impl TychoEncoder for EVMTychoEncoder {
fn encode_router_calldata(
&self,
solutions: Vec<Solution>,
) -> Result<Vec<Transaction>, EncodingError> {
let mut transactions: Vec<Transaction> = Vec::new();
for solution in solutions.iter() {
self.validate_solution(solution)?;
let (contract_interaction, target_address) = self
.strategy_encoder
.encode_strategy(solution.clone())?;
let value = if solution.given_token == self.native_address {
solution.given_amount.clone()
} else {
BigUint::ZERO
};
transactions.push(Transaction {
value,
data: contract_interaction,
to: target_address,
});
}
Ok(transactions)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use tycho_common::models::{protocol::ProtocolComponent, Chain as TychoCoreChain};
use super::*;
use crate::encoding::{
models::Swap, strategy_encoder::StrategyEncoder, swap_encoder::SwapEncoder,
};
fn dai() -> Bytes {
Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap()
}
fn eth() -> Bytes {
Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap()
}
fn weth() -> Bytes {
Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap()
}
fn usdc() -> Bytes {
Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap()
}
fn wbtc() -> Bytes {
Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap()
}
#[derive(Clone)]
struct MockStrategy;
impl StrategyEncoder for MockStrategy {
fn encode_strategy(&self, _solution: Solution) -> Result<(Vec<u8>, Bytes), EncodingError> {
Ok((
Bytes::from_str("0x1234")
.unwrap()
.to_vec(),
Bytes::from_str("0xabcd").unwrap(),
))
}
fn get_swap_encoder(&self, _protocol_system: &str) -> Option<&Box<dyn SwapEncoder>> {
None
}
fn clone_box(&self) -> Box<dyn StrategyEncoder> {
Box::new(self.clone())
}
}
fn get_mocked_tycho_encoder() -> EVMTychoEncoder {
let strategy_encoder = Box::new(MockStrategy {});
EVMTychoEncoder::new(TychoCoreChain::Ethereum, strategy_encoder).unwrap()
}
#[test]
fn test_encode_router_calldata() {
let encoder = get_mocked_tycho_encoder();
let eth_amount_in = BigUint::from(1000u32);
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth(),
token_out: dai(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
given_amount: eth_amount_in.clone(),
given_token: eth(),
swaps: vec![swap],
native_action: Some(NativeAction::Wrap),
..Default::default()
};
let transactions = encoder.encode_router_calldata(vec![solution]);
assert!(transactions.is_ok());
let transactions = transactions.unwrap();
assert_eq!(transactions.len(), 1);
assert_eq!(transactions[0].value, eth_amount_in);
assert_eq!(transactions[0].data, Bytes::from_str("0x1234").unwrap());
assert_eq!(transactions[0].to, Bytes::from_str("0xabcd").unwrap());
}
#[test]
fn test_validate_fails_for_exact_out() {
let encoder = get_mocked_tycho_encoder();
let solution = Solution {
exact_out: true, // This should cause an error
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError(
"Currently only exact input solutions are supported".to_string()
)
);
}
#[test]
fn test_validate_passes_for_wrap() {
let encoder = get_mocked_tycho_encoder();
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth(),
token_out: dai(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
given_token: eth(),
checked_token: dai(),
checked_amount: None,
swaps: vec![swap],
native_action: Some(NativeAction::Wrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_ok());
}
#[test]
fn test_validate_fails_for_wrap_wrong_input() {
let encoder = get_mocked_tycho_encoder();
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth(),
token_out: dai(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
given_token: weth(),
swaps: vec![swap],
native_action: Some(NativeAction::Wrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError(
"Native token must be the input token in order to wrap".to_string()
)
);
}
#[test]
fn test_validate_fails_for_wrap_wrong_first_swap() {
let encoder = get_mocked_tycho_encoder();
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: eth(),
token_out: dai(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
given_token: eth(),
swaps: vec![swap],
native_action: Some(NativeAction::Wrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError(
"Wrapped token must be the first swap's input in order to wrap".to_string()
)
);
}
#[test]
fn test_validate_fails_no_swaps() {
let encoder = get_mocked_tycho_encoder();
let solution = Solution {
exact_out: false,
given_token: eth(),
swaps: vec![],
native_action: Some(NativeAction::Wrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError("No swaps found in solution".to_string())
);
}
#[test]
fn test_validate_passes_for_unwrap() {
let encoder = get_mocked_tycho_encoder();
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
checked_token: eth(),
checked_amount: None,
swaps: vec![swap],
native_action: Some(NativeAction::Unwrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_ok());
}
#[test]
fn test_validate_fails_for_unwrap_wrong_output() {
let encoder = get_mocked_tycho_encoder();
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
given_token: dai(),
checked_token: weth(),
swaps: vec![swap],
native_action: Some(NativeAction::Unwrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError(
"Native token must be the output token in order to unwrap".to_string()
)
);
}
#[test]
fn test_validate_fails_for_unwrap_wrong_last_swap() {
let encoder = get_mocked_tycho_encoder();
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: eth(),
split: 0f64,
};
let solution = Solution {
exact_out: false,
checked_token: eth(),
swaps: vec![swap],
native_action: Some(NativeAction::Unwrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError(
"Wrapped token must be the last swap's output in order to unwrap".to_string()
)
);
}
#[test]
fn test_validate_cyclical_swap() {
// This validation passes because the cyclical swap is the first and last token
// 50% -> WETH
// DAI - -> DAI
// 50% -> WETH
// (some of the pool addresses in this test are fake)
let encoder = get_mocked_tycho_encoder();
let swaps = vec![
Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0.5f64,
},
Swap {
component: ProtocolComponent {
id: "0x0000000000000000000000000000000000000000".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0f64,
},
Swap {
component: ProtocolComponent {
id: "0x0000000000000000000000000000000000000000".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth(),
token_out: dai(),
split: 0f64,
},
];
let solution = Solution {
exact_out: false,
given_token: dai(),
checked_token: dai(),
swaps,
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_ok());
}
#[test]
fn test_validate_cyclical_swap_fail() {
// This test should fail because the cyclical swap is not the first and last token
// DAI -> WETH -> USDC -> DAI -> WBTC
// (some of the pool addresses in this test are fake)
let encoder = get_mocked_tycho_encoder();
let swaps = vec![
Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0f64,
},
Swap {
component: ProtocolComponent {
id: "0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth(),
token_out: usdc(),
split: 0f64,
},
Swap {
component: ProtocolComponent {
id: "0x0000000000000000000000000000000000000000".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: usdc(),
token_out: dai(),
split: 0f64,
},
Swap {
component: ProtocolComponent {
id: "0x0000000000000000000000000000000000000000".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: wbtc(),
split: 0f64,
},
];
let solution = Solution {
exact_out: false,
given_token: dai(),
checked_token: wbtc(),
swaps,
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError(
"Cyclical swaps are only allowed if they are the first and last token of a solution".to_string()
)
);
}
#[test]
fn test_validate_cyclical_swap_split_output() {
// This validation passes because it is a valid cyclical swap
// -> WETH
// WETH -> DAI
// -> WETH
// (some of the pool addresses in this test are fake)
let encoder = get_mocked_tycho_encoder();
let swaps = vec![
Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth(),
token_out: dai(),
split: 0f64,
},
Swap {
component: ProtocolComponent {
id: "0x0000000000000000000000000000000000000000".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0.5f64,
},
Swap {
component: ProtocolComponent {
id: "0x0000000000000000000000000000000000000000".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0f64,
},
];
let solution = Solution {
exact_out: false,
given_token: weth(),
checked_token: weth(),
swaps,
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_ok());
}
#[test]
fn test_validate_cyclical_swap_native_action_fail() {
// This validation fails because there is a native action with a valid cyclical swap
// ETH -> WETH -> DAI -> WETH
// (some of the pool addresses in this test are fake)
let encoder = get_mocked_tycho_encoder();
let swaps = vec![
Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth(),
token_out: dai(),
split: 0f64,
},
Swap {
component: ProtocolComponent {
id: "0x0000000000000000000000000000000000000000".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: dai(),
token_out: weth(),
split: 0f64,
},
];
let solution = Solution {
exact_out: false,
given_token: eth(),
checked_token: weth(),
swaps,
native_action: Some(NativeAction::Wrap),
..Default::default()
};
let result = encoder.validate_solution(&solution);
assert!(result.is_err());
assert_eq!(
result.err().unwrap(),
EncodingError::FatalError(
"Wrapping/Unwrapping is not available in cyclical swaps"
.to_string()
.to_string()
)
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,19 @@
use std::{cmp::max, env, sync::Arc};
use std::{
cmp::max,
env,
fs::OpenOptions,
io::{BufRead, BufReader, Write},
sync::{Arc, Mutex},
};
use alloy::{
providers::{ProviderBuilder, RootProvider},
transports::BoxTransport,
};
use alloy_primitives::{aliases::U24, keccak256, Address, FixedBytes, Keccak256, U256, U8};
use alloy_sol_types::SolValue;
use num_bigint::BigUint;
use once_cell::sync::Lazy;
use tokio::runtime::{Handle, Runtime};
use tycho_common::Bytes;
@@ -22,7 +30,7 @@ pub fn bytes_to_address(address: &Bytes) -> Result<Address, EncodingError> {
if address.len() == 20 {
Ok(Address::from_slice(address))
} else {
Err(EncodingError::InvalidInput(format!("Invalid address: {:?}", address)))
Err(EncodingError::InvalidInput(format!("Invalid address: {address}",)))
}
}
@@ -94,7 +102,7 @@ pub fn get_token_position(tokens: Vec<Bytes>, token: Bytes) -> Result<U8, Encodi
.iter()
.position(|t| *t == token)
.ok_or_else(|| {
EncodingError::InvalidInput(format!("Token {:?} not found in tokens array", token))
EncodingError::InvalidInput(format!("Token {token} not found in tokens array"))
})?,
);
Ok(position)
@@ -120,9 +128,7 @@ pub fn get_static_attribute(swap: &Swap, attribute_name: &str) -> Result<Vec<u8>
.component
.static_attributes
.get(attribute_name)
.ok_or_else(|| {
EncodingError::FatalError(format!("Attribute {} not found", attribute_name))
})?
.ok_or_else(|| EncodingError::FatalError(format!("Attribute {attribute_name} not found")))?
.to_vec())
}
@@ -150,6 +156,66 @@ pub async fn get_client() -> Result<Arc<RootProvider<BoxTransport>>, EncodingErr
Ok(Arc::new(client))
}
/// Uses prefix-length encoding to efficient encode action data.
///
/// Prefix-length encoding is a data encoding method where the beginning of a data segment
/// (the "prefix") contains information about the length of the following data.
pub fn ple_encode(action_data_array: Vec<Vec<u8>>) -> Vec<u8> {
let mut encoded_action_data: Vec<u8> = Vec::new();
for action_data in action_data_array {
let args = (encoded_action_data, action_data.len() as u16, action_data);
encoded_action_data = args.abi_encode_packed();
}
encoded_action_data
}
static CALLDATA_WRITE_MUTEX: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
// Function used in tests to write calldata to a file that then is used by the corresponding
// solidity tests.
pub fn write_calldata_to_file(test_identifier: &str, hex_calldata: &str) {
let _lock = CALLDATA_WRITE_MUTEX
.lock()
.expect("Couldn't acquire lock");
let file_path = "foundry/test/assets/calldata.txt";
let file = OpenOptions::new()
.read(true)
.open(file_path)
.expect("Failed to open calldata file for reading");
let reader = BufReader::new(file);
let mut lines = Vec::new();
let mut found = false;
for line in reader.lines().map_while(Result::ok) {
let mut parts = line.splitn(2, ':'); // split at the :
let key = parts.next().unwrap_or("");
if key == test_identifier {
lines.push(format!("{test_identifier}:{hex_calldata}"));
found = true;
} else {
lines.push(line);
}
}
// If the test identifier wasn't found, append a new line
if !found {
lines.push(format!("{test_identifier}:{hex_calldata}"));
}
// Write the updated contents back to the file
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(file_path)
.expect("Failed to open calldata file for writing");
for line in lines {
writeln!(file, "{line}").expect("Failed to write calldata");
}
}
#[cfg(test)]
mod tests {
use num_bigint::BigUint;

View File

@@ -2,7 +2,7 @@ use hex;
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use tycho_common::{
models::{protocol::ProtocolComponent, Chain as TychoCoreChain},
models::{protocol::ProtocolComponent, Chain as TychoCommonChain},
Bytes,
};
@@ -96,6 +96,27 @@ pub struct Transaction {
pub data: Vec<u8>,
}
/// Represents the type of transfer to be performed into the pool.
///
/// # Fields
///
/// * `TransferToProtocol`: Transfer the token from the router into the protocol.
/// * `TransferFromToProtocol`: Transfer the token from the sender to the protocol.
/// * `TransferPermit2ToProtocol`: Transfer the token from the sender to the protocol using Permit2.
/// * `TransferFromToRouter`: Transfer the token from the sender to the router.
/// * `TransferPermit2ToRouter`: Transfer the token from the sender to the router using Permit2.
/// * `None`: No transfer is needed. Tokens are already in the pool.
#[repr(u8)]
#[derive(Clone, Debug, PartialEq)]
pub enum TransferType {
TransferToProtocol = 0,
TransferFromToProtocol = 1,
TransferPermit2ToProtocol = 2,
TransferFromToRouter = 3,
TransferPermit2ToRouter = 4,
None = 5,
}
/// Represents necessary attributes for encoding an order.
///
/// # Fields
@@ -113,6 +134,7 @@ pub struct EncodingContext {
pub router_address: Option<Bytes>,
pub group_token_in: Bytes,
pub group_token_out: Bytes,
pub transfer_type: TransferType,
}
#[derive(Clone, PartialEq, Eq, Hash)]
@@ -121,15 +143,15 @@ pub struct Chain {
pub name: String,
}
impl From<TychoCoreChain> for Chain {
fn from(chain: TychoCoreChain) -> Self {
impl From<TychoCommonChain> for Chain {
fn from(chain: TychoCommonChain) -> Self {
match chain {
TychoCoreChain::Ethereum => Chain { id: 1, name: chain.to_string() },
TychoCoreChain::ZkSync => Chain { id: 324, name: chain.to_string() },
TychoCoreChain::Arbitrum => Chain { id: 42161, name: chain.to_string() },
TychoCoreChain::Starknet => Chain { id: 0, name: chain.to_string() },
TychoCoreChain::Base => Chain { id: 8453, name: chain.to_string() },
TychoCoreChain::Unichain => Chain { id: 130, name: chain.to_string() },
TychoCommonChain::Ethereum => Chain { id: 1, name: chain.to_string() },
TychoCommonChain::ZkSync => Chain { id: 324, name: chain.to_string() },
TychoCommonChain::Arbitrum => Chain { id: 42161, name: chain.to_string() },
TychoCommonChain::Starknet => Chain { id: 0, name: chain.to_string() },
TychoCommonChain::Base => Chain { id: 8453, name: chain.to_string() },
TychoCommonChain::Unichain => Chain { id: 130, name: chain.to_string() },
}
}
}

View File

@@ -14,8 +14,7 @@ pub trait TychoEncoder {
///
/// # Returns
/// * `Result<Vec<Transaction>, EncodingError>` - Vector of executable transactions
fn encode_router_calldata(
&self,
solutions: Vec<Solution>,
) -> Result<Vec<Transaction>, EncodingError>;
fn encode_calldata(&self, solutions: Vec<Solution>) -> Result<Vec<Transaction>, EncodingError>;
fn validate_solution(&self, solution: &Solution) -> Result<(), EncodingError>;
}