From feb91cc639aaf9e5056662158f2cbbbb61f9021e Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Thu, 30 Jan 2025 11:22:30 +0000 Subject: [PATCH] feat: Implement SplitSwapStrategyEncoder The strategy works as follows: - Manage approvals needed - Compute min amount (if check amount is any): - if slippage is defined, apply slippage on the expected amount and take the min value between that and the check amount - if not, it's just the check amount - Iterate through the swaps - call the corresponding swap encoder to encode the swap - add swap header (tokens indexes and split) - ple encode the swaps - Add extra inputs (amounts, token addresses, min amount, (un)wrap, number of tokens and receiver) Misc: - Move executor address and selector encoding inside the SwapEncoder - Add default executor_selector to SwapEncoder - Pass router address inside the SplitSwapStrategyEncoder - Move Permit2 inside the SplitSwapStrategyEncoder. It is a responsibility and a specificity of the strategy to need permit2 approvals --- don't change below this line --- ENG-4081 Took 1 hour 21 minutes --- src/encoding/evm/approvals/permit2.rs | 6 +- src/encoding/evm/router_encoder.rs | 58 ++-- src/encoding/evm/strategy_encoder/encoder.rs | 257 +++++++++++++++++- src/encoding/evm/strategy_encoder/selector.rs | 20 +- src/encoding/evm/swap_encoder/encoders.rs | 30 +- src/encoding/evm/utils.rs | 13 +- src/encoding/models.rs | 10 +- src/encoding/router_encoder.rs | 1 - src/encoding/strategy_encoder.rs | 17 +- src/encoding/swap_encoder.rs | 8 + 10 files changed, 355 insertions(+), 65 deletions(-) diff --git a/src/encoding/evm/approvals/permit2.rs b/src/encoding/evm/approvals/permit2.rs index ac673ca..c9b687c 100644 --- a/src/encoding/evm/approvals/permit2.rs +++ b/src/encoding/evm/approvals/permit2.rs @@ -1,13 +1,14 @@ use std::{str::FromStr, sync::Arc}; use alloy::{ - primitives::{aliases::U48, Address, Bytes as AlloyBytes, TxKind, U160}, + primitives::{aliases::U48, Address, Bytes as AlloyBytes, ChainId, TxKind, U160, U256}, providers::{Provider, RootProvider}, rpc::types::{TransactionInput, TransactionRequest}, signers::{local::PrivateKeySigner, SignerSync}, transports::BoxTransport, }; -use alloy_primitives::{ChainId, Signature, U256}; +#[allow(deprecated)] +use alloy_primitives::Signature; use alloy_sol_types::{eip712_domain, sol, SolStruct, SolValue}; use chrono::Utc; use num_bigint::BigUint; @@ -108,6 +109,7 @@ impl Permit2 { } } /// Creates permit single and signature + #[allow(deprecated)] pub fn get_permit( &self, spender: &Bytes, diff --git a/src/encoding/evm/router_encoder.rs b/src/encoding/evm/router_encoder.rs index 53ab437..a3c74d7 100644 --- a/src/encoding/evm/router_encoder.rs +++ b/src/encoding/evm/router_encoder.rs @@ -1,5 +1,7 @@ use std::str::FromStr; +use alloy::signers::local::PrivateKeySigner; +use alloy_primitives::ChainId; use num_bigint::BigUint; use tycho_core::Bytes; @@ -9,37 +11,48 @@ use crate::encoding::{ models::{NativeAction, Solution, Transaction}, router_encoder::RouterEncoder, strategy_encoder::StrategySelector, - user_approvals_manager::{Approval, UserApprovalsManager}, }; #[allow(dead_code)] -pub struct EVMRouterEncoder { +pub struct EVMRouterEncoder { strategy_selector: S, - approvals_manager: A, + signer: Option, + chain_id: ChainId, router_address: String, } #[allow(dead_code)] -impl EVMRouterEncoder { - pub fn new(strategy_selector: S, approvals_manager: A, router_address: String) -> Self { - EVMRouterEncoder { strategy_selector, approvals_manager, router_address } +impl EVMRouterEncoder { + pub fn new( + strategy_selector: S, + router_address: String, + signer: Option, + chain_id: ChainId, + ) -> Result { + Ok(EVMRouterEncoder { strategy_selector, signer, chain_id, router_address }) } } -impl RouterEncoder for EVMRouterEncoder { +impl RouterEncoder for EVMRouterEncoder { fn encode_router_calldata( &self, solutions: Vec, ) -> Result, EncodingError> { - let _approvals_calldata = self.handle_approvals(&solutions)?; // TODO: where should we append this? let mut transactions: Vec = Vec::new(); for solution in solutions.iter() { let exact_out = solution.exact_out; let straight_to_pool = solution.straight_to_pool; - - let strategy = self - .strategy_selector - .select_strategy(solution); - let method_calldata = strategy.encode_strategy((*solution).clone())?; + let router_address = solution + .router_address + .clone() + .unwrap_or(Bytes::from_str(&self.router_address).map_err(|_| { + EncodingError::FatalError("Invalid router address".to_string()) + })?); + let strategy = self.strategy_selector.select_strategy( + solution, + self.signer.clone(), + self.chain_id, + )?; + let method_calldata = strategy.encode_strategy(solution.clone(), router_address)?; let contract_interaction = if straight_to_pool { method_calldata @@ -56,23 +69,4 @@ impl RouterEncoder for EVMRo } Ok(transactions) } - - fn handle_approvals(&self, solutions: &[Solution]) -> Result>, EncodingError> { - let mut approvals = Vec::new(); - for solution in solutions.iter() { - approvals.push(Approval { - token: solution.given_token.clone(), - spender: solution - .router_address - .clone() - .unwrap_or(Bytes::from_str(&self.router_address).map_err(|_| { - EncodingError::FatalError("Invalid router address".to_string()) - })?), - amount: solution.given_amount.clone(), - owner: solution.sender.clone(), - }); - } - self.approvals_manager - .encode_approvals(approvals) - } } diff --git a/src/encoding/evm/strategy_encoder/encoder.rs b/src/encoding/evm/strategy_encoder/encoder.rs index 7068608..4a2d17a 100644 --- a/src/encoding/evm/strategy_encoder/encoder.rs +++ b/src/encoding/evm/strategy_encoder/encoder.rs @@ -1,35 +1,150 @@ -use alloy_primitives::Address; +use std::cmp::min; + +use alloy::signers::local::PrivateKeySigner; +use alloy_primitives::{aliases::U24, map::HashSet, ChainId, U256, U8}; use alloy_sol_types::SolValue; +use num_bigint::BigUint; +use tycho_core::Bytes; use crate::encoding::{ errors::EncodingError, - evm::swap_encoder::SWAP_ENCODER_REGISTRY, - models::{EncodingContext, Solution}, + evm::{ + approvals::permit2::Permit2, + swap_encoder::SWAP_ENCODER_REGISTRY, + utils::{biguint_to_u256, bytes_to_address, percentage_to_uint24, ple_encode}, + }, + models::{EncodingContext, NativeAction, Solution}, strategy_encoder::StrategyEncoder, }; #[allow(dead_code)] pub trait EVMStrategyEncoder: StrategyEncoder { - fn encode_protocol_header( + fn encode_swap_header( &self, + token_in: U8, + token_out: U8, + split: U24, 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() + let mut encoded = Vec::new(); + encoded.push(token_in.to_be_bytes_vec()[0]); + encoded.push(token_out.to_be_bytes_vec()[0]); + encoded.extend_from_slice(&split.to_be_bytes_vec()); + encoded.extend(protocol_data); + encoded } } -pub struct SplitSwapStrategyEncoder {} +pub struct SplitSwapStrategyEncoder { + permit2: Permit2, +} + +impl SplitSwapStrategyEncoder { + pub fn new(signer: PrivateKeySigner, chain_id: ChainId) -> Result { + Ok(Self { permit2: Permit2::new(signer, chain_id)? }) + } +} impl EVMStrategyEncoder for SplitSwapStrategyEncoder {} impl StrategyEncoder for SplitSwapStrategyEncoder { - fn encode_strategy(&self, _solution: Solution) -> Result, EncodingError> { - todo!() + fn encode_strategy( + &self, + solution: Solution, + router_address: Bytes, + ) -> Result, EncodingError> { + let (permit, signature) = self.permit2.get_permit( + &router_address, + &solution.sender, + &solution.given_token, + &solution.given_amount, + )?; + let min_amount_out = if solution.check_amount.is_some() { + let mut min_amount_out = solution.check_amount.clone().unwrap(); + if solution.slippage.is_some() { + let one_hundred = BigUint::from(100u32); + let slippage_percent = BigUint::from((solution.slippage.unwrap() * 100.0) as u32); + let multiplier = &one_hundred - slippage_percent; + let expected_amount_with_slippage = + (&solution.expected_amount * multiplier) / one_hundred; + min_amount_out = min(min_amount_out, expected_amount_with_slippage); + } + min_amount_out + } else { + BigUint::ZERO + }; + + let tokens: Vec = solution + .swaps + .iter() + .flat_map(|swap| vec![swap.token_in.clone(), swap.token_out.clone()]) + .collect::>() + .into_iter() + .collect(); + + let mut swaps = vec![]; + for swap in solution.swaps.iter() { + let registry = SWAP_ENCODER_REGISTRY.read().unwrap(); + let swap_encoder = registry + .get_encoder(&swap.component.protocol_system) + .expect("Swap encoder not found"); + + let encoding_context = EncodingContext { + receiver: router_address.clone(), + exact_out: solution.exact_out, + router_address: router_address.clone(), + }; + let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context)?; + let swap_data = self.encode_swap_header( + U8::from( + tokens + .iter() + .position(|t| *t == swap.token_in) + .ok_or_else(|| { + EncodingError::InvalidInput( + "Token in not found in tokens array".to_string(), + ) + })?, + ), + U8::from( + tokens + .iter() + .position(|t| *t == swap.token_out) + .ok_or_else(|| { + EncodingError::InvalidInput( + "Token out not found in tokens array".to_string(), + ) + })?, + ), + percentage_to_uint24(swap.split), + protocol_data, + ); + swaps.push(swap_data); + } + + let encoded_swaps = ple_encode(swaps); + let (mut unwrap, mut wrap) = (false, false); + if solution.native_action.is_some() { + match solution.native_action.unwrap() { + NativeAction::Wrap => wrap = true, + NativeAction::Unwrap => unwrap = true, + } + } + let method_calldata = ( + biguint_to_u256(&solution.given_amount), + bytes_to_address(&solution.given_token)?, + bytes_to_address(&solution.checked_token)?, + biguint_to_u256(&min_amount_out), + wrap, + unwrap, + U256::from(tokens.len()), + bytes_to_address(&solution.receiver)?, + permit, + signature.as_bytes().to_vec(), + encoded_swaps, + ) + .abi_encode(); + Ok(method_calldata) } + fn selector(&self, _exact_out: bool) -> &str { "swap(uint256, address, uint256, bytes[])" } @@ -40,7 +155,11 @@ impl StrategyEncoder for SplitSwapStrategyEncoder { pub struct StraightToPoolStrategyEncoder {} impl EVMStrategyEncoder for StraightToPoolStrategyEncoder {} impl StrategyEncoder for StraightToPoolStrategyEncoder { - fn encode_strategy(&self, solution: Solution) -> Result, EncodingError> { + fn encode_strategy( + &self, + solution: Solution, + _router_address: Bytes, + ) -> Result, EncodingError> { if solution.router_address.is_none() { return Err(EncodingError::InvalidInput( "Router address is required for straight to pool solutions".to_string(), @@ -75,3 +194,111 @@ impl StrategyEncoder for StraightToPoolStrategyEncoder { unimplemented!(); } } + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + use alloy::hex::encode; + use alloy_primitives::B256; + use tycho_core::dto::ProtocolComponent; + + use super::*; + use crate::encoding::models::Swap; + + #[test] + fn test_split_swap_strategy_encoder() { + // Set up a mock private key for signing + let private_key = + B256::from_str("4c0883a69102937d6231471b5dbb6204fe512961708279feb1be6ae5538da033") + .expect("Invalid private key"); + let signer = PrivateKeySigner::from_bytes(&private_key).expect("Failed to create signer"); + + let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(); + let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(); + + let swap = Swap { + component: ProtocolComponent { + id: "0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640".to_string(), + protocol_system: "uniswap_v2".to_string(), + ..Default::default() + }, + token_in: weth.clone(), + token_out: dai.clone(), + split: 0f64, + }; + + let encoder = SplitSwapStrategyEncoder::new(signer, 1).unwrap(); + let solution = Solution { + exact_out: false, + 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, + sender: Bytes::from_str("0x2c6A3cd97c6283b95Ac8C5A4459eBB0d5Fd404F4").unwrap(), + receiver: Bytes::from_str("0x2c6A3cd97c6283b95Ac8C5A4459eBB0d5Fd404F4").unwrap(), + swaps: vec![swap], + ..Default::default() + }; + let router_address = Bytes::from_str("0x2c6A3cd97c6283b95Ac8C5A4459eBB0d5Fd404F4").unwrap(); + + let calldata = encoder + .encode_strategy(solution, router_address) + .unwrap(); + + let expected_input = String::from(concat!( + "0000000000000000000000000000000000000000000000000000000000000020", // offset + "0000000000000000000000000000000000000000000000000de0b6b3a7640000", // amount out + "000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in + "0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f", // token out + "0000000000000000000000000000000000000000000000000000000000000000", // min amount out + "0000000000000000000000000000000000000000000000000000000000000000", // wrap + "0000000000000000000000000000000000000000000000000000000000000000", // unwrap + "0000000000000000000000000000000000000000000000000000000000000002", // tokens length + "0000000000000000000000002c6a3cd97c6283b95ac8c5a4459ebb0d5fd404f4", // 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 + // "0000000000000000000000000000000000000000000000000de0b6b3a7640000", // amount in + // "0000000000000000000000000000000000000000000000000000000067c205fe", // expiration + // "0000000000000000000000000000000000000000000000000000000000000000", // nonce + // "0000000000000000000000002c6a3cd97c6283b95ac8c5a4459ebb0d5fd404f4", // spender + // "00000000000000000000000000000000000000000000000000000000679a8006", // deadline + // offsets??? + // "0000000000000000000000000000000000000000000000000000000000000200", + // "0000000000000000000000000000000000000000000000000000000000000280", + // "0000000000000000000000000000000000000000000000000000000000000041", + // signature + // "fc5bac4e27cd5d71c85d232d8c6b31ea924d2e0031091ff9a39579d9e49c214328ea34876961d9200af691373c71a174e166793d02241c76adb93c5f87fe0f381c", + + let expected_swaps = String::from(concat!( + // ple encode adds aaalll of this :/ is it correct? + "0000000000000000000000000000000000000000000000000000000000000000", + "0000000000000000000000000000000000000000000000000000000000120000", + "0000000000000000000000000000000000000000000000000000000000020000", + "0000000000000000000000000000000000000000000000000000000000060000", + "000000000000000000000000000000000000000000000000000000000005b000", + "0000000000000000000000000000000000000000000000000000000000080000", + "0000000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000005b", + // Swap header + "00", // token in index + "01", // token out index + "000000", // split + // Swap data + "5c2f5a71f67c01775180adc06909288b4c329308", // executor address + "bd0625ab", // selector + "c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in + "88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", // component id + "2c6a3cd97c6283b95ac8c5a4459ebb0d5fd404f4", // receiver + "00", // zero2one + "00", // exact out + "0000000000", // padding + )); + let hex_calldata = encode(&calldata); + assert_eq!(hex_calldata[..576], expected_input); + assert_eq!(hex_calldata[1283..], expected_swaps); + } +} diff --git a/src/encoding/evm/strategy_encoder/selector.rs b/src/encoding/evm/strategy_encoder/selector.rs index 37e397c..7301552 100644 --- a/src/encoding/evm/strategy_encoder/selector.rs +++ b/src/encoding/evm/strategy_encoder/selector.rs @@ -1,4 +1,8 @@ +use alloy::signers::local::PrivateKeySigner; +use alloy_primitives::ChainId; + use crate::encoding::{ + errors::EncodingError, evm::strategy_encoder::encoder::{SplitSwapStrategyEncoder, StraightToPoolStrategyEncoder}, models::Solution, strategy_encoder::{StrategyEncoder, StrategySelector}, @@ -7,11 +11,21 @@ use crate::encoding::{ pub struct EVMStrategySelector; impl StrategySelector for EVMStrategySelector { - fn select_strategy(&self, solution: &Solution) -> Box { + fn select_strategy( + &self, + solution: &Solution, + signer: Option, + chain_id: ChainId, + ) -> Result, EncodingError> { if solution.straight_to_pool { - Box::new(StraightToPoolStrategyEncoder {}) + Ok(Box::new(StraightToPoolStrategyEncoder {})) } else { - Box::new(SplitSwapStrategyEncoder {}) + let signer = signer.ok_or_else(|| { + EncodingError::FatalError( + "Signer is required for SplitSwapStrategyEncoder".to_string(), + ) + })?; + Ok(Box::new(SplitSwapStrategyEncoder::new(signer, chain_id).unwrap())) } } } diff --git a/src/encoding/evm/swap_encoder/encoders.rs b/src/encoding/evm/swap_encoder/encoders.rs index de13cfc..b0ae977 100644 --- a/src/encoding/evm/swap_encoder/encoders.rs +++ b/src/encoding/evm/swap_encoder/encoders.rs @@ -42,6 +42,9 @@ impl SwapEncoder for UniswapV2SwapEncoder { // Token in address is always needed to perform a manual transfer from the router, // since no optimizations are performed that send from one pool to the next let args = ( + Address::from_str(self.executor_address()) + .map_err(|_| EncodingError::FatalError("Invalid executor address".to_string()))?, + self.executor_selector(), token_in_address, component_id, bytes_to_address(&encoding_context.receiver)?, @@ -107,6 +110,9 @@ impl SwapEncoder for UniswapV3SwapEncoder { })?; let args = ( + Address::from_str(self.executor_address()) + .map_err(|_| EncodingError::FatalError("Invalid executor address".to_string()))?, + self.executor_selector(), token_in_address, token_out_address, pool_fee_u24, @@ -155,6 +161,9 @@ impl SwapEncoder for BalancerV2SwapEncoder { .map_err(|_| EncodingError::FatalError("Invalid component ID".to_string()))?; let args = ( + Address::from_str(self.executor_address()) + .map_err(|_| EncodingError::FatalError("Invalid executor address".to_string()))?, + self.executor_selector(), bytes_to_address(&swap.token_in)?, bytes_to_address(&swap.token_out)?, component_id, @@ -196,7 +205,8 @@ mod tests { exact_out: false, router_address: Bytes::zero(20), }; - let encoder = UniswapV2SwapEncoder::new(String::from("0x")); + let encoder = + UniswapV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4")); let encoded_swap = encoder .encode_swap(swap, encoding_context) .unwrap(); @@ -204,6 +214,10 @@ mod tests { assert_eq!( hex_swap, String::from(concat!( + // executor address + "543778987b293c7e8cf0722bb2e935ba6f4068d4", + // executor selector + "bd0625ab", // in token "c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // component id @@ -239,7 +253,8 @@ mod tests { exact_out: false, router_address: Bytes::zero(20), }; - let encoder = UniswapV3SwapEncoder::new(String::from("0x")); + let encoder = + UniswapV3SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4")); let encoded_swap = encoder .encode_swap(swap, encoding_context) .unwrap(); @@ -247,6 +262,10 @@ mod tests { assert_eq!( hex_swap, String::from(concat!( + // executor address + "543778987b293c7e8cf0722bb2e935ba6f4068d4", + // executor selector + "bd0625ab", // in token "c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // out token @@ -283,7 +302,8 @@ mod tests { exact_out: false, router_address: Bytes::zero(20), }; - let encoder = BalancerV2SwapEncoder::new(String::from("0x")); + let encoder = + BalancerV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4")); let encoded_swap = encoder .encode_swap(swap, encoding_context) .unwrap(); @@ -292,6 +312,10 @@ mod tests { assert_eq!( hex_swap, String::from(concat!( + // executor address + "543778987b293c7e8cf0722bb2e935ba6f4068d4", + // executor selector + "bd0625ab", // token in "c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token out diff --git a/src/encoding/evm/utils.rs b/src/encoding/evm/utils.rs index c1b7d56..0afe763 100644 --- a/src/encoding/evm/utils.rs +++ b/src/encoding/evm/utils.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{Address, Keccak256, U256}; +use alloy_primitives::{aliases::U24, Address, Keccak256, U256}; use alloy_sol_types::SolValue; use num_bigint::BigUint; use tycho_core::Bytes; @@ -13,7 +13,7 @@ pub fn bytes_to_address(address: &Bytes) -> Result { if address.len() == 20 { Ok(Address::from_slice(address)) } else { - Err(EncodingError::InvalidInput(format!("Invalid ERC20 token address: {:?}", address))) + Err(EncodingError::InvalidInput(format!("Invalid address: {:?}", address))) } } @@ -56,3 +56,12 @@ pub fn encode_input(selector: &str, mut encoded_args: Vec) -> Vec { call_data.extend(encoded_args); call_data } + +/// Converts a percentage to a `U24` value. The percentage is a `f64` value between 0 and 100. +/// MAX_UINT24 corresponds to 100%. +pub fn percentage_to_uint24(percentage: f64) -> U24 { + const MAX_UINT24: u32 = 16_777_215; // 2^24 - 1 + + let scaled = (percentage / 100.0) * (MAX_UINT24 as f64); + U24::from(scaled.round()) +} diff --git a/src/encoding/models.rs b/src/encoding/models.rs index 4e2cbbd..0bd14bd 100644 --- a/src/encoding/models.rs +++ b/src/encoding/models.rs @@ -1,7 +1,7 @@ use num_bigint::BigUint; use tycho_core::{dto::ProtocolComponent, Bytes}; -#[derive(Clone)] +#[derive(Clone, Default, Debug)] #[allow(dead_code)] pub struct Solution { /// True if the solution is an exact output solution. @@ -11,7 +11,7 @@ pub struct Solution { /// Amount of the given token. pub given_amount: BigUint, /// The token being bought (exact in) or sold (exact out). - checked_token: Bytes, + pub checked_token: Bytes, /// Expected amount of the bought token (exact in) or sold token (exact out). pub expected_amount: BigUint, /// Minimum amount to be checked for the solution to be valid. @@ -35,14 +35,14 @@ pub struct Solution { pub native_action: Option, } -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, Debug)] #[allow(dead_code)] pub enum NativeAction { Wrap, Unwrap, } -#[derive(Clone)] +#[derive(Clone, Debug)] #[allow(dead_code)] pub struct Swap { /// Protocol component from tycho indexer @@ -51,7 +51,7 @@ pub struct Swap { pub token_in: Bytes, /// Token being output from the pool. pub token_out: Bytes, - /// Fraction of the amount to be swapped in this operation. + /// Percentage of the amount to be swapped in this operation. pub split: f64, } diff --git a/src/encoding/router_encoder.rs b/src/encoding/router_encoder.rs index 8136af6..e3af9bb 100644 --- a/src/encoding/router_encoder.rs +++ b/src/encoding/router_encoder.rs @@ -10,5 +10,4 @@ pub trait RouterEncoder { &self, solutions: Vec, ) -> Result, EncodingError>; - fn handle_approvals(&self, solutions: &[Solution]) -> Result>, EncodingError>; } diff --git a/src/encoding/strategy_encoder.rs b/src/encoding/strategy_encoder.rs index 2b4e348..1204e6b 100644 --- a/src/encoding/strategy_encoder.rs +++ b/src/encoding/strategy_encoder.rs @@ -1,12 +1,25 @@ +use alloy::signers::local::PrivateKeySigner; +use alloy_primitives::ChainId; +use tycho_core::Bytes; + use crate::encoding::{errors::EncodingError, models::Solution}; #[allow(dead_code)] pub trait StrategyEncoder { - fn encode_strategy(&self, to_encode: Solution) -> Result, EncodingError>; + fn encode_strategy( + &self, + to_encode: Solution, + router_address: Bytes, + ) -> Result, EncodingError>; fn selector(&self, exact_out: bool) -> &str; } pub trait StrategySelector { #[allow(dead_code)] - fn select_strategy(&self, solution: &Solution) -> Box; + fn select_strategy( + &self, + solution: &Solution, + signer: Option, + chain_id: ChainId, + ) -> Result, EncodingError>; } diff --git a/src/encoding/swap_encoder.rs b/src/encoding/swap_encoder.rs index 1a1fc0c..65e94c3 100644 --- a/src/encoding/swap_encoder.rs +++ b/src/encoding/swap_encoder.rs @@ -1,3 +1,6 @@ +use alloy_primitives::FixedBytes; +use tycho_core::keccak256; + use crate::encoding::{ errors::EncodingError, models::{EncodingContext, Swap}, @@ -14,4 +17,9 @@ pub trait SwapEncoder: Sync + Send { encoding_context: EncodingContext, ) -> Result, EncodingError>; fn executor_address(&self) -> &str; + + fn executor_selector(&self) -> FixedBytes<4> { + let hash = keccak256("swap(uint256,bytes)".as_bytes()); + FixedBytes::<4>::from([hash[0], hash[1], hash[2], hash[3]]) + } }