Skip to main content

tycho_execution/encoding/evm/
encoder_builders.rs

1use tycho_common::{models::Chain, Bytes};
2
3use crate::encoding::{
4    errors::EncodingError,
5    evm::{
6        constants::get_router_address, swap_encoder::swap_encoder_registry::SwapEncoderRegistry,
7        tycho_encoders::TychoRouterEncoder,
8    },
9    tycho_encoder::TychoEncoder,
10};
11
12/// Builder pattern for constructing a `TychoRouterEncoder` with customizable options.
13///
14/// This struct allows setting a chain and strategy encoder before building the final encoder.
15pub struct TychoRouterEncoderBuilder {
16    chain: Option<Chain>,
17    swap_encoder_registry: Option<SwapEncoderRegistry>,
18    router_address: Option<Bytes>,
19}
20
21impl Default for TychoRouterEncoderBuilder {
22    fn default() -> Self {
23        Self::new()
24    }
25}
26
27impl TychoRouterEncoderBuilder {
28    pub fn new() -> Self {
29        TychoRouterEncoderBuilder { chain: None, swap_encoder_registry: None, router_address: None }
30    }
31    pub fn chain(mut self, chain: Chain) -> Self {
32        self.chain = Some(chain);
33        self
34    }
35
36    pub fn swap_encoder_registry(mut self, swap_encoder_registry: SwapEncoderRegistry) -> Self {
37        self.swap_encoder_registry = Some(swap_encoder_registry);
38        self
39    }
40
41    /// Sets the `router_address` manually.
42    /// If it's not set, the default router address will be used (config/router_addresses.json)
43    pub fn router_address(mut self, router_address: Bytes) -> Self {
44        self.router_address = Some(router_address);
45        self
46    }
47
48    /// Builds the `TychoRouterEncoder` instance using the configured chain.
49    /// Returns an error if either the chain has not been set.
50    pub fn build(self) -> Result<Box<dyn TychoEncoder>, EncodingError> {
51        if let (Some(chain), Some(swap_encoder_registry)) = (self.chain, self.swap_encoder_registry)
52        {
53            let tycho_router_address = if let Some(address) = self.router_address {
54                address
55            } else {
56                get_router_address(&chain)?.clone()
57            };
58
59            Ok(Box::new(TychoRouterEncoder::new(swap_encoder_registry, tycho_router_address)?))
60        } else {
61            Err(EncodingError::FatalError(
62                "Please set the chain and swap encoder registry before building the encoder"
63                    .to_string(),
64            ))
65        }
66    }
67}