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
25pub struct PendingUpdate {
31 pub label: String,
32 pub update: Update,
33}
34
35#[derive(Debug, Error)]
36pub enum PendingError {
37 #[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
48pub struct PendingBlockProcessor {
83 indexers: HashMap<String, Box<dyn TxDeltaIndexer>>,
84 decoder: Arc<TychoStreamDecoder<BlockHeader>>,
85 chain: Chain,
86 current_confirmed_block: u64,
88 confirmed_block_tx: watch::Sender<u64>,
90 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 pub fn subscribe_confirmed_block(&self) -> watch::Receiver<u64> {
111 self.confirmed_block_tx.subscribe()
112 }
113
114 pub fn current_confirmed_block(&self) -> u64 {
116 self.current_confirmed_block
117 }
118
119 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 pub async fn generate_pending_update(
152 &mut self,
153 pending: &PendingBlock,
154 label: String,
155 ) -> Result<PendingUpdate, PendingError> {
156 {
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
244fn 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 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 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 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 #[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 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 #[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}