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