Skip to main content

tycho_common/
storage.rs

1//! Storage traits used by Tycho
2use std::{
3    collections::{HashMap, HashSet},
4    fmt::Display,
5};
6
7use async_trait::async_trait;
8use chrono::NaiveDateTime;
9use thiserror::Error;
10
11use crate::{
12    dto,
13    models::{
14        blockchain::{
15            Block, EntryPoint, EntryPointWithTracingParams, TracedEntryPoint, TracedEntryPoints,
16            TracingParams, TracingResult, Transaction,
17        },
18        contract::{Account, AccountBalance, AccountDelta},
19        protocol::{
20            ComponentBalance, ComponentPause, PauseRecord, ProtocolComponent,
21            ProtocolComponentState, ProtocolComponentStateDelta, QualityRange, UnpauseRecord,
22        },
23        token::Token,
24        Address, Balance, BlockHash, Chain, Code, CodeHash, ComponentId, ContractId, EntryPointId,
25        ExtractionState, PaginationParams, ProtocolSystem, ProtocolType, StoreKey, StoreVal,
26        TxHash,
27    },
28    Bytes,
29};
30
31/// Identifies a block in storage.
32#[derive(Debug, Clone, PartialEq, Hash, Eq)]
33pub enum BlockIdentifier {
34    /// Identifies the block by its position on a specified chain.
35    ///
36    /// This form of identification has potential risks as it may become
37    /// ambiguous in certain situations. For example, if the block has not been
38    /// finalised, there exists a possibility of forks occurring. As a result,
39    /// the same number could refer to different blocks on different forks.
40    Number((Chain, i64)),
41
42    /// Identifies a block by its hash.
43    ///
44    /// The hash should be unique across multiple chains. Preferred method if
45    /// the block is very recent.
46    Hash(BlockHash),
47
48    /// Latest stored block for the target chain
49    ///
50    /// Returns the block with the highest block number on the target chain.
51    Latest(Chain),
52}
53
54impl Display for BlockIdentifier {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        write!(f, "{self:?}")
57    }
58}
59
60#[derive(Error, Debug, PartialEq, Clone)]
61pub enum StorageError {
62    #[error("Could not find {0} with id `{1}`!")]
63    NotFound(String, String),
64    #[error("The entity {0} with id {1} was already present!")]
65    DuplicateEntry(String, String),
66    #[error("Could not find related {0} for {1} with id `{2}`!")]
67    NoRelatedEntity(String, String, String),
68    #[error("DecodeError: {0}")]
69    DecodeError(String),
70    #[error("Unexpected storage error: {0}")]
71    Unexpected(String),
72    #[error("Currently unsupported operation: {0}")]
73    Unsupported(String),
74    #[error("Write cache unexpectedly dropped notification channel!")]
75    WriteCacheGoneAway(),
76    #[error("Invalid block range encountered")]
77    InvalidBlockRange(),
78    #[error(
79        "Write rejected: this process claimed writer epoch {claimed} but the database is at \
80         epoch {current}, so another process took over writing"
81    )]
82    Fenced { claimed: i64, current: i64 },
83}
84
85/// Storage methods for chain specific objects.
86///
87/// This trait abstracts the specific implementation details of a blockchain's
88/// entities, allowing the user to add and retrieve blocks and transactions in a
89/// generic way.
90///
91/// For traceability protocol components and contracts changes are linked to
92/// blocks of their respective chain if applicable. This means while indexing we
93/// need to keep a lightweight and cross chain compatible representation of
94/// blocks and transactions in storage.
95///
96/// It's defined generically over two associated types:
97///
98/// * `Block`: represents a block in the blockchain.
99/// * `Transaction`: represents a transaction within a block.
100#[async_trait]
101pub trait ChainGateway {
102    /// Upserts a new block to the blockchain's storage.
103    ///
104    /// Ignores any existing tx, if the new entry has different attributes
105    /// no error is raised and the old entry is kept.
106    ///
107    /// # Parameters
108    /// - `new`: An instance of `Self::Block`, representing the new block to be stored.
109    ///
110    /// # Returns
111    /// - Empty ok result indicates success. Failure might occur if the block is already present.
112    async fn upsert_block(&self, new: &[Block]) -> Result<(), StorageError>;
113    /// Retrieves a block from storage.
114    ///
115    /// # Parameters
116    /// - `id`: Block's unique identifier of type `BlockIdentifier`.
117    ///
118    /// # Returns
119    /// - An Ok result containing the block. Might fail if the block does not exist yet.
120    async fn get_block(&self, id: &BlockIdentifier) -> Result<Block, StorageError>;
121    /// Upserts a transaction to storage.
122    ///
123    /// Ignores any existing tx, if the new entry has different attributes
124    /// no error is raised and the old entry is kept.
125    ///
126    /// # Parameters
127    /// - `new`: An instance of `Self::Transaction`, representing the new transaction to be stored.
128    ///
129    /// # Returns
130    /// - Empty ok result indicates success. Failure might occur if the
131    /// corresponding block does not exists yet, or if the transaction already
132    /// exists.
133    async fn upsert_tx(&self, new: &[Transaction]) -> Result<(), StorageError>;
134
135    /// Tries to retrieve a transaction from the blockchain's storage using its
136    /// hash.
137    ///
138    /// # Parameters
139    /// - `hash`: The byte slice representing the hash of the transaction to be retrieved.
140    ///
141    /// # Returns
142    /// - An Ok result containing the transaction. Might fail if the transaction does not exist yet.
143    async fn get_tx(&self, hash: &TxHash) -> Result<Transaction, StorageError>;
144
145    /// Reverts the blockchain storage to a previous version.
146    ///
147    /// Reverting state signifies deleting database history. Only the main branch will be kept.
148    ///
149    /// Blocks that are greater than the provided block (`to`) are deleted and any versioned rows
150    /// which were invalidated in the deleted blocks are updated to be valid again.
151    ///
152    /// # Parameters
153    /// - `to` The version to revert to. Given a block uses VersionKind::Last behaviour.
154    /// - `db` The database gateway.
155    ///
156    /// # Returns
157    /// - An Ok if the revert is successful, or a `StorageError` if not.
158    async fn revert_state(&self, to: &BlockIdentifier) -> Result<(), StorageError>;
159}
160
161/// Store and retrieve state of Extractors.
162///
163/// Sometimes extractors may wish to persist their state across restart. E.g.
164/// substreams based extractors need to store the cursor, so they can continue
165/// processing where they left off.
166///
167/// Extractors are uniquely identified by a name and the respective chain which
168/// they are indexing.
169#[async_trait]
170pub trait ExtractionStateGateway {
171    /// Retrieves the state of an extractor instance from a storage.
172    ///
173    /// # Parameters
174    /// - `name` A unique name for the extractor instance.
175    /// - `chain` The chain this extractor is indexing.
176    ///
177    /// # Returns
178    /// Ok if the corrsponding state was retrieved successfully, Err in
179    /// case the state was not found.
180    async fn get_state(&self, name: &str, chain: &Chain) -> Result<ExtractionState, StorageError>;
181
182    /// Saves the state of an extractor instance to a storage.
183    ///
184    /// Creates an entry if not present yet, or updates an already existing
185    /// entry.
186    ///
187    /// # Parameters
188    /// - `state` The state of the extractor that needs to be saved.
189    ///
190    /// # Returns
191    /// Ok, if state was stored successfully, Err if the state is not valid.
192    async fn save_state(&self, state: &ExtractionState) -> Result<(), StorageError>;
193}
194
195/// Point in time as either block or timestamp. If a block is chosen it
196/// timestamp attribute is used.
197#[derive(Debug, Clone, PartialEq, Hash, Eq)]
198pub enum BlockOrTimestamp {
199    Block(BlockIdentifier),
200    Timestamp(NaiveDateTime),
201}
202
203#[expect(deprecated, reason = "reads the deprecated chain field of BlockParam")]
204impl TryFrom<&dto::VersionParam> for BlockOrTimestamp {
205    type Error = anyhow::Error;
206
207    fn try_from(version: &dto::VersionParam) -> Result<Self, Self::Error> {
208        match (&version.timestamp, &version.block) {
209            (_, Some(block)) => {
210                // If a full block is provided, we prioritize hash over number and chain
211                let block_identifier = match (&block.hash, &block.chain, &block.number) {
212                    (Some(hash), _, _) => BlockIdentifier::Hash(hash.clone()),
213                    (_, Some(chain), Some(number)) => {
214                        BlockIdentifier::Number((Chain::from(*chain), *number))
215                    }
216                    _ => {
217                        return Err(anyhow::format_err!("Insufficient block information".to_owned()))
218                    }
219                };
220                Ok(BlockOrTimestamp::Block(block_identifier))
221            }
222            (Some(timestamp), None) => Ok(BlockOrTimestamp::Timestamp(*timestamp)),
223            (None, None) => {
224                Err(anyhow::format_err!("Missing timestamp or block identifier".to_owned()))
225            }
226        }
227    }
228}
229
230/// References certain states within a single block.
231///
232/// **Note:** Not all methods that take a version will support all version kinds,
233/// the versions here are included for completeness and to document the
234/// retrieval behaviour that is possible with the storage layout. Please refer
235/// to the individual implementation for information about which version kinds
236/// it supports.
237#[derive(Debug, Clone, Default)]
238pub enum VersionKind {
239    /// Represents the final state within a specific block. Essentially, it
240    /// retrieves the state subsequent to the execution of the last transaction
241    /// executed in that block.
242    #[default]
243    Last,
244    /// Represents the initial state of a specific block. In other words,
245    /// it is the state before any transaction has been executed within that block.
246    First,
247    /// Represents a specific transactions indexed position within a block.
248    /// It includes the state after executing the transaction at that index.
249    Index(i64),
250}
251
252/// A version desribes the state of the DB at a exact point in time.
253/// See the module level docs for more information on how versioning works.
254#[derive(Debug, Clone)]
255pub struct Version(pub BlockOrTimestamp, pub VersionKind);
256
257impl Version {
258    pub fn from_block_number(chain: Chain, number: i64) -> Self {
259        Self(BlockOrTimestamp::Block(BlockIdentifier::Number((chain, number))), VersionKind::Last)
260    }
261    pub fn from_ts(ts: NaiveDateTime) -> Self {
262        Self(BlockOrTimestamp::Timestamp(ts), VersionKind::Last)
263    }
264}
265
266// Helper type to retrieve entities with their total retrievable count.
267#[derive(Debug)]
268pub struct WithTotal<T> {
269    pub entity: T,
270    pub total: Option<i64>,
271}
272
273/// Store and retrieve protocol related structs.
274///
275/// This trait defines how to retrieve protocol components, state as well as
276/// tokens from storage.
277#[async_trait]
278pub trait ProtocolGateway {
279    /// Retrieve ProtocolComponent from the db
280    ///
281    /// # Parameters
282    /// - `chain` The chain of the component
283    /// - `system` Allows to optionally filter by system.
284    /// - `ids` Allows to optionally filter by id.
285    /// - `min_tvl` Allows to optionally filter by min tvl.
286    /// - `pagination_params` Optional pagination parameters to control the number of results.
287    ///
288    /// # Returns
289    /// Ok, if found else Err
290    async fn get_protocol_components(
291        &self,
292        chain: &Chain,
293        system: Option<String>,
294        ids: Option<&[&str]>,
295        min_tvl: Option<f64>,
296        pagination_params: Option<&PaginationParams>,
297    ) -> Result<WithTotal<Vec<ProtocolComponent>>, StorageError>;
298
299    /// Looks up the protocol system of components.
300    ///
301    /// # Parameters
302    /// - `chain` The chain of the components.
303    /// - `ids` The external ids of the components.
304    ///
305    /// # Returns
306    /// The protocol system of each id that has a component on the chain. Leaves out ids with no
307    /// component and ids whose component was deleted. Err if storage access failed.
308    async fn get_component_protocol_systems(
309        &self,
310        chain: &Chain,
311        ids: &[&str],
312    ) -> Result<HashMap<ComponentId, ProtocolSystem>, StorageError>;
313
314    /// Retrieves owners of tokens
315    ///
316    /// Queries for owners (protocol components) of tokens that have a certain minimum
317    /// balance and returns a maximum aggregate of those in case there are multiple
318    /// owners.
319    ///
320    /// # Parameters
321    /// - `chain` The chain of the component
322    /// - `tokens` The tokens to query for, any component with at least one of these tokens is
323    ///   returned.
324    /// - `min_balance` A minimum balance we expect the component to have on any of the tokens
325    ///   mentioned in `tokens`.
326    async fn get_token_owners(
327        &self,
328        chain: &Chain,
329        tokens: &[Address],
330        min_balance: Option<f64>,
331    ) -> Result<HashMap<Address, (ComponentId, Bytes)>, StorageError>;
332
333    async fn add_protocol_components(&self, new: &[ProtocolComponent]) -> Result<(), StorageError>;
334
335    async fn delete_protocol_components(
336        &self,
337        to_delete: &[ProtocolComponent],
338        block_ts: NaiveDateTime,
339    ) -> Result<(), StorageError>;
340
341    /// Stores new found ProtocolTypes.
342    ///
343    /// # Parameters
344    /// - `new_protocol_types`  The new protocol types.
345    ///
346    /// # Returns
347    /// Ok if stored successfully.
348    async fn add_protocol_types(
349        &self,
350        new_protocol_types: &[ProtocolType],
351    ) -> Result<(), StorageError>;
352
353    /// Retrieve protocol component states
354    ///
355    /// This resource is versioned, the version can be specified by either block
356    /// or timestamp, for off-chain components, a block version will error.
357    ///
358    /// As the state is retained on a transaction basis on blockchain systems, a
359    /// single version may relate to more than one state. In these cases a
360    /// versioned result is returned, if requesting `Version:All` with the
361    /// latest entry being the state at the end of the block and the first entry
362    /// represents the first change to the state within the block.
363    ///
364    /// # Parameters
365    /// - `chain` The chain of the component
366    /// - `at` The version at which the state is valid at.
367    /// - `system` The protocol system this component belongs to
368    /// - `ids` The external ids of the components e.g. addresses, or the pairs
369    /// - `retrieve_balances` Whether to retrieve the balances for the components.
370    /// - `pagination_params` Optional pagination parameters to control the number of results.
371    async fn get_protocol_states(
372        &self,
373        chain: &Chain,
374        at: Option<Version>,
375        system: Option<String>,
376        ids: Option<&[&str]>,
377        retrieve_balances: bool,
378        pagination_params: Option<&PaginationParams>,
379    ) -> Result<WithTotal<Vec<ProtocolComponentState>>, StorageError>;
380
381    async fn update_protocol_states(
382        &self,
383        new: &[(TxHash, ProtocolComponentStateDelta)],
384    ) -> Result<(), StorageError>;
385
386    /// Retrieves a tokens from storage
387    ///
388    /// # Parameters
389    /// - `chain` The chain this token is implemented on.
390    /// - `address` The address for the token within the chain.
391    /// - `quality` The quality of the token.
392    /// - `traded_n_days_ago` The number of days ago the token was traded.
393    /// - `pagination_params` Optional pagination parameters to control the number of results.
394    ///
395    /// # Returns
396    /// Ok if the results could be retrieved from the storage, else errors.
397    async fn get_tokens(
398        &self,
399        chain: Chain,
400        address: Option<&[&Address]>,
401        quality: QualityRange,
402        traded_n_days_ago: Option<NaiveDateTime>,
403        pagination_params: Option<&PaginationParams>,
404    ) -> Result<WithTotal<Vec<Token>>, StorageError>;
405
406    /// Saves multiple component balances to storage.
407    ///
408    /// # Parameters
409    /// - `component_balances` The component balances to insert.
410    ///
411    /// # Return
412    /// Ok if all component balances could be inserted, Err if at least one token failed to
413    /// insert.
414    async fn add_component_balances(
415        &self,
416        component_balances: &[ComponentBalance],
417    ) -> Result<(), StorageError>;
418
419    /// Saves multiple tokens to storage.
420    ///
421    /// Inserts token into storage. Tokens and their properties are assumed to
422    /// be immutable.
423    ///
424    /// # Parameters
425    /// - `tokens` The tokens to insert.
426    ///
427    /// # Return
428    /// Ok if all tokens could be inserted, Err if at least one token failed to
429    /// insert.
430    async fn add_tokens(&self, tokens: &[Token]) -> Result<(), StorageError>;
431
432    /// Updates multiple tokens in storage.
433    ///
434    /// Updates token in storage. Will warn if one of the tokens does not exist in the
435    /// database. Currently assumes that token addresses are unique across chains.
436    ///
437    /// # Parameters
438    /// - `tokens` The tokens to update.
439    ///
440    /// # Return
441    /// Ok if all tokens could be inserted, Err if at least one token failed to
442    /// insert.
443    async fn update_tokens(&self, tokens: &[Token]) -> Result<(), StorageError>;
444
445    /// Retrieve protocol state changes
446    ///
447    /// Fetches all state changes that occurred for the given chain
448    ///
449    /// # Parameters
450    /// - `chain` The chain of the component
451    /// - `start_version` The version at which to start looking for changes at.
452    /// - `end_version` The version at which to stop looking for changes.
453    ///
454    /// # Return
455    /// A list of ProtocolStateDeltas containing all state changes, Err if no changes were found.
456    async fn get_protocol_states_delta(
457        &self,
458        chain: &Chain,
459        start_version: Option<&BlockOrTimestamp>,
460        end_version: &BlockOrTimestamp,
461    ) -> Result<Vec<ProtocolComponentStateDelta>, StorageError>;
462
463    /// Retrieve protocol component balance changes
464    ///
465    /// Fetches all balance changes that occurred for the given protocol system
466    ///
467    /// # Parameters
468    /// - `chain` The chain of the component
469    /// - `start_version` The version at which to start looking for changes at.
470    /// - `target_version` The version at which to stop looking for changes.
471    ///
472    /// # Return
473    /// A vec containing ComponentBalance objects for changed components.
474    async fn get_balance_deltas(
475        &self,
476        chain: &Chain,
477        start_version: Option<&BlockOrTimestamp>,
478        target_version: &BlockOrTimestamp,
479    ) -> Result<Vec<ComponentBalance>, StorageError>;
480
481    async fn get_component_balances(
482        &self,
483        chain: &Chain,
484        ids: Option<&[&str]>,
485        version: Option<&Version>,
486    ) -> Result<HashMap<String, HashMap<Bytes, ComponentBalance>>, StorageError>;
487
488    async fn get_token_prices(&self, chain: &Chain) -> Result<HashMap<Bytes, f64>, StorageError>;
489
490    async fn upsert_component_tvl(
491        &self,
492        chain: &Chain,
493        tvl_values: &HashMap<String, f64>,
494    ) -> Result<(), StorageError>;
495
496    /// Retrieve a list of actively supported protocol systems
497    ///
498    /// Fetches the list of protocol systems supported by the Tycho indexing service.
499    ///
500    /// # Parameters
501    /// - `chain` The chain for which to retrieve supported protocol systems.
502    /// - `pagination_params` Optional pagination parameters to control the number of results.
503    ///
504    /// # Return
505    /// A paginated list of supported protocol systems, along with the total count.
506    async fn get_protocol_systems(
507        &self,
508        chain: &Chain,
509        pagination_params: Option<&PaginationParams>,
510    ) -> Result<WithTotal<Vec<String>>, StorageError>;
511
512    /// Retrieve the components total value locked (TVL).
513    ///
514    /// # Parameters
515    /// - `chain` The chain for which to retrieve the total value locked
516    /// - `system` The protocol system for which to retrieve the total value locked
517    /// - `ids` The ids of the components to retrieve the total value locked for
518    /// - `pagination_params` Optional pagination parameters to control the number of results.
519    ///
520    /// # Return
521    /// A result with a map of component ids to their TVL. Err if storage access failed.
522    async fn get_component_tvls(
523        &self,
524        chain: &Chain,
525        system: Option<String>,
526        ids: Option<&[&str]>,
527        pagination_params: Option<&PaginationParams>,
528    ) -> Result<WithTotal<HashMap<String, f64>>, StorageError>;
529}
530
531/// Store and retrieve admin pauses of protocol components.
532#[async_trait]
533pub trait ComponentPauseGateway {
534    /// Records admin pauses of components.
535    ///
536    /// A component that is already paused keeps its existing pause and audit details. A
537    /// component can be paused before it is indexed. The call records every pause or none, so a
538    /// failed call can be retried as a whole.
539    ///
540    /// # Parameters
541    /// - `chain` The chain of the components.
542    /// - `system` The protocol system the components belong to.
543    /// - `pauses` The pauses to record. A repeated id keeps its first pause.
544    ///
545    /// # Returns
546    /// The ids of the components this call paused. Err if the protocol system is unknown or
547    /// storage access failed.
548    async fn pause_components(
549        &self,
550        chain: &Chain,
551        system: &str,
552        pauses: &[PauseRecord],
553    ) -> Result<Vec<ComponentId>, StorageError>;
554
555    /// Ends admin pauses of components.
556    ///
557    /// Ended pauses stay in storage as history. Ids with no pause under `system` are skipped.
558    ///
559    /// # Parameters
560    /// - `chain` The chain of the components.
561    /// - `system` The protocol system the pauses were recorded under.
562    /// - `component_ids` The external ids of the components to unpause.
563    /// - `unpause` Who ended the pauses and why, stored on every pause this call ends.
564    ///
565    /// # Returns
566    /// The ids whose pause this call ended. Err if the protocol system is unknown or storage
567    /// access failed.
568    async fn unpause_components(
569        &self,
570        chain: &Chain,
571        system: &str,
572        component_ids: &[&str],
573        unpause: &UnpauseRecord,
574    ) -> Result<Vec<ComponentId>, StorageError>;
575
576    /// Reads the admin pauses that are in effect.
577    ///
578    /// # Parameters
579    /// - `chain` The chain to read pauses for.
580    ///
581    /// # Returns
582    /// Every pause in effect on the chain, across all protocol systems, ordered by protocol
583    /// system and then component id. Err if storage access failed.
584    async fn get_component_pauses(
585        &self,
586        chain: &Chain,
587    ) -> Result<Vec<ComponentPause>, StorageError>;
588}
589
590/// Filters for entry points queries in the database.
591// Shalow but can be used to add more filters without breaking backwards compatibility in the future
592#[derive(Debug, Clone)]
593pub struct EntryPointFilter {
594    pub protocol_system: ProtocolSystem,
595    pub component_ids: Option<Vec<ComponentId>>,
596}
597
598impl EntryPointFilter {
599    pub fn new(protocol: ProtocolSystem) -> Self {
600        Self { protocol_system: protocol, component_ids: None }
601    }
602
603    pub fn with_component_ids(mut self, component_ids: Vec<ComponentId>) -> Self {
604        self.component_ids = Some(component_ids);
605        self
606    }
607}
608
609// Trait for entry point gateway operations.
610#[async_trait]
611pub trait EntryPointGateway {
612    /// Inserts a list of entry points into the database.
613    ///
614    /// # Arguments
615    /// * `entry_points` - The map of component ids to their entry points to insert.
616    ///
617    /// Note: This function ignores conflicts on inserts.
618    async fn insert_entry_points(
619        &self,
620        entry_points: &HashMap<ComponentId, HashSet<EntryPoint>>,
621    ) -> Result<(), StorageError>;
622
623    /// Inserts a list of entry points with their tracing params into the database.
624    ///
625    /// # Arguments
626    /// * `entry_points_params` - The map of entry points to their tracing params to insert and
627    ///   component id for the component linked to the params.
628    ///
629    /// Note: This function ignores conflicts on inserts.
630    async fn insert_entry_point_tracing_params(
631        &self,
632        entry_points_params: &HashMap<EntryPointId, HashSet<(TracingParams, ComponentId)>>,
633    ) -> Result<(), StorageError>;
634
635    /// Retrieves a map of component ids to a set of entry points from the database.
636    ///
637    /// # Arguments
638    /// * `filter` - The EntryPointFilter to apply to the query.
639    /// * `pagination_params` - The pagination parameters to apply to the query, if None, all
640    ///   results are returned.
641    ///
642    /// # Returns
643    /// A map of component ids to a set of entry points.
644    async fn get_entry_points(
645        &self,
646        filter: EntryPointFilter,
647        pagination_params: Option<&PaginationParams>,
648    ) -> Result<WithTotal<HashMap<ComponentId, HashSet<EntryPoint>>>, StorageError>;
649
650    /// Retrieves a map of component ids to a set of entry points with their tracing data from the
651    /// database.
652    ///
653    /// # Arguments
654    /// * `filter` - The EntryPointFilter to apply to the query.
655    /// * `pagination_params` - The pagination parameters to apply to the query, if None, all
656    ///   results are returned.
657    ///
658    /// # Returns
659    /// A map of component ids to a set of entry points with their tracing params.
660    async fn get_entry_points_tracing_params(
661        &self,
662        filter: EntryPointFilter,
663        pagination_params: Option<&PaginationParams>,
664    ) -> Result<WithTotal<HashMap<ComponentId, HashSet<EntryPointWithTracingParams>>>, StorageError>;
665
666    /// Upserts a list of traced entry points into the database. Updates the result if it already
667    /// exists for the same entry point and tracing params.
668    ///
669    /// # Arguments
670    /// * `traced_entry_points` - The list of traced entry points to upsert.
671    async fn upsert_traced_entry_points(
672        &self,
673        traced_entry_points: &[TracedEntryPoint],
674    ) -> Result<(), StorageError>;
675
676    /// Retrieves all tracing results for a set of entry points from the database.
677    ///
678    /// # Arguments
679    /// * `entry_points` - The set of entry points to retrieve tracing results for.
680    ///
681    /// # Returns
682    /// A map of entry point ids to a map of tracing params to tracing results.
683    async fn get_traced_entry_points(
684        &self,
685        entry_points: &HashSet<EntryPointId>,
686    ) -> Result<HashMap<EntryPointId, HashMap<TracingParams, TracingResult>>, StorageError>;
687
688    /// Retrieves the traced entry points of a set of components from the database.
689    ///
690    /// # Arguments
691    /// * `filter` - The EntryPointFilter to apply to the query.
692    /// * `pagination_params` - The pagination parameters to apply to the query, if None, all
693    ///   results are returned.
694    ///
695    /// # Returns
696    /// A map of component ids to the entry points with the tracing params linked to the
697    /// component, and their tracing results. Params without a tracing result are not included.
698    async fn get_traced_entry_points_by_component(
699        &self,
700        filter: EntryPointFilter,
701        pagination_params: Option<&PaginationParams>,
702    ) -> Result<WithTotal<TracedEntryPoints>, StorageError>;
703}
704
705/// Manage contracts and their state in storage.
706///
707/// Specifies how to retrieve, add and update contracts in storage.
708#[async_trait]
709pub trait ContractStateGateway {
710    /// Get a contracts state from storage
711    ///
712    /// This method retrieves a single contract from the database.
713    ///
714    /// # Parameters
715    /// - `id` The identifier for the contract.
716    /// - `version` Version at which to retrieve state for. None retrieves the latest state.
717    /// - `include_slots`: Flag to determine whether to include slot changes. If set to `true`, it
718    ///   includes storage slot.
719    async fn get_contract(
720        &self,
721        id: &ContractId,
722        version: Option<&Version>,
723        include_slots: bool,
724    ) -> Result<Account, StorageError>;
725
726    /// Get multiple contracts' states from storage.
727    ///
728    /// This method retrieves balance and code, and optionally storage, of
729    /// multiple contracts in a chain. It can optionally filter by given
730    /// addresses and retrieve state for specific versions.
731    ///
732    /// # Parameters:
733    /// - `chain`: The blockchain where the contracts reside.
734    /// - `addresses`: Filter for specific addresses. If set to `None`, it retrieves all indexed
735    ///   contracts in the chain.
736    /// - `version`: Version at which to retrieve state for. If set to `None`, it retrieves the
737    ///   latest state.
738    /// - `include_slots`: Flag to determine whether to include slot changes. If set to `true`, it
739    ///   includes storage slot.
740    /// - `pagination_params`: Optional pagination parameters to control the number of results.
741    ///
742    /// # Returns:
743    /// A `Result` with a list of contract states if the operation is
744    /// successful, or a `StorageError` if the operation fails.
745    async fn get_contracts(
746        &self,
747        chain: &Chain,
748        addresses: Option<&[Address]>,
749        version: Option<&Version>,
750        include_slots: bool,
751        pagination_params: Option<&PaginationParams>,
752    ) -> Result<WithTotal<Vec<Account>>, StorageError>;
753
754    /// Inserts a new contract into the database.
755    ///
756    /// Inserts only the static values of the contract. To insert the contract slots, balance and
757    /// code please use the `update_contracts` method.
758    ///
759    /// # Arguments
760    /// - `new`: A reference to the new contract state to be inserted.
761    ///
762    /// # Returns
763    /// - A Result with Ok if the operation was successful, and an Err containing `StorageError` if
764    ///   there was an issue inserting the contract into the database. E.g. if the contract already
765    ///   existed.
766    async fn insert_contract(&self, new: &Account) -> Result<(), StorageError>;
767
768    /// Update multiple contracts
769    ///
770    /// Given contract deltas, this method will batch all updates to contracts across a single
771    /// chain.
772    ///
773    /// As changes are versioned by transaction, each changeset needs to be associated with a
774    /// transaction hash. All references transaction are assumed to be already persisted.
775    ///
776    /// # Arguments
777    ///
778    /// - `new`: A reference to a slice of tuples where each tuple has a transaction hash (`TxHash`)
779    ///   and a reference to the state delta (`&Self::Delta`) for that transaction.
780    ///
781    /// # Returns
782    ///
783    /// A Result with `Ok` if the operation was successful, and an `Err` containing
784    /// `StorageError` if there was an issue updating the contracts in the database. E.g. if a
785    /// transaction can't be located by it's reference or accounts refer to a different chain then
786    /// the one specified.
787    async fn update_contracts(&self, new: &[(TxHash, AccountDelta)]) -> Result<(), StorageError>;
788
789    /// Mark a contract as deleted
790    ///
791    /// Issues a soft delete of the contract.
792    ///
793    /// # Parameters
794    /// - `id` The identifier for the contract.
795    /// - `at_tx` The transaction hash which deleted the contract. This transaction is assumed to be
796    ///   in storage already. None retrieves the latest state.
797    ///
798    /// # Returns
799    /// Ok if the deletion was successful, might Err if:
800    ///  - Contract is not present in storage.
801    ///  - Deletion transaction is not present in storage.
802    ///  - Contract was already deleted.
803    async fn delete_contract(&self, id: &ContractId, at_tx: &TxHash) -> Result<(), StorageError>;
804
805    /// Retrieve a account delta between two versions.
806    ///
807    /// Given start version V1 and end version V2, this method will return the
808    /// changes necessary to move from V1 to V2. So if V1 < V2, it will contain
809    /// the changes of all accounts that changed between the two versions with the
810    /// values corresponding to V2. If V2 < V1 then it will contain all the
811    /// slots that changed between the two versions with the values corresponding to V1.
812    ///
813    /// This method is mainly meant to handle reverts, but can also be used to create delta changes
814    /// between two historical version thus providing the basis for creating a backtestable stream
815    /// of messages.
816    ///
817    /// # Parameters
818    ///
819    /// - `chain` The chain for which to generate the delta changes.
820    /// - `start_version` The deltas start version, given a block uses VersionKind::Last behaviour.
821    ///   If None the latest version is assumed.
822    /// - `end_version` The deltas end version, given a block uses VersionKind::Last behaviour.
823    ///
824    /// # Note
825    ///
826    /// A choice to utilize `BlockOrTimestamp` has been made intentionally in
827    /// this scenario as passing a `Version` by user isn't quite logical.
828    /// Support for deltas is limited to the states at the start or end of
829    /// blocks because blockchain reorganization at the transaction level is not
830    /// common.
831    ///
832    /// The decision to use either the beginning or end state of a block is
833    /// automatically determined by the underlying logic. For example, if we are
834    /// tracing back, `VersionKind::First` retrieval mode will be used.
835    /// Conversely, if we're progressing forward, we would apply the
836    /// `VersionKind::Last` semantics.
837    ///
838    /// # Returns
839    /// A map containing the necessary changes to update a state from start_version to end_version.
840    /// Errors if:
841    ///     - The versions can't be located in storage.
842    ///     - There was an error with the database
843    async fn get_accounts_delta(
844        &self,
845        chain: &Chain,
846        start_version: Option<&BlockOrTimestamp>,
847        end_version: &BlockOrTimestamp,
848    ) -> Result<Vec<AccountDelta>, StorageError>;
849
850    /// Saves multiple account balances to storage.
851    ///
852    /// # Parameters
853    /// - `account_balances` The account balances to insert.
854    ///
855    /// # Return
856    /// Ok if all account balances could be inserted, Err if at least one token failed to insert.
857    async fn add_account_balances(
858        &self,
859        account_balances: &[AccountBalance],
860    ) -> Result<(), StorageError>;
861
862    /// Retrieve account balances
863    ///
864    /// # Parameters
865    /// - `chain` The chain of the account balances
866    /// - `accounts` The accounts to query for. If set to `None`, it retrieves balances for all
867    ///   indexed
868    ///  accounts in the chain.
869    /// - `version` Version at which to retrieve balances for. If set to `None`, it retrieves the
870    ///   latest balances.
871    async fn get_account_balances(
872        &self,
873        chain: &Chain,
874        accounts: Option<&[Address]>,
875        version: Option<&Version>,
876    ) -> Result<HashMap<Address, HashMap<Address, AccountBalance>>, StorageError>;
877}
878
879pub trait Gateway:
880    ChainGateway
881    + ContractStateGateway
882    + ExtractionStateGateway
883    + ProtocolGateway
884    + ContractStateGateway
885    + EntryPointGateway
886    + Send
887    + Sync
888{
889}
890
891/// When a value was written: the timestamp of the writing block.
892///
893/// This is the unit of the database's `valid_from`, so the cache orders writes the way the
894/// database versions them. Block timestamps are unique per chain: the extractor adds a
895/// microsecond to a block that shares its second with the previous block. A block header supplies
896/// the timestamp; a snapshot row takes it from its `valid_from`.
897#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
898pub struct WriteTimestamp(NaiveDateTime);
899
900impl WriteTimestamp {
901    pub fn new(block_ts: NaiveDateTime) -> Self {
902        Self(block_ts)
903    }
904
905    pub fn block_ts(&self) -> NaiveDateTime {
906        self.0
907    }
908}
909
910impl From<&Block> for WriteTimestamp {
911    fn from(block: &Block) -> Self {
912        Self::new(block.ts)
913    }
914}
915
916/// Write timestamps of one account's values, one per database row.
917#[derive(Debug, Clone, PartialEq)]
918pub struct AccountWriteTimestamps {
919    pub slots: HashMap<StoreKey, WriteTimestamp>,
920    pub native_balance: WriteTimestamp,
921    pub code: WriteTimestamp,
922    pub token_balances: HashMap<Address, WriteTimestamp>,
923}
924
925impl AccountWriteTimestamps {
926    /// One timestamp for every value of `account`.
927    pub fn uniform(account: &Account, at: WriteTimestamp) -> Self {
928        Self {
929            slots: account
930                .slots
931                .keys()
932                .map(|key| (key.clone(), at))
933                .collect(),
934            native_balance: at,
935            code: at,
936            token_balances: account
937                .token_balances
938                .keys()
939                .map(|token| (token.clone(), at))
940                .collect(),
941        }
942    }
943}
944
945/// One account's live state and the write timestamp of every value: the row's `valid_from`.
946#[derive(Debug, Clone, PartialEq)]
947pub struct AccountSnapshot {
948    pub account: Account,
949    pub written_at: AccountWriteTimestamps,
950}
951
952/// One component's live state, timestamped with the newest `valid_from` among its rows or, for a
953/// component without rows, its `created_at`.
954#[derive(Debug, Clone, PartialEq)]
955pub struct ComponentSnapshot {
956    pub system: ProtocolSystem,
957    pub state: ProtocolComponentState,
958    pub updated_at: WriteTimestamp,
959}
960
961/// The stream cursor an extractor saved last, and the block that cursor points to. The extractor
962/// resumes after that block.
963#[derive(Debug, Clone, PartialEq)]
964pub struct ExtractorCursor {
965    pub cursor: Vec<u8>,
966    pub block: Block,
967}
968
969/// A point in the database's commit order, taken when a read starts. Every row version that the
970/// read cannot see carries this transaction id or a newer one.
971///
972/// "Snapshot" here is the Postgres transaction snapshot, the set of transactions a read can see
973/// (`pg_current_snapshot()`), not a [`StateSnapshot`]. The watermark is the `xmin` of that
974/// transaction snapshot, the oldest transaction that was still running when the read started, as
975/// a 64-bit transaction id.
976///
977/// The watermark also holds the block each extractor had committed in the same read. A later
978/// catch-up uses these blocks to find the oldest rows it must read through an index, instead of
979/// a scan of every row.
980#[derive(Debug, Clone, PartialEq, Eq)]
981pub struct CommitWatermark {
982    transaction_id: u64,
983    committed_blocks: HashMap<String, u64>,
984}
985
986impl CommitWatermark {
987    /// A watermark without committed blocks. A catch-up from it scans every row.
988    pub fn new(transaction_id: u64) -> Self {
989        Self { transaction_id, committed_blocks: HashMap::new() }
990    }
991
992    /// Sets the number of the block each extractor had committed when the read started, by
993    /// extractor name.
994    pub fn with_committed_blocks(mut self, committed_blocks: HashMap<String, u64>) -> Self {
995        self.committed_blocks = committed_blocks;
996        self
997    }
998
999    pub fn transaction_id(&self) -> u64 {
1000        self.transaction_id
1001    }
1002
1003    /// The number of the block each extractor had committed when the read started, keyed by
1004    /// extractor name. An extractor that had committed nothing has no entry.
1005    pub fn committed_blocks(&self) -> &HashMap<String, u64> {
1006        &self.committed_blocks
1007    }
1008}
1009
1010/// All live contracts and components of one chain, and the cursor of each extractor, read from
1011/// one transaction snapshot.
1012#[derive(Debug, Clone, PartialEq)]
1013pub struct StateSnapshot {
1014    pub accounts: Vec<AccountSnapshot>,
1015    pub components: Vec<ComponentSnapshot>,
1016    /// The cursor of each extractor, keyed by extractor name. An extractor that has committed
1017    /// nothing has no entry. The snapshot holds the data of every block of an extractor up to the
1018    /// block of its cursor, and of no later block.
1019    pub cursors: HashMap<String, ExtractorCursor>,
1020    /// Every row written after the snapshot is at or after this watermark.
1021    pub watermark: CommitWatermark,
1022}
1023
1024/// The values of one account written after a watermark, each timestamped with the block that
1025/// wrote its row. A deleted slot has an empty value.
1026#[derive(Debug, Clone, Default, PartialEq)]
1027pub struct AccountChanges {
1028    pub slots: HashMap<StoreKey, (StoreVal, WriteTimestamp)>,
1029    pub native_balance: Option<(Balance, WriteTimestamp)>,
1030    pub token_balances: HashMap<Address, (AccountBalance, WriteTimestamp)>,
1031    pub code: Option<(Code, CodeHash, WriteTimestamp)>,
1032}
1033
1034/// What a catch-up of the entity cache reads in one transaction. It holds the account rows of a
1035/// chain written after a watermark, and the full current state of the components of one protocol
1036/// system.
1037///
1038/// The account part can hold more than was written after the watermark, never less.
1039#[derive(Debug, Clone, PartialEq)]
1040pub struct CatchUpRead {
1041    /// The full state of each account whose own row was written after the watermark, which is
1042    /// each contract created since. Later changes to a contract go to its value rows, not to its
1043    /// account row. Deleted accounts and accounts without code are left out, as in a
1044    /// [`StateSnapshot`].
1045    pub accounts: Vec<AccountSnapshot>,
1046    /// The live values written after the watermark, keyed by account address. Covers every
1047    /// account of the chain, including the accounts in `accounts`.
1048    pub changes: HashMap<Address, AccountChanges>,
1049    /// Every live component of the requested protocol system with its full state, whether it
1050    /// changed after the watermark or not.
1051    pub components: Vec<ComponentSnapshot>,
1052    /// The cursor of each extractor, as in [`StateSnapshot::cursors`].
1053    pub cursors: HashMap<String, ExtractorCursor>,
1054    /// Every row written after this read is at or after this watermark.
1055    pub watermark: CommitWatermark,
1056}
1057
1058/// Reads the live contracts and components of a chain, each call from one transaction snapshot.
1059#[async_trait]
1060pub trait StateSnapshotGateway {
1061    /// All live accounts and components of `chain`, every value timestamped with the block
1062    /// that wrote its row, and the cursor of each extractor of `chain`.
1063    ///
1064    /// Implementations must read everything from one transaction snapshot: a row committed after
1065    /// the read starts is invisible to every part of the result. In SQL terms, a read-only
1066    /// `REPEATABLE READ` transaction or stricter.
1067    async fn state_snapshot(&self, chain: &Chain) -> Result<StateSnapshot, StorageError>;
1068
1069    /// The account rows of `chain` written at or after `since`, every live component of
1070    /// `system`, and the cursor of each extractor of `chain`. Read from one transaction snapshot,
1071    /// as [`Self::state_snapshot`].
1072    async fn catch_up_read(
1073        &self,
1074        chain: &Chain,
1075        since: CommitWatermark,
1076        system: &str,
1077    ) -> Result<CatchUpRead, StorageError>;
1078}