chore: fix clippy warnings and nightly fmt

This commit is contained in:
TAMARA LIPOWSKI
2025-01-16 16:13:15 -05:00
parent e93bf11a85
commit f8e8a72c53
14 changed files with 119 additions and 89 deletions

2
Cargo.lock generated
View File

@@ -3039,7 +3039,7 @@ dependencies = [
[[package]] [[package]]
name = "tycho-execution" name = "tycho-execution"
version = "1.0.0" version = "0.1.0"
dependencies = [ dependencies = [
"alloy", "alloy",
"alloy-primitives", "alloy-primitives",

View File

@@ -1,33 +1,32 @@
use std::{env, sync::Arc}; use std::{env, sync::Arc};
use alloy::{ use alloy::{
providers::{Provider, ProviderBuilder, RootProvider}, providers::{ProviderBuilder, RootProvider},
transports::BoxTransport, transports::BoxTransport,
}; };
use alloy_primitives::Address; use alloy_primitives::Address;
use dotenv::dotenv; use dotenv::dotenv;
#[allow(dead_code)]
pub struct ProtocolApprovalsManager { pub struct ProtocolApprovalsManager {
client: Arc<RootProvider<BoxTransport>>, client: Arc<RootProvider<BoxTransport>>,
} }
impl ProtocolApprovalsManager { impl ProtocolApprovalsManager {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self { client: get_client() }
client: get_client(),
}
} }
pub async fn approval_needed( pub async fn approval_needed(
&self, &self,
token: Address, _token: Address,
spender_address: Address, _spender_address: Address,
router_address: Address, _router_address: Address,
) -> bool { ) -> bool {
todo!() todo!()
// should be something like // should be something like
// let allowance = self // let allowance = self
// .client // .client
// .call(token, "allowance(address,address)(uint256)", (router_address, spender_address)) // .call(token, "allowance(address,address)(uint256)", (router_address,
// .await; // spender_address)) .await;
// //
// allowance == U256::ZERO // If allowance is 0, approval is needed // allowance == U256::ZERO // If allowance is 0, approval is needed
} }

View File

@@ -1,6 +1,7 @@
use num_bigint::BigUint; use num_bigint::BigUint;
use tycho_core::Bytes; use tycho_core::Bytes;
#[allow(dead_code)]
pub struct Approval { pub struct Approval {
pub spender: Bytes, pub spender: Bytes,
pub owner: Bytes, pub owner: Bytes,
@@ -9,5 +10,6 @@ pub struct Approval {
} }
pub trait UserApprovalsManager { pub trait UserApprovalsManager {
#[allow(dead_code)]
fn encode_approvals(&self, approvals: Vec<Approval>) -> Vec<u8>; fn encode_approvals(&self, approvals: Vec<Approval>) -> Vec<u8>;
} }

View File

@@ -1,12 +1,16 @@
use crate::encoding::approvals::interface::{Approval, UserApprovalsManager};
use alloy_primitives::U256;
use std::str::FromStr; use std::str::FromStr;
use alloy_primitives::U256;
use tycho_core::Bytes; use tycho_core::Bytes;
use crate::encoding::approvals::interface::{Approval, UserApprovalsManager};
#[allow(dead_code)]
pub struct Permit2 { pub struct Permit2 {
pub address: Bytes, pub address: Bytes,
} }
#[allow(dead_code)]
impl Permit2 { impl Permit2 {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
@@ -16,9 +20,9 @@ impl Permit2 {
} }
fn get_allowance_data( fn get_allowance_data(
&self, &self,
user: Bytes, _user: Bytes,
router_address: Bytes, _router_address: Bytes,
token: Bytes, _token: Bytes,
) -> (U256, u64, U256) { ) -> (U256, u64, U256) {
// get allowance data (if it exists) and the nonce // get allowance data (if it exists) and the nonce
// returns permitAmount, expiration, nonce // returns permitAmount, expiration, nonce
@@ -26,12 +30,12 @@ impl Permit2 {
} }
} }
impl UserApprovalsManager for Permit2 { impl UserApprovalsManager for Permit2 {
fn encode_approvals(&self, approvals: Vec<Approval>) -> Vec<u8> { fn encode_approvals(&self, _approvals: Vec<Approval>) -> Vec<u8> {
// calls get_allowance_data to get nonce // calls get_allowance_data to get nonce
// checks if we are not permitted already // checks if we are not permitted already
// puts data into a permitSingle struct if there is only 1 PermitDetails, if there are several, use PermitBatch // puts data into a permitSingle struct if there is only 1 PermitDetails, if there are
// adds the nonce and the expiration (uniswap recommends 30 days for expiration) // several, use PermitBatch adds the nonce and the expiration (uniswap recommends
// signs data // 30 days for expiration) signs data
// returns encoded data // returns encoded data
todo!() todo!()
} }

View File

@@ -1,7 +1,7 @@
use std::{env, str::FromStr};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use num_bigint::BigUint; use num_bigint::BigUint;
use std::env;
use std::str::FromStr;
use tycho_core::{dto::ProtocolComponent, Bytes}; use tycho_core::{dto::ProtocolComponent, Bytes};
lazy_static! { lazy_static! {
@@ -12,6 +12,7 @@ lazy_static! {
} }
#[derive(Clone)] #[derive(Clone)]
#[allow(dead_code)]
pub struct Solution { pub struct Solution {
/// True if the solution is an exact output solution. /// True if the solution is an exact output solution.
pub exact_out: bool, pub exact_out: bool,
@@ -32,8 +33,9 @@ pub struct Solution {
pub receiver: Bytes, 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 set to true, the solution will be encoded to be sent directly to the SwapExecutor and skip the router. /// If set to true, the solution will be encoded to be sent directly to the SwapExecutor and
/// The user is responsible for managing necessary approvals and token transfers. /// skip the router. The user is responsible for managing necessary approvals and token
/// transfers.
pub straight_to_pool: bool, pub straight_to_pool: bool,
// if not set, then the Propeller Router will be used // if not set, then the Propeller Router will be used
pub router_address: Option<Bytes>, pub router_address: Option<Bytes>,
@@ -44,6 +46,7 @@ pub struct Solution {
} }
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
#[allow(dead_code)]
pub enum NativeAction { pub enum NativeAction {
Wrap, Wrap,
Unwrap, Unwrap,
@@ -61,6 +64,7 @@ pub struct Swap {
pub split: f64, pub split: f64,
} }
#[allow(dead_code)]
pub struct Transaction { pub struct Transaction {
pub data: Vec<u8>, pub data: Vec<u8>,
// ETH value to be sent with the transaction. // ETH value to be sent with the transaction.

View File

@@ -1,44 +1,46 @@
use crate::encoding::approvals::interface::{Approval, UserApprovalsManager};
use crate::encoding::models::{NativeAction, Solution, Transaction, PROPELLER_ROUTER_ADDRESS};
use crate::encoding::strategy_selector::StrategySelector;
use crate::encoding::utils::{encode_input, ple_encode};
use alloy_sol_types::SolValue; use alloy_sol_types::SolValue;
use anyhow::Error; use anyhow::Error;
use num_bigint::BigUint; use num_bigint::BigUint;
use crate::encoding::{
approvals::interface::{Approval, UserApprovalsManager},
models::{NativeAction, Solution, Transaction, PROPELLER_ROUTER_ADDRESS},
strategy_selector::StrategySelector,
utils::{encode_input, ple_encode},
};
#[allow(dead_code)]
struct RouterEncoder<S: StrategySelector, A: UserApprovalsManager> { struct RouterEncoder<S: StrategySelector, A: UserApprovalsManager> {
strategy_selector: S, strategy_selector: S,
approvals_manager: A, approvals_manager: A,
} }
#[allow(dead_code)]
impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> { impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> {
pub fn new(strategy_selector: S, approvals_manager: A) -> Self { pub fn new(strategy_selector: S, approvals_manager: A) -> Self {
RouterEncoder { RouterEncoder { strategy_selector, approvals_manager }
strategy_selector,
approvals_manager,
}
} }
pub fn encode_router_calldata(&self, solutions: Vec<Solution>) -> Result<Transaction, Error> { pub fn encode_router_calldata(&self, solutions: Vec<Solution>) -> Result<Transaction, Error> {
let approvals_calldata = self.handle_approvals(&solutions)?; // TODO: where should we append this? let _approvals_calldata = self.handle_approvals(&solutions)?; // TODO: where should we append this?
let mut calldata_list: Vec<Vec<u8>> = Vec::new(); let mut calldata_list: Vec<Vec<u8>> = Vec::new();
let encode_for_batch_execute = solutions.len() > 1; let encode_for_batch_execute = solutions.len() > 1;
let mut value = BigUint::ZERO; let mut value = BigUint::ZERO;
for solution in solutions.iter() { for solution in solutions.iter() {
let exact_out = solution.exact_out.clone(); let exact_out = solution.exact_out;
let straight_to_pool = solution.straight_to_pool.clone(); let straight_to_pool = solution.straight_to_pool;
let strategy = self.strategy_selector.select_strategy(&solution); let strategy = self
.strategy_selector
.select_strategy(solution);
let method_calldata = strategy.encode_strategy((*solution).clone())?; let method_calldata = strategy.encode_strategy((*solution).clone())?;
let contract_interaction = if encode_for_batch_execute { let contract_interaction = if encode_for_batch_execute {
let args = (strategy.action_type(exact_out) as u16, method_calldata); let args = (strategy.action_type(exact_out) as u16, method_calldata);
args.abi_encode() args.abi_encode()
} else if straight_to_pool {
method_calldata
} else { } else {
if straight_to_pool { encode_input(strategy.selector(exact_out), method_calldata)
method_calldata
} else {
encode_input(strategy.selector(exact_out), method_calldata)
}
}; };
calldata_list.push(contract_interaction); calldata_list.push(contract_interaction);
@@ -56,7 +58,7 @@ impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> {
Ok(Transaction { data, value }) Ok(Transaction { data, value })
} }
fn handle_approvals(&self, solutions: &Vec<Solution>) -> Result<Vec<u8>, Error> { fn handle_approvals(&self, solutions: &[Solution]) -> Result<Vec<u8>, Error> {
let mut approvals = Vec::new(); let mut approvals = Vec::new();
for solution in solutions.iter() { for solution in solutions.iter() {
approvals.push(Approval { approvals.push(Approval {
@@ -69,6 +71,8 @@ impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> {
owner: solution.sender.clone(), owner: solution.sender.clone(),
}); });
} }
Ok(self.approvals_manager.encode_approvals(approvals)) Ok(self
.approvals_manager
.encode_approvals(approvals))
} }
} }

View File

@@ -1,16 +1,18 @@
use std::cmp::min;
use alloy_primitives::Address; use alloy_primitives::Address;
use alloy_sol_types::SolValue; use alloy_sol_types::SolValue;
use anyhow::Error; use anyhow::Error;
use num_bigint::BigUint; use num_bigint::BigUint;
use num_traits::Zero; use num_traits::Zero;
use std::cmp::min;
use crate::encoding::models::{ use crate::encoding::{
ActionType, EncodingContext, NativeAction, Solution, PROPELLER_ROUTER_ADDRESS, models::{ActionType, EncodingContext, NativeAction, Solution, PROPELLER_ROUTER_ADDRESS},
swap_encoder::SWAP_ENCODER_REGISTRY,
utils::{biguint_to_u256, ple_encode},
}; };
use crate::encoding::swap_encoder::SWAP_ENCODER_REGISTRY;
use crate::encoding::utils::{biguint_to_u256, ple_encode};
#[allow(dead_code)]
pub trait StrategyEncoder { pub trait StrategyEncoder {
fn encode_strategy(&self, to_encode: Solution) -> Result<Vec<u8>, Error>; fn encode_strategy(&self, to_encode: Solution) -> Result<Vec<u8>, Error>;
@@ -34,7 +36,7 @@ pub trait StrategyEncoder {
pub struct SingleSwapStrategyEncoder {} pub struct SingleSwapStrategyEncoder {}
impl StrategyEncoder for SingleSwapStrategyEncoder { impl StrategyEncoder for SingleSwapStrategyEncoder {
fn encode_strategy(&self, solution: Solution) -> Result<Vec<u8>, Error> { fn encode_strategy(&self, _solution: Solution) -> Result<Vec<u8>, Error> {
todo!() todo!()
} }
@@ -86,11 +88,7 @@ impl StrategyEncoder for SequentialStrategyEncoder {
} else { } else {
PROPELLER_ROUTER_ADDRESS.clone() PROPELLER_ROUTER_ADDRESS.clone()
}; };
let receiver = if is_last { let receiver = if is_last { solution.receiver.clone() } else { router_address.clone() };
solution.receiver.clone()
} else {
router_address.clone()
};
let encoding_context = EncodingContext { let encoding_context = EncodingContext {
receiver, receiver,
@@ -116,7 +114,7 @@ impl StrategyEncoder for SequentialStrategyEncoder {
wrap, wrap,
unwrap, unwrap,
biguint_to_u256(&solution.given_amount), biguint_to_u256(&solution.given_amount),
if check_amount.is_zero() { false } else { true }, // if check_amount is zero, then we don't need to check !check_amount.is_zero(), /* if check_amount is zero, then we don't need to check */
biguint_to_u256(&check_amount), biguint_to_u256(&check_amount),
encoded_swaps, encoded_swaps,
) )
@@ -144,7 +142,7 @@ impl StrategyEncoder for SequentialStrategyEncoder {
pub struct SplitSwapStrategyEncoder {} pub struct SplitSwapStrategyEncoder {}
impl StrategyEncoder for SplitSwapStrategyEncoder { impl StrategyEncoder for SplitSwapStrategyEncoder {
fn encode_strategy(&self, solution: Solution) -> Result<Vec<u8>, Error> { fn encode_strategy(&self, _solution: Solution) -> Result<Vec<u8>, Error> {
todo!() todo!()
} }
fn action_type(&self, _exact_out: bool) -> ActionType { fn action_type(&self, _exact_out: bool) -> ActionType {

View File

@@ -1,10 +1,13 @@
use crate::encoding::models::Solution; use crate::encoding::{
use crate::encoding::strategy_encoder::{ models::Solution,
SequentialStrategyEncoder, SingleSwapStrategyEncoder, SplitSwapStrategyEncoder, strategy_encoder::{
StraightToPoolStrategyEncoder, StrategyEncoder, SequentialStrategyEncoder, SingleSwapStrategyEncoder, SplitSwapStrategyEncoder,
StraightToPoolStrategyEncoder, StrategyEncoder,
},
}; };
pub trait StrategySelector { pub trait StrategySelector {
#[allow(dead_code)]
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder>; fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder>;
} }
@@ -16,7 +19,11 @@ impl StrategySelector for DefaultStrategySelector {
Box::new(StraightToPoolStrategyEncoder {}) Box::new(StraightToPoolStrategyEncoder {})
} else if solution.swaps.len() == 1 { } else if solution.swaps.len() == 1 {
Box::new(SingleSwapStrategyEncoder {}) Box::new(SingleSwapStrategyEncoder {})
} else if solution.swaps.iter().all(|s| s.split == 0.0) { } else if solution
.swaps
.iter()
.all(|s| s.split == 0.0)
{
Box::new(SequentialStrategyEncoder {}) Box::new(SequentialStrategyEncoder {})
} else { } else {
Box::new(SplitSwapStrategyEncoder {}) Box::new(SplitSwapStrategyEncoder {})

View File

@@ -1,8 +1,10 @@
use crate::encoding::swap_encoder::swap_encoder::{ use std::str::FromStr;
use alloy_primitives::Address;
use crate::encoding::swap_encoder::swap_struct_encoder::{
BalancerV2SwapEncoder, SwapEncoder, UniswapV2SwapEncoder, BalancerV2SwapEncoder, SwapEncoder, UniswapV2SwapEncoder,
}; };
use alloy_primitives::Address;
use std::str::FromStr;
pub struct SwapEncoderBuilder { pub struct SwapEncoderBuilder {
protocol_system: String, protocol_system: String,
@@ -14,7 +16,7 @@ impl SwapEncoderBuilder {
SwapEncoderBuilder { SwapEncoderBuilder {
protocol_system: protocol_system.to_string(), protocol_system: protocol_system.to_string(),
executor_address: Address::from_str(executor_address) executor_address: Address::from_str(executor_address)
.expect(&format!("Invalid address: {}", executor_address)), .unwrap_or_else(|_| panic!("Invalid address: {}", executor_address)),
} }
} }

View File

@@ -1,10 +1,12 @@
use crate::encoding::swap_encoder::registry::{Config, SwapEncoderRegistry};
use lazy_static::lazy_static;
use std::sync::RwLock; use std::sync::RwLock;
use lazy_static::lazy_static;
use crate::encoding::swap_encoder::registry::{Config, SwapEncoderRegistry};
mod builder; mod builder;
mod registry; mod registry;
mod swap_encoder; mod swap_struct_encoder;
lazy_static! { lazy_static! {
pub static ref SWAP_ENCODER_REGISTRY: RwLock<SwapEncoderRegistry> = { pub static ref SWAP_ENCODER_REGISTRY: RwLock<SwapEncoderRegistry> = {

View File

@@ -1,8 +1,10 @@
use crate::encoding::swap_encoder::builder::SwapEncoderBuilder; use std::{collections::HashMap, fs};
use crate::encoding::swap_encoder::swap_encoder::SwapEncoder;
use serde::Deserialize; use serde::Deserialize;
use std::collections::HashMap;
use std::fs; use crate::encoding::swap_encoder::{
builder::SwapEncoderBuilder, swap_struct_encoder::SwapEncoder,
};
pub struct SwapEncoderRegistry { pub struct SwapEncoderRegistry {
encoders: HashMap<String, Box<dyn SwapEncoder>>, encoders: HashMap<String, Box<dyn SwapEncoder>>,
@@ -14,16 +16,16 @@ impl SwapEncoderRegistry {
for (protocol, executor_address) in config.executors { for (protocol, executor_address) in config.executors {
let builder = SwapEncoderBuilder::new(&protocol, &executor_address); let builder = SwapEncoderBuilder::new(&protocol, &executor_address);
let encoder = builder.build().expect(&format!( let encoder = builder.build().unwrap_or_else(|_| {
"Failed to build swap encoder for protocol: {}", panic!("Failed to build swap encoder for protocol: {}", protocol)
protocol });
));
encoders.insert(protocol, encoder); encoders.insert(protocol, encoder);
} }
Self { encoders } Self { encoders }
} }
#[allow(clippy::borrowed_box)]
pub fn get_encoder(&self, protocol_system: &str) -> Option<&Box<dyn SwapEncoder>> { pub fn get_encoder(&self, protocol_system: &str) -> Option<&Box<dyn SwapEncoder>> {
self.encoders.get(protocol_system) self.encoders.get(protocol_system)
} }

View File

@@ -1,10 +1,14 @@
use crate::encoding::approvals::approvals_manager::ProtocolApprovalsManager; use std::str::FromStr;
use crate::encoding::models::{EncodingContext, Swap};
use crate::encoding::utils::bytes_to_address;
use alloy_primitives::Address; use alloy_primitives::Address;
use alloy_sol_types::SolValue; use alloy_sol_types::SolValue;
use anyhow::Error; use anyhow::Error;
use std::str::FromStr;
use crate::encoding::{
approvals::approvals_manager::ProtocolApprovalsManager,
models::{EncodingContext, Swap},
utils::bytes_to_address,
};
pub trait SwapEncoder: Sync + Send { pub trait SwapEncoder: Sync + Send {
fn new(executor_address: Address) -> Self fn new(executor_address: Address) -> Self
@@ -23,7 +27,11 @@ impl SwapEncoder for UniswapV2SwapEncoder {
fn new(executor_address: Address) -> Self { fn new(executor_address: Address) -> Self {
Self { executor_address } Self { executor_address }
} }
fn encode_swap(&self, swap: Swap, encoding_context: EncodingContext) -> Result<Vec<u8>, Error> { fn encode_swap(
&self,
_swap: Swap,
_encoding_context: EncodingContext,
) -> Result<Vec<u8>, Error> {
todo!() todo!()
} }
@@ -55,7 +63,7 @@ impl SwapEncoder for BalancerV2SwapEncoder {
let router_address = bytes_to_address(&encoding_context.address_for_approvals)?; let router_address = bytes_to_address(&encoding_context.address_for_approvals)?;
let approval_needed = runtime.block_on(async { let approval_needed = runtime.block_on(async {
token_approvals_manager token_approvals_manager
.approval_needed(token, self.vault_address.clone(), router_address) .approval_needed(token, self.vault_address, router_address)
.await .await
}); });
// should we return gas estimation here too?? if there is an approval needed, gas will be // should we return gas estimation here too?? if there is an approval needed, gas will be

View File

@@ -12,10 +12,7 @@ pub fn bytes_to_address(address: &Bytes) -> Result<Address, Error> {
if address.len() == 20 { if address.len() == 20 {
Ok(Address::from_slice(address)) Ok(Address::from_slice(address))
} else { } else {
Err(anyhow::format_err!( Err(anyhow::format_err!("Invalid ERC20 token address: {:?}", address))
"Invalid ERC20 token address: {:?}",
address
))
} }
} }
pub fn biguint_to_u256(value: &BigUint) -> U256 { pub fn biguint_to_u256(value: &BigUint) -> U256 {
@@ -34,6 +31,7 @@ pub fn ple_encode(action_data_array: Vec<Vec<u8>>) -> Vec<u8> {
encoded_action_data encoded_action_data
} }
#[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());
@@ -42,9 +40,9 @@ pub fn encode_input(selector: &str, mut encoded_args: Vec<u8>) -> Vec<u8> {
// Remove extra prefix if present (32 bytes for dynamic data) // Remove extra prefix if present (32 bytes for dynamic data)
// Alloy encoding is including a prefix for dynamic data indicating the offset or length // Alloy encoding is including a prefix for dynamic data indicating the offset or length
// but at this point we don't want that // but at this point we don't want that
if encoded_args.len() > 32 if encoded_args.len() > 32 &&
&& encoded_args[..32] encoded_args[..32] ==
== [0u8; 31] [0u8; 31]
.into_iter() .into_iter()
.chain([32].to_vec()) .chain([32].to_vec())
.collect::<Vec<u8>>() .collect::<Vec<u8>>()

View File

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