fix: Remove unnecessary clones from encoding

Use references if possible

Took 3 minutes
This commit is contained in:
Diana Carvalho
2025-06-23 12:54:09 +01:00
parent ce8e9faf32
commit e704151404
11 changed files with 185 additions and 197 deletions

View File

@@ -75,8 +75,8 @@ pub fn encode_tycho_router_call(
chain_id: u64,
encoded_solution: EncodedSolution,
solution: &Solution,
user_transfer_type: UserTransferType,
native_address: Bytes,
user_transfer_type: &UserTransferType,
native_address: &Bytes,
signer: Option<PrivateKeySigner>,
) -> Result<Transaction, EncodingError> {
let (mut unwrap, mut wrap) = (false, false);
@@ -137,7 +137,7 @@ pub fn encode_tycho_router_call(
wrap,
unwrap,
receiver,
user_transfer_type == UserTransferType::TransferFrom,
user_transfer_type == &UserTransferType::TransferFrom,
encoded_solution.swaps,
)
.abi_encode()
@@ -172,7 +172,7 @@ pub fn encode_tycho_router_call(
wrap,
unwrap,
receiver,
user_transfer_type == UserTransferType::TransferFrom,
user_transfer_type == &UserTransferType::TransferFrom,
encoded_solution.swaps,
)
.abi_encode()
@@ -209,7 +209,7 @@ pub fn encode_tycho_router_call(
unwrap,
n_tokens,
receiver,
user_transfer_type == UserTransferType::TransferFrom,
user_transfer_type == &UserTransferType::TransferFrom,
encoded_solution.swaps,
)
.abi_encode()
@@ -218,7 +218,7 @@ pub fn encode_tycho_router_call(
};
let contract_interaction = encode_input(&encoded_solution.function_signature, method_calldata);
let value = if solution.given_token == native_address {
let value = if solution.given_token == *native_address {
solution.given_amount.clone()
} else {
BigUint::ZERO

View File

@@ -24,7 +24,7 @@ pub struct SwapGroup {
///
/// An example where this applies is the case of USV4, which uses a PoolManager contract
/// to save token transfers on consecutive swaps.
pub fn group_swaps(swaps: Vec<Swap>) -> Vec<SwapGroup> {
pub fn group_swaps(swaps: &Vec<Swap>) -> Vec<SwapGroup> {
let mut grouped_swaps: Vec<SwapGroup> = Vec::new();
let mut current_group: Option<SwapGroup> = None;
let mut last_swap_protocol = "".to_string();
@@ -127,7 +127,7 @@ mod tests {
split: 0f64,
user_data: None,
};
let grouped_swaps = group_swaps(vec![
let grouped_swaps = group_swaps(&vec![
swap_weth_wbtc.clone(),
swap_wbtc_usdc.clone(),
swap_usdc_dai.clone(),
@@ -211,7 +211,7 @@ mod tests {
split: 0f64,
user_data: None,
};
let grouped_swaps = group_swaps(vec![
let grouped_swaps = group_swaps(&vec![
swap_wbtc_weth.clone(),
swap_weth_usdc.clone(),
swap_weth_dai.clone(),
@@ -303,7 +303,7 @@ mod tests {
user_data: None,
};
let grouped_swaps = group_swaps(vec![
let grouped_swaps = group_swaps(&vec![
swap_weth_wbtc.clone(),
swap_wbtc_usdc.clone(),
swap_weth_dai.clone(),

View File

@@ -71,8 +71,8 @@ impl SingleSwapStrategyEncoder {
}
impl StrategyEncoder for SingleSwapStrategyEncoder {
fn encode_strategy(&self, solution: Solution) -> Result<EncodedSolution, EncodingError> {
let grouped_swaps = group_swaps(solution.clone().swaps);
fn encode_strategy(&self, solution: &Solution) -> Result<EncodedSolution, EncodingError> {
let grouped_swaps = group_swaps(&solution.swaps);
let number_of_groups = grouped_swaps.len();
if number_of_groups != 1 {
return Err(EncodingError::InvalidInput(format!(
@@ -91,15 +91,15 @@ impl StrategyEncoder for SingleSwapStrategyEncoder {
}
let (mut unwrap, mut wrap) = (false, false);
if let Some(action) = solution.native_action.clone() {
if let Some(action) = &solution.native_action {
match action {
NativeAction::Wrap => wrap = true,
NativeAction::Unwrap => unwrap = true,
&NativeAction::Wrap => wrap = true,
&NativeAction::Unwrap => unwrap = true,
}
}
let protocol = grouped_swap.protocol_system.clone();
let protocol = &grouped_swap.protocol_system;
let swap_encoder = self
.get_swap_encoder(&protocol)
.get_swap_encoder(protocol)
.ok_or_else(|| {
EncodingError::InvalidInput(format!(
"Swap encoder not found for protocol: {protocol}"
@@ -111,9 +111,9 @@ impl StrategyEncoder for SingleSwapStrategyEncoder {
let transfer = self
.transfer_optimization
.get_transfers(grouped_swap.clone(), solution.given_token.clone(), wrap, false);
.get_transfers(grouped_swap, &solution.given_token, wrap, false);
let encoding_context = EncodingContext {
receiver: swap_receiver.clone(),
receiver: swap_receiver,
exact_out: solution.exact_out,
router_address: Some(self.router_address.clone()),
group_token_in: grouped_swap.token_in.clone(),
@@ -123,7 +123,7 @@ impl StrategyEncoder for SingleSwapStrategyEncoder {
let mut grouped_protocol_data: Vec<u8> = vec![];
for swap in grouped_swap.swaps.iter() {
let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context.clone())?;
let protocol_data = swap_encoder.encode_swap(swap, &encoding_context)?;
grouped_protocol_data.extend(protocol_data);
}
@@ -213,7 +213,7 @@ impl SequentialSwapStrategyEncoder {
}
impl StrategyEncoder for SequentialSwapStrategyEncoder {
fn encode_strategy(&self, solution: Solution) -> Result<EncodedSolution, EncodingError> {
fn encode_strategy(&self, solution: &Solution) -> Result<EncodedSolution, EncodingError> {
self.sequential_swap_validator
.validate_swap_path(
&solution.swaps,
@@ -224,11 +224,11 @@ impl StrategyEncoder for SequentialSwapStrategyEncoder {
&self.wrapped_address,
)?;
let grouped_swaps = group_swaps(solution.swaps);
let grouped_swaps = group_swaps(&solution.swaps);
let mut wrap = false;
if let Some(action) = solution.native_action.clone() {
if action == NativeAction::Wrap {
if let Some(action) = &solution.native_action {
if action == &NativeAction::Wrap {
wrap = true
}
}
@@ -236,9 +236,9 @@ impl StrategyEncoder for SequentialSwapStrategyEncoder {
let mut swaps = vec![];
let mut next_in_between_swap_optimization_allowed = true;
for (i, grouped_swap) in grouped_swaps.iter().enumerate() {
let protocol = grouped_swap.protocol_system.clone();
let protocol = &grouped_swap.protocol_system;
let swap_encoder = self
.get_swap_encoder(&protocol)
.get_swap_encoder(protocol)
.ok_or_else(|| {
EncodingError::InvalidInput(format!(
"Swap encoder not found for protocol: {protocol}",
@@ -249,19 +249,19 @@ impl StrategyEncoder for SequentialSwapStrategyEncoder {
let next_swap = grouped_swaps.get(i + 1);
let (swap_receiver, next_swap_optimization) = self
.transfer_optimization
.get_receiver(solution.receiver.clone(), next_swap)?;
.get_receiver(&solution.receiver, next_swap)?;
next_in_between_swap_optimization_allowed = next_swap_optimization;
let transfer = self
.transfer_optimization
.get_transfers(
grouped_swap.clone(),
solution.given_token.clone(),
&grouped_swap,
&solution.given_token,
wrap,
in_between_swap_optimization_allowed,
);
let encoding_context = EncodingContext {
receiver: swap_receiver.clone(),
receiver: swap_receiver,
exact_out: solution.exact_out,
router_address: Some(self.router_address.clone()),
group_token_in: grouped_swap.token_in.clone(),
@@ -271,8 +271,7 @@ impl StrategyEncoder for SequentialSwapStrategyEncoder {
let mut grouped_protocol_data: Vec<u8> = vec![];
for swap in grouped_swap.swaps.iter() {
let protocol_data =
swap_encoder.encode_swap(swap.clone(), encoding_context.clone())?;
let protocol_data = swap_encoder.encode_swap(swap, &encoding_context)?;
grouped_protocol_data.extend(protocol_data);
}
@@ -376,7 +375,7 @@ impl SplitSwapStrategyEncoder {
}
impl StrategyEncoder for SplitSwapStrategyEncoder {
fn encode_strategy(&self, solution: Solution) -> Result<EncodedSolution, EncodingError> {
fn encode_strategy(&self, solution: &Solution) -> Result<EncodedSolution, EncodingError> {
self.split_swap_validator
.validate_split_percentages(&solution.swaps)?;
self.split_swap_validator
@@ -391,20 +390,17 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
// 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.
let solution_tokens: HashSet<Bytes> =
vec![solution.given_token.clone(), solution.checked_token.clone()]
.into_iter()
.collect();
let grouped_swaps = group_swaps(solution.swaps);
let intermediary_tokens: HashSet<Bytes> = grouped_swaps
.iter()
.flat_map(|grouped_swap| {
vec![grouped_swap.token_in.clone(), grouped_swap.token_out.clone()]
})
let solution_tokens: HashSet<&Bytes> = vec![&solution.given_token, &solution.checked_token]
.into_iter()
.collect();
let mut intermediary_tokens: Vec<Bytes> = intermediary_tokens
let grouped_swaps = group_swaps(&solution.swaps);
let intermediary_tokens: HashSet<&Bytes> = grouped_swaps
.iter()
.flat_map(|grouped_swap| vec![&grouped_swap.token_in, &grouped_swap.token_out])
.collect();
let mut intermediary_tokens: Vec<&Bytes> = intermediary_tokens
.difference(&solution_tokens)
.cloned()
.collect();
@@ -413,32 +409,32 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
intermediary_tokens.sort();
let (mut unwrap, mut wrap) = (false, false);
if let Some(action) = solution.native_action.clone() {
if let Some(action) = &solution.native_action {
match action {
NativeAction::Wrap => wrap = true,
NativeAction::Unwrap => unwrap = true,
&NativeAction::Wrap => wrap = true,
&NativeAction::Unwrap => unwrap = true,
}
}
let mut tokens = Vec::with_capacity(2 + intermediary_tokens.len());
if wrap {
tokens.push(self.wrapped_address.clone());
tokens.push(&self.wrapped_address);
} else {
tokens.push(solution.given_token.clone());
tokens.push(&solution.given_token);
}
tokens.extend(intermediary_tokens);
if unwrap {
tokens.push(self.wrapped_address.clone());
tokens.push(&self.wrapped_address);
} else {
tokens.push(solution.checked_token.clone());
tokens.push(&solution.checked_token);
}
let mut swaps = vec![];
for grouped_swap in grouped_swaps.iter() {
let protocol = grouped_swap.protocol_system.clone();
let protocol = &grouped_swap.protocol_system;
let swap_encoder = self
.get_swap_encoder(&protocol)
.get_swap_encoder(protocol)
.ok_or_else(|| {
EncodingError::InvalidInput(format!(
"Swap encoder not found for protocol: {protocol}",
@@ -452,9 +448,9 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
};
let transfer = self
.transfer_optimization
.get_transfers(grouped_swap.clone(), solution.given_token.clone(), wrap, false);
.get_transfers(grouped_swap, &solution.given_token, wrap, false);
let encoding_context = EncodingContext {
receiver: swap_receiver.clone(),
receiver: swap_receiver,
exact_out: solution.exact_out,
router_address: Some(self.router_address.clone()),
group_token_in: grouped_swap.token_in.clone(),
@@ -464,14 +460,13 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
let mut grouped_protocol_data: Vec<u8> = vec![];
for swap in grouped_swap.swaps.iter() {
let protocol_data =
swap_encoder.encode_swap(swap.clone(), encoding_context.clone())?;
let protocol_data = swap_encoder.encode_swap(swap, &encoding_context)?;
grouped_protocol_data.extend(protocol_data);
}
let swap_data = self.encode_swap_header(
get_token_position(tokens.clone(), grouped_swap.token_in.clone())?,
get_token_position(tokens.clone(), grouped_swap.token_out.clone())?,
get_token_position(&tokens, &grouped_swap.token_in)?,
get_token_position(&tokens, &grouped_swap.token_out)?,
percentage_to_uint24(grouped_swap.split),
Bytes::from_str(swap_encoder.executor_address()).map_err(|_| {
EncodingError::FatalError("Invalid executor address".to_string())
@@ -581,7 +576,7 @@ mod tests {
};
let encoded_solution = encoder
.encode_strategy(solution.clone())
.encode_strategy(&solution)
.unwrap();
let expected_swap = String::from(concat!(
@@ -642,7 +637,7 @@ mod tests {
};
let encoded_solution = encoder
.encode_strategy(solution.clone())
.encode_strategy(&solution)
.unwrap();
let expected_input = [
@@ -724,7 +719,7 @@ mod tests {
};
let encoded_solution = encoder
.encode_strategy(solution.clone())
.encode_strategy(&solution)
.unwrap();
let hex_calldata = encode(&encoded_solution.swaps);
@@ -864,7 +859,7 @@ mod tests {
};
let encoded_solution = encoder
.encode_strategy(solution.clone())
.encode_strategy(&solution)
.unwrap();
let hex_calldata = hex::encode(&encoded_solution.swaps);
@@ -1014,7 +1009,7 @@ mod tests {
};
let encoded_solution = encoder
.encode_strategy(solution.clone())
.encode_strategy(&solution)
.unwrap();
let hex_calldata = hex::encode(&encoded_solution.swaps);

View File

@@ -118,7 +118,7 @@ impl SplitSwapValidator {
/// * The sum of all non-remainder splits for each token is < 1 (100%)
/// * There are no negative split amounts
pub fn validate_split_percentages(&self, swaps: &[Swap]) -> Result<(), EncodingError> {
let mut swaps_by_token: HashMap<Bytes, Vec<&Swap>> = HashMap::new();
let mut swaps_by_token: HashMap<&Bytes, Vec<&Swap>> = HashMap::new();
for swap in swaps {
if swap.split >= 1.0 {
return Err(EncodingError::InvalidInput(format!(
@@ -127,7 +127,7 @@ impl SplitSwapValidator {
)));
}
swaps_by_token
.entry(swap.token_in.clone())
.entry(&swap.token_in)
.or_default()
.push(swap);
}

View File

@@ -33,12 +33,12 @@ impl TransferOptimization {
/// Returns the transfer type that should be used for the current transfer.
pub fn get_transfers(
&self,
swap: SwapGroup,
given_token: Bytes,
swap: &SwapGroup,
given_token: &Bytes,
wrap: bool,
in_between_swap_optimization: bool,
) -> TransferType {
let is_first_swap = swap.token_in == given_token;
let is_first_swap = swap.token_in == *given_token;
let in_transfer_required: bool =
IN_TRANSFER_REQUIRED_PROTOCOLS.contains(&swap.protocol_system.as_str());
@@ -80,7 +80,7 @@ impl TransferOptimization {
// is necessary for the next swap transfer type decision).
pub fn get_receiver(
&self,
solution_receiver: Bytes,
solution_receiver: &Bytes,
next_swap: Option<&SwapGroup>,
) -> Result<(Bytes, bool), EncodingError> {
if let Some(next) = next_swap {
@@ -104,7 +104,7 @@ impl TransferOptimization {
}
} else {
// last swap - there is no next swap
Ok((solution_receiver, false))
Ok((solution_receiver.clone(), false))
}
}
}
@@ -189,12 +189,8 @@ mod tests {
};
let optimization =
TransferOptimization::new(eth(), weth(), user_transfer_type, router_address());
let transfer = optimization.get_transfers(
swap.clone(),
given_token,
wrap,
in_between_swap_optimization,
);
let transfer =
optimization.get_transfers(&swap, &given_token, wrap, in_between_swap_optimization);
assert_eq!(transfer, expected_transfer);
}
@@ -249,7 +245,7 @@ mod tests {
})
};
let result = optimization.get_receiver(receiver(), next_swap.as_ref());
let result = optimization.get_receiver(&receiver(), next_swap.as_ref());
assert!(result.is_ok());
let (actual_receiver, optimization_flag) = result.unwrap();

View File

@@ -43,8 +43,8 @@ impl SwapEncoder for UniswapV2SwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
let token_in_address = bytes_to_address(&swap.token_in)?;
let token_out_address = bytes_to_address(&swap.token_out)?;
@@ -101,8 +101,8 @@ impl SwapEncoder for UniswapV3SwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
let token_in_address = bytes_to_address(&swap.token_in)?;
let token_out_address = bytes_to_address(&swap.token_out)?;
@@ -162,8 +162,8 @@ impl SwapEncoder for UniswapV4SwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
let fee = get_static_attribute(&swap, "key_lp_fee")?;
@@ -245,15 +245,15 @@ impl SwapEncoder for BalancerV2SwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
let token_approvals_manager = ProtocolApprovalsManager::new()?;
let token = bytes_to_address(&swap.token_in)?;
let approval_needed: bool;
if let Some(router_address) = encoding_context.router_address {
let tycho_router_address = bytes_to_address(&router_address)?;
if let Some(router_address) = &encoding_context.router_address {
let tycho_router_address = bytes_to_address(router_address)?;
approval_needed = token_approvals_manager.approval_needed(
token,
tycho_router_address,
@@ -306,8 +306,8 @@ impl SwapEncoder for EkuboSwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
if encoding_context.exact_out {
return Err(EncodingError::InvalidInput("exact out swaps not implemented".to_string()));
@@ -405,7 +405,7 @@ impl CurveSwapEncoder {
fn get_coin_indexes(
&self,
swap: Swap,
swap: &Swap,
token_in: Address,
token_out: Address,
) -> Result<(U8, U8), EncodingError> {
@@ -451,8 +451,8 @@ impl SwapEncoder for CurveSwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
let token_approvals_manager = ProtocolApprovalsManager::new()?;
let native_token_curve_address = Address::from_str(&self.native_token_curve_address)
@@ -473,9 +473,9 @@ impl SwapEncoder for CurveSwapEncoder {
let component_address = Address::from_str(&swap.component.id)
.map_err(|_| EncodingError::FatalError("Invalid curve pool address".to_string()))?;
if let Some(router_address) = encoding_context.router_address {
if let Some(router_address) = &encoding_context.router_address {
if token_in != native_token_curve_address {
let tycho_router_address = bytes_to_address(&router_address)?;
let tycho_router_address = bytes_to_address(router_address)?;
approval_needed = token_approvals_manager.approval_needed(
token_in,
tycho_router_address,
@@ -548,8 +548,8 @@ impl SwapEncoder for MaverickV2SwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
let component_id = AlloyBytes::from_str(&swap.component.id)
.map_err(|_| EncodingError::FatalError("Invalid component ID".to_string()))?;
@@ -591,8 +591,8 @@ impl SwapEncoder for BalancerV3SwapEncoder {
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError> {
let pool = Address::from_str(&swap.component.id).map_err(|_| {
EncodingError::FatalError("Invalid pool address for Balancer v3".to_string())
@@ -663,7 +663,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
assert_eq!(
@@ -723,7 +723,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
assert_eq!(
@@ -788,7 +788,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -860,7 +860,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -933,7 +933,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -1028,10 +1028,10 @@ mod tests {
)
.unwrap();
let initial_encoded_swap = encoder
.encode_swap(initial_swap, context.clone())
.encode_swap(&initial_swap, &context)
.unwrap();
let second_encoded_swap = encoder
.encode_swap(second_swap, context)
.encode_swap(&second_swap, &context)
.unwrap();
let combined_hex =
@@ -1112,7 +1112,7 @@ mod tests {
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -1188,11 +1188,11 @@ mod tests {
};
let first_encoded_swap = encoder
.encode_swap(first_swap, encoding_context.clone())
.encode_swap(&first_swap, &encoding_context)
.unwrap();
let second_encoded_swap = encoder
.encode_swap(second_swap, encoding_context)
.encode_swap(&second_swap, &encoding_context)
.unwrap();
let combined_hex =
@@ -1314,7 +1314,7 @@ mod tests {
.unwrap();
let (i, j) = encoder
.get_coin_indexes(
swap,
&swap,
Address::from_str(token_in).unwrap(),
Address::from_str(token_out).unwrap(),
)
@@ -1366,7 +1366,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -1438,7 +1438,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -1520,7 +1520,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -1585,7 +1585,7 @@ mod tests {
)
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);
@@ -1644,7 +1644,7 @@ mod tests {
.unwrap();
let encoded_swap = encoder
.encode_swap(swap, encoding_context)
.encode_swap(&swap, &encoding_context)
.unwrap();
let hex_swap = encode(&encoded_swap);

View File

@@ -89,10 +89,9 @@ impl TychoRouterEncoder {
fn encode_solution(&self, solution: &Solution) -> Result<EncodedSolution, EncodingError> {
self.validate_solution(solution)?;
let protocols: HashSet<String> = solution
.clone()
.swaps
.into_iter()
.map(|swap| swap.component.protocol_system)
.iter()
.map(|swap| swap.component.protocol_system.clone())
.collect();
let mut encoded_solution = if (solution.swaps.len() == 1) ||
@@ -106,20 +105,20 @@ impl TychoRouterEncoder {
.all(|swap| swap.split == 0.0))
{
self.single_swap_strategy
.encode_strategy(solution.clone())?
.encode_strategy(solution)?
} else if solution
.swaps
.iter()
.all(|swap| swap.split == 0.0)
{
self.sequential_swap_strategy
.encode_strategy(solution.clone())?
.encode_strategy(solution)?
} else {
self.split_swap_strategy
.encode_strategy(solution.clone())?
.encode_strategy(solution)?
};
if let Some(permit2) = self.permit2.clone() {
if let Some(permit2) = &self.permit2 {
let permit = permit2.get_permit(
&self.router_address,
&solution.sender,
@@ -157,8 +156,8 @@ impl TychoEncoder for TychoRouterEncoder {
self.chain.id,
encoded_solution,
solution,
self.user_transfer_type.clone(),
self.chain.native_token()?.clone(),
&self.user_transfer_type,
&self.chain.native_token()?,
self.signer.clone(),
)?;
@@ -189,8 +188,8 @@ impl TychoEncoder for TychoRouterEncoder {
}
let native_address = self.chain.native_token()?;
let wrapped_address = self.chain.wrapped_token()?;
if let Some(native_action) = solution.clone().native_action {
if native_action == NativeAction::Wrap {
if let Some(native_action) = &solution.native_action {
if native_action == &NativeAction::Wrap {
if solution.given_token != native_address {
return Err(EncodingError::FatalError(
"Native token must be the input token in order to wrap".to_string(),
@@ -204,7 +203,7 @@ impl TychoEncoder for TychoRouterEncoder {
));
}
}
} else if native_action == NativeAction::Unwrap {
} else if native_action == &NativeAction::Unwrap {
if solution.checked_token != native_address {
return Err(EncodingError::FatalError(
"Native token must be the output token in order to unwrap".to_string(),
@@ -227,17 +226,17 @@ impl TychoEncoder for TychoRouterEncoder {
// so we don't count the split tokens more than once
if swap.split != 0.0 {
if !split_tokens_already_considered.contains(&swap.token_in) {
solution_tokens.push(swap.token_in.clone());
split_tokens_already_considered.insert(swap.token_in.clone());
solution_tokens.push(&swap.token_in);
split_tokens_already_considered.insert(&swap.token_in);
}
} else {
// it might be the last swap of the split or a regular swap
if !split_tokens_already_considered.contains(&swap.token_in) {
solution_tokens.push(swap.token_in.clone());
solution_tokens.push(&swap.token_in);
}
}
if i == solution.swaps.len() - 1 {
solution_tokens.push(swap.token_out.clone());
solution_tokens.push(&swap.token_out);
}
}
@@ -245,7 +244,7 @@ impl TychoEncoder for TychoRouterEncoder {
solution_tokens
.iter()
.cloned()
.collect::<HashSet<Bytes>>()
.collect::<HashSet<&Bytes>>()
.len()
{
if let Some(last_swap) = solution.swaps.last() {
@@ -256,7 +255,7 @@ impl TychoEncoder for TychoRouterEncoder {
} else {
// it is a valid cyclical swap
// we don't support any wrapping or unwrapping in this case
if let Some(_native_action) = solution.clone().native_action {
if let Some(_native_action) = &solution.native_action {
return Err(EncodingError::FatalError(
"Wrapping/Unwrapping is not available in cyclical swaps".to_string(),
));
@@ -287,9 +286,9 @@ impl TychoExecutorEncoder {
fn encode_executor_calldata(
&self,
solution: Solution,
solution: &Solution,
) -> Result<EncodedSolution, EncodingError> {
let grouped_swaps = group_swaps(solution.clone().swaps);
let grouped_swaps = group_swaps(&solution.swaps);
let number_of_groups = grouped_swaps.len();
if number_of_groups > 1 {
return Err(EncodingError::InvalidInput(format!(
@@ -301,8 +300,6 @@ impl TychoExecutorEncoder {
.first()
.ok_or_else(|| EncodingError::FatalError("Swap grouping failed".to_string()))?;
let receiver = solution.receiver;
let swap_encoder = self
.swap_encoder_registry
.get_encoder(&grouped_swap.protocol_system)
@@ -323,14 +320,14 @@ impl TychoExecutorEncoder {
TransferType::None
};
let encoding_context = EncodingContext {
receiver: receiver.clone(),
receiver: solution.receiver.clone(),
exact_out: solution.exact_out,
router_address: None,
group_token_in: grouped_swap.token_in.clone(),
group_token_out: grouped_swap.token_out.clone(),
transfer_type: transfer,
};
let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context.clone())?;
let protocol_data = swap_encoder.encode_swap(swap, &encoding_context)?;
grouped_protocol_data.extend(protocol_data);
}
@@ -357,7 +354,7 @@ impl TychoEncoder for TychoExecutorEncoder {
.ok_or(EncodingError::FatalError("No solutions found".to_string()))?;
self.validate_solution(solution)?;
let encoded_solution = self.encode_executor_calldata(solution.clone())?;
let encoded_solution = self.encode_executor_calldata(solution)?;
Ok(vec![encoded_solution])
}
@@ -1343,8 +1340,8 @@ mod tests {
eth_chain().id,
encoded_solutions[0].clone(),
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -1433,8 +1430,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -1518,8 +1515,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::None,
eth(),
&UserTransferType::None,
&eth(),
None,
)
.unwrap()
@@ -1601,8 +1598,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -1657,8 +1654,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -1734,8 +1731,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -1804,8 +1801,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -1931,8 +1928,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -2058,8 +2055,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -2149,8 +2146,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -2249,8 +2246,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -2326,8 +2323,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -2492,8 +2489,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth,
&UserTransferType::TransferFromPermit2,
&crate::encoding::evm::tycho_encoders::tests::eth(),
Some(get_signer()),
)
.unwrap()
@@ -2571,8 +2568,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -2675,8 +2672,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -2791,8 +2788,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -2960,8 +2957,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
Some(get_signer()),
)
.unwrap()
@@ -3089,8 +3086,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -3145,8 +3142,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -3212,8 +3209,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth,
&UserTransferType::TransferFromPermit2,
&eth,
Some(get_signer()),
)
.unwrap()
@@ -3284,8 +3281,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth,
&UserTransferType::TransferFromPermit2,
&eth,
Some(get_signer()),
)
.unwrap()
@@ -3376,8 +3373,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFromPermit2,
eth,
&UserTransferType::TransferFromPermit2,
&eth,
Some(get_signer()),
)
.unwrap()
@@ -3487,8 +3484,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFromPermit2,
&eth(),
None,
)
.unwrap()
@@ -3558,8 +3555,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()
@@ -3615,8 +3612,8 @@ mod tests {
eth_chain().id,
encoded_solution,
&solution,
UserTransferType::TransferFrom,
eth(),
&UserTransferType::TransferFrom,
&eth(),
None,
)
.unwrap()

View File

@@ -48,7 +48,7 @@ pub fn percentage_to_uint24(decimal: f64) -> U24 {
}
/// Gets the position of a token in a list of tokens.
pub fn get_token_position(tokens: Vec<Bytes>, token: Bytes) -> Result<U8, EncodingError> {
pub fn get_token_position(tokens: &Vec<&Bytes>, token: &Bytes) -> Result<U8, EncodingError> {
let position = U8::from(
tokens
.iter()

View File

@@ -203,7 +203,7 @@ pub struct EncodingContext {
/// * `Transfer`: Transfer the token from the router into the protocol.
/// * `None`: No transfer is needed. Tokens are already in the pool.
#[repr(u8)]
#[derive(Clone, Debug, PartialEq)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum TransferType {
TransferFrom = 0,
Transfer = 1,

View File

@@ -16,7 +16,7 @@ pub trait StrategyEncoder {
///
/// # Returns
/// * `Result<EncodedSwaps, EncodingError>`
fn encode_strategy(&self, solution: Solution) -> Result<EncodedSolution, EncodingError>;
fn encode_strategy(&self, solution: &Solution) -> Result<EncodedSolution, EncodingError>;
/// Retrieves the swap encoder for a specific protocol system.
///

View File

@@ -34,8 +34,8 @@ pub trait SwapEncoder: Sync + Send {
/// The encoded swap data as bytes, directly executable on the executor contract
fn encode_swap(
&self,
swap: Swap,
encoding_context: EncodingContext,
swap: &Swap,
encoding_context: &EncodingContext,
) -> Result<Vec<u8>, EncodingError>;
/// Returns the address of the protocol-specific executor contract.