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
This commit is contained in:
Diana Carvalho
2025-01-31 18:40:59 +00:00
parent 9d32291c97
commit 1a8e0f102c
14 changed files with 32 additions and 200 deletions

View File

@@ -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 /// at a later time may succeed. It may have failed due to a temporary issue, such as a network
/// problem. /// problem.
#[derive(Error, Debug, PartialEq)] #[derive(Error, Debug, PartialEq)]
#[allow(dead_code)]
pub enum EncodingError { pub enum EncodingError {
#[error("Invalid input: {0}")] #[error("Invalid input: {0}")]
InvalidInput(String), InvalidInput(String),

View File

@@ -60,7 +60,6 @@ sol! {
} }
} }
#[allow(dead_code)]
impl Permit2 { impl Permit2 {
pub fn new(signer_pk: String, chain: Chain) -> Result<Self, EncodingError> { pub fn new(signer_pk: String, chain: Chain) -> Result<Self, EncodingError> {
let chain_id = ChainId::from(chain); let chain_id = ChainId::from(chain);

View File

@@ -12,7 +12,6 @@ use tokio::runtime::Runtime;
use crate::encoding::{errors::EncodingError, evm::utils::encode_input}; use crate::encoding::{errors::EncodingError, evm::utils::encode_input};
#[allow(dead_code)]
pub struct ProtocolApprovalsManager { pub struct ProtocolApprovalsManager {
client: Arc<RootProvider<BoxTransport>>, client: Arc<RootProvider<BoxTransport>>,
runtime: Runtime, runtime: Runtime,

View File

@@ -1,6 +1,6 @@
pub mod approvals; mod approvals;
mod models; mod models;
mod strategy_encoder; pub mod strategy_encoder;
mod swap_encoder; mod swap_encoder;
mod tycho_encoder; pub mod tycho_encoder;
mod utils; mod utils;

View File

@@ -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<u8>,
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<u8> {
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<u8>, 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<u8>, 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)");
}
}

View File

@@ -1,2 +1,2 @@
mod strategy_encoders; mod strategy_encoders;
mod strategy_selector; pub mod strategy_selector;

View File

@@ -10,25 +10,23 @@ use crate::encoding::{
tycho_encoder::TychoEncoder, tycho_encoder::TychoEncoder,
}; };
#[allow(dead_code)]
pub struct EVMTychoEncoder<S: StrategySelector> { pub struct EVMTychoEncoder<S: StrategySelector> {
strategy_selector: S, strategy_selector: S,
signer: Option<String>, signer_pk: Option<String>,
chain: Chain, chain: Chain,
router_address: Bytes, router_address: Bytes,
} }
#[allow(dead_code)]
impl<S: StrategySelector> EVMTychoEncoder<S> { impl<S: StrategySelector> EVMTychoEncoder<S> {
pub fn new( pub fn new(
strategy_selector: S, strategy_selector: S,
router_address: String, router_address: String,
signer: Option<String>, signer_pk: Option<String>,
chain: Chain, chain: Chain,
) -> Result<Self, EncodingError> { ) -> Result<Self, EncodingError> {
let router_address = Bytes::from_str(&router_address) let router_address = Bytes::from_str(&router_address)
.map_err(|_| EncodingError::FatalError("Invalid router address".to_string()))?; .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<S: StrategySelector> TychoEncoder<S> for EVMTychoEncoder<S> { impl<S: StrategySelector> TychoEncoder<S> for EVMTychoEncoder<S> {
@@ -51,7 +49,7 @@ impl<S: StrategySelector> TychoEncoder<S> for EVMTychoEncoder<S> {
let strategy = self.strategy_selector.select_strategy( let strategy = self.strategy_selector.select_strategy(
solution, solution,
self.signer.clone(), self.signer_pk.clone(),
self.chain, self.chain,
)?; )?;
let (contract_interaction, target_address) = let (contract_interaction, target_address) =

View File

@@ -16,13 +16,11 @@ pub fn bytes_to_address(address: &Bytes) -> Result<Address, EncodingError> {
} }
} }
#[allow(dead_code)]
pub fn biguint_to_u256(value: &BigUint) -> U256 { pub fn biguint_to_u256(value: &BigUint) -> U256 {
let bytes = value.to_bytes_be(); let bytes = value.to_bytes_be();
U256::from_be_slice(&bytes) U256::from_be_slice(&bytes)
} }
#[allow(dead_code)]
pub fn encode_input(selector: &str, mut encoded_args: Vec<u8>) -> Vec<u8> { pub fn encode_input(selector: &str, mut encoded_args: Vec<u8>) -> Vec<u8> {
let mut hasher = Keccak256::new(); let mut hasher = Keccak256::new();
hasher.update(selector.as_bytes()); hasher.update(selector.as_bytes());

View File

@@ -1,7 +1,7 @@
mod errors; mod errors;
#[cfg(feature = "evm")] #[cfg(feature = "evm")]
mod evm; pub mod evm;
mod models; pub mod models;
mod strategy_encoder; mod strategy_encoder;
mod swap_encoder; mod swap_encoder;
mod tycho_encoder; pub mod tycho_encoder;

View File

@@ -2,48 +2,46 @@ use num_bigint::BigUint;
use tycho_core::{dto::ProtocolComponent, Bytes}; use tycho_core::{dto::ProtocolComponent, Bytes};
#[derive(Clone, Default, Debug)] #[derive(Clone, Default, Debug)]
#[allow(dead_code)]
pub struct Solution { pub struct Solution {
/// True if the solution is an exact output solution. /// Address of the sender.
pub exact_out: bool, pub sender: Bytes,
/// Address of the receiver.
pub receiver: Bytes,
/// The token being sold (exact in) or bought (exact out). /// The token being sold (exact in) or bought (exact out).
pub given_token: Bytes, pub given_token: Bytes,
/// Amount of the given token. /// Amount of the given token.
pub given_amount: BigUint, pub given_amount: BigUint,
/// The token being bought (exact in) or sold (exact out). /// The token being bought (exact in) or sold (exact out).
pub checked_token: Bytes, 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<f64>,
/// Expected amount of the bought token (exact in) or sold token (exact out). /// Expected amount of the bought token (exact in) or sold token (exact out).
pub expected_amount: BigUint, pub expected_amount: Option<BigUint>,
/// Minimum amount to be checked for the solution to be valid. /// Minimum amount to be checked for the solution to be valid.
/// If not set, the check will not be performed. /// If not set, the check will not be performed.
pub check_amount: Option<BigUint>, pub check_amount: Option<BigUint>,
/// Address of the sender.
pub sender: Bytes,
/// Address of the receiver.
pub receiver: Bytes,
/// List of swaps to fulfill the solution. /// List of swaps to fulfill the solution.
pub swaps: Vec<Swap>, pub swaps: Vec<Swap>,
// If not set, then the Tycho Router will be used
pub router_address: Option<Bytes>,
// If set, the corresponding native action will be executed.
pub native_action: Option<NativeAction>,
/// If set to true, the solution will be encoded to be sent directly to the Executor and /// 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 /// skip the router. The user is responsible for managing necessary approvals and token
/// transfers. /// transfers.
pub direct_execution: bool, pub direct_execution: bool,
// if not set, then the Propeller Router will be used
pub router_address: Option<Bytes>,
// if set, it will be applied to check_amount
pub slippage: Option<f64>,
// if set, the corresponding native action will be executed
pub native_action: Option<NativeAction>,
} }
#[derive(Clone, PartialEq, Debug)] #[derive(Clone, PartialEq, Debug)]
#[allow(dead_code)]
pub enum NativeAction { pub enum NativeAction {
Wrap, Wrap,
Unwrap, Unwrap,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
#[allow(dead_code)]
pub struct Swap { pub struct Swap {
/// Protocol component from tycho indexer /// Protocol component from tycho indexer
pub component: ProtocolComponent, pub component: ProtocolComponent,
@@ -51,20 +49,20 @@ pub struct Swap {
pub token_in: Bytes, pub token_in: Bytes,
/// Token being output from the pool. /// Token being output from the pool.
pub token_out: Bytes, 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, pub split: f64,
} }
#[allow(dead_code)] #[derive(Clone, Debug)]
pub struct Transaction { pub struct Transaction {
pub data: Vec<u8>,
// ETH value to be sent with the transaction.
pub value: BigUint,
// Address of the contract to call with the calldata // Address of the contract to call with the calldata
pub to: Bytes, pub to: Bytes,
// ETH value to be sent with the transaction.
pub value: BigUint,
// Encoded calldata for the transaction.
pub data: Vec<u8>,
} }
#[allow(dead_code)]
pub struct EncodingContext { pub struct EncodingContext {
pub receiver: Bytes, pub receiver: Bytes,
pub exact_out: bool, pub exact_out: bool,

View File

@@ -2,7 +2,6 @@ use tycho_core::{models::Chain, Bytes};
use crate::encoding::{errors::EncodingError, models::Solution}; use crate::encoding::{errors::EncodingError, models::Solution};
#[allow(dead_code)]
pub trait StrategyEncoder { pub trait StrategyEncoder {
fn encode_strategy( fn encode_strategy(
&self, &self,
@@ -12,7 +11,6 @@ pub trait StrategyEncoder {
} }
pub trait StrategySelector { pub trait StrategySelector {
#[allow(dead_code)]
fn select_strategy( fn select_strategy(
&self, &self,
solution: &Solution, solution: &Solution,

View File

@@ -3,7 +3,6 @@ use crate::encoding::{
models::{EncodingContext, Swap}, models::{EncodingContext, Swap},
}; };
#[allow(dead_code)]
pub trait SwapEncoder: Sync + Send { pub trait SwapEncoder: Sync + Send {
fn new(executor_address: String) -> Self fn new(executor_address: String) -> Self
where where

View File

@@ -4,7 +4,6 @@ use crate::encoding::{
strategy_encoder::StrategySelector, strategy_encoder::StrategySelector,
}; };
#[allow(dead_code)]
pub trait TychoEncoder<S: StrategySelector> { pub trait TychoEncoder<S: StrategySelector> {
fn encode_router_calldata( fn encode_router_calldata(
&self, &self,

View File

@@ -1 +1 @@
mod encoding; pub mod encoding;