Merge pull request #7 from propeller-heads/encoding/dc/ENG-4075-feature-gate
feat: EVM feature gate
This commit is contained in:
10
Cargo.toml
10
Cargo.toml
@@ -10,9 +10,9 @@ num-bigint = "0.4.6"
|
|||||||
|
|
||||||
tokio = { version = "1.38.0", features = ["full"] }
|
tokio = { version = "1.38.0", features = ["full"] }
|
||||||
|
|
||||||
alloy = { version = "0.5.4", features = ["providers"] }
|
alloy = { version = "0.5.4", features = ["providers"], optional = true }
|
||||||
alloy-sol-types = { version = "0.8.14" }
|
alloy-sol-types = { version = "0.8.14", optional = true }
|
||||||
alloy-primitives = { version = "0.8.9" }
|
alloy-primitives = { version = "0.8.9", optional = true }
|
||||||
tycho-core = { git = "https://github.com/propeller-heads/tycho-indexer.git", package = "tycho-core", tag = "0.46.0" }
|
tycho-core = { git = "https://github.com/propeller-heads/tycho-indexer.git", package = "tycho-core", tag = "0.46.0" }
|
||||||
hex = "0.4.3"
|
hex = "0.4.3"
|
||||||
anyhow = "1.0.95"
|
anyhow = "1.0.95"
|
||||||
@@ -20,5 +20,9 @@ num-traits = "0.2.19"
|
|||||||
serde = { version = "1.0.217", features = ["derive"] }
|
serde = { version = "1.0.217", features = ["derive"] }
|
||||||
serde_json = "1.0.135"
|
serde_json = "1.0.135"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["evm"]
|
||||||
|
evm = ["alloy", "alloy-sol-types", "alloy-primitives"]
|
||||||
|
|
||||||
[profile.bench]
|
[profile.bench]
|
||||||
debug = true
|
debug = true
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
pub(crate) mod approvals_manager;
|
|
||||||
pub(crate) mod interface;
|
|
||||||
mod permit2;
|
|
||||||
8
src/encoding/config/executor_addresses.json
Normal file
8
src/encoding/config/executor_addresses.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"executors": {
|
||||||
|
"ethereum": {
|
||||||
|
"uniswap_v2": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
|
||||||
|
"vm:balancer_v2": "0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
2
src/encoding/evm/approvals/mod.rs
Normal file
2
src/encoding/evm/approvals/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod permit2;
|
||||||
|
pub mod protocol_approvals_manager;
|
||||||
@@ -3,7 +3,7 @@ use std::str::FromStr;
|
|||||||
use alloy_primitives::U256;
|
use alloy_primitives::U256;
|
||||||
use tycho_core::Bytes;
|
use tycho_core::Bytes;
|
||||||
|
|
||||||
use crate::encoding::approvals::interface::{Approval, UserApprovalsManager};
|
use crate::encoding::user_approvals_manager::{Approval, UserApprovalsManager};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct Permit2 {
|
pub struct Permit2 {
|
||||||
5
src/encoding/evm/mod.rs
Normal file
5
src/encoding/evm/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
pub mod approvals;
|
||||||
|
mod router_encoder;
|
||||||
|
mod strategy_encoder;
|
||||||
|
mod swap_encoder;
|
||||||
|
mod utils;
|
||||||
81
src/encoding/evm/router_encoder.rs
Normal file
81
src/encoding/evm/router_encoder.rs
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
use alloy_sol_types::SolValue;
|
||||||
|
use anyhow::Error;
|
||||||
|
use num_bigint::BigUint;
|
||||||
|
|
||||||
|
use crate::encoding::{
|
||||||
|
evm::utils::{encode_input, ple_encode},
|
||||||
|
models::{NativeAction, Solution, Transaction, PROPELLER_ROUTER_ADDRESS},
|
||||||
|
router_encoder::RouterEncoder,
|
||||||
|
strategy_encoder::StrategySelector,
|
||||||
|
user_approvals_manager::{Approval, UserApprovalsManager},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub struct EVMRouterEncoder<S: StrategySelector, A: UserApprovalsManager> {
|
||||||
|
strategy_selector: S,
|
||||||
|
approvals_manager: A,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<S: StrategySelector, A: UserApprovalsManager> EVMRouterEncoder<S, A> {
|
||||||
|
pub fn new(strategy_selector: S, approvals_manager: A) -> Self {
|
||||||
|
EVMRouterEncoder { strategy_selector, approvals_manager }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> for EVMRouterEncoder<S, A> {
|
||||||
|
fn encode_router_calldata(&self, solutions: Vec<Solution>) -> Result<Transaction, Error> {
|
||||||
|
let _approvals_calldata = self.handle_approvals(&solutions)?; // TODO: where should we append this?
|
||||||
|
let mut calldata_list: Vec<Vec<u8>> = Vec::new();
|
||||||
|
let encode_for_batch_execute = solutions.len() > 1;
|
||||||
|
let mut value = BigUint::ZERO;
|
||||||
|
for solution in solutions.iter() {
|
||||||
|
let exact_out = solution.exact_out;
|
||||||
|
let straight_to_pool = solution.straight_to_pool;
|
||||||
|
|
||||||
|
let strategy = self
|
||||||
|
.strategy_selector
|
||||||
|
.select_strategy(solution);
|
||||||
|
let method_calldata = strategy.encode_strategy((*solution).clone())?;
|
||||||
|
|
||||||
|
let contract_interaction = if encode_for_batch_execute {
|
||||||
|
let args = (strategy.action_type(exact_out) as u16, method_calldata);
|
||||||
|
args.abi_encode()
|
||||||
|
} else if straight_to_pool {
|
||||||
|
method_calldata
|
||||||
|
} else {
|
||||||
|
encode_input(strategy.selector(exact_out), method_calldata)
|
||||||
|
};
|
||||||
|
calldata_list.push(contract_interaction);
|
||||||
|
|
||||||
|
if solution.native_action.clone().unwrap() == NativeAction::Wrap {
|
||||||
|
value += solution.given_amount.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let data = if encode_for_batch_execute {
|
||||||
|
let args = (false, ple_encode(calldata_list));
|
||||||
|
encode_input("batchExecute(bytes)", args.abi_encode())
|
||||||
|
} else {
|
||||||
|
calldata_list[0].clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Transaction { data, value })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_approvals(&self, solutions: &[Solution]) -> Result<Vec<u8>, Error> {
|
||||||
|
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(PROPELLER_ROUTER_ADDRESS.clone()),
|
||||||
|
amount: solution.given_amount.clone(),
|
||||||
|
owner: solution.sender.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(self
|
||||||
|
.approvals_manager
|
||||||
|
.encode_approvals(approvals))
|
||||||
|
}
|
||||||
|
}
|
||||||
198
src/encoding/evm/strategy_encoder/encoder.rs
Normal file
198
src/encoding/evm/strategy_encoder/encoder.rs
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
use std::{cmp::min, str::FromStr};
|
||||||
|
|
||||||
|
use alloy_primitives::Address;
|
||||||
|
use alloy_sol_types::SolValue;
|
||||||
|
use anyhow::Error;
|
||||||
|
use num_bigint::BigUint;
|
||||||
|
use num_traits::Zero;
|
||||||
|
|
||||||
|
use crate::encoding::{
|
||||||
|
evm::{
|
||||||
|
swap_encoder::SWAP_ENCODER_REGISTRY,
|
||||||
|
utils::{biguint_to_u256, ple_encode},
|
||||||
|
},
|
||||||
|
models::{ActionType, EncodingContext, NativeAction, Solution, PROPELLER_ROUTER_ADDRESS},
|
||||||
|
strategy_encoder::StrategyEncoder,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub trait EVMStrategyEncoder: StrategyEncoder {
|
||||||
|
fn encode_protocol_header(
|
||||||
|
&self,
|
||||||
|
protocol_data: Vec<u8>,
|
||||||
|
executor_address: Address,
|
||||||
|
// Token indices, split, and token inclusion are only used for split swaps
|
||||||
|
token_in: u16,
|
||||||
|
token_out: u16,
|
||||||
|
split: u16, // not sure what should be the type of this :/
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let args = (executor_address, token_in, token_out, split, protocol_data);
|
||||||
|
args.abi_encode()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SingleSwapStrategyEncoder {}
|
||||||
|
impl EVMStrategyEncoder for SingleSwapStrategyEncoder {}
|
||||||
|
|
||||||
|
impl StrategyEncoder for SingleSwapStrategyEncoder {
|
||||||
|
fn encode_strategy(&self, _solution: Solution) -> Result<Vec<u8>, Error> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn action_type(&self, exact_out: bool) -> ActionType {
|
||||||
|
if exact_out {
|
||||||
|
ActionType::SingleExactOut
|
||||||
|
} else {
|
||||||
|
ActionType::SingleExactIn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selector(&self, exact_out: bool) -> &str {
|
||||||
|
if exact_out {
|
||||||
|
"singleExactOut(uint256, bytes)"
|
||||||
|
} else {
|
||||||
|
"singleExactIn(uint256, bytes)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SequentialStrategyEncoder {}
|
||||||
|
impl EVMStrategyEncoder for SequentialStrategyEncoder {}
|
||||||
|
|
||||||
|
impl StrategyEncoder for SequentialStrategyEncoder {
|
||||||
|
fn encode_strategy(&self, solution: Solution) -> Result<Vec<u8>, Error> {
|
||||||
|
let check_amount = if solution.check_amount.is_some() {
|
||||||
|
let mut check_amount = 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;
|
||||||
|
check_amount = min(check_amount, expected_amount_with_slippage);
|
||||||
|
}
|
||||||
|
check_amount
|
||||||
|
} else {
|
||||||
|
BigUint::ZERO
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut swaps = vec![];
|
||||||
|
for (index, swap) in solution.swaps.iter().enumerate() {
|
||||||
|
let is_last = index == solution.swaps.len() - 1;
|
||||||
|
let registry = SWAP_ENCODER_REGISTRY.read().unwrap();
|
||||||
|
let swap_encoder = registry
|
||||||
|
.get_encoder(&swap.component.protocol_system)
|
||||||
|
.expect("Swap encoder not found");
|
||||||
|
let router_address = if solution.router_address.is_some() {
|
||||||
|
solution.router_address.clone().unwrap()
|
||||||
|
} else {
|
||||||
|
PROPELLER_ROUTER_ADDRESS.clone()
|
||||||
|
};
|
||||||
|
let receiver = if is_last { solution.receiver.clone() } else { router_address.clone() };
|
||||||
|
|
||||||
|
let encoding_context = EncodingContext {
|
||||||
|
receiver,
|
||||||
|
exact_out: solution.exact_out,
|
||||||
|
address_for_approvals: router_address,
|
||||||
|
};
|
||||||
|
let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context)?;
|
||||||
|
let executor_address = swap_encoder.executor_address();
|
||||||
|
let swap_data = self.encode_protocol_header(
|
||||||
|
protocol_data,
|
||||||
|
Address::from_str(executor_address).expect("Couldn't convert executor address"),
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
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 = (
|
||||||
|
wrap,
|
||||||
|
unwrap,
|
||||||
|
biguint_to_u256(&solution.given_amount),
|
||||||
|
!check_amount.is_zero(), /* if check_amount is zero, then we don't need to check */
|
||||||
|
biguint_to_u256(&check_amount),
|
||||||
|
encoded_swaps,
|
||||||
|
)
|
||||||
|
.abi_encode();
|
||||||
|
Ok(method_calldata)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn action_type(&self, exact_out: bool) -> ActionType {
|
||||||
|
if exact_out {
|
||||||
|
ActionType::SequentialExactOut
|
||||||
|
} else {
|
||||||
|
ActionType::SequentialExactIn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selector(&self, exact_out: bool) -> &str {
|
||||||
|
if exact_out {
|
||||||
|
"sequentialExactOut(uint256, uint256, bytes[])"
|
||||||
|
} else {
|
||||||
|
"sequentialExactIn(uint256, uint256, bytes[])"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SplitSwapStrategyEncoder {}
|
||||||
|
impl EVMStrategyEncoder for SplitSwapStrategyEncoder {}
|
||||||
|
impl StrategyEncoder for SplitSwapStrategyEncoder {
|
||||||
|
fn encode_strategy(&self, _solution: Solution) -> Result<Vec<u8>, Error> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
fn action_type(&self, _exact_out: bool) -> ActionType {
|
||||||
|
ActionType::SplitIn
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selector(&self, _exact_out: bool) -> &str {
|
||||||
|
"splitExactIn(uint256, address, uint256, bytes[])"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This strategy encoder is used for solutions that are sent directly to the pool.
|
||||||
|
/// Only 1 solution with 1 swap is supported.
|
||||||
|
pub struct StraightToPoolStrategyEncoder {}
|
||||||
|
impl EVMStrategyEncoder for StraightToPoolStrategyEncoder {}
|
||||||
|
impl StrategyEncoder for StraightToPoolStrategyEncoder {
|
||||||
|
fn encode_strategy(&self, solution: Solution) -> Result<Vec<u8>, Error> {
|
||||||
|
if solution.router_address.is_none() {
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Router address is required for straight to pool solutions"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let swap = solution.swaps.first().unwrap();
|
||||||
|
let registry = SWAP_ENCODER_REGISTRY.read().unwrap();
|
||||||
|
let swap_encoder = registry
|
||||||
|
.get_encoder(&swap.component.protocol_system)
|
||||||
|
.expect("Swap encoder not found");
|
||||||
|
let router_address = solution.router_address.unwrap();
|
||||||
|
|
||||||
|
let encoding_context = EncodingContext {
|
||||||
|
receiver: solution.receiver,
|
||||||
|
exact_out: solution.exact_out,
|
||||||
|
address_for_approvals: router_address,
|
||||||
|
};
|
||||||
|
let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context)?;
|
||||||
|
// TODO: here we need to pass also the address of the executor to be used
|
||||||
|
Ok(protocol_data)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn action_type(&self, _exact_out: bool) -> ActionType {
|
||||||
|
unimplemented!();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selector(&self, _exact_out: bool) -> &str {
|
||||||
|
unimplemented!();
|
||||||
|
}
|
||||||
|
}
|
||||||
2
src/encoding/evm/strategy_encoder/mod.rs
Normal file
2
src/encoding/evm/strategy_encoder/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
mod encoder;
|
||||||
|
mod selector;
|
||||||
@@ -1,19 +1,15 @@
|
|||||||
use crate::encoding::{
|
use crate::encoding::{
|
||||||
models::Solution,
|
evm::strategy_encoder::encoder::{
|
||||||
strategy_encoder::{
|
|
||||||
SequentialStrategyEncoder, SingleSwapStrategyEncoder, SplitSwapStrategyEncoder,
|
SequentialStrategyEncoder, SingleSwapStrategyEncoder, SplitSwapStrategyEncoder,
|
||||||
StraightToPoolStrategyEncoder, StrategyEncoder,
|
StraightToPoolStrategyEncoder,
|
||||||
},
|
},
|
||||||
|
models::Solution,
|
||||||
|
strategy_encoder::{StrategyEncoder, StrategySelector},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub trait StrategySelector {
|
pub struct EVMStrategySelector;
|
||||||
#[allow(dead_code)]
|
|
||||||
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct DefaultStrategySelector;
|
impl StrategySelector for EVMStrategySelector {
|
||||||
|
|
||||||
impl StrategySelector for DefaultStrategySelector {
|
|
||||||
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder> {
|
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder> {
|
||||||
if solution.straight_to_pool {
|
if solution.straight_to_pool {
|
||||||
Box::new(StraightToPoolStrategyEncoder {})
|
Box::new(StraightToPoolStrategyEncoder {})
|
||||||
@@ -1,22 +1,18 @@
|
|||||||
use std::str::FromStr;
|
use crate::encoding::{
|
||||||
|
evm::swap_encoder::encoders::{BalancerV2SwapEncoder, UniswapV2SwapEncoder},
|
||||||
use alloy_primitives::Address;
|
swap_encoder::SwapEncoder,
|
||||||
|
|
||||||
use crate::encoding::swap_encoder::swap_struct_encoder::{
|
|
||||||
BalancerV2SwapEncoder, SwapEncoder, UniswapV2SwapEncoder,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub struct SwapEncoderBuilder {
|
pub struct SwapEncoderBuilder {
|
||||||
protocol_system: String,
|
protocol_system: String,
|
||||||
executor_address: Address,
|
executor_address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SwapEncoderBuilder {
|
impl SwapEncoderBuilder {
|
||||||
pub fn new(protocol_system: &str, executor_address: &str) -> Self {
|
pub fn new(protocol_system: &str, executor_address: &str) -> Self {
|
||||||
SwapEncoderBuilder {
|
SwapEncoderBuilder {
|
||||||
protocol_system: protocol_system.to_string(),
|
protocol_system: protocol_system.to_string(),
|
||||||
executor_address: Address::from_str(executor_address)
|
executor_address: executor_address.to_string(),
|
||||||
.unwrap_or_else(|_| panic!("Invalid address: {}", executor_address)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5,26 +5,20 @@ use alloy_sol_types::SolValue;
|
|||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
|
|
||||||
use crate::encoding::{
|
use crate::encoding::{
|
||||||
approvals::approvals_manager::ProtocolApprovalsManager,
|
evm::{
|
||||||
|
approvals::protocol_approvals_manager::ProtocolApprovalsManager, utils::bytes_to_address,
|
||||||
|
},
|
||||||
models::{EncodingContext, Swap},
|
models::{EncodingContext, Swap},
|
||||||
utils::bytes_to_address,
|
swap_encoder::SwapEncoder,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub trait SwapEncoder: Sync + Send {
|
|
||||||
fn new(executor_address: Address) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized;
|
|
||||||
fn encode_swap(&self, swap: Swap, encoding_context: EncodingContext) -> Result<Vec<u8>, Error>;
|
|
||||||
fn executor_address(&self) -> Address;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct UniswapV2SwapEncoder {
|
pub struct UniswapV2SwapEncoder {
|
||||||
executor_address: Address,
|
executor_address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UniswapV2SwapEncoder {}
|
impl UniswapV2SwapEncoder {}
|
||||||
impl SwapEncoder for UniswapV2SwapEncoder {
|
impl SwapEncoder for UniswapV2SwapEncoder {
|
||||||
fn new(executor_address: Address) -> Self {
|
fn new(executor_address: String) -> Self {
|
||||||
Self { executor_address }
|
Self { executor_address }
|
||||||
}
|
}
|
||||||
fn encode_swap(
|
fn encode_swap(
|
||||||
@@ -35,18 +29,18 @@ impl SwapEncoder for UniswapV2SwapEncoder {
|
|||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn executor_address(&self) -> Address {
|
fn executor_address(&self) -> &str {
|
||||||
self.executor_address
|
&self.executor_address
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct BalancerV2SwapEncoder {
|
pub struct BalancerV2SwapEncoder {
|
||||||
executor_address: Address,
|
executor_address: String,
|
||||||
vault_address: Address,
|
vault_address: Address,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SwapEncoder for BalancerV2SwapEncoder {
|
impl SwapEncoder for BalancerV2SwapEncoder {
|
||||||
fn new(executor_address: Address) -> Self {
|
fn new(executor_address: String) -> Self {
|
||||||
Self {
|
Self {
|
||||||
executor_address,
|
executor_address,
|
||||||
vault_address: Address::from_str("0xba12222222228d8ba445958a75a0704d566bf2c8")
|
vault_address: Address::from_str("0xba12222222228d8ba445958a75a0704d566bf2c8")
|
||||||
@@ -79,8 +73,8 @@ impl SwapEncoder for BalancerV2SwapEncoder {
|
|||||||
Ok(args.abi_encode())
|
Ok(args.abi_encode())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn executor_address(&self) -> Address {
|
fn executor_address(&self) -> &str {
|
||||||
self.executor_address
|
&self.executor_address
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
18
src/encoding/evm/swap_encoder/mod.rs
Normal file
18
src/encoding/evm/swap_encoder/mod.rs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
mod builder;
|
||||||
|
mod encoders;
|
||||||
|
mod registry;
|
||||||
|
|
||||||
|
use std::sync::RwLock;
|
||||||
|
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use tycho_core::dto::Chain;
|
||||||
|
|
||||||
|
use crate::encoding::evm::swap_encoder::registry::{Config, SwapEncoderRegistry};
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
pub static ref SWAP_ENCODER_REGISTRY: RwLock<SwapEncoderRegistry> = {
|
||||||
|
let config = Config::from_file("src/encoding/config/executor_addresses.json")
|
||||||
|
.expect("Failed to load configuration file");
|
||||||
|
RwLock::new(SwapEncoderRegistry::new(config, Chain::Ethereum))
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,25 +1,27 @@
|
|||||||
use std::{collections::HashMap, fs};
|
use std::{collections::HashMap, fs};
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
use tycho_core::dto::Chain;
|
||||||
|
|
||||||
use crate::encoding::swap_encoder::{
|
use crate::encoding::{evm::swap_encoder::builder::SwapEncoderBuilder, swap_encoder::SwapEncoder};
|
||||||
builder::SwapEncoderBuilder, swap_struct_encoder::SwapEncoder,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct SwapEncoderRegistry {
|
pub struct SwapEncoderRegistry {
|
||||||
encoders: HashMap<String, Box<dyn SwapEncoder>>,
|
encoders: HashMap<String, Box<dyn SwapEncoder>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SwapEncoderRegistry {
|
impl SwapEncoderRegistry {
|
||||||
pub fn new(config: Config) -> Self {
|
pub fn new(config: Config, blockchain: Chain) -> Self {
|
||||||
let mut encoders = HashMap::new();
|
let mut encoders = HashMap::new();
|
||||||
|
let executors = config
|
||||||
for (protocol, executor_address) in config.executors {
|
.executors
|
||||||
let builder = SwapEncoderBuilder::new(&protocol, &executor_address);
|
.get(&blockchain)
|
||||||
|
.unwrap_or_else(|| panic!("No executors found for blockchain: {}", blockchain));
|
||||||
|
for (protocol, executor_address) in executors {
|
||||||
|
let builder = SwapEncoderBuilder::new(protocol, executor_address);
|
||||||
let encoder = builder.build().unwrap_or_else(|_| {
|
let encoder = builder.build().unwrap_or_else(|_| {
|
||||||
panic!("Failed to build swap encoder for protocol: {}", protocol)
|
panic!("Failed to build swap encoder for protocol: {}", protocol)
|
||||||
});
|
});
|
||||||
encoders.insert(protocol, encoder);
|
encoders.insert(protocol.to_string(), encoder);
|
||||||
}
|
}
|
||||||
|
|
||||||
Self { encoders }
|
Self { encoders }
|
||||||
@@ -33,7 +35,8 @@ impl SwapEncoderRegistry {
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub executors: HashMap<String, String>, // Protocol -> Executor address mapping
|
pub executors: HashMap<Chain, HashMap<String, String>>, /* Blockchain -> {Protocol ->
|
||||||
|
* Executor address} mapping */
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
mod approvals;
|
#[cfg(feature = "evm")]
|
||||||
|
mod evm;
|
||||||
mod models;
|
mod models;
|
||||||
mod router_encoder;
|
mod router_encoder;
|
||||||
mod strategy_encoder;
|
mod strategy_encoder;
|
||||||
mod strategy_selector;
|
|
||||||
mod swap_encoder;
|
mod swap_encoder;
|
||||||
mod utils;
|
mod user_approvals_manager;
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ pub enum NativeAction {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
#[allow(dead_code)]
|
||||||
pub struct Swap {
|
pub struct Swap {
|
||||||
/// Protocol component from tycho indexer
|
/// Protocol component from tycho indexer
|
||||||
pub component: ProtocolComponent,
|
pub component: ProtocolComponent,
|
||||||
@@ -71,12 +72,14 @@ pub struct Transaction {
|
|||||||
pub value: BigUint,
|
pub value: BigUint,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
pub struct EncodingContext {
|
pub struct EncodingContext {
|
||||||
pub receiver: Bytes,
|
pub receiver: Bytes,
|
||||||
pub exact_out: bool,
|
pub exact_out: bool,
|
||||||
pub address_for_approvals: Bytes,
|
pub address_for_approvals: Bytes,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
pub enum ActionType {
|
pub enum ActionType {
|
||||||
SingleExactIn = 1,
|
SingleExactIn = 1,
|
||||||
SingleExactOut = 2,
|
SingleExactOut = 2,
|
||||||
|
|||||||
@@ -1,78 +1,13 @@
|
|||||||
use alloy_sol_types::SolValue;
|
|
||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use num_bigint::BigUint;
|
|
||||||
|
|
||||||
use crate::encoding::{
|
use crate::encoding::{
|
||||||
approvals::interface::{Approval, UserApprovalsManager},
|
models::{Solution, Transaction},
|
||||||
models::{NativeAction, Solution, Transaction, PROPELLER_ROUTER_ADDRESS},
|
strategy_encoder::StrategySelector,
|
||||||
strategy_selector::StrategySelector,
|
user_approvals_manager::UserApprovalsManager,
|
||||||
utils::{encode_input, ple_encode},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
struct RouterEncoder<S: StrategySelector, A: UserApprovalsManager> {
|
pub trait RouterEncoder<S: StrategySelector, A: UserApprovalsManager> {
|
||||||
strategy_selector: S,
|
fn encode_router_calldata(&self, solutions: Vec<Solution>) -> Result<Transaction, Error>;
|
||||||
approvals_manager: A,
|
fn handle_approvals(&self, solutions: &[Solution]) -> Result<Vec<u8>, Error>;
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
impl<S: StrategySelector, A: UserApprovalsManager> RouterEncoder<S, A> {
|
|
||||||
pub fn new(strategy_selector: S, approvals_manager: A) -> Self {
|
|
||||||
RouterEncoder { strategy_selector, approvals_manager }
|
|
||||||
}
|
|
||||||
pub fn encode_router_calldata(&self, solutions: Vec<Solution>) -> Result<Transaction, Error> {
|
|
||||||
let _approvals_calldata = self.handle_approvals(&solutions)?; // TODO: where should we append this?
|
|
||||||
let mut calldata_list: Vec<Vec<u8>> = Vec::new();
|
|
||||||
let encode_for_batch_execute = solutions.len() > 1;
|
|
||||||
let mut value = BigUint::ZERO;
|
|
||||||
for solution in solutions.iter() {
|
|
||||||
let exact_out = solution.exact_out;
|
|
||||||
let straight_to_pool = solution.straight_to_pool;
|
|
||||||
|
|
||||||
let strategy = self
|
|
||||||
.strategy_selector
|
|
||||||
.select_strategy(solution);
|
|
||||||
let method_calldata = strategy.encode_strategy((*solution).clone())?;
|
|
||||||
|
|
||||||
let contract_interaction = if encode_for_batch_execute {
|
|
||||||
let args = (strategy.action_type(exact_out) as u16, method_calldata);
|
|
||||||
args.abi_encode()
|
|
||||||
} else if straight_to_pool {
|
|
||||||
method_calldata
|
|
||||||
} else {
|
|
||||||
encode_input(strategy.selector(exact_out), method_calldata)
|
|
||||||
};
|
|
||||||
calldata_list.push(contract_interaction);
|
|
||||||
|
|
||||||
if solution.native_action.clone().unwrap() == NativeAction::Wrap {
|
|
||||||
value += solution.given_amount.clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let data = if encode_for_batch_execute {
|
|
||||||
let args = (false, ple_encode(calldata_list));
|
|
||||||
encode_input("batchExecute(bytes)", args.abi_encode())
|
|
||||||
} else {
|
|
||||||
calldata_list[0].clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(Transaction { data, value })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_approvals(&self, solutions: &[Solution]) -> Result<Vec<u8>, Error> {
|
|
||||||
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(PROPELLER_ROUTER_ADDRESS.clone()),
|
|
||||||
amount: solution.given_amount.clone(),
|
|
||||||
owner: solution.sender.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(self
|
|
||||||
.approvals_manager
|
|
||||||
.encode_approvals(approvals))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,6 @@
|
|||||||
use std::cmp::min;
|
|
||||||
|
|
||||||
use alloy_primitives::Address;
|
|
||||||
use alloy_sol_types::SolValue;
|
|
||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use num_bigint::BigUint;
|
|
||||||
use num_traits::Zero;
|
|
||||||
|
|
||||||
use crate::encoding::{
|
use crate::encoding::models::{ActionType, Solution};
|
||||||
models::{ActionType, EncodingContext, NativeAction, Solution, PROPELLER_ROUTER_ADDRESS},
|
|
||||||
swap_encoder::SWAP_ENCODER_REGISTRY,
|
|
||||||
utils::{biguint_to_u256, ple_encode},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub trait StrategyEncoder {
|
pub trait StrategyEncoder {
|
||||||
@@ -18,175 +8,9 @@ pub trait StrategyEncoder {
|
|||||||
|
|
||||||
fn action_type(&self, exact_out: bool) -> ActionType;
|
fn action_type(&self, exact_out: bool) -> ActionType;
|
||||||
fn selector(&self, exact_out: bool) -> &str;
|
fn selector(&self, exact_out: bool) -> &str;
|
||||||
|
|
||||||
fn encode_protocol_header(
|
|
||||||
&self,
|
|
||||||
protocol_data: Vec<u8>,
|
|
||||||
executor_address: Address,
|
|
||||||
// Token indices, split, and token inclusion are only used for split swaps
|
|
||||||
token_in: u16,
|
|
||||||
token_out: u16,
|
|
||||||
split: u16, // not sure what should be the type of this :/
|
|
||||||
) -> Vec<u8> {
|
|
||||||
let args = (executor_address, token_in, token_out, split, protocol_data);
|
|
||||||
args.abi_encode()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct SingleSwapStrategyEncoder {}
|
pub trait StrategySelector {
|
||||||
|
#[allow(dead_code)]
|
||||||
impl StrategyEncoder for SingleSwapStrategyEncoder {
|
fn select_strategy(&self, solution: &Solution) -> Box<dyn StrategyEncoder>;
|
||||||
fn encode_strategy(&self, _solution: Solution) -> Result<Vec<u8>, Error> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn action_type(&self, exact_out: bool) -> ActionType {
|
|
||||||
if exact_out {
|
|
||||||
ActionType::SingleExactOut
|
|
||||||
} else {
|
|
||||||
ActionType::SingleExactIn
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn selector(&self, exact_out: bool) -> &str {
|
|
||||||
if exact_out {
|
|
||||||
"singleExactOut(uint256, bytes)"
|
|
||||||
} else {
|
|
||||||
"singleExactIn(uint256, bytes)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SequentialStrategyEncoder {}
|
|
||||||
|
|
||||||
impl StrategyEncoder for SequentialStrategyEncoder {
|
|
||||||
fn encode_strategy(&self, solution: Solution) -> Result<Vec<u8>, Error> {
|
|
||||||
let check_amount = if solution.check_amount.is_some() {
|
|
||||||
let mut check_amount = 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;
|
|
||||||
check_amount = min(check_amount, expected_amount_with_slippage);
|
|
||||||
}
|
|
||||||
check_amount
|
|
||||||
} else {
|
|
||||||
BigUint::ZERO
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut swaps = vec![];
|
|
||||||
for (index, swap) in solution.swaps.iter().enumerate() {
|
|
||||||
let is_last = index == solution.swaps.len() - 1;
|
|
||||||
let registry = SWAP_ENCODER_REGISTRY.read().unwrap();
|
|
||||||
let swap_encoder = registry
|
|
||||||
.get_encoder(&swap.component.protocol_system)
|
|
||||||
.expect("Swap encoder not found");
|
|
||||||
let router_address = if solution.router_address.is_some() {
|
|
||||||
solution.router_address.clone().unwrap()
|
|
||||||
} else {
|
|
||||||
PROPELLER_ROUTER_ADDRESS.clone()
|
|
||||||
};
|
|
||||||
let receiver = if is_last { solution.receiver.clone() } else { router_address.clone() };
|
|
||||||
|
|
||||||
let encoding_context = EncodingContext {
|
|
||||||
receiver,
|
|
||||||
exact_out: solution.exact_out,
|
|
||||||
address_for_approvals: router_address,
|
|
||||||
};
|
|
||||||
let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context)?;
|
|
||||||
let executor_address = swap_encoder.executor_address();
|
|
||||||
let swap_data = self.encode_protocol_header(protocol_data, executor_address, 0, 0, 0);
|
|
||||||
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 = (
|
|
||||||
wrap,
|
|
||||||
unwrap,
|
|
||||||
biguint_to_u256(&solution.given_amount),
|
|
||||||
!check_amount.is_zero(), /* if check_amount is zero, then we don't need to check */
|
|
||||||
biguint_to_u256(&check_amount),
|
|
||||||
encoded_swaps,
|
|
||||||
)
|
|
||||||
.abi_encode();
|
|
||||||
Ok(method_calldata)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn action_type(&self, exact_out: bool) -> ActionType {
|
|
||||||
if exact_out {
|
|
||||||
ActionType::SequentialExactOut
|
|
||||||
} else {
|
|
||||||
ActionType::SequentialExactIn
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn selector(&self, exact_out: bool) -> &str {
|
|
||||||
if exact_out {
|
|
||||||
"sequentialExactOut(uint256, uint256, bytes[])"
|
|
||||||
} else {
|
|
||||||
"sequentialExactIn(uint256, uint256, bytes[])"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SplitSwapStrategyEncoder {}
|
|
||||||
|
|
||||||
impl StrategyEncoder for SplitSwapStrategyEncoder {
|
|
||||||
fn encode_strategy(&self, _solution: Solution) -> Result<Vec<u8>, Error> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
fn action_type(&self, _exact_out: bool) -> ActionType {
|
|
||||||
ActionType::SplitIn
|
|
||||||
}
|
|
||||||
|
|
||||||
fn selector(&self, _exact_out: bool) -> &str {
|
|
||||||
"splitExactIn(uint256, address, uint256, bytes[])"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This strategy encoder is used for solutions that are sent directly to the pool.
|
|
||||||
/// Only 1 solution with 1 swap is supported.
|
|
||||||
pub struct StraightToPoolStrategyEncoder {}
|
|
||||||
|
|
||||||
impl StrategyEncoder for StraightToPoolStrategyEncoder {
|
|
||||||
fn encode_strategy(&self, solution: Solution) -> Result<Vec<u8>, Error> {
|
|
||||||
if solution.router_address.is_none() {
|
|
||||||
return Err(anyhow::anyhow!(
|
|
||||||
"Router address is required for straight to pool solutions"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let swap = solution.swaps.first().unwrap();
|
|
||||||
let registry = SWAP_ENCODER_REGISTRY.read().unwrap();
|
|
||||||
let swap_encoder = registry
|
|
||||||
.get_encoder(&swap.component.protocol_system)
|
|
||||||
.expect("Swap encoder not found");
|
|
||||||
let router_address = solution.router_address.unwrap();
|
|
||||||
|
|
||||||
let encoding_context = EncodingContext {
|
|
||||||
receiver: solution.receiver,
|
|
||||||
exact_out: solution.exact_out,
|
|
||||||
address_for_approvals: router_address,
|
|
||||||
};
|
|
||||||
let protocol_data = swap_encoder.encode_swap(swap.clone(), encoding_context)?;
|
|
||||||
// TODO: here we need to pass also the address of the executor to be used
|
|
||||||
Ok(protocol_data)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn action_type(&self, _exact_out: bool) -> ActionType {
|
|
||||||
unimplemented!();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn selector(&self, _exact_out: bool) -> &str {
|
|
||||||
unimplemented!();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
12
src/encoding/swap_encoder.rs
Normal file
12
src/encoding/swap_encoder.rs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
use anyhow::Error;
|
||||||
|
|
||||||
|
use crate::encoding::models::{EncodingContext, Swap};
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub trait SwapEncoder: Sync + Send {
|
||||||
|
fn new(executor_address: String) -> Self
|
||||||
|
where
|
||||||
|
Self: Sized;
|
||||||
|
fn encode_swap(&self, swap: Swap, encoding_context: EncodingContext) -> Result<Vec<u8>, Error>;
|
||||||
|
fn executor_address(&self) -> &str;
|
||||||
|
}
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"executors": {
|
|
||||||
"uniswap_v2": "0x5C2F5a71f67c01775180ADc06909288B4C329308",
|
|
||||||
"vm:balancer_v2": "0x543778987b293C7E8Cf0722BB2e935ba6f4068D4"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
use std::sync::RwLock;
|
|
||||||
|
|
||||||
use lazy_static::lazy_static;
|
|
||||||
|
|
||||||
use crate::encoding::swap_encoder::registry::{Config, SwapEncoderRegistry};
|
|
||||||
|
|
||||||
mod builder;
|
|
||||||
mod registry;
|
|
||||||
mod swap_struct_encoder;
|
|
||||||
|
|
||||||
lazy_static! {
|
|
||||||
pub static ref SWAP_ENCODER_REGISTRY: RwLock<SwapEncoderRegistry> = {
|
|
||||||
let config = Config::from_file("config.json").expect("Failed to load configuration file");
|
|
||||||
RwLock::new(SwapEncoderRegistry::new(config))
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user