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
This commit is contained in:
@@ -1,13 +1,14 @@
|
|||||||
use std::{str::FromStr, sync::Arc};
|
use std::{str::FromStr, sync::Arc};
|
||||||
|
|
||||||
use alloy::{
|
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},
|
providers::{Provider, RootProvider},
|
||||||
rpc::types::{TransactionInput, TransactionRequest},
|
rpc::types::{TransactionInput, TransactionRequest},
|
||||||
signers::{local::PrivateKeySigner, SignerSync},
|
signers::{local::PrivateKeySigner, SignerSync},
|
||||||
transports::BoxTransport,
|
transports::BoxTransport,
|
||||||
};
|
};
|
||||||
use alloy_primitives::{ChainId, Signature, U256};
|
#[allow(deprecated)]
|
||||||
|
use alloy_primitives::Signature;
|
||||||
use alloy_sol_types::{eip712_domain, sol, SolStruct, SolValue};
|
use alloy_sol_types::{eip712_domain, sol, SolStruct, SolValue};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use num_bigint::BigUint;
|
use num_bigint::BigUint;
|
||||||
@@ -108,6 +109,7 @@ impl Permit2 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Creates permit single and signature
|
/// Creates permit single and signature
|
||||||
|
#[allow(deprecated)]
|
||||||
pub fn get_permit(
|
pub fn get_permit(
|
||||||
&self,
|
&self,
|
||||||
spender: &Bytes,
|
spender: &Bytes,
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use alloy::signers::local::PrivateKeySigner;
|
||||||
|
use alloy_primitives::ChainId;
|
||||||
use num_bigint::BigUint;
|
use num_bigint::BigUint;
|
||||||
use tycho_core::Bytes;
|
use tycho_core::Bytes;
|
||||||
|
|
||||||
@@ -9,37 +11,48 @@ use crate::encoding::{
|
|||||||
models::{NativeAction, Solution, Transaction},
|
models::{NativeAction, Solution, Transaction},
|
||||||
router_encoder::RouterEncoder,
|
router_encoder::RouterEncoder,
|
||||||
strategy_encoder::StrategySelector,
|
strategy_encoder::StrategySelector,
|
||||||
user_approvals_manager::{Approval, UserApprovalsManager},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct EVMRouterEncoder<S: StrategySelector, A: UserApprovalsManager> {
|
pub struct EVMRouterEncoder<S: StrategySelector> {
|
||||||
strategy_selector: S,
|
strategy_selector: S,
|
||||||
approvals_manager: A,
|
signer: Option<PrivateKeySigner>,
|
||||||
|
chain_id: ChainId,
|
||||||
router_address: String,
|
router_address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
impl<S: StrategySelector, A: UserApprovalsManager> EVMRouterEncoder<S, A> {
|
impl<S: StrategySelector> EVMRouterEncoder<S> {
|
||||||
pub fn new(strategy_selector: S, approvals_manager: A, router_address: String) -> Self {
|
pub fn new(
|
||||||
EVMRouterEncoder { strategy_selector, approvals_manager, router_address }
|
strategy_selector: S,
|
||||||
|
router_address: String,
|
||||||
|
signer: Option<PrivateKeySigner>,
|
||||||
|
chain_id: ChainId,
|
||||||
|
) -> Result<Self, EncodingError> {
|
||||||
|
Ok(EVMRouterEncoder { strategy_selector, signer, chain_id, router_address })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> for EVMRouterEncoder<S, A> {
|
impl<S: StrategySelector> RouterEncoder<S> for EVMRouterEncoder<S> {
|
||||||
fn encode_router_calldata(
|
fn encode_router_calldata(
|
||||||
&self,
|
&self,
|
||||||
solutions: Vec<Solution>,
|
solutions: Vec<Solution>,
|
||||||
) -> Result<Vec<Transaction>, EncodingError> {
|
) -> Result<Vec<Transaction>, EncodingError> {
|
||||||
let _approvals_calldata = self.handle_approvals(&solutions)?; // TODO: where should we append this?
|
|
||||||
let mut transactions: Vec<Transaction> = Vec::new();
|
let mut transactions: Vec<Transaction> = Vec::new();
|
||||||
for solution in solutions.iter() {
|
for solution in solutions.iter() {
|
||||||
let exact_out = solution.exact_out;
|
let exact_out = solution.exact_out;
|
||||||
let straight_to_pool = solution.straight_to_pool;
|
let straight_to_pool = solution.straight_to_pool;
|
||||||
|
let router_address = solution
|
||||||
let strategy = self
|
.router_address
|
||||||
.strategy_selector
|
.clone()
|
||||||
.select_strategy(solution);
|
.unwrap_or(Bytes::from_str(&self.router_address).map_err(|_| {
|
||||||
let method_calldata = strategy.encode_strategy((*solution).clone())?;
|
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 {
|
let contract_interaction = if straight_to_pool {
|
||||||
method_calldata
|
method_calldata
|
||||||
@@ -56,23 +69,4 @@ impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> for EVMRo
|
|||||||
}
|
}
|
||||||
Ok(transactions)
|
Ok(transactions)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_approvals(&self, solutions: &[Solution]) -> Result<Vec<Vec<u8>>, 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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 alloy_sol_types::SolValue;
|
||||||
|
use num_bigint::BigUint;
|
||||||
|
use tycho_core::Bytes;
|
||||||
|
|
||||||
use crate::encoding::{
|
use crate::encoding::{
|
||||||
errors::EncodingError,
|
errors::EncodingError,
|
||||||
evm::swap_encoder::SWAP_ENCODER_REGISTRY,
|
evm::{
|
||||||
models::{EncodingContext, Solution},
|
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,
|
strategy_encoder::StrategyEncoder,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub trait EVMStrategyEncoder: StrategyEncoder {
|
pub trait EVMStrategyEncoder: StrategyEncoder {
|
||||||
fn encode_protocol_header(
|
fn encode_swap_header(
|
||||||
&self,
|
&self,
|
||||||
|
token_in: U8,
|
||||||
|
token_out: U8,
|
||||||
|
split: U24,
|
||||||
protocol_data: Vec<u8>,
|
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> {
|
) -> Vec<u8> {
|
||||||
let args = (executor_address, token_in, token_out, split, protocol_data);
|
let mut encoded = Vec::new();
|
||||||
args.abi_encode()
|
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<Self, EncodingError> {
|
||||||
|
Ok(Self { permit2: Permit2::new(signer, chain_id)? })
|
||||||
|
}
|
||||||
|
}
|
||||||
impl EVMStrategyEncoder for SplitSwapStrategyEncoder {}
|
impl EVMStrategyEncoder for SplitSwapStrategyEncoder {}
|
||||||
impl StrategyEncoder for SplitSwapStrategyEncoder {
|
impl StrategyEncoder for SplitSwapStrategyEncoder {
|
||||||
fn encode_strategy(&self, _solution: Solution) -> Result<Vec<u8>, EncodingError> {
|
fn encode_strategy(
|
||||||
todo!()
|
&self,
|
||||||
|
solution: Solution,
|
||||||
|
router_address: Bytes,
|
||||||
|
) -> Result<Vec<u8>, 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<Bytes> = solution
|
||||||
|
.swaps
|
||||||
|
.iter()
|
||||||
|
.flat_map(|swap| vec![swap.token_in.clone(), swap.token_out.clone()])
|
||||||
|
.collect::<HashSet<Bytes>>()
|
||||||
|
.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 {
|
fn selector(&self, _exact_out: bool) -> &str {
|
||||||
"swap(uint256, address, uint256, bytes[])"
|
"swap(uint256, address, uint256, bytes[])"
|
||||||
}
|
}
|
||||||
@@ -40,7 +155,11 @@ impl StrategyEncoder for SplitSwapStrategyEncoder {
|
|||||||
pub struct StraightToPoolStrategyEncoder {}
|
pub struct StraightToPoolStrategyEncoder {}
|
||||||
impl EVMStrategyEncoder for StraightToPoolStrategyEncoder {}
|
impl EVMStrategyEncoder for StraightToPoolStrategyEncoder {}
|
||||||
impl StrategyEncoder for StraightToPoolStrategyEncoder {
|
impl StrategyEncoder for StraightToPoolStrategyEncoder {
|
||||||
fn encode_strategy(&self, solution: Solution) -> Result<Vec<u8>, EncodingError> {
|
fn encode_strategy(
|
||||||
|
&self,
|
||||||
|
solution: Solution,
|
||||||
|
_router_address: Bytes,
|
||||||
|
) -> Result<Vec<u8>, EncodingError> {
|
||||||
if solution.router_address.is_none() {
|
if solution.router_address.is_none() {
|
||||||
return Err(EncodingError::InvalidInput(
|
return Err(EncodingError::InvalidInput(
|
||||||
"Router address is required for straight to pool solutions".to_string(),
|
"Router address is required for straight to pool solutions".to_string(),
|
||||||
@@ -75,3 +194,111 @@ impl StrategyEncoder for StraightToPoolStrategyEncoder {
|
|||||||
unimplemented!();
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
|
use alloy::signers::local::PrivateKeySigner;
|
||||||
|
use alloy_primitives::ChainId;
|
||||||
|
|
||||||
use crate::encoding::{
|
use crate::encoding::{
|
||||||
|
errors::EncodingError,
|
||||||
evm::strategy_encoder::encoder::{SplitSwapStrategyEncoder, StraightToPoolStrategyEncoder},
|
evm::strategy_encoder::encoder::{SplitSwapStrategyEncoder, StraightToPoolStrategyEncoder},
|
||||||
models::Solution,
|
models::Solution,
|
||||||
strategy_encoder::{StrategyEncoder, StrategySelector},
|
strategy_encoder::{StrategyEncoder, StrategySelector},
|
||||||
@@ -7,11 +11,21 @@ use crate::encoding::{
|
|||||||
pub struct EVMStrategySelector;
|
pub struct EVMStrategySelector;
|
||||||
|
|
||||||
impl StrategySelector for EVMStrategySelector {
|
impl StrategySelector for EVMStrategySelector {
|
||||||
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder> {
|
fn select_strategy(
|
||||||
|
&self,
|
||||||
|
solution: &Solution,
|
||||||
|
signer: Option<PrivateKeySigner>,
|
||||||
|
chain_id: ChainId,
|
||||||
|
) -> Result<Box<dyn StrategyEncoder>, EncodingError> {
|
||||||
if solution.straight_to_pool {
|
if solution.straight_to_pool {
|
||||||
Box::new(StraightToPoolStrategyEncoder {})
|
Ok(Box::new(StraightToPoolStrategyEncoder {}))
|
||||||
} else {
|
} 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()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ impl SwapEncoder for UniswapV2SwapEncoder {
|
|||||||
// Token in address is always needed to perform a manual transfer from the router,
|
// 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
|
// since no optimizations are performed that send from one pool to the next
|
||||||
let args = (
|
let args = (
|
||||||
|
Address::from_str(self.executor_address())
|
||||||
|
.map_err(|_| EncodingError::FatalError("Invalid executor address".to_string()))?,
|
||||||
|
self.executor_selector(),
|
||||||
token_in_address,
|
token_in_address,
|
||||||
component_id,
|
component_id,
|
||||||
bytes_to_address(&encoding_context.receiver)?,
|
bytes_to_address(&encoding_context.receiver)?,
|
||||||
@@ -107,6 +110,9 @@ impl SwapEncoder for UniswapV3SwapEncoder {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let args = (
|
let args = (
|
||||||
|
Address::from_str(self.executor_address())
|
||||||
|
.map_err(|_| EncodingError::FatalError("Invalid executor address".to_string()))?,
|
||||||
|
self.executor_selector(),
|
||||||
token_in_address,
|
token_in_address,
|
||||||
token_out_address,
|
token_out_address,
|
||||||
pool_fee_u24,
|
pool_fee_u24,
|
||||||
@@ -155,6 +161,9 @@ impl SwapEncoder for BalancerV2SwapEncoder {
|
|||||||
.map_err(|_| EncodingError::FatalError("Invalid component ID".to_string()))?;
|
.map_err(|_| EncodingError::FatalError("Invalid component ID".to_string()))?;
|
||||||
|
|
||||||
let args = (
|
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_in)?,
|
||||||
bytes_to_address(&swap.token_out)?,
|
bytes_to_address(&swap.token_out)?,
|
||||||
component_id,
|
component_id,
|
||||||
@@ -196,7 +205,8 @@ mod tests {
|
|||||||
exact_out: false,
|
exact_out: false,
|
||||||
router_address: Bytes::zero(20),
|
router_address: Bytes::zero(20),
|
||||||
};
|
};
|
||||||
let encoder = UniswapV2SwapEncoder::new(String::from("0x"));
|
let encoder =
|
||||||
|
UniswapV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
|
||||||
let encoded_swap = encoder
|
let encoded_swap = encoder
|
||||||
.encode_swap(swap, encoding_context)
|
.encode_swap(swap, encoding_context)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -204,6 +214,10 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
hex_swap,
|
hex_swap,
|
||||||
String::from(concat!(
|
String::from(concat!(
|
||||||
|
// executor address
|
||||||
|
"543778987b293c7e8cf0722bb2e935ba6f4068d4",
|
||||||
|
// executor selector
|
||||||
|
"bd0625ab",
|
||||||
// in token
|
// in token
|
||||||
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
|
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
|
||||||
// component id
|
// component id
|
||||||
@@ -239,7 +253,8 @@ mod tests {
|
|||||||
exact_out: false,
|
exact_out: false,
|
||||||
router_address: Bytes::zero(20),
|
router_address: Bytes::zero(20),
|
||||||
};
|
};
|
||||||
let encoder = UniswapV3SwapEncoder::new(String::from("0x"));
|
let encoder =
|
||||||
|
UniswapV3SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
|
||||||
let encoded_swap = encoder
|
let encoded_swap = encoder
|
||||||
.encode_swap(swap, encoding_context)
|
.encode_swap(swap, encoding_context)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -247,6 +262,10 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
hex_swap,
|
hex_swap,
|
||||||
String::from(concat!(
|
String::from(concat!(
|
||||||
|
// executor address
|
||||||
|
"543778987b293c7e8cf0722bb2e935ba6f4068d4",
|
||||||
|
// executor selector
|
||||||
|
"bd0625ab",
|
||||||
// in token
|
// in token
|
||||||
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
|
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
|
||||||
// out token
|
// out token
|
||||||
@@ -283,7 +302,8 @@ mod tests {
|
|||||||
exact_out: false,
|
exact_out: false,
|
||||||
router_address: Bytes::zero(20),
|
router_address: Bytes::zero(20),
|
||||||
};
|
};
|
||||||
let encoder = BalancerV2SwapEncoder::new(String::from("0x"));
|
let encoder =
|
||||||
|
BalancerV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
|
||||||
let encoded_swap = encoder
|
let encoded_swap = encoder
|
||||||
.encode_swap(swap, encoding_context)
|
.encode_swap(swap, encoding_context)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -292,6 +312,10 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
hex_swap,
|
hex_swap,
|
||||||
String::from(concat!(
|
String::from(concat!(
|
||||||
|
// executor address
|
||||||
|
"543778987b293c7e8cf0722bb2e935ba6f4068d4",
|
||||||
|
// executor selector
|
||||||
|
"bd0625ab",
|
||||||
// token in
|
// token in
|
||||||
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
|
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
|
||||||
// token out
|
// token out
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use alloy_primitives::{Address, Keccak256, U256};
|
use alloy_primitives::{aliases::U24, Address, Keccak256, U256};
|
||||||
use alloy_sol_types::SolValue;
|
use alloy_sol_types::SolValue;
|
||||||
use num_bigint::BigUint;
|
use num_bigint::BigUint;
|
||||||
use tycho_core::Bytes;
|
use tycho_core::Bytes;
|
||||||
@@ -13,7 +13,7 @@ pub fn bytes_to_address(address: &Bytes) -> Result<Address, EncodingError> {
|
|||||||
if address.len() == 20 {
|
if address.len() == 20 {
|
||||||
Ok(Address::from_slice(address))
|
Ok(Address::from_slice(address))
|
||||||
} else {
|
} 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<u8>) -> Vec<u8> {
|
|||||||
call_data.extend(encoded_args);
|
call_data.extend(encoded_args);
|
||||||
call_data
|
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())
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use num_bigint::BigUint;
|
use num_bigint::BigUint;
|
||||||
use tycho_core::{dto::ProtocolComponent, Bytes};
|
use tycho_core::{dto::ProtocolComponent, Bytes};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Default, Debug)]
|
||||||
#[allow(dead_code)]
|
#[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.
|
||||||
@@ -11,7 +11,7 @@ pub struct Solution {
|
|||||||
/// 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).
|
||||||
checked_token: Bytes,
|
pub checked_token: Bytes,
|
||||||
/// 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: BigUint,
|
||||||
/// Minimum amount to be checked for the solution to be valid.
|
/// Minimum amount to be checked for the solution to be valid.
|
||||||
@@ -35,14 +35,14 @@ pub struct Solution {
|
|||||||
pub native_action: Option<NativeAction>,
|
pub native_action: Option<NativeAction>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub enum NativeAction {
|
pub enum NativeAction {
|
||||||
Wrap,
|
Wrap,
|
||||||
Unwrap,
|
Unwrap,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Debug)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct Swap {
|
pub struct Swap {
|
||||||
/// Protocol component from tycho indexer
|
/// Protocol component from tycho indexer
|
||||||
@@ -51,7 +51,7 @@ 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,
|
||||||
/// Fraction of the amount to be swapped in this operation.
|
/// Percentage of the amount to be swapped in this operation.
|
||||||
pub split: f64,
|
pub split: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,5 +10,4 @@ pub trait RouterEncoder<S: StrategySelector> {
|
|||||||
&self,
|
&self,
|
||||||
solutions: Vec<Solution>,
|
solutions: Vec<Solution>,
|
||||||
) -> Result<Vec<Transaction>, EncodingError>;
|
) -> Result<Vec<Transaction>, EncodingError>;
|
||||||
fn handle_approvals(&self, solutions: &[Solution]) -> Result<Vec<Vec<u8>>, EncodingError>;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,25 @@
|
|||||||
|
use alloy::signers::local::PrivateKeySigner;
|
||||||
|
use alloy_primitives::ChainId;
|
||||||
|
use tycho_core::Bytes;
|
||||||
|
|
||||||
use crate::encoding::{errors::EncodingError, models::Solution};
|
use crate::encoding::{errors::EncodingError, models::Solution};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub trait StrategyEncoder {
|
pub trait StrategyEncoder {
|
||||||
fn encode_strategy(&self, to_encode: Solution) -> Result<Vec<u8>, EncodingError>;
|
fn encode_strategy(
|
||||||
|
&self,
|
||||||
|
to_encode: Solution,
|
||||||
|
router_address: Bytes,
|
||||||
|
) -> Result<Vec<u8>, EncodingError>;
|
||||||
fn selector(&self, exact_out: bool) -> &str;
|
fn selector(&self, exact_out: bool) -> &str;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait StrategySelector {
|
pub trait StrategySelector {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder>;
|
fn select_strategy(
|
||||||
|
&self,
|
||||||
|
solution: &Solution,
|
||||||
|
signer: Option<PrivateKeySigner>,
|
||||||
|
chain_id: ChainId,
|
||||||
|
) -> Result<Box<dyn StrategyEncoder>, EncodingError>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
use alloy_primitives::FixedBytes;
|
||||||
|
use tycho_core::keccak256;
|
||||||
|
|
||||||
use crate::encoding::{
|
use crate::encoding::{
|
||||||
errors::EncodingError,
|
errors::EncodingError,
|
||||||
models::{EncodingContext, Swap},
|
models::{EncodingContext, Swap},
|
||||||
@@ -14,4 +17,9 @@ pub trait SwapEncoder: Sync + Send {
|
|||||||
encoding_context: EncodingContext,
|
encoding_context: EncodingContext,
|
||||||
) -> Result<Vec<u8>, EncodingError>;
|
) -> Result<Vec<u8>, EncodingError>;
|
||||||
fn executor_address(&self) -> &str;
|
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]])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user