Merge pull request #35 from propeller-heads/encoding/dc/ENG-4081-split-swap-strategy
feat: Implement Split Swap strategy encoder
This commit is contained in:
@@ -1,25 +1,28 @@
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
|
||||
use alloy::{
|
||||
primitives::{aliases::U48, Address, Bytes as AlloyBytes, TxKind, U160},
|
||||
primitives::{aliases::U48, Address, Bytes as AlloyBytes, TxKind, U160, U256},
|
||||
providers::{Provider, RootProvider},
|
||||
rpc::types::{TransactionInput, TransactionRequest},
|
||||
signers::{local::PrivateKeySigner, SignerSync},
|
||||
transports::BoxTransport,
|
||||
};
|
||||
use alloy_primitives::{ChainId, U256};
|
||||
#[allow(deprecated)]
|
||||
use alloy_primitives::Signature;
|
||||
use alloy_primitives::B256;
|
||||
use alloy_sol_types::{eip712_domain, sol, SolStruct, SolValue};
|
||||
use chrono::Utc;
|
||||
use num_bigint::BigUint;
|
||||
use tokio::runtime::Runtime;
|
||||
use tycho_core::Bytes;
|
||||
use tycho_core::{models::Chain, Bytes};
|
||||
|
||||
use crate::encoding::{
|
||||
errors::EncodingError,
|
||||
evm::{
|
||||
approvals::protocol_approvals_manager::get_client,
|
||||
models::ChainId,
|
||||
utils::{biguint_to_u256, bytes_to_address, encode_input},
|
||||
},
|
||||
user_approvals_manager::{Approval, UserApprovalsManager},
|
||||
};
|
||||
|
||||
/// Struct for managing Permit2 operations, including encoding approvals and fetching allowance
|
||||
@@ -59,10 +62,17 @@ sol! {
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl Permit2 {
|
||||
pub fn new(signer: PrivateKeySigner, chain_id: ChainId) -> Result<Self, EncodingError> {
|
||||
pub fn new(signer_pk: String, chain: Chain) -> Result<Self, EncodingError> {
|
||||
let chain_id = ChainId::from(chain);
|
||||
let runtime = Runtime::new()
|
||||
.map_err(|_| EncodingError::FatalError("Failed to create runtime".to_string()))?;
|
||||
let client = runtime.block_on(get_client())?;
|
||||
let pk = B256::from_str(&signer_pk).map_err(|_| {
|
||||
EncodingError::FatalError("Failed to convert signer private key to B256".to_string())
|
||||
})?;
|
||||
let signer = PrivateKeySigner::from_bytes(&pk).map_err(|_| {
|
||||
EncodingError::FatalError("Failed to create signer from private key".to_string())
|
||||
})?;
|
||||
Ok(Self {
|
||||
address: Address::from_str("0x000000000022D473030F116dDEE9F6B43aC78BA3")
|
||||
.map_err(|_| EncodingError::FatalError("Permit2 address not valid".to_string()))?,
|
||||
@@ -107,59 +117,49 @@ impl Permit2 {
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl UserApprovalsManager for Permit2 {
|
||||
/// Encodes multiple approvals into ABI-encoded data and signs them.
|
||||
fn encode_approvals(&self, approvals: Vec<Approval>) -> Result<Vec<Vec<u8>>, EncodingError> {
|
||||
/// Creates permit single and signature
|
||||
#[allow(deprecated)]
|
||||
pub fn get_permit(
|
||||
&self,
|
||||
spender: &Bytes,
|
||||
owner: &Bytes,
|
||||
token: &Bytes,
|
||||
amount: &BigUint,
|
||||
) -> Result<(PermitSingle, Signature), EncodingError> {
|
||||
let current_time = Utc::now()
|
||||
.naive_utc()
|
||||
.and_utc()
|
||||
.timestamp() as u64;
|
||||
|
||||
let mut encoded_approvals = Vec::new();
|
||||
let (_, _, nonce) = self.get_existing_allowance(owner, spender, token)?;
|
||||
let expiration = U48::from(current_time + PERMIT_EXPIRATION);
|
||||
let sig_deadline = U256::from(current_time + PERMIT_SIG_EXPIRATION);
|
||||
let amount = U160::from(biguint_to_u256(amount));
|
||||
|
||||
for approval in approvals {
|
||||
let (_, _, nonce) =
|
||||
self.get_existing_allowance(&approval.owner, &approval.spender, &approval.token)?;
|
||||
let expiration = U48::from(current_time + PERMIT_EXPIRATION);
|
||||
let sig_deadline = U256::from(current_time + PERMIT_SIG_EXPIRATION);
|
||||
let amount = U160::from(biguint_to_u256(&approval.amount));
|
||||
let details = PermitDetails { token: bytes_to_address(token)?, amount, expiration, nonce };
|
||||
|
||||
let details = PermitDetails {
|
||||
token: bytes_to_address(&approval.token)?,
|
||||
amount,
|
||||
expiration,
|
||||
nonce,
|
||||
};
|
||||
let permit_single = PermitSingle {
|
||||
details,
|
||||
spender: bytes_to_address(spender)?,
|
||||
sigDeadline: sig_deadline,
|
||||
};
|
||||
|
||||
let permit_single = PermitSingle {
|
||||
details,
|
||||
spender: bytes_to_address(&approval.spender)?,
|
||||
sigDeadline: sig_deadline,
|
||||
};
|
||||
|
||||
let domain = eip712_domain! {
|
||||
name: "Permit2",
|
||||
chain_id: self.chain_id,
|
||||
verifying_contract: self.address,
|
||||
};
|
||||
let hash = permit_single.eip712_signing_hash(&domain);
|
||||
let signature = self
|
||||
.signer
|
||||
.sign_hash_sync(&hash)
|
||||
.map_err(|e| {
|
||||
EncodingError::FatalError(format!(
|
||||
"Failed to sign permit2 approval with error: {}",
|
||||
e
|
||||
))
|
||||
})?;
|
||||
let encoded =
|
||||
(bytes_to_address(&approval.owner)?, permit_single, signature.as_bytes().to_vec())
|
||||
.abi_encode();
|
||||
encoded_approvals.push(encoded);
|
||||
}
|
||||
|
||||
Ok(encoded_approvals)
|
||||
let domain = eip712_domain! {
|
||||
name: "Permit2",
|
||||
chain_id: self.chain_id.id(),
|
||||
verifying_contract: self.address,
|
||||
};
|
||||
let hash = permit_single.eip712_signing_hash(&domain);
|
||||
let signature = self
|
||||
.signer
|
||||
.sign_hash_sync(&hash)
|
||||
.map_err(|e| {
|
||||
EncodingError::FatalError(format!(
|
||||
"Failed to sign permit2 approval with error: {}",
|
||||
e
|
||||
))
|
||||
})?;
|
||||
Ok((permit_single, signature))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ impl UserApprovalsManager for Permit2 {
|
||||
mod tests {
|
||||
use std::str::FromStr;
|
||||
|
||||
use alloy_primitives::{Uint, B256};
|
||||
use alloy_primitives::Uint;
|
||||
use num_bigint::BigUint;
|
||||
|
||||
use super::*;
|
||||
@@ -205,8 +205,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_get_existing_allowance() {
|
||||
let signer = PrivateKeySigner::random();
|
||||
let manager = Permit2::new(signer, 1).unwrap();
|
||||
let signer_pk =
|
||||
"4c0883a69102937d6231471b5dbb6204fe512961708279feb1be6ae5538da033".to_string();
|
||||
let manager = Permit2::new(signer_pk, Chain::Ethereum).unwrap();
|
||||
|
||||
let token = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
let owner = Bytes::from_str("0x2c6a3cd97c6283b95ac8c5a4459ebb0d5fd404f4").unwrap();
|
||||
@@ -222,33 +223,20 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encode_approvals() {
|
||||
fn test_get_permit() {
|
||||
// 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 permit2 = Permit2::new(signer, 1).expect("Failed to create Permit2");
|
||||
"4c0883a69102937d6231471b5dbb6204fe512961708279feb1be6ae5538da033".to_string();
|
||||
let permit2 = Permit2::new(private_key, Chain::Ethereum).expect("Failed to create Permit2");
|
||||
|
||||
let owner = Bytes::from_str("0x2c6a3cd97c6283b95ac8c5a4459ebb0d5fd404f4").unwrap();
|
||||
let spender = Bytes::from_str("0xba12222222228d8ba445958a75a0704d566bf2c8").unwrap();
|
||||
let token = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
let amount = BigUint::from(1000u64);
|
||||
let approvals =
|
||||
vec![Approval { owner, spender, token: token.clone(), amount: amount.clone() }];
|
||||
|
||||
let encoded_approvals = permit2
|
||||
.encode_approvals(approvals)
|
||||
let (permit, _) = permit2
|
||||
.get_permit(&spender, &owner, &token, &amount)
|
||||
.unwrap();
|
||||
assert_eq!(encoded_approvals.len(), 1, "Expected 1 encoded approval");
|
||||
|
||||
let encoded = &encoded_approvals[0];
|
||||
|
||||
// Remove prefix and owner (first 64 bytes) and signature (last 65 bytes)
|
||||
let permit_single_encoded = &encoded[64..encoded.len() - 65];
|
||||
|
||||
let decoded_permit_single = PermitSingle::abi_decode(permit_single_encoded, false)
|
||||
.expect("Failed to decode PermitSingle");
|
||||
|
||||
let expected_details = PermitDetails {
|
||||
token: bytes_to_address(&token).unwrap(),
|
||||
@@ -263,7 +251,7 @@ mod tests {
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
decoded_permit_single, expected_permit_single,
|
||||
permit, expected_permit_single,
|
||||
"Decoded PermitSingle does not match expected values"
|
||||
);
|
||||
}
|
||||
@@ -277,12 +265,10 @@ mod tests {
|
||||
fn test_permit() {
|
||||
let anvil_account = Bytes::from_str("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266").unwrap();
|
||||
let anvil_private_key =
|
||||
B256::from_str("0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80")
|
||||
.unwrap();
|
||||
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80".to_string();
|
||||
|
||||
let signer =
|
||||
PrivateKeySigner::from_bytes(&anvil_private_key).expect("Failed to create signer");
|
||||
let permit2 = Permit2::new(signer, 1).expect("Failed to create Permit2");
|
||||
let permit2 =
|
||||
Permit2::new(anvil_private_key, Chain::Ethereum).expect("Failed to create Permit2");
|
||||
|
||||
let token = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
|
||||
let amount = BigUint::from(1000u64);
|
||||
@@ -309,18 +295,13 @@ mod tests {
|
||||
assert!(receipt.status(), "Approve transaction failed");
|
||||
|
||||
let spender = Bytes::from_str("0xba12222222228d8ba445958a75a0704d566bf2c8").unwrap();
|
||||
let approvals = vec![Approval {
|
||||
owner: anvil_account.clone(),
|
||||
spender: spender.clone(),
|
||||
token: token.clone(),
|
||||
amount: amount.clone(),
|
||||
}];
|
||||
|
||||
let encoded_approvals = permit2
|
||||
.encode_approvals(approvals)
|
||||
let (permit, signature) = permit2
|
||||
.get_permit(&spender, &anvil_account, &token, &amount)
|
||||
.unwrap();
|
||||
|
||||
let encoded = &encoded_approvals[0];
|
||||
let encoded =
|
||||
(bytes_to_address(&anvil_account).unwrap(), permit, signature.as_bytes().to_vec())
|
||||
.abi_encode();
|
||||
|
||||
let function_signature =
|
||||
"permit(address,((address,uint160,uint48,uint48),address,uint256),bytes)";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod approvals;
|
||||
mod models;
|
||||
mod router_encoder;
|
||||
mod strategy_encoder;
|
||||
mod swap_encoder;
|
||||
|
||||
20
src/encoding/evm/models.rs
Normal file
20
src/encoding/evm/models.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use tycho_core::models::Chain;
|
||||
|
||||
pub struct ChainId(u64);
|
||||
|
||||
impl ChainId {
|
||||
pub fn id(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Chain> for ChainId {
|
||||
fn from(chain: Chain) -> Self {
|
||||
match chain {
|
||||
Chain::Ethereum => ChainId(1),
|
||||
Chain::ZkSync => ChainId(324),
|
||||
Chain::Arbitrum => ChainId(42161),
|
||||
Chain::Starknet => ChainId(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,58 +1,67 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use num_bigint::BigUint;
|
||||
use tycho_core::Bytes;
|
||||
use tycho_core::{models::Chain, Bytes};
|
||||
|
||||
use crate::encoding::{
|
||||
errors::EncodingError,
|
||||
evm::utils::encode_input,
|
||||
models::{NativeAction, Solution, Transaction},
|
||||
router_encoder::RouterEncoder,
|
||||
strategy_encoder::StrategySelector,
|
||||
user_approvals_manager::{Approval, UserApprovalsManager},
|
||||
};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct EVMRouterEncoder<S: StrategySelector, A: UserApprovalsManager> {
|
||||
pub struct EVMRouterEncoder<S: StrategySelector> {
|
||||
strategy_selector: S,
|
||||
approvals_manager: A,
|
||||
router_address: String,
|
||||
signer: Option<String>,
|
||||
chain: Chain,
|
||||
router_address: Bytes,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl<S: StrategySelector, A: UserApprovalsManager> EVMRouterEncoder<S, A> {
|
||||
pub fn new(strategy_selector: S, approvals_manager: A, router_address: String) -> Self {
|
||||
EVMRouterEncoder { strategy_selector, approvals_manager, router_address }
|
||||
impl<S: StrategySelector> EVMRouterEncoder<S> {
|
||||
pub fn new(
|
||||
strategy_selector: S,
|
||||
router_address: String,
|
||||
signer: Option<String>,
|
||||
chain: Chain,
|
||||
) -> Result<Self, EncodingError> {
|
||||
let router_address = Bytes::from_str(&router_address)
|
||||
.map_err(|_| EncodingError::FatalError("Invalid router address".to_string()))?;
|
||||
Ok(EVMRouterEncoder { strategy_selector, signer, chain, 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(
|
||||
&self,
|
||||
solutions: Vec<Solution>,
|
||||
) -> Result<Vec<Transaction>, EncodingError> {
|
||||
let _approvals_calldata = self.handle_approvals(&solutions)?;
|
||||
let mut transactions: Vec<Transaction> = Vec::new();
|
||||
for solution in solutions.iter() {
|
||||
let exact_out = solution.exact_out;
|
||||
let straight_to_pool = solution.direct_execution;
|
||||
if solution.exact_out {
|
||||
return Err(EncodingError::FatalError(
|
||||
"Currently only exact input solutions are supported".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let strategy = self
|
||||
.strategy_selector
|
||||
.select_strategy(solution);
|
||||
let (method_calldata, target_address) =
|
||||
strategy.encode_strategy((*solution).clone())?;
|
||||
let router_address = solution
|
||||
.router_address
|
||||
.clone()
|
||||
.unwrap_or(self.router_address.clone());
|
||||
let strategy = self.strategy_selector.select_strategy(
|
||||
solution,
|
||||
self.signer.clone(),
|
||||
self.chain,
|
||||
)?;
|
||||
|
||||
let contract_interaction = if straight_to_pool {
|
||||
method_calldata
|
||||
} else {
|
||||
encode_input(strategy.selector(exact_out), method_calldata)
|
||||
let (contract_interaction, target_address) =
|
||||
strategy.encode_strategy(solution.clone(), router_address)?;
|
||||
|
||||
let value = match solution.native_action.as_ref() {
|
||||
Some(NativeAction::Wrap) => solution.given_amount.clone(),
|
||||
_ => BigUint::ZERO,
|
||||
};
|
||||
|
||||
let value = if solution.native_action.clone().unwrap() == NativeAction::Wrap {
|
||||
solution.given_amount.clone()
|
||||
} else {
|
||||
BigUint::ZERO
|
||||
};
|
||||
transactions.push(Transaction {
|
||||
value,
|
||||
data: contract_interaction,
|
||||
@@ -61,23 +70,4 @@ impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> for EVMRo
|
||||
}
|
||||
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,2 +1,2 @@
|
||||
mod encoder;
|
||||
mod selector;
|
||||
mod strategy_encoders;
|
||||
mod strategy_selector;
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
use crate::encoding::{
|
||||
evm::strategy_encoder::encoder::{ExecutorStrategyEncoder, SplitSwapStrategyEncoder},
|
||||
models::Solution,
|
||||
strategy_encoder::{StrategyEncoder, StrategySelector},
|
||||
};
|
||||
|
||||
pub struct EVMStrategySelector;
|
||||
|
||||
impl StrategySelector for EVMStrategySelector {
|
||||
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder> {
|
||||
if solution.direct_execution {
|
||||
Box::new(ExecutorStrategyEncoder {})
|
||||
} else {
|
||||
Box::new(SplitSwapStrategyEncoder {})
|
||||
}
|
||||
}
|
||||
}
|
||||
391
src/encoding/evm/strategy_encoder/strategy_encoders.rs
Normal file
391
src/encoding/evm/strategy_encoder/strategy_encoders.rs
Normal file
@@ -0,0 +1,391 @@
|
||||
use std::{cmp::max, str::FromStr};
|
||||
|
||||
use alloy_primitives::{aliases::U24, map::HashSet, FixedBytes, U256, U8};
|
||||
use alloy_sol_types::SolValue;
|
||||
use num_bigint::BigUint;
|
||||
use tycho_core::{keccak256, models::Chain, Bytes};
|
||||
|
||||
use crate::encoding::{
|
||||
errors::EncodingError,
|
||||
evm::{
|
||||
approvals::permit2::Permit2,
|
||||
swap_encoder::SWAP_ENCODER_REGISTRY,
|
||||
utils::{biguint_to_u256, bytes_to_address, encode_input, percentage_to_uint24},
|
||||
},
|
||||
models::{EncodingContext, NativeAction, Solution},
|
||||
strategy_encoder::StrategyEncoder,
|
||||
};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub trait EVMStrategyEncoder: StrategyEncoder {
|
||||
fn encode_swap_header(
|
||||
&self,
|
||||
token_in: U8,
|
||||
token_out: U8,
|
||||
split: U24,
|
||||
executor_address: Bytes,
|
||||
executor_selector: FixedBytes<4>,
|
||||
protocol_data: Vec<u8>,
|
||||
) -> Vec<u8> {
|
||||
let mut encoded = Vec::new();
|
||||
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(executor_address.to_vec());
|
||||
encoded.extend(executor_selector);
|
||||
encoded.extend(protocol_data);
|
||||
encoded
|
||||
}
|
||||
fn encode_executor_selector(&self, selector: &str) -> FixedBytes<4> {
|
||||
let hash = keccak256(selector.as_bytes());
|
||||
FixedBytes::<4>::from([hash[0], hash[1], hash[2], hash[3]])
|
||||
}
|
||||
|
||||
fn ple_encode(&self, action_data_array: Vec<Vec<u8>>) -> Vec<u8> {
|
||||
let mut encoded_action_data: Vec<u8> = Vec::new();
|
||||
|
||||
for action_data in action_data_array {
|
||||
let args = (encoded_action_data, action_data.len() as u16, action_data);
|
||||
encoded_action_data = args.abi_encode_packed();
|
||||
}
|
||||
|
||||
encoded_action_data
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SplitSwapStrategyEncoder {
|
||||
permit2: Permit2,
|
||||
selector: String,
|
||||
}
|
||||
|
||||
impl SplitSwapStrategyEncoder {
|
||||
pub fn new(signer_pk: String, chain: Chain) -> Result<Self, EncodingError> {
|
||||
let selector = "swap(uint256, address, address, uint256, bool, bool, uint256, address, ((address,uint160,uint48,uint48),address,uint256),bytes, bytes)".to_string();
|
||||
Ok(Self { permit2: Permit2::new(signer_pk, chain)?, selector })
|
||||
}
|
||||
}
|
||||
impl EVMStrategyEncoder for SplitSwapStrategyEncoder {}
|
||||
impl StrategyEncoder for SplitSwapStrategyEncoder {
|
||||
fn encode_strategy(
|
||||
&self,
|
||||
solution: Solution,
|
||||
router_address: Bytes,
|
||||
) -> Result<(Vec<u8>, Bytes), EncodingError> {
|
||||
let (permit, signature) = self.permit2.get_permit(
|
||||
&router_address,
|
||||
&solution.sender,
|
||||
&solution.given_token,
|
||||
&solution.given_amount,
|
||||
)?;
|
||||
let mut min_amount_out = BigUint::ZERO;
|
||||
if let Some(user_specified_min_amount) = solution.check_amount {
|
||||
if let Some(slippage) = solution.slippage {
|
||||
let one_hundred = BigUint::from(100u32);
|
||||
let slippage_percent = BigUint::from((slippage * 100.0) as u32);
|
||||
let multiplier = &one_hundred - slippage_percent;
|
||||
let expected_amount_with_slippage =
|
||||
(&solution.expected_amount * multiplier) / one_hundred;
|
||||
min_amount_out = max(user_specified_min_amount, expected_amount_with_slippage);
|
||||
}
|
||||
}
|
||||
|
||||
let mut tokens: Vec<Bytes> = solution
|
||||
.swaps
|
||||
.iter()
|
||||
.flat_map(|swap| vec![swap.token_in.clone(), swap.token_out.clone()])
|
||||
.collect::<HashSet<Bytes>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
// this is only to make the test deterministic (same index for the same token for different
|
||||
// runs)
|
||||
tokens.sort();
|
||||
|
||||
let mut swaps = vec![];
|
||||
for swap in solution.swaps.iter() {
|
||||
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)
|
||||
.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(
|
||||
"In token not found in tokens array".to_string(),
|
||||
)
|
||||
})?,
|
||||
),
|
||||
U8::from(
|
||||
tokens
|
||||
.iter()
|
||||
.position(|t| *t == swap.token_out)
|
||||
.ok_or_else(|| {
|
||||
EncodingError::InvalidInput(
|
||||
"Out token not found in tokens array".to_string(),
|
||||
)
|
||||
})?,
|
||||
),
|
||||
percentage_to_uint24(swap.split),
|
||||
Bytes::from_str(swap_encoder.executor_address()).map_err(|_| {
|
||||
EncodingError::FatalError("Invalid executor address".to_string())
|
||||
})?,
|
||||
self.encode_executor_selector(swap_encoder.executor_selector()),
|
||||
protocol_data,
|
||||
);
|
||||
swaps.push(swap_data);
|
||||
}
|
||||
|
||||
let encoded_swaps = self.ple_encode(swaps);
|
||||
let (mut unwrap, mut wrap) = (false, false);
|
||||
if let Some(action) = solution.native_action {
|
||||
match action {
|
||||
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();
|
||||
|
||||
let contract_interaction = encode_input(&self.selector, method_calldata);
|
||||
Ok((contract_interaction, router_address))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
_router_address: Bytes,
|
||||
) -> Result<(Vec<u8>, Bytes), EncodingError> {
|
||||
let router_address = solution.router_address.ok_or_else(|| {
|
||||
EncodingError::InvalidInput(
|
||||
"Router address is required for straight to pool solutions".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let swap = solution
|
||||
.swaps
|
||||
.first()
|
||||
.ok_or_else(|| EncodingError::InvalidInput("No swaps found in solution".to_string()))?;
|
||||
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 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))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::str::FromStr;
|
||||
|
||||
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, Bytes::zero(20))
|
||||
.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_split_swap_strategy_encoder() {
|
||||
// Set up a mock private key for signing
|
||||
let private_key =
|
||||
"4c0883a69102937d6231471b5dbb6204fe512961708279feb1be6ae5538da033".to_string();
|
||||
|
||||
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(private_key, Chain::Ethereum).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!(
|
||||
"e73e3baa",
|
||||
"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
|
||||
// offset of signature (from start of call data to beginning of length indication)
|
||||
// "0000000000000000000000000000000000000000000000000000000000000200",
|
||||
// offset of ple encoded swaps (from start of call data to beginning of length indication)
|
||||
// "0000000000000000000000000000000000000000000000000000000000000280",
|
||||
// length of signature without padding
|
||||
// "0000000000000000000000000000000000000000000000000000000000000041",
|
||||
// signature + padding
|
||||
// "a031b63a01ef5d25975663e5d6c420ef498e3a5968b593cdf846c6729a788186",
|
||||
// "1ddaf79c51453cd501d321ee541d13593e3a266be44103eefdf6e76a032d2870",
|
||||
// "1b00000000000000000000000000000000000000000000000000000000000000"
|
||||
|
||||
let expected_swaps = String::from(concat!(
|
||||
// length of ple encoded swaps without padding
|
||||
"000000000000000000000000000000000000000000000000000000000000005c",
|
||||
// ple encoded swaps
|
||||
"005a",
|
||||
// Swap header
|
||||
"01", // token in index
|
||||
"00", // 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
|
||||
"000000", // padding
|
||||
));
|
||||
let hex_calldata = encode(&calldata);
|
||||
|
||||
assert_eq!(hex_calldata[..520], expected_input);
|
||||
assert_eq!(hex_calldata[1288..], expected_swaps);
|
||||
}
|
||||
}
|
||||
30
src/encoding/evm/strategy_encoder/strategy_selector.rs
Normal file
30
src/encoding/evm/strategy_encoder/strategy_selector.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use tycho_core::models::Chain;
|
||||
|
||||
use crate::encoding::{
|
||||
errors::EncodingError,
|
||||
evm::strategy_encoder::strategy_encoders::{ExecutorStrategyEncoder, SplitSwapStrategyEncoder},
|
||||
models::Solution,
|
||||
strategy_encoder::{StrategyEncoder, StrategySelector},
|
||||
};
|
||||
|
||||
pub struct EVMStrategySelector;
|
||||
|
||||
impl StrategySelector for EVMStrategySelector {
|
||||
fn select_strategy(
|
||||
&self,
|
||||
solution: &Solution,
|
||||
signer: Option<String>,
|
||||
chain: Chain,
|
||||
) -> Result<Box<dyn StrategyEncoder>, EncodingError> {
|
||||
if solution.direct_execution {
|
||||
Ok(Box::new(ExecutorStrategyEncoder {}))
|
||||
} else {
|
||||
let signer_pk = signer.ok_or_else(|| {
|
||||
EncodingError::FatalError(
|
||||
"Signer is required for SplitSwapStrategyEncoder".to_string(),
|
||||
)
|
||||
})?;
|
||||
Ok(Box::new(SplitSwapStrategyEncoder::new(signer_pk, chain)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::encoding::{
|
||||
evm::swap_encoder::encoders::{BalancerV2SwapEncoder, UniswapV2SwapEncoder},
|
||||
evm::swap_encoder::swap_encoders::{BalancerV2SwapEncoder, UniswapV2SwapEncoder},
|
||||
swap_encoder::SwapEncoder,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
mod builder;
|
||||
mod encoders;
|
||||
mod registry;
|
||||
mod swap_encoders;
|
||||
|
||||
use std::sync::RwLock;
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::encoding::{
|
||||
|
||||
pub struct UniswapV2SwapEncoder {
|
||||
executor_address: String,
|
||||
executor_selector: String,
|
||||
}
|
||||
|
||||
impl UniswapV2SwapEncoder {
|
||||
@@ -24,7 +25,7 @@ impl UniswapV2SwapEncoder {
|
||||
|
||||
impl SwapEncoder for UniswapV2SwapEncoder {
|
||||
fn new(executor_address: String) -> Self {
|
||||
Self { executor_address }
|
||||
Self { executor_address, executor_selector: "swap(uint256,bytes)".to_string() }
|
||||
}
|
||||
|
||||
fn encode_swap(
|
||||
@@ -54,10 +55,15 @@ impl SwapEncoder for UniswapV2SwapEncoder {
|
||||
fn executor_address(&self) -> &str {
|
||||
&self.executor_address
|
||||
}
|
||||
|
||||
fn executor_selector(&self) -> &str {
|
||||
&self.executor_selector
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UniswapV3SwapEncoder {
|
||||
executor_address: String,
|
||||
executor_selector: String,
|
||||
}
|
||||
|
||||
impl UniswapV3SwapEncoder {
|
||||
@@ -68,7 +74,7 @@ impl UniswapV3SwapEncoder {
|
||||
|
||||
impl SwapEncoder for UniswapV3SwapEncoder {
|
||||
fn new(executor_address: String) -> Self {
|
||||
Self { executor_address }
|
||||
Self { executor_address, executor_selector: "swap(uint256,bytes)".to_string() }
|
||||
}
|
||||
|
||||
fn encode_swap(
|
||||
@@ -120,10 +126,14 @@ impl SwapEncoder for UniswapV3SwapEncoder {
|
||||
fn executor_address(&self) -> &str {
|
||||
&self.executor_address
|
||||
}
|
||||
fn executor_selector(&self) -> &str {
|
||||
&self.executor_selector
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BalancerV2SwapEncoder {
|
||||
executor_address: String,
|
||||
executor_selector: String,
|
||||
vault_address: String,
|
||||
}
|
||||
|
||||
@@ -131,6 +141,7 @@ impl SwapEncoder for BalancerV2SwapEncoder {
|
||||
fn new(executor_address: String) -> Self {
|
||||
Self {
|
||||
executor_address,
|
||||
executor_selector: "swap(uint256,bytes)".to_string(),
|
||||
vault_address: "0xba12222222228d8ba445958a75a0704d566bf2c8".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -166,6 +177,9 @@ impl SwapEncoder for BalancerV2SwapEncoder {
|
||||
fn executor_address(&self) -> &str {
|
||||
&self.executor_address
|
||||
}
|
||||
fn executor_selector(&self) -> &str {
|
||||
&self.executor_selector
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -194,7 +208,8 @@ mod tests {
|
||||
exact_out: false,
|
||||
router_address: Bytes::zero(20),
|
||||
};
|
||||
let encoder = UniswapV2SwapEncoder::new(String::from("0x"));
|
||||
let encoder =
|
||||
UniswapV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
|
||||
let encoded_swap = encoder
|
||||
.encode_swap(swap, encoding_context)
|
||||
.unwrap();
|
||||
@@ -235,7 +250,8 @@ mod tests {
|
||||
exact_out: false,
|
||||
router_address: Bytes::zero(20),
|
||||
};
|
||||
let encoder = UniswapV3SwapEncoder::new(String::from("0x"));
|
||||
let encoder =
|
||||
UniswapV3SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
|
||||
let encoded_swap = encoder
|
||||
.encode_swap(swap, encoding_context)
|
||||
.unwrap();
|
||||
@@ -277,7 +293,8 @@ mod tests {
|
||||
exact_out: false,
|
||||
router_address: Bytes::zero(20),
|
||||
};
|
||||
let encoder = BalancerV2SwapEncoder::new(String::from("0x"));
|
||||
let encoder =
|
||||
BalancerV2SwapEncoder::new(String::from("0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"));
|
||||
let encoded_swap = encoder
|
||||
.encode_swap(swap, encoding_context)
|
||||
.unwrap();
|
||||
@@ -1,5 +1,4 @@
|
||||
use alloy_primitives::{Address, Keccak256, U256};
|
||||
use alloy_sol_types::SolValue;
|
||||
use alloy_primitives::{aliases::U24, Address, Keccak256, U256};
|
||||
use num_bigint::BigUint;
|
||||
use tycho_core::Bytes;
|
||||
|
||||
@@ -13,7 +12,7 @@ pub fn bytes_to_address(address: &Bytes) -> Result<Address, EncodingError> {
|
||||
if address.len() == 20 {
|
||||
Ok(Address::from_slice(address))
|
||||
} else {
|
||||
Err(EncodingError::InvalidInput(format!("Invalid ERC20 token address: {:?}", address)))
|
||||
Err(EncodingError::InvalidInput(format!("Invalid address: {:?}", address)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,18 +22,6 @@ pub fn biguint_to_u256(value: &BigUint) -> U256 {
|
||||
U256::from_be_slice(&bytes)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn ple_encode(action_data_array: Vec<Vec<u8>>) -> Vec<u8> {
|
||||
let mut encoded_action_data: Vec<u8> = Vec::new();
|
||||
|
||||
for action_data in action_data_array {
|
||||
let args = (encoded_action_data, action_data.len() as u16, action_data);
|
||||
encoded_action_data = args.abi_encode();
|
||||
}
|
||||
|
||||
encoded_action_data
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn encode_input(selector: &str, mut encoded_args: Vec<u8>) -> Vec<u8> {
|
||||
let mut hasher = Keccak256::new();
|
||||
@@ -56,3 +43,12 @@ pub fn encode_input(selector: &str, mut encoded_args: Vec<u8>) -> Vec<u8> {
|
||||
call_data.extend(encoded_args);
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -5,4 +5,3 @@ mod models;
|
||||
mod router_encoder;
|
||||
mod strategy_encoder;
|
||||
mod swap_encoder;
|
||||
mod user_approvals_manager;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use num_bigint::BigUint;
|
||||
use tycho_core::{dto::ProtocolComponent, Bytes};
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Default, Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct Solution {
|
||||
/// True if the solution is an exact output solution.
|
||||
@@ -35,14 +35,14 @@ pub struct Solution {
|
||||
pub native_action: Option<NativeAction>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub enum NativeAction {
|
||||
Wrap,
|
||||
Unwrap,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct Swap {
|
||||
/// Protocol component from tycho indexer
|
||||
@@ -51,7 +51,7 @@ pub struct Swap {
|
||||
pub token_in: Bytes,
|
||||
/// Token being output from the pool.
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
@@ -2,14 +2,12 @@ use crate::encoding::{
|
||||
errors::EncodingError,
|
||||
models::{Solution, Transaction},
|
||||
strategy_encoder::StrategySelector,
|
||||
user_approvals_manager::UserApprovalsManager,
|
||||
};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub trait RouterEncoder<S: StrategySelector, A: UserApprovalsManager> {
|
||||
pub trait RouterEncoder<S: StrategySelector> {
|
||||
fn encode_router_calldata(
|
||||
&self,
|
||||
solutions: Vec<Solution>,
|
||||
) -> Result<Vec<Transaction>, EncodingError>;
|
||||
fn handle_approvals(&self, solutions: &[Solution]) -> Result<Vec<Vec<u8>>, EncodingError>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
use tycho_core::Bytes;
|
||||
use tycho_core::{models::Chain, Bytes};
|
||||
|
||||
use crate::encoding::{errors::EncodingError, models::Solution};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub trait StrategyEncoder {
|
||||
fn encode_strategy(&self, to_encode: Solution) -> Result<(Vec<u8>, Bytes), EncodingError>;
|
||||
fn selector(&self, exact_out: bool) -> &str;
|
||||
fn encode_strategy(
|
||||
&self,
|
||||
to_encode: Solution,
|
||||
router_address: Bytes,
|
||||
) -> Result<(Vec<u8>, Bytes), EncodingError>;
|
||||
}
|
||||
|
||||
pub trait StrategySelector {
|
||||
#[allow(dead_code)]
|
||||
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder>;
|
||||
fn select_strategy(
|
||||
&self,
|
||||
solution: &Solution,
|
||||
signer_pk: Option<String>,
|
||||
chain_id: Chain,
|
||||
) -> Result<Box<dyn StrategyEncoder>, EncodingError>;
|
||||
}
|
||||
|
||||
@@ -14,4 +14,5 @@ pub trait SwapEncoder: Sync + Send {
|
||||
encoding_context: EncodingContext,
|
||||
) -> Result<Vec<u8>, EncodingError>;
|
||||
fn executor_address(&self) -> &str;
|
||||
fn executor_selector(&self) -> &str;
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
use num_bigint::BigUint;
|
||||
use tycho_core::Bytes;
|
||||
|
||||
use crate::encoding::errors::EncodingError;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Approval {
|
||||
pub spender: Bytes,
|
||||
pub owner: Bytes,
|
||||
pub token: Bytes,
|
||||
pub amount: BigUint,
|
||||
}
|
||||
|
||||
pub trait UserApprovalsManager {
|
||||
#[allow(dead_code)]
|
||||
fn encode_approvals(&self, approvals: Vec<Approval>) -> Result<Vec<Vec<u8>>, EncodingError>;
|
||||
}
|
||||
Reference in New Issue
Block a user