chore: merge main

This commit is contained in:
TAMARA LIPOWSKI
2025-02-21 09:48:22 -05:00
10 changed files with 244 additions and 101 deletions

View File

@@ -1,11 +1,9 @@
use std::io::{self, Read};
use clap::{Parser, Subcommand};
use serde_json::Value;
use tycho_core::models::Chain;
use tycho_execution::encoding::{
errors::EncodingError, evm::encoder_builder::EVMEncoderBuilder, models::Solution,
tycho_encoder::TychoEncoder,
evm::encoder_builder::EVMEncoderBuilder, models::Solution, tycho_encoder::TychoEncoder,
};
#[derive(Parser)]
@@ -52,6 +50,11 @@ pub enum Commands {
TychoRouter {
#[arg(short, long)]
config_path: Option<String>,
},
/// Use the Tycho router encoding strategy with Permit2 approval and token in transfer
TychoRouterPermit2 {
#[arg(short, long)]
config_path: Option<String>,
#[arg(short, long)]
swapper_pk: String,
},
@@ -64,6 +67,7 @@ pub enum Commands {
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
let chain = Chain::Ethereum;
// Read from stdin until EOF
let mut buffer = String::new();
@@ -74,16 +78,24 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
if buffer.trim().is_empty() {
return Err("No input provided. Expected JSON input on stdin.".into());
}
let solution: Solution = serde_json::from_str(&buffer)?;
// Encode the solution
let encoded = match cli.command {
Commands::TychoRouter { config_path, swapper_pk } => {
encode_swaps(&buffer, config_path, Some(swapper_pk), true)?
}
Commands::DirectExecution { config_path } => {
encode_swaps(&buffer, config_path, None, false)?
let mut builder = EVMEncoderBuilder::new().chain(chain);
builder = match cli.command {
Commands::TychoRouter { config_path } => builder.tycho_router(config_path)?,
Commands::TychoRouterPermit2 { config_path, swapper_pk } => {
builder.tycho_router_with_permit2(config_path, swapper_pk)?
}
Commands::DirectExecution { config_path } => builder.direct_execution(config_path)?,
};
let encoder = builder.build()?;
let transactions = encoder.encode_router_calldata(vec![solution])?;
let encoded = serde_json::json!({
"to": format!("0x{}", hex::encode(&transactions[0].to)),
"value": format!("0x{}", hex::encode(transactions[0].value.to_bytes_be())),
"data": format!("0x{}", hex::encode(&transactions[0].data)),
});
// Output the encoded result as JSON to stdout
println!(
"{}",
@@ -93,32 +105,3 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn encode_swaps(
input: &str,
config_path: Option<String>,
swapper_pk: Option<String>,
use_tycho_router: bool,
) -> Result<Value, EncodingError> {
let solution: Solution = serde_json::from_str(input)?;
let chain = Chain::Ethereum;
let mut builder = EVMEncoderBuilder::new().chain(chain);
builder = if use_tycho_router {
let private_key = swapper_pk.ok_or(EncodingError::FatalError(
"Swapper private key is required for tycho_router".to_string(),
))?;
builder.tycho_router(private_key, config_path)?
} else {
builder.direct_execution(config_path)?
};
let encoder = builder.build()?;
let transactions = encoder.encode_router_calldata(vec![solution])?;
Ok(serde_json::json!({
"to": format!("0x{}", hex::encode(&transactions[0].to)),
"value": format!("0x{}", hex::encode(transactions[0].value.to_bytes_be())),
"data": format!("0x{}", hex::encode(&transactions[0].data)),
}))
}

View File

@@ -42,17 +42,35 @@ impl EVMEncoderBuilder {
self
}
/// Shortcut method to initialize a `SplitSwapStrategyEncoder` with a given `swapper_pk`.
/// **Note**: Should not be used at the same time as `strategy_encoder`.
pub fn tycho_router(
self,
swapper_pk: String,
executors_file_path: Option<String>,
) -> Result<Self, EncodingError> {
/// 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 tycho_router(self, executors_file_path: Option<String>) -> Result<Self, EncodingError> {
if let Some(chain) = self.chain {
let swap_encoder_registry = SwapEncoderRegistry::new(executors_file_path, chain)?;
let strategy =
Box::new(SplitSwapStrategyEncoder::new(swapper_pk, chain, swap_encoder_registry)?);
Box::new(SplitSwapStrategyEncoder::new(chain, swap_encoder_registry, None)?);
Ok(EVMEncoderBuilder { chain: Some(chain), strategy: Some(strategy) })
} 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 tycho_router_with_permit2(
self,
executors_file_path: Option<String>,
swapper_pk: String,
) -> Result<Self, EncodingError> {
if let Some(chain) = self.chain {
let swap_encoder_registry = SwapEncoderRegistry::new(executors_file_path, chain)?;
let strategy = Box::new(SplitSwapStrategyEncoder::new(
chain,
swap_encoder_registry,
Some(swapper_pk),
)?);
Ok(EVMEncoderBuilder { chain: Some(chain), strategy: Some(strategy) })
} else {
Err(EncodingError::FatalError(

View File

@@ -79,7 +79,7 @@ pub trait EVMStrategyEncoder: StrategyEncoder {
#[derive(Clone)]
pub struct SplitSwapStrategyEncoder {
swap_encoder_registry: SwapEncoderRegistry,
permit2: Permit2,
permit2: Option<Permit2>,
selector: String,
native_address: Bytes,
wrapped_address: Bytes,
@@ -88,14 +88,21 @@ pub struct SplitSwapStrategyEncoder {
impl SplitSwapStrategyEncoder {
pub fn new(
swapper_pk: String,
blockchain: tycho_core::models::Chain,
swap_encoder_registry: SwapEncoderRegistry,
swapper_pk: Option<String>,
) -> Result<Self, EncodingError> {
let chain = Chain::from(blockchain);
let selector = "swapPermit2(uint256,address,address,uint256,bool,bool,uint256,address,((address,uint160,uint48,uint48),address,uint256),bytes,bytes)".to_string();
let (permit2, selector) = if let Some(swapper_pk) = swapper_pk {
(Some(Permit2::new(swapper_pk, chain.clone())?), "swapPermit2(uint256,address,address,uint256,bool,bool,uint256,address,((address,uint160,uint48,uint48),address,uint256),bytes,bytes)".to_string())
} else {
(
None,
"swap(uint256,address,address,uint256,bool,bool,uint256,address,bytes)".to_string(),
)
};
Ok(Self {
permit2: Permit2::new(swapper_pk, chain.clone())?,
permit2,
selector,
swap_encoder_registry,
native_address: chain.native_token()?,
@@ -122,12 +129,7 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
&self.native_address,
&self.wrapped_address,
)?;
let (permit, signature) = self.permit2.get_permit(
&solution.router_address,
&solution.sender,
&solution.given_token,
&solution.given_amount,
)?;
let min_amount_out = get_min_amount_for_solution(solution.clone());
// The tokens array is composed of the given token, the checked token and all the
@@ -214,20 +216,41 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
}
let encoded_swaps = self.ple_encode(swaps);
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();
let method_calldata = if let Some(permit2) = self.permit2.clone() {
let (permit, signature) = permit2.get_permit(
&solution.router_address,
&solution.sender,
&solution.given_token,
&solution.given_amount,
)?;
(
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()
} else {
(
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)?,
encoded_swaps,
)
.abi_encode()
};
let contract_interaction = encode_input(&self.selector, method_calldata);
Ok((contract_interaction, solution.router_address, None))
@@ -606,7 +629,8 @@ mod tests {
};
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, Some(private_key))
.unwrap();
let solution = Solution {
exact_out: false,
given_token: weth,
@@ -707,7 +731,8 @@ mod tests {
};
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, Some(private_key))
.unwrap();
let solution = Solution {
exact_out: false,
given_token: eth(),
@@ -755,7 +780,8 @@ mod tests {
};
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, Some(private_key))
.unwrap();
let solution = Solution {
exact_out: false,
given_token: dai,
@@ -844,7 +870,8 @@ mod tests {
};
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, Some(private_key))
.unwrap();
let solution = Solution {
exact_out: false,
given_token: weth,
@@ -924,7 +951,8 @@ mod tests {
};
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, Some(private_key))
.unwrap();
let solution = Solution {
exact_out: false,
given_token: usdc,
@@ -1010,6 +1038,86 @@ mod tests {
assert_eq!(hex_calldata[1288..], expected_swaps);
}
#[test]
fn test_split_swap_strategy_encoder_simple_route_no_permit2() {
// Performs a single swap from WETH to DAI on a USV2 pool, without permit2 and no grouping
// optimizations.
let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
let dai = Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap();
let expected_amount = Some(BigUint::from_str("2_650_000000000000000000").unwrap());
let slippage = Some(0.01f64);
let checked_amount = Some(BigUint::from_str("2_640_000000000000000000").unwrap());
let expected_min_amount = U256::from_str("2_640_000000000000000000").unwrap();
let swap = Swap {
component: ProtocolComponent {
id: "0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11".to_string(),
protocol_system: "uniswap_v2".to_string(),
..Default::default()
},
token_in: weth.clone(),
token_out: dai.clone(),
split: 0f64,
};
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, None).unwrap();
let solution = Solution {
exact_out: false,
given_token: weth,
given_amount: BigUint::from_str("1_000000000000000000").unwrap(),
checked_token: dai,
expected_amount,
slippage,
checked_amount,
sender: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(),
receiver: Bytes::from_str("0xcd09f75E2BF2A4d11F3AB23f1389FcC1621c0cc2").unwrap(),
router_address: Bytes::from_str("0x3Ede3eCa2a72B3aeCC820E955B36f38437D01395").unwrap(),
swaps: vec![swap],
..Default::default()
};
let (calldata, _, _) = encoder
.encode_strategy(solution)
.unwrap();
let expected_min_amount_encoded = hex::encode(U256::abi_encode(&expected_min_amount));
let expected_input = [
"0a83cb08", // 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
"0000000000000000000000000000000000000000000000000000000000000120", // offset of ple encoded swaps
"000000000000000000000000000000000000000000000000000000000000005c", // length of ple encoded swaps without padding
"005a", // ple encoded swaps
// Swap header
"00", // token in index
"01", // token out index
"000000", // split
// Swap data
"5c2f5a71f67c01775180adc06909288b4c329308", // executor address
"bd0625ab", // selector
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // token in
"a478c2975ab1ea89e8196811f51a7b7ade33eb11", // component id
"3ede3eca2a72b3aecc820e955b36f38437d01395", // receiver
"00", // zero2one
"00", // exact out
"000000", // padding
]
.join("");
let hex_calldata = encode(&calldata);
assert_eq!(hex_calldata, expected_input);
println!("{}", hex_calldata);
}
#[test]
fn test_split_encoding_strategy_usv4_eth_in() {
// Performs a single swap from ETH to PEPE using a USV4 pool
@@ -1045,7 +1153,8 @@ mod tests {
};
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, Some(private_key))
.unwrap();
let solution = Solution {
exact_out: false,
@@ -1108,7 +1217,9 @@ mod tests {
let swap_encoder_registry = get_swap_encoder_registry();
let encoder =
SplitSwapStrategyEncoder::new(private_key, eth_chain(), swap_encoder_registry).unwrap();
SplitSwapStrategyEncoder::new(eth_chain(), swap_encoder_registry, Some(private_key))
.unwrap();
let solution = Solution {
exact_out: false,
given_token: usdc,

View File

@@ -20,6 +20,16 @@ pub struct EVMTychoEncoder {
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_core::models::Chain,