From 1a8e0f102cc1aad27cdaa438b25ce67db130830e Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Fri, 31 Jan 2025 18:40:59 +0000 Subject: [PATCH 01/11] chore: Make objects public Remove dead_code check and leftover file after a merge Improve some docstrings --- don't change below this line --- ENG-4087 Took 1 hour 39 minutes --- src/encoding/errors.rs | 1 - src/encoding/evm/approvals/permit2.rs | 1 - .../approvals/protocol_approvals_manager.rs | 1 - src/encoding/evm/mod.rs | 6 +- src/encoding/evm/strategy_encoder/encoder.rs | 155 ------------------ src/encoding/evm/strategy_encoder/mod.rs | 2 +- src/encoding/evm/tycho_encoder.rs | 10 +- src/encoding/evm/utils.rs | 2 - src/encoding/mod.rs | 6 +- src/encoding/models.rs | 42 +++-- src/encoding/strategy_encoder.rs | 2 - src/encoding/swap_encoder.rs | 1 - src/encoding/tycho_encoder.rs | 1 - src/lib.rs | 2 +- 14 files changed, 32 insertions(+), 200 deletions(-) delete mode 100644 src/encoding/evm/strategy_encoder/encoder.rs diff --git a/src/encoding/errors.rs b/src/encoding/errors.rs index 6581c6c..dacd807 100644 --- a/src/encoding/errors.rs +++ b/src/encoding/errors.rs @@ -13,7 +13,6 @@ use thiserror::Error; /// at a later time may succeed. It may have failed due to a temporary issue, such as a network /// problem. #[derive(Error, Debug, PartialEq)] -#[allow(dead_code)] pub enum EncodingError { #[error("Invalid input: {0}")] InvalidInput(String), diff --git a/src/encoding/evm/approvals/permit2.rs b/src/encoding/evm/approvals/permit2.rs index aca2c0c..1423ce0 100644 --- a/src/encoding/evm/approvals/permit2.rs +++ b/src/encoding/evm/approvals/permit2.rs @@ -60,7 +60,6 @@ sol! { } } -#[allow(dead_code)] impl Permit2 { pub fn new(signer_pk: String, chain: Chain) -> Result { let chain_id = ChainId::from(chain); diff --git a/src/encoding/evm/approvals/protocol_approvals_manager.rs b/src/encoding/evm/approvals/protocol_approvals_manager.rs index dad228f..8d1d16f 100644 --- a/src/encoding/evm/approvals/protocol_approvals_manager.rs +++ b/src/encoding/evm/approvals/protocol_approvals_manager.rs @@ -12,7 +12,6 @@ use tokio::runtime::Runtime; use crate::encoding::{errors::EncodingError, evm::utils::encode_input}; -#[allow(dead_code)] pub struct ProtocolApprovalsManager { client: Arc>, runtime: Runtime, diff --git a/src/encoding/evm/mod.rs b/src/encoding/evm/mod.rs index bffb498..4f02c0f 100644 --- a/src/encoding/evm/mod.rs +++ b/src/encoding/evm/mod.rs @@ -1,6 +1,6 @@ -pub mod approvals; +mod approvals; mod models; -mod strategy_encoder; +pub mod strategy_encoder; mod swap_encoder; -mod tycho_encoder; +pub mod tycho_encoder; mod utils; diff --git a/src/encoding/evm/strategy_encoder/encoder.rs b/src/encoding/evm/strategy_encoder/encoder.rs deleted file mode 100644 index 09525a2..0000000 --- a/src/encoding/evm/strategy_encoder/encoder.rs +++ /dev/null @@ -1,155 +0,0 @@ -use std::str::FromStr; - -use alloy_primitives::Address; -use alloy_sol_types::SolValue; -use tycho_core::Bytes; - -use crate::encoding::{ - errors::EncodingError, - evm::swap_encoder::SWAP_ENCODER_REGISTRY, - models::{EncodingContext, Solution}, - strategy_encoder::StrategyEncoder, -}; - -#[allow(dead_code)] -pub trait EVMStrategyEncoder: StrategyEncoder { - fn encode_protocol_header( - &self, - protocol_data: Vec, - executor_address: Address, - // Token indices, split, and token inclusion are only used for split swaps - token_in: u16, - token_out: u16, - split: u16, // not sure what should be the type of this :/ - ) -> Vec { - let args = (executor_address, token_in, token_out, split, protocol_data); - args.abi_encode() - } -} - -pub struct SplitSwapStrategyEncoder {} -impl EVMStrategyEncoder for SplitSwapStrategyEncoder {} -impl StrategyEncoder for SplitSwapStrategyEncoder { - fn encode_strategy(&self, _solution: Solution) -> Result<(Vec, Bytes), EncodingError> { - todo!() - } - fn selector(&self, _exact_out: bool) -> &str { - "swap(uint256, address, uint256, bytes[])" - } -} - -/// This strategy encoder is used for solutions that are sent directly to the pool. -/// Only 1 solution with 1 swap is supported. -pub struct ExecutorStrategyEncoder {} -impl EVMStrategyEncoder for ExecutorStrategyEncoder {} -impl StrategyEncoder for ExecutorStrategyEncoder { - fn encode_strategy(&self, solution: Solution) -> Result<(Vec, Bytes), EncodingError> { - if solution.router_address.is_none() { - return Err(EncodingError::InvalidInput( - "Router address is required for straight to pool solutions".to_string(), - )); - } - let swap = solution.swaps.first().unwrap(); - let registry = SWAP_ENCODER_REGISTRY - .read() - .map_err(|_| { - EncodingError::FatalError("Failed to read the swap encoder registry".to_string()) - })?; - let swap_encoder = registry - .get_encoder(&swap.component.protocol_system) - .ok_or_else(|| { - EncodingError::InvalidInput(format!( - "Swap encoder not found for protocol: {}", - swap.component.protocol_system - )) - })?; - let router_address = solution.router_address.unwrap(); - - let encoding_context = EncodingContext { - receiver: solution.receiver, - exact_out: solution.exact_out, - router_address, - }; - let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context)?; - let executor_address = Bytes::from_str(swap_encoder.executor_address()) - .map_err(|_| EncodingError::FatalError("Invalid executor address".to_string()))?; - Ok((protocol_data, executor_address)) - } - fn selector(&self, _exact_out: bool) -> &str { - "swap(uint256, bytes)" - } -} - -#[cfg(test)] -mod tests { - use alloy::hex::encode; - use num_bigint::BigUint; - use tycho_core::{dto::ProtocolComponent, Bytes}; - - use super::*; - use crate::encoding::models::Swap; - - #[test] - fn test_executor_strategy_encode() { - let encoder = ExecutorStrategyEncoder {}; - - let token_in = Bytes::from("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"); - let token_out = Bytes::from("0x6b175474e89094c44da98b954eedeac495271d0f"); - - let swap = Swap { - component: ProtocolComponent { - id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(), - protocol_system: "uniswap_v2".to_string(), - ..Default::default() - }, - token_in: token_in.clone(), - token_out: token_out.clone(), - split: 0f64, - }; - - let solution = Solution { - exact_out: false, - given_token: token_in, - given_amount: BigUint::from(1000000000000000000u64), - expected_amount: BigUint::from(1000000000000000000u64), - checked_token: token_out, - check_amount: None, - sender: Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(), - // The receiver was generated with `makeAddr("bob") using forge` - receiver: Bytes::from_str("0x1d96f2f6bef1202e4ce1ff6dad0c2cb002861d3e").unwrap(), - swaps: vec![swap], - direct_execution: true, - router_address: Some(Bytes::zero(20)), - slippage: None, - native_action: None, - }; - - let (protocol_data, executor_address) = encoder - .encode_strategy(solution) - .unwrap(); - let hex_protocol_data = encode(&protocol_data); - assert_eq!( - executor_address, - Bytes::from_str("0x5c2f5a71f67c01775180adc06909288b4c329308").unwrap() - ); - assert_eq!( - hex_protocol_data, - String::from(concat!( - // in token - "c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", - // component id - "a478c2975ab1ea89e8196811f51a7b7ade33eb11", - // receiver - "1d96f2f6bef1202e4ce1ff6dad0c2cb002861d3e", - // zero for one - "00", - )) - ); - } - - #[test] - fn test_selector() { - let encoder = ExecutorStrategyEncoder {}; - assert_eq!(encoder.selector(false), "swap(uint256, bytes)"); - } -} diff --git a/src/encoding/evm/strategy_encoder/mod.rs b/src/encoding/evm/strategy_encoder/mod.rs index 44c9689..0142707 100644 --- a/src/encoding/evm/strategy_encoder/mod.rs +++ b/src/encoding/evm/strategy_encoder/mod.rs @@ -1,2 +1,2 @@ mod strategy_encoders; -mod strategy_selector; +pub mod strategy_selector; diff --git a/src/encoding/evm/tycho_encoder.rs b/src/encoding/evm/tycho_encoder.rs index 5be718d..989f8f6 100644 --- a/src/encoding/evm/tycho_encoder.rs +++ b/src/encoding/evm/tycho_encoder.rs @@ -10,25 +10,23 @@ use crate::encoding::{ tycho_encoder::TychoEncoder, }; -#[allow(dead_code)] pub struct EVMTychoEncoder { strategy_selector: S, - signer: Option, + signer_pk: Option, chain: Chain, router_address: Bytes, } -#[allow(dead_code)] impl EVMTychoEncoder { pub fn new( strategy_selector: S, router_address: String, - signer: Option, + signer_pk: Option, chain: Chain, ) -> Result { let router_address = Bytes::from_str(&router_address) .map_err(|_| EncodingError::FatalError("Invalid router address".to_string()))?; - Ok(EVMTychoEncoder { strategy_selector, signer, chain, router_address }) + Ok(EVMTychoEncoder { strategy_selector, signer_pk, chain, router_address }) } } impl TychoEncoder for EVMTychoEncoder { @@ -51,7 +49,7 @@ impl TychoEncoder for EVMTychoEncoder { let strategy = self.strategy_selector.select_strategy( solution, - self.signer.clone(), + self.signer_pk.clone(), self.chain, )?; let (contract_interaction, target_address) = diff --git a/src/encoding/evm/utils.rs b/src/encoding/evm/utils.rs index 0f2db2a..05a13e0 100644 --- a/src/encoding/evm/utils.rs +++ b/src/encoding/evm/utils.rs @@ -16,13 +16,11 @@ pub fn bytes_to_address(address: &Bytes) -> Result { } } -#[allow(dead_code)] pub fn biguint_to_u256(value: &BigUint) -> U256 { let bytes = value.to_bytes_be(); U256::from_be_slice(&bytes) } -#[allow(dead_code)] pub fn encode_input(selector: &str, mut encoded_args: Vec) -> Vec { let mut hasher = Keccak256::new(); hasher.update(selector.as_bytes()); diff --git a/src/encoding/mod.rs b/src/encoding/mod.rs index 6d169f5..255b40d 100644 --- a/src/encoding/mod.rs +++ b/src/encoding/mod.rs @@ -1,7 +1,7 @@ mod errors; #[cfg(feature = "evm")] -mod evm; -mod models; +pub mod evm; +pub mod models; mod strategy_encoder; mod swap_encoder; -mod tycho_encoder; +pub mod tycho_encoder; diff --git a/src/encoding/models.rs b/src/encoding/models.rs index ace014a..24c7c9d 100644 --- a/src/encoding/models.rs +++ b/src/encoding/models.rs @@ -2,48 +2,46 @@ use num_bigint::BigUint; use tycho_core::{dto::ProtocolComponent, Bytes}; #[derive(Clone, Default, Debug)] -#[allow(dead_code)] pub struct Solution { - /// True if the solution is an exact output solution. - pub exact_out: bool, + /// Address of the sender. + pub sender: Bytes, + /// Address of the receiver. + pub receiver: Bytes, /// The token being sold (exact in) or bought (exact out). pub given_token: Bytes, /// Amount of the given token. pub given_amount: BigUint, /// The token being bought (exact in) or sold (exact out). pub checked_token: Bytes, + /// False if the solution is an exact input solution. Currently only exact input solutions are + /// supported. + pub exact_out: bool, + // If set, it will be applied to expected_amount + pub slippage: Option, /// Expected amount of the bought token (exact in) or sold token (exact out). - pub expected_amount: BigUint, + pub expected_amount: Option, /// Minimum amount to be checked for the solution to be valid. /// If not set, the check will not be performed. pub check_amount: Option, - /// Address of the sender. - pub sender: Bytes, - /// Address of the receiver. - pub receiver: Bytes, /// List of swaps to fulfill the solution. pub swaps: Vec, + // If not set, then the Tycho Router will be used + pub router_address: Option, + // If set, the corresponding native action will be executed. + pub native_action: Option, /// If set to true, the solution will be encoded to be sent directly to the Executor and /// skip the router. The user is responsible for managing necessary approvals and token /// transfers. pub direct_execution: bool, - // if not set, then the Propeller Router will be used - pub router_address: Option, - // if set, it will be applied to check_amount - pub slippage: Option, - // if set, the corresponding native action will be executed - pub native_action: Option, } #[derive(Clone, PartialEq, Debug)] -#[allow(dead_code)] pub enum NativeAction { Wrap, Unwrap, } #[derive(Clone, Debug)] -#[allow(dead_code)] pub struct Swap { /// Protocol component from tycho indexer pub component: ProtocolComponent, @@ -51,20 +49,20 @@ pub struct Swap { pub token_in: Bytes, /// Token being output from the pool. pub token_out: Bytes, - /// Percentage of the amount to be swapped in this operation. + /// Percentage of the amount to be swapped in this operation (for example, 0.5 means 50%) pub split: f64, } -#[allow(dead_code)] +#[derive(Clone, Debug)] pub struct Transaction { - pub data: Vec, - // ETH value to be sent with the transaction. - pub value: BigUint, // Address of the contract to call with the calldata pub to: Bytes, + // ETH value to be sent with the transaction. + pub value: BigUint, + // Encoded calldata for the transaction. + pub data: Vec, } -#[allow(dead_code)] pub struct EncodingContext { pub receiver: Bytes, pub exact_out: bool, diff --git a/src/encoding/strategy_encoder.rs b/src/encoding/strategy_encoder.rs index 99dfb36..94e4e19 100644 --- a/src/encoding/strategy_encoder.rs +++ b/src/encoding/strategy_encoder.rs @@ -2,7 +2,6 @@ use tycho_core::{models::Chain, Bytes}; use crate::encoding::{errors::EncodingError, models::Solution}; -#[allow(dead_code)] pub trait StrategyEncoder { fn encode_strategy( &self, @@ -12,7 +11,6 @@ pub trait StrategyEncoder { } pub trait StrategySelector { - #[allow(dead_code)] fn select_strategy( &self, solution: &Solution, diff --git a/src/encoding/swap_encoder.rs b/src/encoding/swap_encoder.rs index 14f49f2..8cd8b4c 100644 --- a/src/encoding/swap_encoder.rs +++ b/src/encoding/swap_encoder.rs @@ -3,7 +3,6 @@ use crate::encoding::{ models::{EncodingContext, Swap}, }; -#[allow(dead_code)] pub trait SwapEncoder: Sync + Send { fn new(executor_address: String) -> Self where diff --git a/src/encoding/tycho_encoder.rs b/src/encoding/tycho_encoder.rs index bfec250..42d92f6 100644 --- a/src/encoding/tycho_encoder.rs +++ b/src/encoding/tycho_encoder.rs @@ -4,7 +4,6 @@ use crate::encoding::{ strategy_encoder::StrategySelector, }; -#[allow(dead_code)] pub trait TychoEncoder { fn encode_router_calldata( &self, diff --git a/src/lib.rs b/src/lib.rs index 35ed87a..2956942 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1 @@ -mod encoding; +pub mod encoding; From de1c782bc1184f8437226986fc148ebf3995ece9 Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Fri, 31 Jan 2025 18:42:09 +0000 Subject: [PATCH 02/11] fix: Calculate min_amount_out correctly and extend test to prove this --- don't change below this line --- ENG-4087 Took 1 minute --- .../evm/strategy_encoder/strategy_encoders.rs | 90 +++++++++++++------ 1 file changed, 62 insertions(+), 28 deletions(-) diff --git a/src/encoding/evm/strategy_encoder/strategy_encoders.rs b/src/encoding/evm/strategy_encoder/strategy_encoders.rs index 38dbeda..ec30642 100644 --- a/src/encoding/evm/strategy_encoder/strategy_encoders.rs +++ b/src/encoding/evm/strategy_encoder/strategy_encoders.rs @@ -16,7 +16,6 @@ use crate::encoding::{ strategy_encoder::StrategyEncoder, }; -#[allow(dead_code)] pub trait EVMStrategyEncoder: StrategyEncoder { fn encode_swap_header( &self, @@ -77,16 +76,18 @@ impl StrategyEncoder for SplitSwapStrategyEncoder { &solution.given_token, &solution.given_amount, )?; - let mut min_amount_out = BigUint::ZERO; - if let Some(user_specified_min_amount) = solution.check_amount { - if let Some(slippage) = 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 = - (&solution.expected_amount * multiplier) / one_hundred; - min_amount_out = max(user_specified_min_amount, expected_amount_with_slippage); - } + let mut min_amount_out = solution + .check_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); } // The tokens array is composed of the given token, the checked token and all the // intermediary tokens in between. The contract expects the tokens to be in this order. @@ -244,6 +245,7 @@ mod tests { use alloy::hex::encode; use num_bigint::BigUint; + use rstest::rstest; use tycho_core::{dto::ProtocolComponent, Bytes}; use super::*; @@ -271,7 +273,7 @@ mod tests { exact_out: false, given_token: token_in, given_amount: BigUint::from(1000000000000000000u64), - expected_amount: BigUint::from(1000000000000000000u64), + expected_amount: Some(BigUint::from(1000000000000000000u64)), checked_token: token_out, check_amount: None, sender: Bytes::from_str("0x0000000000000000000000000000000000000000").unwrap(), @@ -307,8 +309,37 @@ mod tests { ); } - #[test] - fn test_split_swap_strategy_encoder_simple_route() { + #[rstest] + #[case::no_check_no_slippage( + None, + None, + None, + U256::from_str("0").unwrap(), + )] + #[case::with_check_no_slippage( + None, + None, + Some(BigUint::from_str("3_000_000000000000000000").unwrap()), + U256::from_str("3_000_000000000000000000").unwrap(), + )] + #[case::no_check_with_slippage( + Some(BigUint::from_str("3_000_000000000000000000").unwrap()), + Some(0.01f64), + None, + U256::from_str("2_970_000000000000000000").unwrap(), + )] + #[case::with_check_and_slippage( + Some(BigUint::from_str("3_000_000000000000000000").unwrap()), + Some(0.01f64), + Some(BigUint::from_str("2_999_000000000000000000").unwrap()), + U256::from_str("2_999_000000000000000000").unwrap(), + )] + fn test_split_swap_strategy_encoder_simple_route( + #[case] expected_amount: Option, + #[case] slippage: Option, + #[case] check_amount: Option, + #[case] expected_min_amount: U256, + ) { // Performs a single swap from WETH to DAI on a USV2 pool // Set up a mock private key for signing @@ -335,8 +366,9 @@ mod tests { given_token: weth, given_amount: BigUint::from_str("1_000000000000000000").unwrap(), checked_token: dai, - expected_amount: BigUint::from_str("3_000_000000000000000000").unwrap(), - check_amount: None, + expected_amount, + slippage, + check_amount, sender: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(), receiver: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(), swaps: vec![swap], @@ -347,18 +379,20 @@ mod tests { let (calldata, _) = encoder .encode_strategy(solution, router_address) .unwrap(); + let expected_min_amount_encoded = hex::encode(U256::abi_encode(&expected_min_amount)); + let expected_input = [ + "4860f9ed", // Function selector + "0000000000000000000000000000000000000000000000000de0b6b3a7640000", // amount out + "000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in + "0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f", // token out + &expected_min_amount_encoded, // min amount out + "0000000000000000000000000000000000000000000000000000000000000000", // wrap + "0000000000000000000000000000000000000000000000000000000000000000", // unwrap + "0000000000000000000000000000000000000000000000000000000000000002", // tokens length + "000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2", // receiver + ] + .join(""); - let expected_input = String::from(concat!( - "4860f9ed", - "0000000000000000000000000000000000000000000000000de0b6b3a7640000", // amount out - "000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in - "0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f", // token out - "0000000000000000000000000000000000000000000000000000000000000000", // min amount out - "0000000000000000000000000000000000000000000000000000000000000000", // wrap - "0000000000000000000000000000000000000000000000000000000000000000", // unwrap - "0000000000000000000000000000000000000000000000000000000000000002", // tokens length - "000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2", // receiver - )); // after this there is the permit and because of the deadlines (that depend on block time) // it's hard to assert // "000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in @@ -473,7 +507,7 @@ mod tests { given_token: weth, given_amount: BigUint::from_str("1_000000000000000000").unwrap(), checked_token: usdc, - expected_amount: BigUint::from_str("3_000_000000").unwrap(), + expected_amount: Some(BigUint::from_str("3_000_000000").unwrap()), check_amount: None, sender: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(), receiver: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(), From 84d162d418f383bb9dee56ba281f24f686bff19d Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Fri, 31 Jan 2025 18:42:23 +0000 Subject: [PATCH 03/11] feat: Add simple quickstart example --- don't change below this line --- ENG-4087 Took 14 seconds --- examples/quickstart/Readme.md | 12 ++++++ examples/quickstart/main.rs | 73 +++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 examples/quickstart/Readme.md create mode 100644 examples/quickstart/main.rs diff --git a/examples/quickstart/Readme.md b/examples/quickstart/Readme.md new file mode 100644 index 0000000..0978ffd --- /dev/null +++ b/examples/quickstart/Readme.md @@ -0,0 +1,12 @@ +# QuickStart + +This quickstart guide enables you to: + +1. Create a Solution object +2. Encode the solution to interact with the Ethereum blockchain + +## How to run + +```bash +cargo run --release --example quickstart +``` \ No newline at end of file diff --git a/examples/quickstart/main.rs b/examples/quickstart/main.rs new file mode 100644 index 0000000..c68be70 --- /dev/null +++ b/examples/quickstart/main.rs @@ -0,0 +1,73 @@ +use std::str::FromStr; + +use num_bigint::BigUint; +use tycho_core::{dto::ProtocolComponent, models::Chain, Bytes}; +use tycho_execution::encoding::{ + evm::{ + strategy_encoder::strategy_selector::EVMStrategySelector, tycho_encoder::EVMTychoEncoder, + }, + models::{Solution, Swap}, + tycho_encoder::TychoEncoder, +}; + +fn main() { + // Setup variables + let router_address = "0x1234567890abcdef1234567890abcdef12345678".to_string(); + let signer_pk = + Some("0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234".to_string()); + let user_address = Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2") + .expect("Failed to create user address"); + + // Initialize the encoder + let encoder = + EVMTychoEncoder::new(EVMStrategySelector, router_address, signer_pk, Chain::Ethereum) + .expect("Failed to create encoder"); + + // Prepare data to encode. We will encode a simple swap from WETH to DAI + // First we need to create a swap object + let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2") + .expect("Failed to create WETH address"); + let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f") + .expect("Failed to create DAI address"); + + let swap = Swap { + // The protocol component data comes from tycho-indexer + component: ProtocolComponent { + id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(), + protocol_system: "uniswap_v2".to_string(), + ..Default::default() + }, + token_in: weth.clone(), + token_out: dai.clone(), + // Split represents the percentage of the amount to be swapped. If it's 0 it represents 100% + // or what is left of the amount in. + split: 0f64, + }; + + // Then we create a solution object with the previous swap + let solution = Solution { + sender: user_address.clone(), + receiver: user_address, + given_token: weth, + given_amount: BigUint::from_str("1_000000000000000000").expect("Failed to create amount"), + checked_token: dai, + exact_out: false, // it's an exact in solution + check_amount: None, // the amount out will not be checked in execution + swaps: vec![swap], + ..Default::default() + }; + + // Encode the solution + let transactions = encoder + .encode_router_calldata(vec![solution]) + .expect("Failed to encode router calldata"); + let tx = transactions[0].clone(); + + println!( + "The encoded transaction should be sent to address {:?} with the value of {:?} and the \ + following encoded data: {:?}", + tx.to, + tx.value, + hex::encode(tx.data) + ); +} From ae315b452aa231d63529aca5834ef80d7eb1f320 Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Fri, 31 Jan 2025 18:45:29 +0000 Subject: [PATCH 04/11] fix: bring back one #[allow(dead_code)] --- don't change below this line --- ENG-4087 Took 3 minutes --- src/encoding/swap_encoder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/encoding/swap_encoder.rs b/src/encoding/swap_encoder.rs index 8cd8b4c..d350f1e 100644 --- a/src/encoding/swap_encoder.rs +++ b/src/encoding/swap_encoder.rs @@ -2,7 +2,7 @@ use crate::encoding::{ errors::EncodingError, models::{EncodingContext, Swap}, }; - +#[allow(dead_code)] pub trait SwapEncoder: Sync + Send { fn new(executor_address: String) -> Self where From 80454f012d1d6c9a79aed02ab95c8290c02ceaba Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Mon, 3 Feb 2025 10:55:37 +0000 Subject: [PATCH 05/11] feat: Add complex swap to quickstart example --- don't change below this line --- ENG-4087 Took 16 minutes --- examples/quickstart/main.rs | 126 +++++++++++++++++++++++++++++------- 1 file changed, 101 insertions(+), 25 deletions(-) diff --git a/examples/quickstart/main.rs b/examples/quickstart/main.rs index c68be70..5b46e1d 100644 --- a/examples/quickstart/main.rs +++ b/examples/quickstart/main.rs @@ -23,15 +23,71 @@ fn main() { EVMTychoEncoder::new(EVMStrategySelector, router_address, signer_pk, Chain::Ethereum) .expect("Failed to create encoder"); - // Prepare data to encode. We will encode a simple swap from WETH to DAI + // ------------------- Encode a simple swap ------------------- + + // Prepare data to encode. We will encode a simple swap from WETH to USDC // First we need to create a swap object let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2") .expect("Failed to create WETH address"); + let usdc = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48") + .expect("Failed to create USDC address"); + + let simple_swap = Swap { + // The protocol component data comes from tycho-indexer + component: ProtocolComponent { + id: "0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc".to_string(), + protocol_system: "uniswap_v2".to_string(), + ..Default::default() + }, + token_in: weth.clone(), + token_out: usdc.clone(), + // Split defines the fraction of the amount to be swapped. A value of 0 indicates 100% of + // the amount or the total remaining balance. + split: 0f64, + }; + + // Then we create a solution object with the previous swap + let solution = Solution { + sender: user_address.clone(), + receiver: user_address.clone(), + given_token: weth.clone(), + given_amount: BigUint::from_str("1_000000000000000000").expect("Failed to create amount"), + checked_token: usdc.clone(), + exact_out: false, // it's an exact in solution + check_amount: None, // the amount out will not be checked in execution + swaps: vec![simple_swap], + ..Default::default() + }; + + // Encode the solution + let tx = encoder + .encode_router_calldata(vec![solution.clone()]) + .expect("Failed to encode router calldata")[0] + .clone(); + println!(" ====== Simple swap WETH -> USDC ======"); + println!( + "The simple swap encoded transaction should be sent to address {:?} with the value of {:?} and the \ + following encoded data: {:?}", + tx.to, + tx.value, + hex::encode(tx.data) + ); + + // ------------------- Encode a swap with multiple splits ------------------- + // To illustrate a more complex solution, we will encode a swap from WETH to USDC with multiple + // splits. Performs a split swap from WETH to USDC though WBTC and DAI using USV2 pools + // + // ┌──(USV2)──> WBTC ───(USV2)──> USDC + // WETH ─┤ + // └──(USV2)──> DAI ───(USV2)──> USDC + // + + let wbtc = Bytes::from_str("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599") + .expect("Failed to create WBTC address"); let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f") .expect("Failed to create DAI address"); - let swap = Swap { - // The protocol component data comes from tycho-indexer + let swap_weth_dai = Swap { component: ProtocolComponent { id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(), protocol_system: "uniswap_v2".to_string(), @@ -39,35 +95,55 @@ fn main() { }, token_in: weth.clone(), token_out: dai.clone(), - // Split represents the percentage of the amount to be swapped. If it's 0 it represents 100% - // or what is left of the amount in. + split: 0.5f64, + }; + let swap_weth_wbtc = Swap { + component: ProtocolComponent { + id: "0xBb2b8038a1640196FbE3e38816F3e67Cba72D940".to_string(), + protocol_system: "uniswap_v2".to_string(), + ..Default::default() + }, + token_in: weth.clone(), + token_out: wbtc.clone(), + // This represents the remaining 50%, but to avoid any rounding errors we set this to + // 0 to signify "the remainder of the WETH value". It should still be very close to 50% split: 0f64, }; - - // Then we create a solution object with the previous swap - let solution = Solution { - sender: user_address.clone(), - receiver: user_address, - given_token: weth, - given_amount: BigUint::from_str("1_000000000000000000").expect("Failed to create amount"), - checked_token: dai, - exact_out: false, // it's an exact in solution - check_amount: None, // the amount out will not be checked in execution - swaps: vec![swap], - ..Default::default() + let swap_dai_usdc = Swap { + component: ProtocolComponent { + id: "0xAE461cA67B15dc8dc81CE7615e0320dA1A9aB8D5".to_string(), + protocol_system: "uniswap_v2".to_string(), + ..Default::default() + }, + token_in: dai.clone(), + token_out: usdc.clone(), + split: 0f64, }; + let swap_wbtc_usdc = Swap { + component: ProtocolComponent { + id: "0x004375Dff511095CC5A197A54140a24eFEF3A416".to_string(), + protocol_system: "uniswap_v2".to_string(), + ..Default::default() + }, + token_in: wbtc.clone(), + token_out: usdc.clone(), + split: 0f64, + }; + let mut complex_solution = solution.clone(); + complex_solution.swaps = vec![swap_weth_dai, swap_weth_wbtc, swap_dai_usdc, swap_wbtc_usdc]; // Encode the solution - let transactions = encoder - .encode_router_calldata(vec![solution]) - .expect("Failed to encode router calldata"); - let tx = transactions[0].clone(); + let complex_tx = encoder + .encode_router_calldata(vec![complex_solution]) + .expect("Failed to encode router calldata")[0] + .clone(); + println!(" ====== Complex split swap WETH -> USDC ======"); println!( - "The encoded transaction should be sent to address {:?} with the value of {:?} and the \ + "The complex solution encoded transaction should be sent to address {:?} with the value of {:?} and the \ following encoded data: {:?}", - tx.to, - tx.value, - hex::encode(tx.data) + complex_tx.to, + complex_tx.value, + hex::encode(complex_tx.data) ); } From 0860d67d7a339a0fcc2533be856b64b1db394764 Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Mon, 3 Feb 2025 16:50:19 +0000 Subject: [PATCH 06/11] feat: Verify that no amount in is left in the router --- don't change below this line --- ENG-4087 Took 1 hour 41 minutes Took 2 minutes --- foundry/src/TychoRouter.sol | 7 +++++ foundry/test/TychoRouter.t.sol | 52 ++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index b9f4d1c..84d686d 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -18,6 +18,7 @@ import {LibSwap} from "../lib/LibSwap.sol"; error TychoRouter__WithdrawalFailed(); error TychoRouter__AddressZero(); error TychoRouter__NegativeSlippage(uint256 amount, uint256 minAmount); +error TychoRouter__AmountInNotFullySpent(uint256 leftoverAmount); error TychoRouter__MessageValueMismatch(uint256 value, uint256 amount); contract TychoRouter is @@ -153,6 +154,7 @@ contract TychoRouter is // For native ETH, assume funds already in our router. Else, transfer and handle approval. if (wrapEth) { _wrapETH(amountIn); + tokenIn = address(_weth); } else if (tokenIn != address(0)) { permit2.permit(msg.sender, permitSingle, signature); permit2.transferFrom( @@ -175,6 +177,11 @@ contract TychoRouter is revert TychoRouter__NegativeSlippage(amountOut, minAmountOut); } + uint256 leftoverAmountIn = IERC20(tokenIn).balanceOf(address(this)); + if (leftoverAmountIn > 0) { + revert TychoRouter__AmountInNotFullySpent(leftoverAmountIn); + } + if (unwrapEth) { _unwrapETH(amountOut); } diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index a842595..af6d925 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -733,4 +733,56 @@ contract TychoRouterTest is TychoRouterTestSetup { // all of it (and thus our splits are correct). assertEq(IERC20(WETH_ADDR).balanceOf(tychoRouterAddr), 0); } + + function testSwapAmountInNotFullySpent() public { + // Trade 1 WETH for DAI with 1 swap on Uniswap V2 + // Has invalid data as input! There is only one swap with 60% of the input amount + uint256 amountIn = 1 ether; + deal(WETH_ADDR, ALICE, amountIn); + + vm.startPrank(ALICE); + + ( + IAllowanceTransfer.PermitSingle memory permitSingle, + bytes memory signature + ) = handlePermit2Approval(WETH_ADDR, amountIn); + + bytes memory protocolData = encodeUniswapV2Swap( + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + ); + + bytes memory swap = encodeSwap( + uint8(0), + uint8(1), + (0xffffff * 60) / 100, // 60% + address(usv2Executor), + bytes4(0), + protocolData + ); + + bytes[] memory swaps = new bytes[](1); + swaps[0] = swap; + + vm.expectRevert( + abi.encodeWithSelector( + TychoRouter__AmountInNotFullySpent.selector, 400000000000000000 + ) + ); + + tychoRouter.swap( + amountIn, + WETH_ADDR, + DAI_ADDR, + 0, + false, + false, + 2, + ALICE, + permitSingle, + signature, + pleEncode(swaps) + ); + + vm.stopPrank(); + } } From 2aa1df9b0d094125bf89489744ea19e8be289e38 Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Mon, 3 Feb 2025 16:50:42 +0000 Subject: [PATCH 07/11] chore: Move methods around and improve docstrings --- don't change below this line --- ENG-4087 Took 30 seconds Took 5 seconds --- .../src/CallbackVerificationDispatcher.sol | 2 +- foundry/src/ExecutionDispatcher.sol | 2 +- foundry/src/TychoRouter.sol | 74 ++++++++++++------- 3 files changed, 49 insertions(+), 29 deletions(-) diff --git a/foundry/src/CallbackVerificationDispatcher.sol b/foundry/src/CallbackVerificationDispatcher.sol index 17c318e..87ccc8e 100644 --- a/foundry/src/CallbackVerificationDispatcher.sol +++ b/foundry/src/CallbackVerificationDispatcher.sol @@ -13,7 +13,7 @@ error CallbackVerificationDispatcher__NonContractVerifier(); * verification. This allows dynamically adding new supported protocols * without needing to upgrade any contracts. * - * Note Verifier contracts need to implement the ICallbackVerifier interface + * Note: Verifier contracts need to implement the ICallbackVerifier interface */ contract CallbackVerificationDispatcher { mapping(address => bool) public callbackVerifiers; diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/ExecutionDispatcher.sol index e8b36e8..9e084c0 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/ExecutionDispatcher.sol @@ -15,7 +15,7 @@ error ExecutionDispatcher__NonContractExecutor(); * be called using delegatecall so they can share state with the main * contract if needed. * - * Note Executor contracts need to implement the IExecutor interface unless + * Note: Executor contracts need to implement the IExecutor interface unless * an alternate selector is specified. */ contract ExecutionDispatcher { diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 84d686d..c08ad4b 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -74,32 +74,6 @@ contract TychoRouter is _usv3Factory = usv3Factory; } - /** - * @dev We use the fallback function to allow flexibility on callback. - * This function will delegate call a verifier contract and should revert if the - * caller is not a pool. - */ - fallback() external { - _executeGenericCallback(msg.data); - } - - /** - * @dev Check if the sender is correct and executes callback actions. - * @param msgData encoded data. It must includes data for the verification. - */ - function _executeGenericCallback(bytes calldata msgData) internal { - (uint256 amountOwed, address tokenOwed) = _callVerifyCallback(msgData); - - IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); - } - - /** - * @dev Pauses the contract - */ - function pause() external onlyRole(PAUSER_ROLE) { - _pause(); - } - /** * @dev Unpauses the contract */ @@ -116,7 +90,7 @@ contract TychoRouter is * - If `wrapEth` is true, the contract wraps the provided native ETH into WETH and uses it as the sell token. * - If `unwrapEth` is true, the contract converts the resulting WETH back into native ETH before sending it to the receiver. * - For ERC20 tokens, Permit2 is used to approve and transfer tokens from the caller to the router. - * - Swaps are executed sequentially using the `_splitSwap` function. + * - Swaps are executed sequentially using the `_swap` function. * - A fee is deducted from the output token if `fee > 0`, and the remaining amount is sent to the receiver. * - Reverts with `TychoRouter__NegativeSlippage` if the output amount is less than `minAmountOut` and `minAmountOut` is bigger than 0. * @@ -193,6 +167,26 @@ contract TychoRouter is } } + /** + * @dev Executes sequential swaps as defined by the provided swap graph. + * + * This function processes a series of swaps encoded in the `swaps_` byte array. Each swap operation determines: + * - The indices of the input and output tokens (via `tokenInIndex()` and `tokenOutIndex()`). + * - The portion of the available amount to be used for the swap, indicated by the `split` value. + * + * Two important notes: + * - The contract assumes that token indexes follow a specific order: the sell token is at index 0, followed by any + * intermediary tokens, and finally the buy token. + * - A `split` value of 0 is interpreted as 100% of the available amount (i.e., the entire remaining balance). + * This means that in scenarios without explicit splits the value should be 0, and when splits are present, + * the last swap should also have a split value of 0. + * + * @param amountIn The initial amount of the sell token to be swapped. + * @param nTokens The total number of tokens involved in the swap path, used to initialize arrays for internal tracking. + * @param swaps_ Encoded swap graph data containing the details of each swap operation. + * + * @return The total amount of the buy token obtained after all swaps have been executed. + */ function _swap(uint256 amountIn, uint256 nTokens, bytes calldata swaps_) internal returns (uint256) @@ -231,6 +225,32 @@ contract TychoRouter is return amounts[tokenOutIndex]; } + /** + * @dev We use the fallback function to allow flexibility on callback. + * This function will static call a verifier contract and should revert if the + * caller is not a pool. + */ + fallback() external { + _executeGenericCallback(msg.data); + } + + /** + * @dev Check if the sender is correct and executes callback actions. + * @param msgData encoded data. It must includes data for the verification. + */ + function _executeGenericCallback(bytes calldata msgData) internal { + (uint256 amountOwed, address tokenOwed) = _callVerifyCallback(msgData); + + IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); + } + + /** + * @dev Pauses the contract + */ + function pause() external onlyRole(PAUSER_ROLE) { + _pause(); + } + /** * @dev Allows granting roles to multiple accounts in a single call. */ From c4eb7b03b2660b814e6560ae6bb10beb4dfe68d3 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 3 Feb 2025 17:43:04 +0000 Subject: [PATCH 08/11] chore(release): 0.26.0 [skip ci] ## [0.26.0](https://github.com/propeller-heads/tycho-execution/compare/0.25.3...0.26.0) (2025-02-03) ### Features * Verify that no amount in is left in the router ([0860d67](https://github.com/propeller-heads/tycho-execution/commit/0860d67d7a339a0fcc2533be856b64b1db394764)) --- CHANGELOG.md | 7 +++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f3950e..bb693b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [0.26.0](https://github.com/propeller-heads/tycho-execution/compare/0.25.3...0.26.0) (2025-02-03) + + +### Features + +* Verify that no amount in is left in the router ([0860d67](https://github.com/propeller-heads/tycho-execution/commit/0860d67d7a339a0fcc2533be856b64b1db394764)) + ## [0.25.3](https://github.com/propeller-heads/tycho-execution/compare/0.25.2...0.25.3) (2025-01-31) diff --git a/Cargo.lock b/Cargo.lock index 0d94215..5afed2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4163,7 +4163,7 @@ dependencies = [ [[package]] name = "tycho-execution" -version = "0.25.3" +version = "0.26.0" dependencies = [ "alloy", "alloy-primitives", diff --git a/Cargo.toml b/Cargo.toml index 89f5b55..eecc2ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tycho-execution" -version = "0.25.3" +version = "0.26.0" edition = "2021" [dependencies] From 580a86bc0ff58e323ce18e24c006ec7162e0a579 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 4 Feb 2025 09:27:05 +0000 Subject: [PATCH 09/11] chore(release): 0.27.0 [skip ci] ## [0.27.0](https://github.com/propeller-heads/tycho-execution/compare/0.26.0...0.27.0) (2025-02-04) ### Features * Add complex swap to quickstart example ([80454f0](https://github.com/propeller-heads/tycho-execution/commit/80454f012d1d6c9a79aed02ab95c8290c02ceaba)) * Add simple quickstart example ([84d162d](https://github.com/propeller-heads/tycho-execution/commit/84d162d418f383bb9dee56ba281f24f686bff19d)) ### Bug Fixes * bring back one #[allow(dead_code)] ([ae315b4](https://github.com/propeller-heads/tycho-execution/commit/ae315b452aa231d63529aca5834ef80d7eb1f320)) * Calculate min_amount_out correctly and extend test to prove this ([de1c782](https://github.com/propeller-heads/tycho-execution/commit/de1c782bc1184f8437226986fc148ebf3995ece9)) --- CHANGELOG.md | 14 ++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb693b5..1cb75f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,17 @@ +## [0.27.0](https://github.com/propeller-heads/tycho-execution/compare/0.26.0...0.27.0) (2025-02-04) + + +### Features + +* Add complex swap to quickstart example ([80454f0](https://github.com/propeller-heads/tycho-execution/commit/80454f012d1d6c9a79aed02ab95c8290c02ceaba)) +* Add simple quickstart example ([84d162d](https://github.com/propeller-heads/tycho-execution/commit/84d162d418f383bb9dee56ba281f24f686bff19d)) + + +### Bug Fixes + +* bring back one #[allow(dead_code)] ([ae315b4](https://github.com/propeller-heads/tycho-execution/commit/ae315b452aa231d63529aca5834ef80d7eb1f320)) +* Calculate min_amount_out correctly and extend test to prove this ([de1c782](https://github.com/propeller-heads/tycho-execution/commit/de1c782bc1184f8437226986fc148ebf3995ece9)) + ## [0.26.0](https://github.com/propeller-heads/tycho-execution/compare/0.25.3...0.26.0) (2025-02-03) diff --git a/Cargo.lock b/Cargo.lock index 5afed2f..484282a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4163,7 +4163,7 @@ dependencies = [ [[package]] name = "tycho-execution" -version = "0.26.0" +version = "0.27.0" dependencies = [ "alloy", "alloy-primitives", diff --git a/Cargo.toml b/Cargo.toml index eecc2ee..958189f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tycho-execution" -version = "0.26.0" +version = "0.27.0" edition = "2021" [dependencies] From f873bb5187d8f0e24894c15d7ed189b27c5edcf7 Mon Sep 17 00:00:00 2001 From: TAMARA LIPOWSKI Date: Tue, 4 Feb 2025 10:01:38 -0500 Subject: [PATCH 10/11] refactor: check given/checked tokens before swap tokens It's a more intuitive order, since these are higher-level attributes. Also remove the validation from the trait - it doesn't have to be part of the trait. --- src/encoding/evm/tycho_encoder.rs | 85 ++++++++++++++++--------------- src/encoding/tycho_encoder.rs | 2 - 2 files changed, 44 insertions(+), 43 deletions(-) diff --git a/src/encoding/evm/tycho_encoder.rs b/src/encoding/evm/tycho_encoder.rs index 44c3f9f..76fbd1d 100644 --- a/src/encoding/evm/tycho_encoder.rs +++ b/src/encoding/evm/tycho_encoder.rs @@ -32,6 +32,50 @@ impl EVMTychoEncoder { Ok(EVMTychoEncoder { strategy_selector, signer, chain, router_address }) } } + +impl EVMTychoEncoder { + 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 != *NATIVE_ADDRESS { + return Err(EncodingError::FatalError( + "ETH must be the input token in order to wrap".to_string(), + )); + } + if let Some(first_swap) = solution.swaps.first() { + if first_swap.token_in != *WETH_ADDRESS { + return Err(EncodingError::FatalError( + "WETH must be the first swap's input in order to wrap".to_string(), + )); + } + } + } else if native_action == NativeAction::Unwrap { + if solution.checked_token != *NATIVE_ADDRESS { + return Err(EncodingError::FatalError( + "ETH must be the output token in order to unwrap".to_string(), + )); + } + if let Some(last_swap) = solution.swaps.last() { + if last_swap.token_out != *WETH_ADDRESS { + return Err(EncodingError::FatalError( + "WETH must be the last swap's output in order to unwrap".to_string(), + )); + } + } + } + } + Ok(()) + } +} + impl TychoEncoder for EVMTychoEncoder { fn encode_router_calldata( &self, @@ -67,47 +111,6 @@ impl TychoEncoder for EVMTychoEncoder { } Ok(transactions) } - - 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 let Some(first_swap) = solution.swaps.first() { - if first_swap.token_in != *WETH_ADDRESS { - return Err(EncodingError::FatalError( - "WETH must be the first swap's input in order to wrap".to_string(), - )); - } - } - if solution.given_token != *NATIVE_ADDRESS { - return Err(EncodingError::FatalError( - "ETH must be the input token in order to wrap".to_string(), - )); - } - } else if native_action == NativeAction::Unwrap { - if let Some(last_swap) = solution.swaps.last() { - if last_swap.token_out != *WETH_ADDRESS { - return Err(EncodingError::FatalError( - "WETH must be the last swap's output in order to unwrap".to_string(), - )); - } - } - if solution.checked_token != *NATIVE_ADDRESS { - return Err(EncodingError::FatalError( - "ETH must be the output token in order to unwrap".to_string(), - )); - } - } - } - Ok(()) - } } #[cfg(test)] diff --git a/src/encoding/tycho_encoder.rs b/src/encoding/tycho_encoder.rs index 0c92820..bfec250 100644 --- a/src/encoding/tycho_encoder.rs +++ b/src/encoding/tycho_encoder.rs @@ -10,6 +10,4 @@ pub trait TychoEncoder { &self, solutions: Vec, ) -> Result, EncodingError>; - - fn validate_solution(&self, solution: &Solution) -> Result<(), EncodingError>; } From 06603210bcd567ce50ec79344024ea2b722ebcd3 Mon Sep 17 00:00:00 2001 From: TAMARA LIPOWSKI Date: Tue, 4 Feb 2025 10:28:16 -0500 Subject: [PATCH 11/11] fix: test_validate_fails_for_unwrap_wrong_last_swap ETH was the given token not the checked token, which was wrong. --- src/encoding/evm/tycho_encoder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/encoding/evm/tycho_encoder.rs b/src/encoding/evm/tycho_encoder.rs index 1ad1f6f..3006ee3 100644 --- a/src/encoding/evm/tycho_encoder.rs +++ b/src/encoding/evm/tycho_encoder.rs @@ -407,7 +407,7 @@ mod tests { let solution = Solution { exact_out: false, - given_token: NATIVE_ADDRESS.clone(), + checked_token: NATIVE_ADDRESS.clone(), swaps: vec![swap], native_action: Some(NativeAction::Unwrap), ..Default::default()