kabu_core_components/
builder.rs

1use crate::Component;
2use crate::traits::{
3    BroadcasterBuilder, EstimatorBuilder, ExecutorBuilder, HealthMonitorBuilder, MarketBuilder, NetworkBuilder, PoolBuilder, SignerBuilder,
4    StrategyBuilder,
5};
6use eyre::Result;
7use reth_tasks::TaskExecutor;
8use std::marker::PhantomData;
9use std::sync::Arc;
10use tokio::sync::{RwLock, broadcast};
11
12// Import MEV-specific types for channel communication
13use kabu_evm_db::KabuDB;
14use kabu_types_entities::{AccountNonceAndBalanceState, TxSigners};
15use kabu_types_events::{MarketEvents, MempoolEvents, MessageHealthEvent, MessageSwapCompose, MessageTxCompose};
16use reth_ethereum_primitives::EthPrimitives;
17
18/// MEV Component Communication Channels
19/// This struct holds all the broadcast channels used for inter-component communication
20#[derive(Clone)]
21pub struct MevComponentChannels<DB = KabuDB> {
22    /// Channel for swap composition messages (Strategy -> Router -> Signer)
23    pub swap_compose: broadcast::Sender<MessageSwapCompose<DB, EthPrimitives>>,
24    /// Channel for transaction composition messages (Signer -> Broadcaster)
25    pub tx_compose: broadcast::Sender<MessageTxCompose<EthPrimitives>>,
26    /// Channel for market events (Market -> Strategy/HealthMonitor)
27    pub market_events: broadcast::Sender<MarketEvents>,
28    /// Channel for mempool events (Pool -> Strategy)
29    pub mempool_events: broadcast::Sender<MempoolEvents>,
30    /// Channel for health monitoring events (HealthMonitor -> Market/Strategy)
31    pub health_events: broadcast::Sender<MessageHealthEvent>,
32    /// Shared signers state (used by Router and Signer)
33    pub signers: Arc<RwLock<TxSigners<EthPrimitives>>>,
34    /// Account nonce and balance tracking (used by Signer and Broadcaster)
35    pub account_state: Arc<RwLock<AccountNonceAndBalanceState>>,
36}
37
38impl<DB: Clone> Default for MevComponentChannels<DB> {
39    fn default() -> Self {
40        let (swap_compose, _) = broadcast::channel(1000);
41        let (tx_compose, _) = broadcast::channel(1000);
42        let (market_events, _) = broadcast::channel(1000);
43        let (mempool_events, _) = broadcast::channel(1000);
44        let (health_events, _) = broadcast::channel(1000);
45
46        Self {
47            swap_compose,
48            tx_compose,
49            market_events,
50            mempool_events,
51            health_events,
52            signers: Arc::new(RwLock::new(TxSigners::<EthPrimitives>::new())),
53            account_state: Arc::new(RwLock::new(AccountNonceAndBalanceState::new())),
54        }
55    }
56}
57
58/// Context provided to component builders
59#[derive(Clone)]
60pub struct BuilderContext<State, DB = KabuDB> {
61    pub state: State,
62    pub channels: MevComponentChannels<DB>,
63}
64
65impl<State, DB: Clone> BuilderContext<State, DB> {
66    pub fn new(state: State) -> Self {
67        Self { state, channels: MevComponentChannels::default() }
68    }
69
70    pub fn with_channels(state: State, channels: MevComponentChannels<DB>) -> Self {
71        Self { state, channels }
72    }
73}
74
75/// Generic components builder
76pub struct ComponentsBuilder<State, Pool = (), Network = (), Executor = (), Strategy = ()> {
77    pool: Pool,
78    network: Network,
79    executor: Executor,
80    strategy: Strategy,
81    _state: PhantomData<State>,
82}
83
84impl<State> Default for ComponentsBuilder<State> {
85    fn default() -> Self {
86        Self { pool: (), network: (), executor: (), strategy: (), _state: PhantomData }
87    }
88}
89
90impl<State> ComponentsBuilder<State> {
91    pub fn new() -> Self {
92        Self::default()
93    }
94}
95
96impl<State, Pool, Network, Executor, Strategy> ComponentsBuilder<State, Pool, Network, Executor, Strategy> {
97    /// Set the pool builder
98    pub fn pool<P>(self, pool: P) -> ComponentsBuilder<State, P, Network, Executor, Strategy> {
99        ComponentsBuilder { pool, network: self.network, executor: self.executor, strategy: self.strategy, _state: PhantomData }
100    }
101
102    /// Set the network builder
103    pub fn network<N>(self, network: N) -> ComponentsBuilder<State, Pool, N, Executor, Strategy> {
104        ComponentsBuilder { pool: self.pool, network, executor: self.executor, strategy: self.strategy, _state: PhantomData }
105    }
106
107    /// Set the executor builder
108    pub fn executor<E>(self, executor: E) -> ComponentsBuilder<State, Pool, Network, E, Strategy> {
109        ComponentsBuilder { pool: self.pool, network: self.network, executor, strategy: self.strategy, _state: PhantomData }
110    }
111
112    /// Set the strategy builder
113    pub fn strategy<S>(self, strategy: S) -> ComponentsBuilder<State, Pool, Network, Executor, S> {
114        ComponentsBuilder { pool: self.pool, network: self.network, executor: self.executor, strategy, _state: PhantomData }
115    }
116
117    /// Map the pool builder
118    pub fn map_pool<F, P>(self, f: F) -> ComponentsBuilder<State, P, Network, Executor, Strategy>
119    where
120        F: FnOnce(Pool) -> P,
121    {
122        ComponentsBuilder {
123            pool: f(self.pool),
124            network: self.network,
125            executor: self.executor,
126            strategy: self.strategy,
127            _state: PhantomData,
128        }
129    }
130
131    /// Map the network builder
132    pub fn map_network<F, N>(self, f: F) -> ComponentsBuilder<State, Pool, N, Executor, Strategy>
133    where
134        F: FnOnce(Network) -> N,
135    {
136        ComponentsBuilder {
137            pool: self.pool,
138            network: f(self.network),
139            executor: self.executor,
140            strategy: self.strategy,
141            _state: PhantomData,
142        }
143    }
144
145    /// Map the executor builder
146    pub fn map_executor<F, E>(self, f: F) -> ComponentsBuilder<State, Pool, Network, E, Strategy>
147    where
148        F: FnOnce(Executor) -> E,
149    {
150        ComponentsBuilder {
151            pool: self.pool,
152            network: self.network,
153            executor: f(self.executor),
154            strategy: self.strategy,
155            _state: PhantomData,
156        }
157    }
158
159    /// Map the strategy builder
160    pub fn map_strategy<F, S>(self, f: F) -> ComponentsBuilder<State, Pool, Network, Executor, S>
161    where
162        F: FnOnce(Strategy) -> S,
163    {
164        ComponentsBuilder {
165            pool: self.pool,
166            network: self.network,
167            executor: self.executor,
168            strategy: f(self.strategy),
169            _state: PhantomData,
170        }
171    }
172}
173
174impl<State, Pool, Network, Executor, Strategy> ComponentsBuilder<State, Pool, Network, Executor, Strategy>
175where
176    State: Clone + Send + Sync + 'static,
177    Pool: PoolBuilder<State>,
178    Network: NetworkBuilder<State>,
179    Executor: ExecutorBuilder<State>,
180    Strategy: StrategyBuilder<State>,
181{
182    /// Build all components and spawn them
183    pub async fn build_and_spawn(self, ctx: BuilderContext<State>, executor: TaskExecutor) -> Result<()> {
184        // Build components in dependency order
185        let pool = self.pool.build_pool(&ctx).await?;
186        let network = self.network.build_network(&ctx).await?;
187        let exec_comp = self.executor.build_executor(&ctx).await?;
188        let strategy = self.strategy.build_strategy(&ctx).await?;
189
190        // Spawn components
191        pool.spawn(executor.clone())?;
192        network.spawn(executor.clone())?;
193        exec_comp.spawn(executor.clone())?;
194        strategy.spawn(executor)?;
195
196        Ok(())
197    }
198
199    /// Build all components without spawning
200    pub async fn build(
201        self,
202        ctx: BuilderContext<State>,
203    ) -> Result<Components<Pool::Pool, Network::Network, Executor::Executor, Strategy::Strategy>> {
204        let pool = self.pool.build_pool(&ctx).await?;
205        let network = self.network.build_network(&ctx).await?;
206        let executor = self.executor.build_executor(&ctx).await?;
207        let strategy = self.strategy.build_strategy(&ctx).await?;
208
209        Ok(Components::new(pool, network, executor, strategy))
210    }
211}
212
213/// Components bundle that holds all built components
214pub struct Components<Pool, Network, Executor, Strategy> {
215    pub pool: Pool,
216    pub network: Network,
217    pub executor: Executor,
218    pub strategy: Strategy,
219}
220
221impl<Pool, Network, Executor, Strategy> Components<Pool, Network, Executor, Strategy> {
222    pub fn new(pool: Pool, network: Network, executor: Executor, strategy: Strategy) -> Self {
223        Self { pool, network, executor, strategy }
224    }
225}
226
227impl<Pool, Network, Executor, Strategy> Components<Pool, Network, Executor, Strategy>
228where
229    Pool: Component,
230    Network: Component,
231    Executor: Component,
232    Strategy: Component,
233{
234    /// Spawn all components
235    pub fn spawn_all(self, executor: TaskExecutor) -> Result<()> {
236        self.pool.spawn(executor.clone())?;
237        self.network.spawn(executor.clone())?;
238        self.executor.spawn(executor.clone())?;
239        self.strategy.spawn(executor)?;
240        Ok(())
241    }
242}
243
244/// Comprehensive MEV components builder for full MEV bot functionality
245pub struct MevComponentsBuilder<
246    State,
247    Pool = (),
248    Network = (),
249    Executor = (),
250    Strategy = (),
251    Signer = (),
252    Market = (),
253    Broadcaster = (),
254    Estimator = (),
255    HealthMonitor = (),
256> {
257    pool: Pool,
258    network: Network,
259    executor: Executor,
260    strategy: Strategy,
261    signer: Signer,
262    market: Market,
263    broadcaster: Broadcaster,
264    estimator: Estimator,
265    health_monitor: HealthMonitor,
266    _state: PhantomData<State>,
267}
268
269impl<State> Default for MevComponentsBuilder<State> {
270    fn default() -> Self {
271        Self {
272            pool: (),
273            network: (),
274            executor: (),
275            strategy: (),
276            signer: (),
277            market: (),
278            broadcaster: (),
279            estimator: (),
280            health_monitor: (),
281            _state: PhantomData,
282        }
283    }
284}
285
286impl<State> MevComponentsBuilder<State> {
287    pub fn new() -> Self {
288        Self::default()
289    }
290}
291
292impl<State, Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor>
293    MevComponentsBuilder<State, Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor>
294{
295    /// Set the pool builder
296    pub fn pool<P>(
297        self,
298        pool: P,
299    ) -> MevComponentsBuilder<State, P, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor> {
300        MevComponentsBuilder {
301            pool,
302            network: self.network,
303            executor: self.executor,
304            strategy: self.strategy,
305            signer: self.signer,
306            market: self.market,
307            broadcaster: self.broadcaster,
308            estimator: self.estimator,
309            health_monitor: self.health_monitor,
310            _state: PhantomData,
311        }
312    }
313
314    /// Set the network builder
315    pub fn network<N>(
316        self,
317        network: N,
318    ) -> MevComponentsBuilder<State, Pool, N, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor> {
319        MevComponentsBuilder {
320            pool: self.pool,
321            network,
322            executor: self.executor,
323            strategy: self.strategy,
324            signer: self.signer,
325            market: self.market,
326            broadcaster: self.broadcaster,
327            estimator: self.estimator,
328            health_monitor: self.health_monitor,
329            _state: PhantomData,
330        }
331    }
332
333    /// Set the executor builder
334    pub fn executor<E>(
335        self,
336        executor: E,
337    ) -> MevComponentsBuilder<State, Pool, Network, E, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor> {
338        MevComponentsBuilder {
339            pool: self.pool,
340            network: self.network,
341            executor,
342            strategy: self.strategy,
343            signer: self.signer,
344            market: self.market,
345            broadcaster: self.broadcaster,
346            estimator: self.estimator,
347            health_monitor: self.health_monitor,
348            _state: PhantomData,
349        }
350    }
351
352    /// Set the strategy builder
353    pub fn strategy<S>(
354        self,
355        strategy: S,
356    ) -> MevComponentsBuilder<State, Pool, Network, Executor, S, Signer, Market, Broadcaster, Estimator, HealthMonitor> {
357        MevComponentsBuilder {
358            pool: self.pool,
359            network: self.network,
360            executor: self.executor,
361            strategy,
362            signer: self.signer,
363            market: self.market,
364            broadcaster: self.broadcaster,
365            estimator: self.estimator,
366            health_monitor: self.health_monitor,
367            _state: PhantomData,
368        }
369    }
370
371    /// Set the signer builder
372    pub fn signer<SI>(
373        self,
374        signer: SI,
375    ) -> MevComponentsBuilder<State, Pool, Network, Executor, Strategy, SI, Market, Broadcaster, Estimator, HealthMonitor> {
376        MevComponentsBuilder {
377            pool: self.pool,
378            network: self.network,
379            executor: self.executor,
380            strategy: self.strategy,
381            signer,
382            market: self.market,
383            broadcaster: self.broadcaster,
384            estimator: self.estimator,
385            health_monitor: self.health_monitor,
386            _state: PhantomData,
387        }
388    }
389
390    /// Set the market builder
391    pub fn market<M>(
392        self,
393        market: M,
394    ) -> MevComponentsBuilder<State, Pool, Network, Executor, Strategy, Signer, M, Broadcaster, Estimator, HealthMonitor> {
395        MevComponentsBuilder {
396            pool: self.pool,
397            network: self.network,
398            executor: self.executor,
399            strategy: self.strategy,
400            signer: self.signer,
401            market,
402            broadcaster: self.broadcaster,
403            estimator: self.estimator,
404            health_monitor: self.health_monitor,
405            _state: PhantomData,
406        }
407    }
408
409    /// Set the broadcaster builder
410    pub fn broadcaster<B>(
411        self,
412        broadcaster: B,
413    ) -> MevComponentsBuilder<State, Pool, Network, Executor, Strategy, Signer, Market, B, Estimator, HealthMonitor> {
414        MevComponentsBuilder {
415            pool: self.pool,
416            network: self.network,
417            executor: self.executor,
418            strategy: self.strategy,
419            signer: self.signer,
420            market: self.market,
421            broadcaster,
422            estimator: self.estimator,
423            health_monitor: self.health_monitor,
424            _state: PhantomData,
425        }
426    }
427
428    /// Set the estimator builder
429    pub fn estimator<ES>(
430        self,
431        estimator: ES,
432    ) -> MevComponentsBuilder<State, Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, ES, HealthMonitor> {
433        MevComponentsBuilder {
434            pool: self.pool,
435            network: self.network,
436            executor: self.executor,
437            strategy: self.strategy,
438            signer: self.signer,
439            market: self.market,
440            broadcaster: self.broadcaster,
441            estimator,
442            health_monitor: self.health_monitor,
443            _state: PhantomData,
444        }
445    }
446
447    /// Set the health monitor builder
448    pub fn health_monitor<H>(
449        self,
450        health_monitor: H,
451    ) -> MevComponentsBuilder<State, Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, H> {
452        MevComponentsBuilder {
453            pool: self.pool,
454            network: self.network,
455            executor: self.executor,
456            strategy: self.strategy,
457            signer: self.signer,
458            market: self.market,
459            broadcaster: self.broadcaster,
460            estimator: self.estimator,
461            health_monitor,
462            _state: PhantomData,
463        }
464    }
465}
466
467impl<State, Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor>
468    MevComponentsBuilder<State, Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor>
469where
470    State: Clone + Send + Sync + 'static,
471    Pool: PoolBuilder<State>,
472    Network: NetworkBuilder<State>,
473    Executor: ExecutorBuilder<State>,
474    Strategy: StrategyBuilder<State>,
475    Signer: SignerBuilder<State>,
476    Market: MarketBuilder<State>,
477    Broadcaster: BroadcasterBuilder<State>,
478    Estimator: EstimatorBuilder<State>,
479    HealthMonitor: HealthMonitorBuilder<State>,
480{
481    /// Build all MEV components and spawn them
482    pub async fn build_and_spawn(self, ctx: BuilderContext<State>, executor: TaskExecutor) -> Result<()> {
483        // Build components in dependency order
484        let pool = self.pool.build_pool(&ctx).await?;
485        let network = self.network.build_network(&ctx).await?;
486        let exec_comp = self.executor.build_executor(&ctx).await?;
487        let strategy = self.strategy.build_strategy(&ctx).await?;
488        let signer = self.signer.build_signer(&ctx).await?;
489        let market = self.market.build_market(&ctx).await?;
490        let broadcaster = self.broadcaster.build_broadcaster(&ctx).await?;
491        let estimator = self.estimator.build_estimator(&ctx).await?;
492        let health_monitor = self.health_monitor.build_health_monitor(&ctx).await?;
493
494        // Spawn components in dependency order
495        market.spawn(executor.clone())?; // Core market data first
496        pool.spawn(executor.clone())?; // Pool/mempool access
497        network.spawn(executor.clone())?; // Network connectivity
498        estimator.spawn(executor.clone())?; // Gas/profit estimation
499        strategy.spawn(executor.clone())?; // MEV strategy detection
500        exec_comp.spawn(executor.clone())?; // Transaction routing/encoding
501        signer.spawn(executor.clone())?; // Transaction signing
502        broadcaster.spawn(executor.clone())?; // Transaction broadcasting
503        health_monitor.spawn(executor)?; // Health monitoring last
504
505        Ok(())
506    }
507
508    /// Build all MEV components without spawning (Reth-style component wiring)
509    pub async fn build(
510        self,
511        ctx: BuilderContext<State>,
512    ) -> Result<
513        MevComponents<
514            Pool::Pool,
515            Network::Network,
516            Executor::Executor,
517            Strategy::Strategy,
518            Signer::Signer,
519            Market::Market,
520            Broadcaster::Broadcaster,
521            Estimator::Estimator,
522            HealthMonitor::HealthMonitor,
523        >,
524    > {
525        let Self {
526            pool: pool_builder,
527            network: network_builder,
528            executor: executor_builder,
529            strategy: strategy_builder,
530            signer: signer_builder,
531            market: market_builder,
532            broadcaster: broadcaster_builder,
533            estimator: estimator_builder,
534            health_monitor: health_monitor_builder,
535            _state,
536        } = self;
537
538        // Build components in dependency order:
539        // 1. First build standalone components (market, pools)
540        // 2. Then build components that depend on shared state (signers, account state)
541        // 3. Finally build service components that wire everything together
542
543        // Step 1: Build market and shared state components
544        let market = market_builder.build_market(&ctx).await?;
545
546        // Step 2: Build pool component (needs market state access)
547        let pool = pool_builder.build_pool(&ctx).await?;
548
549        // Step 3: Build network component (may need pool for mempool integration)
550        let network = network_builder.build_network(&ctx).await?;
551
552        // Step 4: Build estimation component (needs market access)
553        let estimator = estimator_builder.build_estimator(&ctx).await?;
554
555        // Step 5: Build strategy component (needs market, mempool channels)
556        let strategy = strategy_builder.build_strategy(&ctx).await?;
557
558        // Step 6: Build executor/router component (needs strategy output, signer access)
559        let executor = executor_builder.build_executor(&ctx).await?;
560
561        // Step 7: Build signer component (needs executor output)
562        let signer = signer_builder.build_signer(&ctx).await?;
563
564        // Step 8: Build broadcaster component (needs signed transactions)
565        let broadcaster = broadcaster_builder.build_broadcaster(&ctx).await?;
566
567        // Step 9: Build health monitor (observes all other components)
568        let health_monitor = health_monitor_builder.build_health_monitor(&ctx).await?;
569
570        Ok(MevComponents { pool, network, executor, strategy, signer, market, broadcaster, estimator, health_monitor })
571    }
572}
573
574/// MEV components bundle that holds all built MEV components
575pub struct MevComponents<Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor> {
576    pub pool: Pool,
577    pub network: Network,
578    pub executor: Executor,
579    pub strategy: Strategy,
580    pub signer: Signer,
581    pub market: Market,
582    pub broadcaster: Broadcaster,
583    pub estimator: Estimator,
584    pub health_monitor: HealthMonitor,
585}
586
587impl<Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor>
588    MevComponents<Pool, Network, Executor, Strategy, Signer, Market, Broadcaster, Estimator, HealthMonitor>
589where
590    Pool: Component,
591    Network: Component,
592    Executor: Component,
593    Strategy: Component,
594    Signer: Component,
595    Market: Component,
596    Broadcaster: Component,
597    Estimator: Component,
598    HealthMonitor: Component,
599{
600    /// Spawn all MEV components
601    pub fn spawn_all(self, executor: TaskExecutor) -> Result<()> {
602        self.market.spawn(executor.clone())?;
603        self.pool.spawn(executor.clone())?;
604        self.network.spawn(executor.clone())?;
605        self.estimator.spawn(executor.clone())?;
606        self.strategy.spawn(executor.clone())?;
607        self.executor.spawn(executor.clone())?;
608        self.signer.spawn(executor.clone())?;
609        self.broadcaster.spawn(executor.clone())?;
610        self.health_monitor.spawn(executor)?;
611        Ok(())
612    }
613}