Skip to main content

tycho_simulation/evm/
pending.rs

1use std::{
2    collections::{HashMap, HashSet},
3    sync::Arc,
4};
5
6use thiserror::Error;
7use tokio::sync::{mpsc::UnboundedReceiver, watch};
8use tycho_client::feed::{synchronizer::Snapshot, BlockHeader, FeedMessage};
9use tycho_common::{
10    models::{
11        blockchain::{Block, BlockAggregatedChanges, DCIUpdate, PendingBlock},
12        protocol::{ComponentBalance, ProtocolComponent, ProtocolComponentStateDelta},
13        token::Token,
14        Chain,
15    },
16    traits::TxDeltaIndexer,
17    Bytes,
18};
19
20use crate::{
21    evm::decoder::{StreamDecodeError, TychoStreamDecoder},
22    protocol::models::Update,
23};
24
25/// An ephemeral [`Update`] tagged with a caller-supplied label.
26///
27/// The label is an opaque string chosen by the caller to distinguish parallel bundle evaluations
28/// (e.g. bundle ID, strategy name). It is separate from `update.block_number`,
29/// which carries the target block the bundle was evaluated against.
30pub struct PendingUpdate {
31    pub label: String,
32    pub update: Update,
33}
34
35#[derive(Debug, Error)]
36pub enum PendingError {
37    /// Returned when the parent of `pending.block()` has not been confirmed. Use
38    /// [`subscribe_confirmed_block`](PendingBlockProcessor::subscribe_confirmed_block) to wait
39    /// for the right block before calling.
40    #[error("parent block {needed} not yet confirmed (current: {current})")]
41    ParentNotYetConfirmed { needed: u64, current: u64 },
42    #[error("decoder error: {0}")]
43    Decoder(#[from] StreamDecodeError),
44    #[error("indexer error for extractor '{extractor}': {message}")]
45    Indexer { extractor: String, message: String },
46}
47
48/// Wires one or more [`TxDeltaIndexer`]s to an existing [`TychoStreamDecoder`], enabling
49/// ephemeral simulation of candidate transaction bundles against the correct parent state
50/// for a specific target block.
51///
52/// # Block targeting
53///
54/// Call [`subscribe_confirmed_block`](Self::subscribe_confirmed_block) to obtain a
55/// [`watch::Receiver<u64>`] that fires on every confirmed block. Use it to wait for the
56/// right parent before submitting a bundle:
57///
58/// ```no_run
59/// # async fn example(
60/// #     mut processor: tycho_simulation::evm::pending::PendingBlockProcessor,
61/// #     pending_block: &tycho_common::models::blockchain::PendingBlock,
62/// # ) {
63/// processor
64///     .subscribe_confirmed_block()
65///     .wait_for(|&n| n >= pending_block.block().number - 1)
66///     .await
67///     .expect("stream closed");
68/// let update = processor
69///     .generate_pending_update(pending_block, "bundle-1".to_string())
70///     .await
71///     .expect("pending update failed");
72/// # }
73/// ```
74///
75/// # Concurrency
76///
77/// `PendingBlockProcessor` is intentionally **not** wrapped in a `Mutex` at construction
78/// time. The confirmed stream forwards blocks via an unbounded channel — it never blocks
79/// waiting for the consumer. Multiple callers can each hold a watch receiver and
80/// independently decide when to acquire whatever external lock they use around
81/// `generate_pending_update`.
82pub struct PendingBlockProcessor {
83    indexers: HashMap<String, Box<dyn TxDeltaIndexer>>,
84    decoder: Arc<TychoStreamDecoder<BlockHeader>>,
85    chain: Chain,
86    /// Block number of the most recently confirmed block applied to `indexers`.
87    current_confirmed_block: u64,
88    /// Notified on every `advance_inner` call; drives `subscribe_confirmed_block`.
89    confirmed_block_tx: watch::Sender<u64>,
90    /// Confirmed blocks forwarded by the stream pipeline.
91    block_rx: UnboundedReceiver<FeedMessage<BlockHeader>>,
92}
93
94impl PendingBlockProcessor {
95    pub(crate) fn new(
96        indexers: HashMap<String, Box<dyn TxDeltaIndexer>>,
97        decoder: Arc<TychoStreamDecoder<BlockHeader>>,
98        chain: Chain,
99        block_rx: UnboundedReceiver<FeedMessage<BlockHeader>>,
100    ) -> Self {
101        let (confirmed_block_tx, _) = watch::channel(0u64);
102        Self { indexers, decoder, chain, current_confirmed_block: 0, confirmed_block_tx, block_rx }
103    }
104
105    /// Returns a receiver that is notified with the latest confirmed block number every time
106    /// a new block is applied.
107    ///
108    /// Typical usage: `.wait_for(|&n| n >= target_block - 1).await` before calling
109    /// [`generate_pending_update`](Self::generate_pending_update).
110    pub fn subscribe_confirmed_block(&self) -> watch::Receiver<u64> {
111        self.confirmed_block_tx.subscribe()
112    }
113
114    /// Returns the block number of the last confirmed block applied to the indexers.
115    pub fn current_confirmed_block(&self) -> u64 {
116        self.current_confirmed_block
117    }
118
119    /// Advances each registered indexer by applying one confirmed block.
120    ///
121    /// Only needed when using the processor standalone (without
122    /// [`ProtocolStreamBuilder::build_with_pending`](crate::evm::stream::ProtocolStreamBuilder::build_with_pending)).
123    /// When using `build_with_pending`, confirmed blocks are forwarded automatically.
124    ///
125    /// The block built from a startup snapshot lists in `new_tokens` only the component tokens
126    /// the decoder has metadata for (see [`TychoStreamDecoder::set_tokens`]). An indexer must
127    /// handle a component whose tokens are missing.
128    pub async fn advance(&mut self, msg: &FeedMessage<BlockHeader>) -> Result<(), PendingError> {
129        let decoder = Arc::clone(&self.decoder);
130        let tokens = decoder.tokens().await;
131        self.advance_inner(msg, &tokens)
132    }
133
134    /// Simulates `pending` against the confirmed parent of `pending.block()`.
135    ///
136    /// Drains any confirmed blocks that have arrived since the last call, then immediately
137    /// checks whether `pending.block().number - 1` is available. If not, returns
138    /// [`PendingError::ParentNotYetConfirmed`] — **no blocking**. Use
139    /// [`subscribe_confirmed_block`](Self::subscribe_confirmed_block) to wait for the right
140    /// block before calling.
141    ///
142    /// Neither the indexers' internal state nor the decoder's confirmed pool states are
143    /// mutated. Calling this twice with the same arguments returns identical results.
144    ///
145    /// # Parameters
146    /// * `pending` — the in-flight block: the block being built, the candidate bundle in execution
147    ///   order (failed transactions are skipped), and post-execution account state for the accounts
148    ///   it touched. The returned deltas use this block's number and timestamp.
149    /// * `label` — opaque caller-supplied tag stamped onto the returned [`PendingUpdate`]. Use it
150    ///   to associate the result with a specific bundle or evaluation context.
151    pub async fn generate_pending_update(
152        &mut self,
153        pending: &PendingBlock,
154        label: String,
155    ) -> Result<PendingUpdate, PendingError> {
156        // Drain any confirmed blocks that have arrived since our last call. The lock is taken
157        // before the first `try_recv`, so a cancelled call never drops a received block.
158        {
159            let decoder = Arc::clone(&self.decoder);
160            let tokens = decoder.tokens().await;
161            while let Ok(msg) = self.block_rx.try_recv() {
162                self.advance_inner(&msg, &tokens)?;
163            }
164        }
165
166        let target_block = pending.block();
167        let parent = target_block.number.saturating_sub(1);
168        if self.current_confirmed_block < parent {
169            return Err(PendingError::ParentNotYetConfirmed {
170                needed: parent,
171                current: self.current_confirmed_block,
172            });
173        }
174        let target_header = BlockHeader::from(target_block);
175
176        let mut pending_deltas: HashMap<String, BlockAggregatedChanges> = HashMap::new();
177        for (protocol_system, indexer) in &self.indexers {
178            let changes = indexer.generate_deltas(pending);
179            pending_deltas.insert(protocol_system.clone(), changes);
180        }
181
182        let update = self
183            .decoder
184            .apply_deltas_ephemeral(&pending_deltas, target_header)
185            .await?;
186        Ok(PendingUpdate { label, update })
187    }
188
189    fn advance_inner(
190        &mut self,
191        msg: &FeedMessage<BlockHeader>,
192        tokens: &HashMap<Bytes, Token>,
193    ) -> Result<(), PendingError> {
194        let msg_block = msg
195            .state_msgs
196            .values()
197            .map(|s| s.header.number)
198            .max()
199            .unwrap_or(0);
200
201        for (extractor, state_msg) in &msg.state_msgs {
202            let Some(indexer) = self.indexers.get_mut(extractor) else {
203                continue;
204            };
205
206            if !state_msg.snapshots.states.is_empty() {
207                let block_changes = snapshot_to_block_changes(
208                    extractor,
209                    &state_msg.snapshots,
210                    &state_msg.header,
211                    self.chain,
212                    tokens,
213                )?;
214                indexer
215                    .apply_block(&block_changes)
216                    .map_err(|e| PendingError::Indexer {
217                        extractor: extractor.clone(),
218                        message: format!("{e:#}"),
219                    })?;
220            }
221
222            if let Some(deltas) = &state_msg.deltas {
223                indexer
224                    .apply_block(deltas)
225                    .map_err(|e| PendingError::Indexer {
226                        extractor: extractor.clone(),
227                        message: format!("{e:#}"),
228                    })?;
229            }
230        }
231
232        if msg_block > self.current_confirmed_block {
233            self.current_confirmed_block = msg_block;
234            #[expect(
235                clippy::let_underscore_must_use,
236                reason = "the confirmed-block receivers are optional; having none is normal"
237            )]
238            let _ = self.confirmed_block_tx.send(msg_block);
239        }
240        Ok(())
241    }
242}
243
244/// Converts a startup snapshot into a `BlockAggregatedChanges` suitable for
245/// [`TxDeltaIndexer::apply_block`].
246///
247/// Each component's traced entrypoints are folded into `dci_update`, so an indexer sees the
248/// contracts a component reads through DCI the same way it does on the delta path. `new_tokens`
249/// holds the components' tokens found in `tokens`, where an indexer also finds the tokens of a
250/// component that a block creates.
251fn snapshot_to_block_changes(
252    extractor: &str,
253    snapshot: &Snapshot,
254    header: &BlockHeader,
255    chain: Chain,
256    tokens: &HashMap<Bytes, Token>,
257) -> Result<BlockAggregatedChanges, PendingError> {
258    let ts = i64::try_from(header.timestamp)
259        .ok()
260        .and_then(|secs| chrono::DateTime::from_timestamp(secs, 0))
261        .ok_or_else(|| PendingError::Indexer {
262            extractor: extractor.to_string(),
263            message: format!(
264                "block {} has an invalid timestamp {}",
265                header.number, header.timestamp
266            ),
267        })?
268        .naive_utc();
269    let block = Block {
270        number: header.number,
271        chain,
272        hash: header.hash.clone(),
273        parent_hash: header.parent_hash.clone(),
274        ts,
275    };
276
277    let mut new_tokens: HashMap<Bytes, Token> = HashMap::new();
278    let mut new_protocol_components: HashMap<String, ProtocolComponent> = HashMap::new();
279    let mut state_deltas: HashMap<String, ProtocolComponentStateDelta> = HashMap::new();
280    let mut component_balances: HashMap<String, HashMap<Bytes, ComponentBalance>> = HashMap::new();
281    let mut dci_update = DCIUpdate::default();
282
283    for (id, comp_with_state) in &snapshot.states {
284        for address in &comp_with_state.component.tokens {
285            if let Some(token) = tokens.get(address) {
286                new_tokens.insert(address.clone(), token.clone());
287            }
288        }
289        new_protocol_components.insert(id.clone(), comp_with_state.component.clone());
290
291        for (entrypoint, trace) in &comp_with_state.entrypoints {
292            let ep_id = entrypoint
293                .entry_point
294                .external_id
295                .clone();
296            dci_update
297                .new_entrypoints
298                .entry(id.clone())
299                .or_default()
300                .insert(entrypoint.entry_point.clone());
301            dci_update
302                .new_entrypoint_params
303                .entry(ep_id.clone())
304                .or_default()
305                .insert((entrypoint.params.clone(), id.clone()));
306            dci_update
307                .trace_results
308                .entry(ep_id)
309                .or_default()
310                .merge(trace.clone());
311        }
312
313        state_deltas.insert(
314            id.clone(),
315            ProtocolComponentStateDelta {
316                component_id: id.clone(),
317                updated_attributes: comp_with_state.state.attributes.clone(),
318                deleted_attributes: HashSet::new(),
319                created_attributes: HashSet::new(),
320            },
321        );
322
323        let token_balances: HashMap<Bytes, ComponentBalance> = comp_with_state
324            .state
325            .balances
326            .iter()
327            .map(|(token, balance)| {
328                (
329                    token.clone(),
330                    ComponentBalance {
331                        token: token.clone(),
332                        balance: balance.clone(),
333                        balance_float: 0.0,
334                        modify_tx: Bytes::default(),
335                        component_id: id.clone(),
336                    },
337                )
338            })
339            .collect();
340        component_balances.insert(id.clone(), token_balances);
341    }
342
343    Ok(BlockAggregatedChanges {
344        extractor: extractor.to_string(),
345        chain,
346        block,
347        finalized_block_height: header.number,
348        new_tokens,
349        new_protocol_components,
350        state_deltas,
351        component_balances,
352        dci_update,
353        ..Default::default()
354    })
355}
356
357#[cfg(test)]
358mod tests {
359    use std::sync::Mutex;
360
361    use tycho_common::models::blockchain::{Block, PendingBlock};
362
363    use super::*;
364
365    /// Records the block it was handed, so a test can assert what the processor passed down.
366    struct RecordingIndexer {
367        seen: Arc<Mutex<Vec<Block>>>,
368    }
369
370    impl TxDeltaIndexer for RecordingIndexer {
371        fn apply_block(&mut self, _block: &BlockAggregatedChanges) -> anyhow::Result<()> {
372            Ok(())
373        }
374
375        fn generate_deltas(&self, pending: &PendingBlock) -> BlockAggregatedChanges {
376            self.seen
377                .lock()
378                .unwrap()
379                .push(pending.block().clone());
380            BlockAggregatedChanges::default()
381        }
382    }
383
384    fn target_block(number: u64, timestamp: i64) -> Block {
385        Block {
386            number,
387            chain: Chain::Ethereum,
388            hash: Bytes::from([1u8; 32]),
389            parent_hash: Bytes::from([2u8; 32]),
390            ts: chrono::DateTime::from_timestamp(timestamp, 0)
391                .unwrap()
392                .naive_utc(),
393        }
394    }
395
396    fn processor(seen: Arc<Mutex<Vec<Block>>>) -> PendingBlockProcessor {
397        let indexers: HashMap<String, Box<dyn TxDeltaIndexer>> =
398            HashMap::from([("fluid".to_string(), Box::new(RecordingIndexer { seen }) as _)]);
399        let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
400        PendingBlockProcessor::new(
401            indexers,
402            Arc::new(TychoStreamDecoder::<BlockHeader>::new(Chain::Ethereum)),
403            Chain::Ethereum,
404            rx,
405        )
406    }
407
408    #[test]
409    fn test_snapshot_entrypoints_land_in_dci_update() {
410        use tycho_client::feed::synchronizer::ComponentWithState;
411        use tycho_common::models::{
412            blockchain::{
413                EntryPoint, EntryPointWithTracingParams, RPCTracerParams, TracingParams,
414                TracingResult,
415            },
416            protocol::ProtocolComponentState,
417        };
418
419        let component_id = "0xpool".to_string();
420        let entry_point = EntryPoint {
421            external_id: "0xpool:get_virtual_price()".to_string(),
422            target: Bytes::from([0xaa; 20]),
423            signature: "get_virtual_price()".to_string(),
424        };
425        let params =
426            TracingParams::RPCTracer(RPCTracerParams::new(None, Bytes::from([0x12, 0x34])));
427        let oracle = Bytes::from([0xbb; 20]);
428        let trace = TracingResult::new(
429            HashSet::new(),
430            HashMap::from([(oracle.clone(), HashSet::from([Bytes::from([0u8; 32])]))]),
431        );
432        let snapshot = Snapshot {
433            states: HashMap::from([(
434                component_id.clone(),
435                ComponentWithState {
436                    state: ProtocolComponentState::new(
437                        &component_id,
438                        HashMap::new(),
439                        HashMap::new(),
440                    ),
441                    component: ProtocolComponent::default(),
442                    component_tvl: None,
443                    entrypoints: vec![(
444                        EntryPointWithTracingParams::new(entry_point.clone(), params.clone()),
445                        trace,
446                    )],
447                },
448            )]),
449            vm_storage: HashMap::new(),
450        };
451        let header = BlockHeader { number: 7, ..Default::default() };
452
453        let changes = snapshot_to_block_changes(
454            "vm:curve",
455            &snapshot,
456            &header,
457            Chain::Ethereum,
458            &HashMap::new(),
459        )
460        .unwrap();
461
462        let dci = &changes.dci_update;
463        assert_eq!(dci.new_entrypoints[&component_id], HashSet::from([entry_point.clone()]));
464        assert_eq!(
465            dci.new_entrypoint_params[&entry_point.external_id],
466            HashSet::from([(params, component_id)])
467        );
468        assert!(dci.trace_results[&entry_point.external_id]
469            .accessed_slots
470            .contains_key(&oracle));
471    }
472
473    #[tokio::test]
474    async fn test_indexer_receives_the_callers_target_block() {
475        let seen = Arc::new(Mutex::new(Vec::new()));
476        let mut pending_processor = processor(seen.clone());
477        // Parent is block 0, which the processor considers confirmed from the start.
478        let block = target_block(1, 1_759_842_947);
479
480        pending_processor
481            .generate_pending_update(
482                &PendingBlock::new(block.clone(), vec![], HashMap::new()),
483                "bundle-1".to_string(),
484            )
485            .await
486            .expect("pending update failed");
487
488        let seen = seen.lock().unwrap();
489        assert_eq!(
490            seen.as_slice(),
491            [block],
492            "The indexer must be handed the caller's block, not one derived from the parent."
493        );
494    }
495
496    /// A confirmed block carrying no snapshots or deltas: it only advances the tip.
497    fn confirmed_at(number: u64) -> FeedMessage<BlockHeader> {
498        FeedMessage {
499            state_msgs: HashMap::from([(
500                "fluid".to_string(),
501                tycho_client::feed::synchronizer::StateSyncMessage {
502                    header: BlockHeader { number, ..Default::default() },
503                    ..Default::default()
504                },
505            )]),
506            sync_states: HashMap::new(),
507        }
508    }
509
510    /// The header stamped onto every delta must come from the pending block too, not from the
511    /// confirmed tip. Priced against a tip of 5, a target of 3 tells the two apart.
512    #[tokio::test]
513    async fn test_stamped_header_comes_from_the_pending_block() {
514        let seen = Arc::new(Mutex::new(Vec::new()));
515        let mut pending_processor = processor(seen);
516        pending_processor
517            .advance(&confirmed_at(5))
518            .await
519            .expect("advance failed");
520
521        let update = pending_processor
522            .generate_pending_update(
523                &PendingBlock::new(target_block(3, 1_759_842_947), vec![], HashMap::new()),
524                "bundle-1".to_string(),
525            )
526            .await
527            .expect("pending update failed");
528
529        assert_eq!(
530            update.update.block_number, 3,
531            "The update must be stamped with the pending block, not the confirmed tip."
532        );
533    }
534
535    #[tokio::test]
536    async fn test_parent_guard_reads_the_pending_blocks_number() {
537        let seen = Arc::new(Mutex::new(Vec::new()));
538        let mut pending_processor = processor(seen.clone());
539        let block = target_block(23_526_115, 1_759_842_947);
540
541        let result = pending_processor
542            .generate_pending_update(
543                &PendingBlock::new(block, vec![], HashMap::new()),
544                "bundle-1".to_string(),
545            )
546            .await;
547
548        match result {
549            Err(PendingError::ParentNotYetConfirmed { needed, current }) => {
550                assert_eq!(needed, 23_526_114);
551                assert_eq!(current, 0);
552            }
553            Err(other) => panic!("expected ParentNotYetConfirmed, got {other:?}"),
554            Ok(_) => panic!("expected ParentNotYetConfirmed, got a successful update"),
555        }
556        assert!(
557            seen.lock().unwrap().is_empty(),
558            "No indexer should run when the parent is not confirmed."
559        );
560    }
561
562    /// Records the `new_tokens` of each block it applies.
563    struct TokenRecordingIndexer {
564        new_tokens: Arc<Mutex<Vec<HashMap<Bytes, Token>>>>,
565    }
566
567    impl TxDeltaIndexer for TokenRecordingIndexer {
568        fn apply_block(&mut self, block: &BlockAggregatedChanges) -> anyhow::Result<()> {
569            self.new_tokens
570                .lock()
571                .unwrap_or_else(std::sync::PoisonError::into_inner)
572                .push(block.new_tokens.clone());
573            Ok(())
574        }
575
576        fn generate_deltas(&self, _pending: &PendingBlock) -> BlockAggregatedChanges {
577            BlockAggregatedChanges::default()
578        }
579    }
580
581    /// An indexer that applies a startup snapshot receives, in `new_tokens`, every component
582    /// token the decoder knows, as it would from a block that creates the components.
583    #[tokio::test]
584    async fn test_snapshot_known_tokens_land_in_new_tokens() {
585        use tycho_client::feed::synchronizer::{ComponentWithState, StateSyncMessage};
586        use tycho_common::models::protocol::ProtocolComponentState;
587
588        let known = Bytes::from([0xaa; 20]);
589        let unknown = Bytes::from([0xbb; 20]);
590        let token = Token::new(&known, "KNOWN", 6, 0, &[], Chain::Ethereum, 100);
591        let decoder = TychoStreamDecoder::<BlockHeader>::new(Chain::Ethereum);
592        decoder
593            .set_tokens(HashMap::from([(known.clone(), token.clone())]))
594            .await;
595        let new_tokens = Arc::new(Mutex::new(Vec::new()));
596        let indexers: HashMap<String, Box<dyn TxDeltaIndexer>> = HashMap::from([(
597            "vm:curve".to_string(),
598            Box::new(TokenRecordingIndexer { new_tokens: new_tokens.clone() }) as _,
599        )]);
600        let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
601        let mut pending_processor =
602            PendingBlockProcessor::new(indexers, Arc::new(decoder), Chain::Ethereum, rx);
603        let id = "0xpool".to_string();
604        let snapshot = Snapshot {
605            states: HashMap::from([(
606                id.clone(),
607                ComponentWithState {
608                    state: ProtocolComponentState::new(&id, HashMap::new(), HashMap::new()),
609                    component: ProtocolComponent {
610                        id: id.clone(),
611                        tokens: vec![known.clone(), unknown],
612                        ..Default::default()
613                    },
614                    component_tvl: None,
615                    entrypoints: vec![],
616                },
617            )]),
618            vm_storage: HashMap::new(),
619        };
620        let msg = FeedMessage {
621            state_msgs: HashMap::from([(
622                "vm:curve".to_string(),
623                StateSyncMessage {
624                    header: BlockHeader { number: 7, ..Default::default() },
625                    snapshots: snapshot,
626                    ..Default::default()
627                },
628            )]),
629            sync_states: HashMap::new(),
630        };
631
632        pending_processor
633            .advance(&msg)
634            .await
635            .expect("advance failed");
636
637        assert_eq!(new_tokens.lock().unwrap().as_slice(), [HashMap::from([(known, token)])]);
638    }
639}