Skip to main content

tycho_common/models/
blockchain.rs

1use std::collections::{hash_map::Entry, BTreeMap, HashMap, HashSet};
2
3use chrono::NaiveDateTime;
4use deepsize::DeepSizeOf;
5use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
6use tracing::warn;
7
8use crate::{
9    dto,
10    models::{
11        contract::{AccountBalance, AccountDelta, AccountToContractChanges},
12        protocol::{ComponentBalance, ProtocolComponent, ProtocolComponentStateDelta},
13        token::Token,
14        Address, Balance, BlockHash, Chain, Code, ComponentId, EntryPointId, MergeError, StoreKey,
15        StoreVal,
16    },
17    Bytes,
18};
19
20#[derive(Clone, Default, PartialEq, Serialize, Deserialize, Debug)]
21pub struct Block {
22    pub number: u64,
23    pub chain: Chain,
24    pub hash: Bytes,
25    pub parent_hash: Bytes,
26    pub ts: NaiveDateTime,
27}
28
29impl Block {
30    pub fn new(
31        number: u64,
32        chain: Chain,
33        hash: Bytes,
34        parent_hash: Bytes,
35        ts: NaiveDateTime,
36    ) -> Self {
37        Block { hash, parent_hash, number, chain, ts }
38    }
39}
40
41// Manual impl as `NaiveDateTime` structure referenced in `ts` does not implement DeepSizeOf
42impl DeepSizeOf for Block {
43    fn deep_size_of_children(&self, context: &mut deepsize::Context) -> usize {
44        self.chain
45            .deep_size_of_children(context) +
46            self.hash.deep_size_of_children(context) +
47            self.parent_hash
48                .deep_size_of_children(context)
49    }
50}
51
52#[derive(Clone, Default, PartialEq, Debug, Eq, Hash, DeepSizeOf)]
53pub struct Transaction {
54    pub hash: Bytes,
55    pub block_hash: Bytes,
56    pub from: Bytes,
57    pub to: Option<Bytes>,
58    pub index: u64,
59}
60
61impl Transaction {
62    pub fn new(hash: Bytes, block_hash: Bytes, from: Bytes, to: Option<Bytes>, index: u64) -> Self {
63        Transaction { hash, block_hash, from, to, index }
64    }
65}
66
67/// Raw EVM log emitted by a contract during transaction execution.
68///
69/// Used as the primary input to [`TxDeltaIndexer`] implementations.
70///
71/// [`TxDeltaIndexer`]: crate::traits::TxDeltaIndexer
72#[derive(Debug, Clone)]
73pub struct LogInput {
74    address: Bytes,
75    topics: Vec<Bytes>,
76    data: Bytes,
77    log_index: u32,
78}
79
80impl LogInput {
81    pub fn new(address: Bytes, topics: Vec<Bytes>, data: Bytes, log_index: u32) -> Self {
82        Self { address, topics, data, log_index }
83    }
84
85    pub fn address(&self) -> &Bytes {
86        &self.address
87    }
88
89    pub fn topics(&self) -> &[Bytes] {
90        &self.topics
91    }
92
93    pub fn data(&self) -> &Bytes {
94        &self.data
95    }
96
97    pub fn log_index(&self) -> u32 {
98        self.log_index
99    }
100}
101
102/// Raw EVM transaction with its associated logs.
103///
104/// The `succeeded` flag allows callers to pass all transactions in a block and
105/// have the processor skip reverted ones, avoiding a separate pre-filter.
106#[derive(Debug, Clone)]
107pub struct TxInput {
108    hash: Bytes,
109    from: Bytes,
110    to: Bytes,
111    index: u64,
112    logs: Vec<LogInput>,
113    succeeded: bool,
114}
115
116impl TxInput {
117    pub fn new(
118        hash: Bytes,
119        from: Bytes,
120        to: Bytes,
121        index: u64,
122        logs: Vec<LogInput>,
123        succeeded: bool,
124    ) -> Self {
125        Self { hash, from, to, index, logs, succeeded }
126    }
127
128    pub fn hash(&self) -> &Bytes {
129        &self.hash
130    }
131
132    pub fn from(&self) -> &Bytes {
133        &self.from
134    }
135
136    pub fn to(&self) -> &Bytes {
137        &self.to
138    }
139
140    pub fn index(&self) -> u64 {
141        self.index
142    }
143
144    pub fn logs(&self) -> &[LogInput] {
145        &self.logs
146    }
147
148    pub fn succeeded(&self) -> bool {
149        self.succeeded
150    }
151}
152
153/// A block under construction with ordered transactions and post-execution account state.
154#[derive(Debug, Clone, Default)]
155pub struct PendingBlock {
156    block: Block,
157    txs: Vec<TxInput>,
158    accounts: HashMap<Address, AccountDelta>,
159}
160
161impl PendingBlock {
162    pub fn new(block: Block, txs: Vec<TxInput>, accounts: HashMap<Address, AccountDelta>) -> Self {
163        Self { block, txs, accounts }
164    }
165
166    /// The block being assembled; its number and timestamp are the transaction execution clock.
167    pub fn block(&self) -> &Block {
168        &self.block
169    }
170
171    /// Transactions in execution order.
172    pub fn txs(&self) -> &[TxInput] {
173        &self.txs
174    }
175
176    /// Post-execution state for accounts touched by the transactions.
177    /// May be empty when no consuming indexer needs account state.
178    pub fn accounts(&self) -> &HashMap<Address, AccountDelta> {
179        &self.accounts
180    }
181}
182
183pub struct BlockTransactionDeltas<T> {
184    pub extractor: String,
185    pub chain: Chain,
186    pub block: Block,
187    pub revert: bool,
188    pub deltas: Vec<TransactionDeltaGroup<T>>,
189}
190
191#[expect(
192    dead_code,
193    reason = "named by the public BlockTransactionDeltas::deltas field but never constructed; removing it is a breaking change"
194)]
195pub struct TransactionDeltaGroup<T> {
196    changes: T,
197    protocol_component: HashMap<String, ProtocolComponent>,
198    component_balances: HashMap<String, ComponentBalance>,
199    component_tvl: HashMap<String, f64>,
200    tx: Transaction,
201}
202
203#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, DeepSizeOf)]
204pub struct BlockAggregatedChanges {
205    pub extractor: String,
206    pub chain: Chain,
207    pub block: Block,
208    pub finalized_block_height: u64,
209    pub db_committed_block_height: Option<u64>,
210    pub revert: bool,
211    pub state_deltas: HashMap<String, ProtocolComponentStateDelta>,
212    pub account_deltas: HashMap<Bytes, AccountDelta>,
213    pub new_tokens: HashMap<Address, Token>,
214    pub new_protocol_components: HashMap<String, ProtocolComponent>,
215    pub deleted_protocol_components: HashMap<String, ProtocolComponent>,
216    pub component_balances: HashMap<ComponentId, HashMap<Bytes, ComponentBalance>>,
217    pub account_balances: HashMap<Address, HashMap<Address, AccountBalance>>,
218    pub component_tvl: HashMap<String, f64>,
219    pub dci_update: DCIUpdate,
220    /// The index of the partial block. None if it's a full block.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub partial_block_index: Option<u32>,
223    /// Components paused in this block. Clients should stop tracking them.
224    #[serde(default)]
225    pub paused_components: HashSet<ComponentId>,
226    /// Components unpaused in this block. Clients may track them again.
227    #[serde(default)]
228    pub unpaused_components: HashSet<ComponentId>,
229}
230
231impl BlockAggregatedChanges {
232    #[expect(
233        clippy::too_many_arguments,
234        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
235    )]
236    pub fn new(
237        extractor: &str,
238        chain: Chain,
239        block: Block,
240        db_committed_block_height: Option<u64>,
241        finalized_block_height: u64,
242        revert: bool,
243        state_deltas: HashMap<String, ProtocolComponentStateDelta>,
244        account_deltas: HashMap<Bytes, AccountDelta>,
245        new_tokens: HashMap<Address, Token>,
246        new_components: HashMap<String, ProtocolComponent>,
247        deleted_components: HashMap<String, ProtocolComponent>,
248        component_balances: HashMap<ComponentId, HashMap<Bytes, ComponentBalance>>,
249        account_balances: HashMap<Address, HashMap<Address, AccountBalance>>,
250        component_tvl: HashMap<String, f64>,
251        dci_update: DCIUpdate,
252    ) -> Self {
253        Self {
254            extractor: extractor.to_string(),
255            chain,
256            block,
257            db_committed_block_height,
258            finalized_block_height,
259            revert,
260            state_deltas,
261            account_deltas,
262            new_tokens,
263            new_protocol_components: new_components,
264            deleted_protocol_components: deleted_components,
265            component_balances,
266            account_balances,
267            component_tvl,
268            dci_update,
269            partial_block_index: None,
270            paused_components: HashSet::new(),
271            unpaused_components: HashSet::new(),
272        }
273    }
274
275    pub fn drop_state(&self) -> Self {
276        Self {
277            extractor: self.extractor.clone(),
278            chain: self.chain,
279            block: self.block.clone(),
280            db_committed_block_height: self.db_committed_block_height,
281            finalized_block_height: self.finalized_block_height,
282            revert: self.revert,
283            account_deltas: HashMap::new(),
284            state_deltas: HashMap::new(),
285            new_tokens: self.new_tokens.clone(),
286            new_protocol_components: self.new_protocol_components.clone(),
287            deleted_protocol_components: self.deleted_protocol_components.clone(),
288            component_balances: self.component_balances.clone(),
289            account_balances: self.account_balances.clone(),
290            component_tvl: self.component_tvl.clone(),
291            dci_update: self.dci_update.clone(),
292            partial_block_index: self.partial_block_index,
293            paused_components: self.paused_components.clone(),
294            unpaused_components: self.unpaused_components.clone(),
295        }
296    }
297
298    pub fn is_partial(&self) -> bool {
299        self.partial_block_index.is_some()
300    }
301
302    pub fn get_block(&self) -> &Block {
303        &self.block
304    }
305
306    pub fn n_changes(&self) -> usize {
307        self.account_deltas.len() + self.state_deltas.len()
308    }
309
310    pub fn filter_by_component<F: Fn(&str) -> bool>(&mut self, keep: F) {
311        self.state_deltas.retain(|k, _| keep(k));
312        self.component_balances
313            .retain(|k, _| keep(k));
314        self.component_tvl
315            .retain(|k, _| keep(k));
316    }
317
318    pub fn filter_by_contract<F: Fn(&Bytes) -> bool>(&mut self, keep: F) {
319        self.account_deltas
320            .retain(|k, _| keep(k));
321        self.account_balances
322            .retain(|k, _| keep(k));
323    }
324
325    /// Merges this update with another one, consuming both.
326    ///
327    /// `other` is assumed to be a more recent update than `self`.
328    pub fn merge(mut self, other: Self) -> Self {
329        for (k, v) in other.account_deltas {
330            match self.account_deltas.entry(k) {
331                Entry::Occupied(mut e) => {
332                    // The entry is keyed by address, so a merge error is an address mismatch bug.
333                    if let Err(err) = e.get_mut().merge(v) {
334                        warn!("failed to merge account delta: {err}");
335                    }
336                }
337                Entry::Vacant(e) => {
338                    e.insert(v);
339                }
340            }
341        }
342
343        for (k, v) in other.state_deltas {
344            match self.state_deltas.entry(k) {
345                Entry::Occupied(mut e) => {
346                    if let Err(err) = e.get_mut().merge(v) {
347                        warn!("failed to merge protocol state delta: {err}");
348                    }
349                }
350                Entry::Vacant(e) => {
351                    e.insert(v);
352                }
353            }
354        }
355
356        for (component_id, balances) in other.component_balances {
357            self.component_balances
358                .entry(component_id)
359                .or_default()
360                .extend(balances);
361        }
362
363        for (account, balances) in other.account_balances {
364            self.account_balances
365                .entry(account)
366                .or_default()
367                .extend(balances);
368        }
369
370        self.component_tvl
371            .extend(other.component_tvl);
372        self.new_tokens.extend(other.new_tokens);
373        self.new_protocol_components
374            .extend(other.new_protocol_components);
375        self.deleted_protocol_components
376            .extend(other.deleted_protocol_components);
377        // A later pause or unpause of the same component overrides the earlier one.
378        for id in other.paused_components {
379            self.unpaused_components.remove(&id);
380            self.paused_components.insert(id);
381        }
382        for id in other.unpaused_components {
383            self.paused_components.remove(&id);
384            self.unpaused_components.insert(id);
385        }
386        self.revert = other.revert;
387        self.block = other.block;
388        self
389    }
390}
391
392impl std::fmt::Display for BlockAggregatedChanges {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        write!(f, "block_number: {}, extractor: {}", self.block.number, self.extractor)
395    }
396}
397
398pub trait BlockScoped {
399    fn block(&self) -> Block;
400}
401
402impl<T: BlockScoped> BlockScoped for std::sync::Arc<T> {
403    fn block(&self) -> Block {
404        (**self).block()
405    }
406}
407
408impl BlockScoped for BlockAggregatedChanges {
409    fn block(&self) -> Block {
410        self.block.clone()
411    }
412}
413
414impl From<dto::Block> for Block {
415    fn from(value: dto::Block) -> Self {
416        Self {
417            number: value.number,
418            chain: value.chain.into(),
419            hash: value.hash,
420            parent_hash: value.parent_hash,
421            ts: value.ts,
422        }
423    }
424}
425
426impl From<dto::AddressStorageLocation> for AddressStorageLocation {
427    fn from(value: dto::AddressStorageLocation) -> Self {
428        Self { key: value.key, offset: value.offset }
429    }
430}
431
432impl From<dto::TracingResult> for TracingResult {
433    fn from(value: dto::TracingResult) -> Self {
434        Self {
435            retriggers: value
436                .retriggers
437                .into_iter()
438                .map(|(addr, loc)| (addr, loc.into()))
439                .collect(),
440            accessed_slots: value.accessed_slots,
441        }
442    }
443}
444
445impl From<dto::DCIUpdate> for DCIUpdate {
446    fn from(value: dto::DCIUpdate) -> Self {
447        Self {
448            new_entrypoints: value
449                .new_entrypoints
450                .into_iter()
451                .map(|(k, v)| {
452                    (
453                        k,
454                        v.into_iter()
455                            .map(EntryPoint::from)
456                            .collect(),
457                    )
458                })
459                .collect(),
460            new_entrypoint_params: value
461                .new_entrypoint_params
462                .into_iter()
463                .map(|(k, v)| {
464                    (
465                        k,
466                        v.into_iter()
467                            .map(|(p, c)| (TracingParams::from(p), c))
468                            .collect(),
469                    )
470                })
471                .collect(),
472            trace_results: value
473                .trace_results
474                .into_iter()
475                .map(|(k, v)| (k, TracingResult::from(v)))
476                .collect(),
477        }
478    }
479}
480
481impl From<dto::BlockAggregatedChanges> for BlockAggregatedChanges {
482    fn from(value: dto::BlockAggregatedChanges) -> Self {
483        use crate::models::{
484            contract::{AccountBalance, AccountDelta},
485            protocol::{ComponentBalance, ProtocolComponent, ProtocolComponentStateDelta},
486            token::Token,
487        };
488        Self {
489            extractor: value.extractor,
490            chain: value.chain.into(),
491            block: value.block.into(),
492            finalized_block_height: value.finalized_block_height,
493            db_committed_block_height: None,
494            revert: value.revert,
495            state_deltas: value
496                .state_updates
497                .into_iter()
498                .map(|(k, v)| (k, ProtocolComponentStateDelta::from(v)))
499                .collect(),
500            account_deltas: value
501                .account_updates
502                .into_iter()
503                .map(|(k, v)| (k, AccountDelta::from(v)))
504                .collect(),
505            new_tokens: value
506                .new_tokens
507                .into_iter()
508                .map(|(k, v)| (k, Token::from(v)))
509                .collect(),
510            new_protocol_components: value
511                .new_protocol_components
512                .into_iter()
513                .map(|(k, v)| (k, ProtocolComponent::from(v)))
514                .collect(),
515            deleted_protocol_components: value
516                .deleted_protocol_components
517                .into_iter()
518                .map(|(k, v)| (k, ProtocolComponent::from(v)))
519                .collect(),
520            component_balances: value
521                .component_balances
522                .into_iter()
523                .map(|(component_id, token_balances)| {
524                    (
525                        component_id,
526                        token_balances
527                            .0
528                            .into_iter()
529                            .map(|(k, v)| (k, ComponentBalance::from(v)))
530                            .collect(),
531                    )
532                })
533                .collect(),
534            account_balances: value
535                .account_balances
536                .into_iter()
537                .map(|(account, balances)| {
538                    (
539                        account,
540                        balances
541                            .into_iter()
542                            .map(|(k, v)| (k, AccountBalance::from(v)))
543                            .collect(),
544                    )
545                })
546                .collect(),
547            component_tvl: value.component_tvl,
548            dci_update: DCIUpdate::from(value.dci_update),
549            partial_block_index: value.partial_block_index,
550            paused_components: value.paused_components,
551            unpaused_components: value.unpaused_components,
552        }
553    }
554}
555
556#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, DeepSizeOf)]
557pub struct DCIUpdate {
558    pub new_entrypoints: HashMap<ComponentId, HashSet<EntryPoint>>,
559    pub new_entrypoint_params: HashMap<EntryPointId, HashSet<(TracingParams, ComponentId)>>,
560    pub trace_results: HashMap<EntryPointId, TracingResult>,
561}
562
563/// Traced entry points for a set of components, as returned by the Tycho RPC.
564///
565/// Maps each component ID to the list of `(EntryPointWithTracingParams, TracingResult)` pairs
566/// produced by the tracer for that component.
567pub type TracedEntryPoints =
568    HashMap<ComponentId, Vec<(EntryPointWithTracingParams, TracingResult)>>;
569
570impl From<TracedEntryPoints> for DCIUpdate {
571    fn from(traced_entry_points: TracedEntryPoints) -> Self {
572        let mut new_entrypoints: HashMap<ComponentId, HashSet<EntryPoint>> = HashMap::new();
573        let mut new_entrypoint_params: HashMap<
574            EntryPointId,
575            HashSet<(TracingParams, ComponentId)>,
576        > = HashMap::new();
577        let mut trace_results: HashMap<EntryPointId, TracingResult> = HashMap::new();
578
579        for (component_id, traces) in traced_entry_points {
580            let mut entrypoints = HashSet::new();
581
582            for (ep_with_params, trace) in traces {
583                let ep_id = ep_with_params
584                    .entry_point
585                    .external_id
586                    .clone();
587
588                entrypoints.insert(ep_with_params.entry_point.clone());
589
590                new_entrypoint_params
591                    .entry(ep_id.clone())
592                    .or_default()
593                    .insert((ep_with_params.params, component_id.clone()));
594
595                trace_results
596                    .entry(ep_id)
597                    .and_modify(|existing: &mut TracingResult| {
598                        existing
599                            .retriggers
600                            .extend(trace.retriggers.clone());
601                        for (address, slots) in trace.accessed_slots.clone() {
602                            existing
603                                .accessed_slots
604                                .entry(address)
605                                .or_default()
606                                .extend(slots);
607                        }
608                    })
609                    .or_insert(trace);
610            }
611
612            if !entrypoints.is_empty() {
613                new_entrypoints.insert(component_id, entrypoints);
614            }
615        }
616
617        DCIUpdate { new_entrypoints, new_entrypoint_params, trace_results }
618    }
619}
620
621/// Changes grouped by their respective transaction.
622#[derive(Debug, Clone, PartialEq, Default, DeepSizeOf)]
623pub struct TxWithChanges {
624    pub tx: Transaction,
625    pub protocol_components: HashMap<ComponentId, ProtocolComponent>,
626    pub account_deltas: HashMap<Address, AccountDelta>,
627    pub state_updates: HashMap<ComponentId, ProtocolComponentStateDelta>,
628    pub balance_changes: HashMap<ComponentId, HashMap<Address, ComponentBalance>>,
629    pub account_balance_changes: HashMap<Address, HashMap<Address, AccountBalance>>,
630    pub entrypoints: HashMap<ComponentId, HashSet<EntryPoint>>,
631    pub entrypoint_params: HashMap<EntryPointId, HashSet<(TracingParams, ComponentId)>>,
632}
633
634impl TxWithChanges {
635    #[expect(
636        clippy::too_many_arguments,
637        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
638    )]
639    pub fn new(
640        tx: Transaction,
641        protocol_components: HashMap<ComponentId, ProtocolComponent>,
642        account_deltas: HashMap<Address, AccountDelta>,
643        protocol_states: HashMap<ComponentId, ProtocolComponentStateDelta>,
644        balance_changes: HashMap<ComponentId, HashMap<Address, ComponentBalance>>,
645        account_balance_changes: HashMap<Address, HashMap<Address, AccountBalance>>,
646        entrypoints: HashMap<ComponentId, HashSet<EntryPoint>>,
647        entrypoint_params: HashMap<EntryPointId, HashSet<(TracingParams, ComponentId)>>,
648    ) -> Self {
649        Self {
650            tx,
651            account_deltas,
652            protocol_components,
653            state_updates: protocol_states,
654            balance_changes,
655            account_balance_changes,
656            entrypoints,
657            entrypoint_params,
658        }
659    }
660
661    /// Merges this update with another one.
662    ///
663    /// The method combines two [`TxWithChanges`] instances if they are on the same block.
664    ///
665    /// NB: It is expected that `other` is a more recent update than `self` is and the two are
666    /// combined accordingly.
667    ///
668    /// # Errors
669    /// Returns a `MergeError` if any of the above conditions are violated.
670    pub fn merge(&mut self, other: TxWithChanges) -> Result<(), MergeError> {
671        if self.tx.block_hash != other.tx.block_hash {
672            return Err(MergeError::BlockMismatch(
673                "TxWithChanges".to_string(),
674                self.tx.block_hash.clone(),
675                other.tx.block_hash,
676            ));
677        }
678        if self.tx.index > other.tx.index {
679            return Err(MergeError::TransactionOrderError(
680                "TxWithChanges".to_string(),
681                self.tx.index,
682                other.tx.index,
683            ));
684        }
685
686        self.tx = other.tx;
687
688        // Merge new protocol components
689        // Log a warning if a new protocol component for the same id already exists, because this
690        // should never happen.
691        for (key, value) in other.protocol_components {
692            match self.protocol_components.entry(key) {
693                Entry::Occupied(mut entry) => {
694                    warn!(
695                        "Overwriting new protocol component for id {} with a new one. This should never happen! Please check logic",
696                        entry.get().id
697                    );
698                    entry.insert(value);
699                }
700                Entry::Vacant(entry) => {
701                    entry.insert(value);
702                }
703            }
704        }
705
706        // Merge account deltas
707        for (address, update) in other.account_deltas.clone().into_iter() {
708            match self.account_deltas.entry(address) {
709                Entry::Occupied(mut e) => {
710                    e.get_mut().merge(update)?;
711                }
712                Entry::Vacant(e) => {
713                    e.insert(update);
714                }
715            }
716        }
717
718        // Merge protocol state updates
719        for (key, value) in other.state_updates {
720            match self.state_updates.entry(key) {
721                Entry::Occupied(mut entry) => {
722                    entry.get_mut().merge(value)?;
723                }
724                Entry::Vacant(entry) => {
725                    entry.insert(value);
726                }
727            }
728        }
729
730        // Merge component balance changes
731        for (component_id, balance_changes) in other.balance_changes {
732            let token_balances = self
733                .balance_changes
734                .entry(component_id)
735                .or_default();
736            for (token, balance) in balance_changes {
737                token_balances.insert(token, balance);
738            }
739        }
740
741        // Merge account balance changes
742        for (account_addr, balance_changes) in other.account_balance_changes {
743            let token_balances = self
744                .account_balance_changes
745                .entry(account_addr)
746                .or_default();
747            for (token, balance) in balance_changes {
748                token_balances.insert(token, balance);
749            }
750        }
751
752        // Merge new entrypoints
753        for (component_id, entrypoints) in other.entrypoints {
754            self.entrypoints
755                .entry(component_id)
756                .or_default()
757                .extend(entrypoints);
758        }
759
760        // Merge new entrypoint params
761        for (entrypoint_id, params) in other.entrypoint_params {
762            self.entrypoint_params
763                .entry(entrypoint_id)
764                .or_default()
765                .extend(params);
766        }
767
768        Ok(())
769    }
770}
771
772#[derive(Copy, Clone, Debug, PartialEq)]
773pub enum BlockTag {
774    /// Finalized block
775    Finalized,
776    /// Safe block
777    Safe,
778    /// Latest block
779    Latest,
780    /// Earliest block (genesis)
781    Earliest,
782    /// Pending block (not yet part of the blockchain)
783    Pending,
784    /// Block by number
785    Number(u64),
786}
787#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, DeepSizeOf)]
788pub struct EntryPoint {
789    /// Entry point id
790    pub external_id: String,
791    /// The address of the contract to trace.
792    pub target: Address,
793    /// The signature of the function to trace.
794    pub signature: String,
795}
796
797impl EntryPoint {
798    pub fn new(external_id: String, target: Address, signature: String) -> Self {
799        Self { external_id, target, signature }
800    }
801}
802
803impl From<dto::EntryPoint> for EntryPoint {
804    fn from(value: dto::EntryPoint) -> Self {
805        Self { external_id: value.external_id, target: value.target, signature: value.signature }
806    }
807}
808
809/// A struct that combines an entry point with its associated tracing params.
810#[derive(Debug, Clone, PartialEq, Eq, Hash, DeepSizeOf)]
811pub struct EntryPointWithTracingParams {
812    /// The entry point to trace, containing the target contract address and function signature
813    pub entry_point: EntryPoint,
814    /// The tracing parameters for this entry point
815    pub params: TracingParams,
816}
817
818impl From<dto::EntryPointWithTracingParams> for EntryPointWithTracingParams {
819    fn from(value: dto::EntryPointWithTracingParams) -> Self {
820        match value.params {
821            dto::TracingParams::RPCTracer(ref tracer_params) => Self {
822                entry_point: EntryPoint {
823                    external_id: value.entry_point.external_id,
824                    target: value.entry_point.target,
825                    signature: value.entry_point.signature,
826                },
827                params: TracingParams::RPCTracer(RPCTracerParams {
828                    caller: tracer_params.caller.clone(),
829                    calldata: tracer_params.calldata.clone(),
830                    state_overrides: tracer_params
831                        .state_overrides
832                        .clone()
833                        .map(|s| {
834                            s.into_iter()
835                                .map(|(k, v)| (k, v.into()))
836                                .collect()
837                        }),
838                    prune_addresses: tracer_params.prune_addresses.clone(),
839                }),
840            },
841        }
842    }
843}
844
845impl EntryPointWithTracingParams {
846    pub fn new(entry_point: EntryPoint, params: TracingParams) -> Self {
847        Self { entry_point, params }
848    }
849}
850
851impl std::fmt::Display for EntryPointWithTracingParams {
852    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
853        let tracer_type = match &self.params {
854            TracingParams::RPCTracer(_) => "RPC",
855        };
856        write!(f, "{} [{}]", self.entry_point.external_id, tracer_type)
857    }
858}
859
860#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash, DeepSizeOf)]
861/// An entry point to trace. Different types of entry points tracing will be supported in the
862/// future. Like RPC debug tracing, symbolic execution, etc.
863pub enum TracingParams {
864    /// Uses RPC calls to retrieve the called addresses and retriggers
865    RPCTracer(RPCTracerParams),
866}
867
868impl std::fmt::Display for TracingParams {
869    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
870        match self {
871            TracingParams::RPCTracer(params) => write!(f, "RPC: {params}"),
872        }
873    }
874}
875
876impl From<dto::TracingParams> for TracingParams {
877    fn from(value: dto::TracingParams) -> Self {
878        match value {
879            dto::TracingParams::RPCTracer(tracer_params) => {
880                TracingParams::RPCTracer(tracer_params.into())
881            }
882        }
883    }
884}
885
886#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash, DeepSizeOf)]
887pub enum StorageOverride {
888    Diff(BTreeMap<StoreKey, StoreVal>),
889    Replace(BTreeMap<StoreKey, StoreVal>),
890}
891
892impl From<dto::StorageOverride> for StorageOverride {
893    fn from(value: dto::StorageOverride) -> Self {
894        match value {
895            dto::StorageOverride::Diff(diff) => StorageOverride::Diff(diff),
896            dto::StorageOverride::Replace(replace) => StorageOverride::Replace(replace),
897        }
898    }
899}
900
901#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash, DeepSizeOf)]
902pub struct AccountOverrides {
903    pub slots: Option<StorageOverride>,
904    pub native_balance: Option<Balance>,
905    pub code: Option<Code>,
906}
907
908impl From<dto::AccountOverrides> for AccountOverrides {
909    fn from(value: dto::AccountOverrides) -> Self {
910        Self {
911            slots: value.slots.map(|s| s.into()),
912            native_balance: value.native_balance,
913            code: value.code,
914        }
915    }
916}
917
918#[derive(Debug, Clone, PartialEq, Deserialize, Eq, Hash, DeepSizeOf)]
919pub struct RPCTracerParams {
920    /// The caller address of the transaction, if not provided tracing will use the default value
921    /// for an address defined by the VM.
922    pub caller: Option<Address>,
923    /// The call data used for the tracing call, this needs to include the function selector
924    pub calldata: Bytes,
925    /// Optionally allow for state overrides so that the call works as expected
926    pub state_overrides: Option<BTreeMap<Address, AccountOverrides>>,
927    /// Addresses to prune from trace results. Useful for hooks that use mock
928    /// accounts/routers that shouldn't be tracked in the final DCI results.
929    pub prune_addresses: Option<Vec<Address>>,
930}
931
932impl From<dto::RPCTracerParams> for RPCTracerParams {
933    fn from(value: dto::RPCTracerParams) -> Self {
934        Self {
935            caller: value.caller,
936            calldata: value.calldata,
937            state_overrides: value.state_overrides.map(|overrides| {
938                overrides
939                    .into_iter()
940                    .map(|(address, account_overrides)| (address, account_overrides.into()))
941                    .collect()
942            }),
943            prune_addresses: value.prune_addresses,
944        }
945    }
946}
947
948impl RPCTracerParams {
949    pub fn new(caller: Option<Address>, calldata: Bytes) -> Self {
950        Self { caller, calldata, state_overrides: None, prune_addresses: None }
951    }
952
953    pub fn with_state_overrides(mut self, state: BTreeMap<Address, AccountOverrides>) -> Self {
954        self.state_overrides = Some(state);
955        self
956    }
957
958    pub fn with_prune_addresses(mut self, addresses: Vec<Address>) -> Self {
959        self.prune_addresses = Some(addresses);
960        self
961    }
962}
963
964impl std::fmt::Display for RPCTracerParams {
965    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966        let caller_str = match &self.caller {
967            Some(addr) => format!("caller={addr}"),
968            None => String::new(),
969        };
970
971        let calldata_str = if self.calldata.len() >= 8 {
972            format!(
973                "calldata=0x{}..({} bytes)",
974                hex::encode(&self.calldata[..8]),
975                self.calldata.len()
976            )
977        } else {
978            format!("calldata={}", self.calldata)
979        };
980
981        let overrides_str = match &self.state_overrides {
982            Some(overrides) if !overrides.is_empty() => {
983                format!(", {} state override(s)", overrides.len())
984            }
985            _ => String::new(),
986        };
987
988        write!(f, "{caller_str}, {calldata_str}{overrides_str}")
989    }
990}
991
992// Ensure serialization order, required by the storage layer
993impl Serialize for RPCTracerParams {
994    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
995    where
996        S: Serializer,
997    {
998        // Count fields: always serialize caller and calldata, plus optional fields
999        let mut field_count = 2;
1000        if self.state_overrides.is_some() {
1001            field_count += 1;
1002        }
1003        if self.prune_addresses.is_some() {
1004            field_count += 1;
1005        }
1006
1007        let mut state = serializer.serialize_struct("RPCTracerEntryPoint", field_count)?;
1008        state.serialize_field("caller", &self.caller)?;
1009        state.serialize_field("calldata", &self.calldata)?;
1010
1011        // Only serialize optional fields if they are present
1012        if let Some(ref overrides) = self.state_overrides {
1013            state.serialize_field("state_overrides", overrides)?;
1014        }
1015        if let Some(ref prune_addrs) = self.prune_addresses {
1016            state.serialize_field("prune_addresses", prune_addrs)?;
1017        }
1018
1019        state.end()
1020    }
1021}
1022
1023#[derive(
1024    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, DeepSizeOf,
1025)]
1026pub struct AddressStorageLocation {
1027    pub key: StoreKey,
1028    pub offset: u8,
1029}
1030
1031impl AddressStorageLocation {
1032    pub fn new(key: StoreKey, offset: u8) -> Self {
1033        Self { key, offset }
1034    }
1035}
1036
1037#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, DeepSizeOf)]
1038pub struct TracingResult {
1039    /// A set of (address, storage slot) pairs representing state that contain a called address.
1040    /// If any of these storage slots change, the execution path might change.
1041    pub retriggers: HashSet<(Address, AddressStorageLocation)>,
1042    /// A map of all addresses that were called during the trace with a list of storage slots that
1043    /// were accessed.
1044    pub accessed_slots: HashMap<Address, HashSet<StoreKey>>,
1045}
1046
1047impl TracingResult {
1048    pub fn new(
1049        retriggers: HashSet<(Address, AddressStorageLocation)>,
1050        accessed_slots: HashMap<Address, HashSet<StoreKey>>,
1051    ) -> Self {
1052        Self { retriggers, accessed_slots }
1053    }
1054
1055    /// Merges this tracing result with another one.
1056    ///
1057    /// The method combines two [`TracingResult`] instances.
1058    pub fn merge(&mut self, other: TracingResult) {
1059        self.retriggers.extend(other.retriggers);
1060        for (address, slots) in other.accessed_slots {
1061            self.accessed_slots
1062                .entry(address)
1063                .or_default()
1064                .extend(slots);
1065        }
1066    }
1067}
1068
1069#[derive(Debug, Clone, PartialEq, DeepSizeOf)]
1070/// Represents a traced entry point and the results of the tracing operation.
1071pub struct TracedEntryPoint {
1072    /// The combined entry point and tracing params that was traced
1073    pub entry_point_with_params: EntryPointWithTracingParams,
1074    /// The block hash of the block that the entry point was traced on.
1075    pub detection_block_hash: BlockHash,
1076    /// The results of the tracing operation
1077    pub tracing_result: TracingResult,
1078}
1079
1080impl TracedEntryPoint {
1081    pub fn new(
1082        entry_point_with_params: EntryPointWithTracingParams,
1083        detection_block_hash: BlockHash,
1084        result: TracingResult,
1085    ) -> Self {
1086        Self { entry_point_with_params, detection_block_hash, tracing_result: result }
1087    }
1088
1089    pub fn entry_point_id(&self) -> String {
1090        self.entry_point_with_params
1091            .entry_point
1092            .external_id
1093            .clone()
1094    }
1095}
1096
1097impl std::fmt::Display for TracedEntryPoint {
1098    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1099        write!(
1100            f,
1101            "[{}: {} retriggers, {} accessed addresses]",
1102            self.entry_point_id(),
1103            self.tracing_result.retriggers.len(),
1104            self.tracing_result.accessed_slots.len()
1105        )
1106    }
1107}
1108
1109/// Storage changes grouped by transaction.
1110#[derive(Debug, PartialEq, Default, Clone, DeepSizeOf)]
1111pub struct TxWithContractChanges {
1112    pub tx: Transaction,
1113    pub contract_changes: AccountToContractChanges,
1114}
1115
1116#[derive(Debug, PartialEq, Default, Clone, DeepSizeOf)]
1117pub struct BlockChanges {
1118    pub extractor: String,
1119    pub chain: Chain,
1120    pub block: Block,
1121    pub finalized_block_height: u64,
1122    pub revert: bool,
1123    pub new_tokens: HashMap<Address, Token>,
1124    /// Vec of updates at this block, aggregated by tx and sorted by tx index in ascending order
1125    pub txs_with_update: Vec<TxWithChanges>,
1126    // Raw block contract changes. This is intended as DCI input and is to be omitted from the
1127    // reorg buffer and aggregation into the `BlockAggregatedChanges` object.
1128    pub block_contract_changes: Vec<TxWithContractChanges>,
1129    /// Required here so that it is part of the reorg buffer and thus inserted into storage once
1130    /// finalized.
1131    /// Populated by the `DynamicContractIndexer`
1132    pub trace_results: Vec<TracedEntryPoint>,
1133    /// The index of the partial block. None if it's a full block.
1134    pub partial_block_index: Option<u32>,
1135}
1136
1137impl BlockChanges {
1138    pub fn new(
1139        extractor: String,
1140        chain: Chain,
1141        block: Block,
1142        finalized_block_height: u64,
1143        revert: bool,
1144        txs_with_update: Vec<TxWithChanges>,
1145        block_contract_changes: Vec<TxWithContractChanges>,
1146    ) -> Self {
1147        BlockChanges {
1148            extractor,
1149            chain,
1150            block,
1151            finalized_block_height,
1152            revert,
1153            new_tokens: HashMap::new(),
1154            txs_with_update,
1155            block_contract_changes,
1156            trace_results: Vec::new(),
1157            partial_block_index: None,
1158        }
1159    }
1160
1161    /// Aggregates component and account updates.
1162    ///
1163    /// This function aggregates all protocol updates into a [`BlockAggregatedChanges`] object. This
1164    /// new object should have all individual changes merged into only one final/compacted change
1165    /// per component and account. This means there is only one state delta and component balance
1166    /// per component, and one account delta and account balance per account. DCI trace results are
1167    /// also aggregated into a result per entry point.
1168    ///
1169    /// Note - all non-protocol specific data in the BlockChanges object are lost during
1170    /// aggregation. This means block_storage_changes is dropped.
1171    ///
1172    /// # Errors
1173    ///
1174    /// This returns a `MergeError` if there was a problem during merge.
1175    pub fn into_aggregated(
1176        self,
1177        db_committed_block_height: Option<u64>,
1178    ) -> Result<BlockAggregatedChanges, MergeError> {
1179        if db_committed_block_height.is_some_and(|h| h > self.finalized_block_height) {
1180            return Err(MergeError::InvalidState(format!(
1181                "Database committed block height {:?} is greater than finalized_block_height {}",
1182                db_committed_block_height, self.finalized_block_height
1183            )));
1184        }
1185
1186        let mut iter = self.txs_with_update.into_iter();
1187
1188        let first_state = iter.next().unwrap_or_default();
1189
1190        let aggregated_changes = iter.try_fold(first_state, |mut acc_state, new_state| {
1191            acc_state.merge(new_state)?;
1192            Ok::<_, MergeError>(acc_state)
1193        })?;
1194
1195        // Aggregate trace_results
1196        let mut aggregated_trace_results = HashMap::new();
1197        for result in self.trace_results {
1198            let external_id = result.entry_point_id();
1199            aggregated_trace_results
1200                .entry(external_id)
1201                .and_modify(|existing: &mut TracingResult| {
1202                    existing.merge(result.tracing_result.clone())
1203                })
1204                .or_insert(result.tracing_result);
1205        }
1206
1207        Ok(BlockAggregatedChanges {
1208            extractor: self.extractor,
1209            chain: self.chain,
1210            block: self.block,
1211            db_committed_block_height,
1212            finalized_block_height: self.finalized_block_height,
1213            revert: self.revert,
1214            new_protocol_components: aggregated_changes.protocol_components,
1215            new_tokens: self.new_tokens,
1216            deleted_protocol_components: HashMap::new(),
1217            state_deltas: aggregated_changes.state_updates,
1218            account_deltas: aggregated_changes.account_deltas,
1219            component_balances: aggregated_changes.balance_changes,
1220            account_balances: aggregated_changes.account_balance_changes,
1221            component_tvl: HashMap::new(),
1222            dci_update: DCIUpdate {
1223                new_entrypoints: aggregated_changes.entrypoints,
1224                new_entrypoint_params: aggregated_changes.entrypoint_params,
1225                trace_results: aggregated_trace_results,
1226            },
1227            partial_block_index: self.partial_block_index,
1228            paused_components: HashSet::new(),
1229            unpaused_components: HashSet::new(),
1230        })
1231    }
1232
1233    pub fn protocol_components(&self) -> Vec<ProtocolComponent> {
1234        self.txs_with_update
1235            .iter()
1236            .flat_map(|tx_u| {
1237                tx_u.protocol_components
1238                    .values()
1239                    .cloned()
1240            })
1241            .collect()
1242    }
1243
1244    /// Returns true if the block is a partial block.
1245    pub fn is_partial_block(&self) -> bool {
1246        self.partial_block_index.is_some()
1247    }
1248
1249    /// Sets the partial block index.
1250    pub fn set_partial_block_index(&mut self, index: Option<u32>) {
1251        self.partial_block_index = index;
1252    }
1253
1254    /// Sets every transaction's `block_hash` in `txs_with_update` and `block_contract_changes`
1255    /// to this block's hash. Used after merging partials so all txs refer to the same block
1256    /// (e.g. the final block hash).
1257    pub fn normalize_block_hash(&mut self) {
1258        let h = self.block.hash.clone();
1259        for tx_with_changes in self.txs_with_update.iter_mut() {
1260            tx_with_changes.tx.block_hash = h.clone();
1261        }
1262        for tx_with_contract in self.block_contract_changes.iter_mut() {
1263            tx_with_contract.tx.block_hash = h.clone();
1264        }
1265    }
1266
1267    /// Merges another partial block into this one, preserving later changes.
1268    ///
1269    /// The partial block with the higher index represents later changes and takes precedence.
1270    /// Merges `new_tokens`, `txs_with_update` (sorted by index), `block_contract_changes`,
1271    /// and `trace_results`. When both blocks have the same token address, the token from the
1272    /// block with the higher partial index is kept.
1273    ///
1274    /// Works regardless of merge order: `partial_0.merge_partial(partial_1)` and
1275    /// `partial_1.merge_partial(partial_0)` produce equivalent results.
1276    ///
1277    /// # Errors
1278    /// - Non-partial block: Either block is not marked as partial
1279    /// - Extractor mismatch: Blocks from different extractors
1280    /// - Chain mismatch: Blocks from different chains
1281    /// - Block mismatch: Different block numbers (hash may differ for temp vs final partial)
1282    /// - Revert mismatch: Different revert status
1283    pub fn merge_partial(self, other: Self) -> Result<Self, MergeError> {
1284        let Some(self_index) = self.partial_block_index else {
1285            return Err(MergeError::InvalidState("self is not a partial block".to_string()));
1286        };
1287
1288        let Some(other_index) = other.partial_block_index else {
1289            return Err(MergeError::InvalidState("other is not a partial block".to_string()));
1290        };
1291
1292        if self.extractor != other.extractor {
1293            return Err(MergeError::IdMismatch(
1294                "partial blocks (extractor)".to_string(),
1295                self.extractor,
1296                other.extractor,
1297            ));
1298        }
1299
1300        if self.chain != other.chain {
1301            return Err(MergeError::IdMismatch(
1302                "partial blocks (chain)".to_string(),
1303                format!("{:?}", self.chain),
1304                format!("{:?}", other.chain),
1305            ));
1306        }
1307
1308        if self.block.number != other.block.number {
1309            return Err(MergeError::BlockMismatch(
1310                "partial blocks".to_string(),
1311                self.block.hash,
1312                other.block.hash,
1313            ));
1314        }
1315
1316        if self.revert != other.revert {
1317            return Err(MergeError::InvalidState(format!(
1318                "different revert status: {} vs {}",
1319                self.revert, other.revert
1320            )));
1321        }
1322
1323        let (mut current, previous) = if self_index > other_index {
1324            (self, other)
1325        } else if self_index < other_index {
1326            (other, self)
1327        } else {
1328            return Err(MergeError::InvalidState(format!("same partial block index: {self_index}")));
1329        };
1330
1331        for (addr, token) in previous.new_tokens {
1332            current
1333                .new_tokens
1334                .entry(addr)
1335                .or_insert(token);
1336        }
1337
1338        current
1339            .txs_with_update
1340            .extend(previous.txs_with_update);
1341        current
1342            .txs_with_update
1343            .sort_by_key(|tx| tx.tx.index);
1344
1345        current
1346            .block_contract_changes
1347            .extend(previous.block_contract_changes);
1348
1349        current.normalize_block_hash();
1350
1351        current
1352            .trace_results
1353            .extend(previous.trace_results);
1354
1355        Ok(current)
1356    }
1357}
1358
1359impl BlockScoped for BlockChanges {
1360    fn block(&self) -> Block {
1361        self.block.clone()
1362    }
1363}
1364
1365#[cfg(test)]
1366pub mod fixtures {
1367    use std::str::FromStr;
1368
1369    use rstest::rstest;
1370
1371    use super::*;
1372    use crate::models::ChangeType;
1373
1374    // PERF: duplicated in crate::extractor::models::fixtures — consider a `test-utils`
1375    // feature flag to share test fixtures cross-crate.
1376    pub fn create_transaction(hash: &str, block: &str, index: u64) -> Transaction {
1377        Transaction::new(
1378            hash.parse().unwrap(),
1379            block.parse().unwrap(),
1380            Bytes::zero(20),
1381            Some(Bytes::zero(20)),
1382            index,
1383        )
1384    }
1385
1386    /// Returns a pre-built `TxWithChanges` for testing.
1387    ///
1388    /// Both indices share the same keys (component `"pool_0"`, token `0xaa..`, contract `0xbb..`)
1389    /// but with different values, so "later wins" precedence can be verified across all fields:
1390    ///
1391    /// - Index 0: tx_index=1, component_balance {token=800, token2=300}, account_balance
1392    ///   {token=500, token2=150}, slots {1=>100, 2=>200}, state {"reserve"=>1000, "fee"=>50}, 1
1393    ///   entrypoint, ChangeType::Creation
1394    /// - Index 1: tx_index=2, component_balance {token=1000}, account_balance {token=700}, slots
1395    ///   {1=>300} (overlaps slot 1), state {"reserve"=>2000} (overlaps), 2 entrypoints (superset),
1396    ///   ChangeType::Update
1397    // PERF: duplicated in crate::extractor::models::fixtures — consider a `test-utils`
1398    // feature flag to share test fixtures cross-crate.
1399    pub fn tx_with_changes(index: u8) -> TxWithChanges {
1400        let token = Bytes::from(vec![0xaa; 20]);
1401        let token2 = Bytes::from(vec![0xcc; 20]);
1402        let contract = Bytes::from(vec![0xbb; 20]);
1403        let c_id = "pool_0".to_string();
1404
1405        match index {
1406            0 => {
1407                let tx = create_transaction("0x01", "0x00", 1);
1408                TxWithChanges {
1409                    tx: tx.clone(),
1410                    protocol_components: HashMap::from([(
1411                        c_id.clone(),
1412                        ProtocolComponent { id: c_id.clone(), ..Default::default() },
1413                    )]),
1414                    account_deltas: HashMap::from([(
1415                        contract.clone(),
1416                        AccountDelta::new(
1417                            Chain::Ethereum,
1418                            contract.clone(),
1419                            HashMap::from([
1420                                (
1421                                    Bytes::from(1u64).lpad(32, 0),
1422                                    Some(Bytes::from(100u64).lpad(32, 0)),
1423                                ),
1424                                (
1425                                    Bytes::from(2u64).lpad(32, 0),
1426                                    Some(Bytes::from(200u64).lpad(32, 0)),
1427                                ),
1428                            ]),
1429                            None,
1430                            Some(Bytes::from(vec![0; 4])),
1431                            ChangeType::Creation,
1432                        ),
1433                    )]),
1434                    state_updates: HashMap::from([(
1435                        c_id.clone(),
1436                        ProtocolComponentStateDelta::new(
1437                            &c_id,
1438                            HashMap::from([
1439                                ("reserve".into(), Bytes::from(1000u64).lpad(32, 0)),
1440                                ("fee".into(), Bytes::from(50u64).lpad(32, 0)),
1441                            ]),
1442                            HashSet::new(),
1443                        ),
1444                    )]),
1445                    balance_changes: HashMap::from([(
1446                        c_id.clone(),
1447                        HashMap::from([
1448                            (
1449                                token.clone(),
1450                                ComponentBalance {
1451                                    token: token.clone(),
1452                                    balance: Bytes::from(800_u64).lpad(32, 0),
1453                                    balance_float: 800.0,
1454                                    component_id: c_id.clone(),
1455                                    modify_tx: tx.hash.clone(),
1456                                },
1457                            ),
1458                            (
1459                                token2.clone(),
1460                                ComponentBalance {
1461                                    token: token2.clone(),
1462                                    balance: Bytes::from(300_u64).lpad(32, 0),
1463                                    balance_float: 300.0,
1464                                    component_id: c_id.clone(),
1465                                    modify_tx: tx.hash.clone(),
1466                                },
1467                            ),
1468                        ]),
1469                    )]),
1470                    account_balance_changes: HashMap::from([(
1471                        contract.clone(),
1472                        HashMap::from([
1473                            (
1474                                token.clone(),
1475                                AccountBalance {
1476                                    token,
1477                                    balance: Bytes::from(500_u64).lpad(32, 0),
1478                                    modify_tx: tx.hash.clone(),
1479                                    account: contract.clone(),
1480                                },
1481                            ),
1482                            (
1483                                token2,
1484                                AccountBalance {
1485                                    token: Bytes::from(vec![0xcc; 20]),
1486                                    balance: Bytes::from(150_u64).lpad(32, 0),
1487                                    modify_tx: tx.hash,
1488                                    account: contract,
1489                                },
1490                            ),
1491                        ]),
1492                    )]),
1493                    entrypoints: HashMap::from([(
1494                        c_id.clone(),
1495                        HashSet::from([EntryPoint::new(
1496                            "ep_0".into(),
1497                            Bytes::zero(20),
1498                            "fn_a()".into(),
1499                        )]),
1500                    )]),
1501                    entrypoint_params: HashMap::from([(
1502                        "ep_0".into(),
1503                        HashSet::from([(
1504                            TracingParams::RPCTracer(RPCTracerParams::new(
1505                                None,
1506                                Bytes::from(vec![1]),
1507                            )),
1508                            c_id,
1509                        )]),
1510                    )]),
1511                }
1512            }
1513            1 => {
1514                let tx = create_transaction("0x02", "0x00", 2);
1515                TxWithChanges {
1516                    tx: tx.clone(),
1517                    protocol_components: HashMap::from([(
1518                        c_id.clone(),
1519                        ProtocolComponent { id: c_id.clone(), ..Default::default() },
1520                    )]),
1521                    account_deltas: HashMap::from([(
1522                        contract.clone(),
1523                        AccountDelta::new(
1524                            Chain::Ethereum,
1525                            contract.clone(),
1526                            HashMap::from([(
1527                                Bytes::from(1u64).lpad(32, 0),
1528                                Some(Bytes::from(300u64).lpad(32, 0)),
1529                            )]),
1530                            None,
1531                            None,
1532                            ChangeType::Update,
1533                        ),
1534                    )]),
1535                    state_updates: HashMap::from([(
1536                        c_id.clone(),
1537                        ProtocolComponentStateDelta::new(
1538                            &c_id,
1539                            HashMap::from([("reserve".into(), Bytes::from(2000u64).lpad(32, 0))]),
1540                            HashSet::new(),
1541                        ),
1542                    )]),
1543                    balance_changes: HashMap::from([(
1544                        c_id.clone(),
1545                        HashMap::from([(
1546                            token.clone(),
1547                            ComponentBalance {
1548                                token: token.clone(),
1549                                balance: Bytes::from(1000_u64).lpad(32, 0),
1550                                balance_float: 1000.0,
1551                                component_id: c_id.clone(),
1552                                modify_tx: tx.hash.clone(),
1553                            },
1554                        )]),
1555                    )]),
1556                    account_balance_changes: HashMap::from([(
1557                        contract.clone(),
1558                        HashMap::from([(
1559                            token.clone(),
1560                            AccountBalance {
1561                                token,
1562                                balance: Bytes::from(700_u64).lpad(32, 0),
1563                                modify_tx: tx.hash,
1564                                account: contract,
1565                            },
1566                        )]),
1567                    )]),
1568                    entrypoints: HashMap::from([(
1569                        c_id.clone(),
1570                        HashSet::from([
1571                            EntryPoint::new("ep_0".into(), Bytes::zero(20), "fn_a()".into()),
1572                            EntryPoint::new("ep_1".into(), Bytes::zero(20), "fn_b()".into()),
1573                        ]),
1574                    )]),
1575                    entrypoint_params: HashMap::from([(
1576                        "ep_1".into(),
1577                        HashSet::from([(
1578                            TracingParams::RPCTracer(RPCTracerParams::new(
1579                                None,
1580                                Bytes::from(vec![2]),
1581                            )),
1582                            c_id,
1583                        )]),
1584                    )]),
1585                }
1586            }
1587            _ => panic!("tx_with_changes: index must be 0 or 1, got {index}"),
1588        }
1589    }
1590
1591    #[test]
1592    fn test_merge_tx_with_changes() {
1593        let mut changes1 = tx_with_changes(0);
1594        let changes2 = tx_with_changes(1);
1595
1596        let token = Bytes::from(vec![0xaa; 20]);
1597        let contract = Bytes::from(vec![0xbb; 20]);
1598        let c_id = "pool_0".to_string();
1599
1600        assert!(changes1.merge(changes2).is_ok());
1601
1602        // After merge, balances should reflect changes2 ("later wins")
1603        assert_eq!(
1604            changes1.balance_changes[&c_id][&token].balance,
1605            Bytes::from(1000_u64).lpad(32, 0),
1606        );
1607        assert_eq!(
1608            changes1.account_balance_changes[&contract][&token].balance,
1609            Bytes::from(700_u64).lpad(32, 0),
1610        );
1611        // tx should be updated to changes2's tx
1612        assert_eq!(changes1.tx.hash, Bytes::from(vec![2]));
1613        // Entrypoints should be merged (union of both)
1614        assert_eq!(changes1.entrypoints[&c_id].len(), 2);
1615        let mut sigs: Vec<_> = changes1.entrypoints[&c_id]
1616            .iter()
1617            .map(|ep| ep.signature.clone())
1618            .collect();
1619        sigs.sort();
1620        assert_eq!(sigs, vec!["fn_a()", "fn_b()"]);
1621    }
1622
1623    #[test]
1624    fn test_merge_tx_with_changes_keeps_a_later_account_creation() {
1625        let contract = Bytes::from(vec![0xdd; 20]);
1626        let update = AccountDelta::new(
1627            Chain::Ethereum,
1628            contract.clone(),
1629            HashMap::from([(Bytes::from(1u8).lpad(32, 0), Some(Bytes::from(1u8).lpad(32, 0)))]),
1630            None,
1631            None,
1632            ChangeType::Update,
1633        );
1634        let creation = AccountDelta::new(
1635            Chain::Ethereum,
1636            contract.clone(),
1637            HashMap::new(),
1638            Some(Bytes::from(0u8).lpad(32, 0)),
1639            Some(Bytes::from("0x6000")),
1640            ChangeType::Creation,
1641        );
1642        let mut changes = TxWithChanges {
1643            tx: create_transaction("0x03", "0x00", 3),
1644            account_deltas: HashMap::from([(contract.clone(), update)]),
1645            ..Default::default()
1646        };
1647        let later = TxWithChanges {
1648            tx: create_transaction("0x0a", "0x00", 10),
1649            account_deltas: HashMap::from([(contract.clone(), creation)]),
1650            ..Default::default()
1651        };
1652
1653        changes.merge(later).unwrap();
1654
1655        assert_eq!(changes.account_deltas[&contract].change_type(), ChangeType::Creation);
1656    }
1657
1658    #[test]
1659    fn test_block_changes_merge_keeps_new_tokens_of_both() {
1660        let changes = |addr: &Bytes| BlockAggregatedChanges {
1661            new_tokens: HashMap::from([(
1662                addr.clone(),
1663                Token::new(addr, "T", 18, 0, &[], Chain::Ethereum, 100),
1664            )]),
1665            ..Default::default()
1666        };
1667        let first = Bytes::from(vec![0x11; 20]);
1668        let second = Bytes::from(vec![0x22; 20]);
1669
1670        let merged = changes(&first).merge(changes(&second));
1671
1672        assert!(merged.new_tokens.contains_key(&first));
1673        assert!(merged.new_tokens.contains_key(&second));
1674    }
1675
1676    #[rstest]
1677    #[case::mismatched_blocks(
1678        fixtures::create_transaction("0x01", "0x0abc", 1),
1679        fixtures::create_transaction("0x02", "0x0def", 2)
1680    )]
1681    #[case::older_transaction(
1682        fixtures::create_transaction("0x02", "0x0abc", 2),
1683        fixtures::create_transaction("0x01", "0x0abc", 1)
1684    )]
1685    fn test_merge_errors(#[case] tx1: Transaction, #[case] tx2: Transaction) {
1686        let mut changes1 = TxWithChanges { tx: tx1, ..Default::default() };
1687
1688        let changes2 = TxWithChanges { tx: tx2, ..Default::default() };
1689
1690        assert!(changes1.merge(changes2).is_err());
1691    }
1692
1693    #[test]
1694    fn test_rpc_tracer_entry_point_serialization_order() {
1695        use std::str::FromStr;
1696
1697        use serde_json;
1698
1699        let entry_point = RPCTracerParams::new(
1700            Some(Address::from_str("0x1234567890123456789012345678901234567890").unwrap()),
1701            Bytes::from_str("0xabcdef").unwrap(),
1702        );
1703
1704        let serialized = serde_json::to_string(&entry_point).unwrap();
1705
1706        // Verify that "caller" comes before "calldata" in the serialized output
1707        assert!(serialized.find("\"caller\"").unwrap() < serialized.find("\"calldata\"").unwrap());
1708
1709        // Verify we can deserialize it back
1710        let deserialized: RPCTracerParams = serde_json::from_str(&serialized).unwrap();
1711        assert_eq!(entry_point, deserialized);
1712    }
1713
1714    #[test]
1715    fn test_tracing_result_merge() {
1716        let address1 = Address::from_str("0x1234567890123456789012345678901234567890").unwrap();
1717        let address2 = Address::from_str("0x2345678901234567890123456789012345678901").unwrap();
1718        let address3 = Address::from_str("0x3456789012345678901234567890123456789012").unwrap();
1719
1720        let store_key1 = StoreKey::from(vec![1, 2, 3, 4]);
1721        let store_key2 = StoreKey::from(vec![5, 6, 7, 8]);
1722
1723        let mut result1 = TracingResult::new(
1724            HashSet::from([(
1725                address1.clone(),
1726                AddressStorageLocation::new(store_key1.clone(), 12),
1727            )]),
1728            HashMap::from([
1729                (address2.clone(), HashSet::from([store_key1.clone()])),
1730                (address3.clone(), HashSet::from([store_key2.clone()])),
1731            ]),
1732        );
1733
1734        let result2 = TracingResult::new(
1735            HashSet::from([(
1736                address3.clone(),
1737                AddressStorageLocation::new(store_key2.clone(), 12),
1738            )]),
1739            HashMap::from([
1740                (address1.clone(), HashSet::from([store_key1.clone()])),
1741                (address2.clone(), HashSet::from([store_key2.clone()])),
1742            ]),
1743        );
1744
1745        result1.merge(result2);
1746
1747        // Verify retriggers were merged
1748        assert_eq!(result1.retriggers.len(), 2);
1749        assert!(result1
1750            .retriggers
1751            .contains(&(address1.clone(), AddressStorageLocation::new(store_key1.clone(), 12))));
1752        assert!(result1
1753            .retriggers
1754            .contains(&(address3.clone(), AddressStorageLocation::new(store_key2.clone(), 12))));
1755
1756        // Verify accessed slots were merged
1757        assert_eq!(result1.accessed_slots.len(), 3);
1758        assert!(result1
1759            .accessed_slots
1760            .contains_key(&address1));
1761        assert!(result1
1762            .accessed_slots
1763            .contains_key(&address2));
1764        assert!(result1
1765            .accessed_slots
1766            .contains_key(&address3));
1767
1768        assert_eq!(
1769            result1
1770                .accessed_slots
1771                .get(&address2)
1772                .unwrap(),
1773            &HashSet::from([store_key1, store_key2])
1774        );
1775    }
1776
1777    #[test]
1778    fn test_entry_point_with_tracing_params_display() {
1779        use std::str::FromStr;
1780
1781        let entry_point = EntryPoint::new(
1782            "uniswap_v3_pool_swap".to_string(),
1783            Address::from_str("0x1234567890123456789012345678901234567890").unwrap(),
1784            "swapExactETHForTokens(uint256,address[],address,uint256)".to_string(),
1785        );
1786
1787        let tracing_params = TracingParams::RPCTracer(RPCTracerParams::new(
1788            Some(Address::from_str("0x9876543210987654321098765432109876543210").unwrap()),
1789            Bytes::from_str("0xabcdef").unwrap(),
1790        ));
1791
1792        let entry_point_with_params = EntryPointWithTracingParams::new(entry_point, tracing_params);
1793
1794        let display_output = entry_point_with_params.to_string();
1795        assert_eq!(display_output, "uniswap_v3_pool_swap [RPC]");
1796    }
1797
1798    #[test]
1799    fn test_traced_entry_point_display() {
1800        use std::str::FromStr;
1801
1802        let entry_point = EntryPoint::new(
1803            "uniswap_v3_pool_swap".to_string(),
1804            Address::from_str("0x1234567890123456789012345678901234567890").unwrap(),
1805            "swapExactETHForTokens(uint256,address[],address,uint256)".to_string(),
1806        );
1807
1808        let tracing_params = TracingParams::RPCTracer(RPCTracerParams::new(
1809            Some(Address::from_str("0x9876543210987654321098765432109876543210").unwrap()),
1810            Bytes::from_str("0xabcdef").unwrap(),
1811        ));
1812
1813        let entry_point_with_params = EntryPointWithTracingParams::new(entry_point, tracing_params);
1814
1815        // Create tracing result with 2 retriggers and 3 accessed addresses
1816        let address1 = Address::from_str("0x1111111111111111111111111111111111111111").unwrap();
1817        let address2 = Address::from_str("0x2222222222222222222222222222222222222222").unwrap();
1818        let address3 = Address::from_str("0x3333333333333333333333333333333333333333").unwrap();
1819
1820        let store_key1 = StoreKey::from(vec![1, 2, 3, 4]);
1821        let store_key2 = StoreKey::from(vec![5, 6, 7, 8]);
1822
1823        let tracing_result = TracingResult::new(
1824            HashSet::from([
1825                (address1.clone(), AddressStorageLocation::new(store_key1.clone(), 0)),
1826                (address2.clone(), AddressStorageLocation::new(store_key2.clone(), 12)),
1827            ]),
1828            HashMap::from([
1829                (address1, HashSet::from([store_key1.clone()])),
1830                (address2, HashSet::from([store_key2])),
1831                (address3, HashSet::from([store_key1])),
1832            ]),
1833        );
1834
1835        let traced_entry_point = TracedEntryPoint::new(
1836            entry_point_with_params,
1837            Bytes::from_str("0xabcdef1234567890").unwrap(),
1838            tracing_result,
1839        );
1840
1841        let display_output = traced_entry_point.to_string();
1842        assert_eq!(display_output, "[uniswap_v3_pool_swap: 2 retriggers, 3 accessed addresses]");
1843    }
1844
1845    fn ids(ids: &[&str]) -> HashSet<ComponentId> {
1846        ids.iter()
1847            .map(|id| id.to_string())
1848            .collect()
1849    }
1850
1851    fn pause_changes(paused: &[&str], unpaused: &[&str]) -> BlockAggregatedChanges {
1852        BlockAggregatedChanges {
1853            paused_components: ids(paused),
1854            unpaused_components: ids(unpaused),
1855            ..Default::default()
1856        }
1857    }
1858
1859    #[rstest]
1860    #[case::pause_then_unpause(pause_changes(&["a"], &[]), pause_changes(&[], &["a"]), &[], &["a"])]
1861    #[case::unpause_then_pause(pause_changes(&[], &["a"]), pause_changes(&["a"], &[]), &["a"], &[])]
1862    #[case::disjoint_ids(pause_changes(&["a"], &["b"]), pause_changes(&["c"], &["d"]), &["a", "c"], &["b", "d"])]
1863    fn test_block_aggregated_changes_merge_pause_events(
1864        #[case] earlier: BlockAggregatedChanges,
1865        #[case] later: BlockAggregatedChanges,
1866        #[case] expected_paused: &[&str],
1867        #[case] expected_unpaused: &[&str],
1868    ) {
1869        let merged = earlier.merge(later);
1870
1871        assert_eq!(merged.paused_components, ids(expected_paused));
1872        assert_eq!(merged.unpaused_components, ids(expected_unpaused));
1873    }
1874
1875    #[test]
1876    fn test_block_aggregated_changes_drop_state_keeps_pause_events() {
1877        let changes = pause_changes(&["a"], &["b"]);
1878
1879        let dropped = changes.drop_state();
1880
1881        assert_eq!(dropped.paused_components, ids(&["a"]));
1882        assert_eq!(dropped.unpaused_components, ids(&["b"]));
1883    }
1884}