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    /// Retrieves owners of tokens
300    ///
301    /// Queries for owners (protocol components) of tokens that have a certain minimum
302    /// balance and returns a maximum aggregate of those in case there are multiple
303    /// owners.
304    ///
305    /// # Parameters
306    /// - `chain` The chain of the component
307    /// - `tokens` The tokens to query for, any component with at least one of these tokens is
308    ///   returned.
309    /// - `min_balance` A minimum balance we expect the component to have on any of the tokens
310    ///   mentioned in `tokens`.
311    async fn get_token_owners(
312        &self,
313        chain: &Chain,
314        tokens: &[Address],
315        min_balance: Option<f64>,
316    ) -> Result<HashMap<Address, (ComponentId, Bytes)>, StorageError>;
317
318    async fn add_protocol_components(&self, new: &[ProtocolComponent]) -> Result<(), StorageError>;
319
320    async fn delete_protocol_components(
321        &self,
322        to_delete: &[ProtocolComponent],
323        block_ts: NaiveDateTime,
324    ) -> Result<(), StorageError>;
325
326    /// Stores new found ProtocolTypes.
327    ///
328    /// # Parameters
329    /// - `new_protocol_types`  The new protocol types.
330    ///
331    /// # Returns
332    /// Ok if stored successfully.
333    async fn add_protocol_types(
334        &self,
335        new_protocol_types: &[ProtocolType],
336    ) -> Result<(), StorageError>;
337
338    /// Retrieve protocol component states
339    ///
340    /// This resource is versioned, the version can be specified by either block
341    /// or timestamp, for off-chain components, a block version will error.
342    ///
343    /// As the state is retained on a transaction basis on blockchain systems, a
344    /// single version may relate to more than one state. In these cases a
345    /// versioned result is returned, if requesting `Version:All` with the
346    /// latest entry being the state at the end of the block and the first entry
347    /// represents the first change to the state within the block.
348    ///
349    /// # Parameters
350    /// - `chain` The chain of the component
351    /// - `at` The version at which the state is valid at.
352    /// - `system` The protocol system this component belongs to
353    /// - `ids` The external ids of the components e.g. addresses, or the pairs
354    /// - `retrieve_balances` Whether to retrieve the balances for the components.
355    /// - `pagination_params` Optional pagination parameters to control the number of results.
356    async fn get_protocol_states(
357        &self,
358        chain: &Chain,
359        at: Option<Version>,
360        system: Option<String>,
361        ids: Option<&[&str]>,
362        retrieve_balances: bool,
363        pagination_params: Option<&PaginationParams>,
364    ) -> Result<WithTotal<Vec<ProtocolComponentState>>, StorageError>;
365
366    async fn update_protocol_states(
367        &self,
368        new: &[(TxHash, ProtocolComponentStateDelta)],
369    ) -> Result<(), StorageError>;
370
371    /// Retrieves a tokens from storage
372    ///
373    /// # Parameters
374    /// - `chain` The chain this token is implemented on.
375    /// - `address` The address for the token within the chain.
376    /// - `quality` The quality of the token.
377    /// - `traded_n_days_ago` The number of days ago the token was traded.
378    /// - `pagination_params` Optional pagination parameters to control the number of results.
379    ///
380    /// # Returns
381    /// Ok if the results could be retrieved from the storage, else errors.
382    async fn get_tokens(
383        &self,
384        chain: Chain,
385        address: Option<&[&Address]>,
386        quality: QualityRange,
387        traded_n_days_ago: Option<NaiveDateTime>,
388        pagination_params: Option<&PaginationParams>,
389    ) -> Result<WithTotal<Vec<Token>>, StorageError>;
390
391    /// Saves multiple component balances to storage.
392    ///
393    /// # Parameters
394    /// - `component_balances` The component balances to insert.
395    ///
396    /// # Return
397    /// Ok if all component balances could be inserted, Err if at least one token failed to
398    /// insert.
399    async fn add_component_balances(
400        &self,
401        component_balances: &[ComponentBalance],
402    ) -> Result<(), StorageError>;
403
404    /// Saves multiple tokens to storage.
405    ///
406    /// Inserts token into storage. Tokens and their properties are assumed to
407    /// be immutable.
408    ///
409    /// # Parameters
410    /// - `tokens` The tokens to insert.
411    ///
412    /// # Return
413    /// Ok if all tokens could be inserted, Err if at least one token failed to
414    /// insert.
415    async fn add_tokens(&self, tokens: &[Token]) -> Result<(), StorageError>;
416
417    /// Updates multiple tokens in storage.
418    ///
419    /// Updates token in storage. Will warn if one of the tokens does not exist in the
420    /// database. Currently assumes that token addresses are unique across chains.
421    ///
422    /// # Parameters
423    /// - `tokens` The tokens to update.
424    ///
425    /// # Return
426    /// Ok if all tokens could be inserted, Err if at least one token failed to
427    /// insert.
428    async fn update_tokens(&self, tokens: &[Token]) -> Result<(), StorageError>;
429
430    /// Retrieve protocol state changes
431    ///
432    /// Fetches all state changes that occurred for the given chain
433    ///
434    /// # Parameters
435    /// - `chain` The chain of the component
436    /// - `start_version` The version at which to start looking for changes at.
437    /// - `end_version` The version at which to stop looking for changes.
438    ///
439    /// # Return
440    /// A list of ProtocolStateDeltas containing all state changes, Err if no changes were found.
441    async fn get_protocol_states_delta(
442        &self,
443        chain: &Chain,
444        start_version: Option<&BlockOrTimestamp>,
445        end_version: &BlockOrTimestamp,
446    ) -> Result<Vec<ProtocolComponentStateDelta>, StorageError>;
447
448    /// Retrieve protocol component balance changes
449    ///
450    /// Fetches all balance changes that occurred for the given protocol system
451    ///
452    /// # Parameters
453    /// - `chain` The chain of the component
454    /// - `start_version` The version at which to start looking for changes at.
455    /// - `target_version` The version at which to stop looking for changes.
456    ///
457    /// # Return
458    /// A vec containing ComponentBalance objects for changed components.
459    async fn get_balance_deltas(
460        &self,
461        chain: &Chain,
462        start_version: Option<&BlockOrTimestamp>,
463        target_version: &BlockOrTimestamp,
464    ) -> Result<Vec<ComponentBalance>, StorageError>;
465
466    async fn get_component_balances(
467        &self,
468        chain: &Chain,
469        ids: Option<&[&str]>,
470        version: Option<&Version>,
471    ) -> Result<HashMap<String, HashMap<Bytes, ComponentBalance>>, StorageError>;
472
473    async fn get_token_prices(&self, chain: &Chain) -> Result<HashMap<Bytes, f64>, StorageError>;
474
475    async fn upsert_component_tvl(
476        &self,
477        chain: &Chain,
478        tvl_values: &HashMap<String, f64>,
479    ) -> Result<(), StorageError>;
480
481    /// Retrieve a list of actively supported protocol systems
482    ///
483    /// Fetches the list of protocol systems supported by the Tycho indexing service.
484    ///
485    /// # Parameters
486    /// - `chain` The chain for which to retrieve supported protocol systems.
487    /// - `pagination_params` Optional pagination parameters to control the number of results.
488    ///
489    /// # Return
490    /// A paginated list of supported protocol systems, along with the total count.
491    async fn get_protocol_systems(
492        &self,
493        chain: &Chain,
494        pagination_params: Option<&PaginationParams>,
495    ) -> Result<WithTotal<Vec<String>>, StorageError>;
496
497    /// Retrieve the components total value locked (TVL).
498    ///
499    /// # Parameters
500    /// - `chain` The chain for which to retrieve the total value locked
501    /// - `system` The protocol system for which to retrieve the total value locked
502    /// - `ids` The ids of the components to retrieve the total value locked for
503    /// - `pagination_params` Optional pagination parameters to control the number of results.
504    ///
505    /// # Return
506    /// A result with a map of component ids to their TVL. Err if storage access failed.
507    async fn get_component_tvls(
508        &self,
509        chain: &Chain,
510        system: Option<String>,
511        ids: Option<&[&str]>,
512        pagination_params: Option<&PaginationParams>,
513    ) -> Result<WithTotal<HashMap<String, f64>>, StorageError>;
514}
515
516/// Store and retrieve admin pauses of protocol components.
517#[async_trait]
518pub trait ComponentPauseGateway {
519    /// Records admin pauses of components.
520    ///
521    /// A component that is already paused keeps its existing pause and audit details. A
522    /// component can be paused before it is indexed. The call records every pause or none, so a
523    /// failed call can be retried as a whole.
524    ///
525    /// # Parameters
526    /// - `chain` The chain of the components.
527    /// - `system` The protocol system the components belong to.
528    /// - `pauses` The pauses to record. A repeated id keeps its first pause.
529    ///
530    /// # Returns
531    /// The ids of the components this call paused. Err if the protocol system is unknown or
532    /// storage access failed.
533    async fn pause_components(
534        &self,
535        chain: &Chain,
536        system: &str,
537        pauses: &[PauseRecord],
538    ) -> Result<Vec<ComponentId>, StorageError>;
539
540    /// Ends admin pauses of components.
541    ///
542    /// Ended pauses stay stored as history. Ids that are not paused are ignored.
543    ///
544    /// # Parameters
545    /// - `chain` The chain of the components.
546    /// - `component_ids` The external ids of the components to unpause.
547    /// - `unpause` Who ended the pauses and why, stored on every pause this call ends.
548    ///
549    /// # Returns
550    /// The ids of the components whose pause this call ended. Err if storage access failed.
551    async fn unpause_components(
552        &self,
553        chain: &Chain,
554        component_ids: &[&str],
555        unpause: &UnpauseRecord,
556    ) -> Result<Vec<ComponentId>, StorageError>;
557
558    /// Reads the admin pauses that are in effect.
559    ///
560    /// # Parameters
561    /// - `chain` The chain to read pauses for.
562    ///
563    /// # Returns
564    /// Every pause in effect on the chain, across all protocol systems. Err if storage access
565    /// failed.
566    async fn get_component_pauses(
567        &self,
568        chain: &Chain,
569    ) -> Result<Vec<ComponentPause>, StorageError>;
570}
571
572/// Filters for entry points queries in the database.
573// Shalow but can be used to add more filters without breaking backwards compatibility in the future
574#[derive(Debug, Clone)]
575pub struct EntryPointFilter {
576    pub protocol_system: ProtocolSystem,
577    pub component_ids: Option<Vec<ComponentId>>,
578}
579
580impl EntryPointFilter {
581    pub fn new(protocol: ProtocolSystem) -> Self {
582        Self { protocol_system: protocol, component_ids: None }
583    }
584
585    pub fn with_component_ids(mut self, component_ids: Vec<ComponentId>) -> Self {
586        self.component_ids = Some(component_ids);
587        self
588    }
589}
590
591// Trait for entry point gateway operations.
592#[async_trait]
593pub trait EntryPointGateway {
594    /// Inserts a list of entry points into the database.
595    ///
596    /// # Arguments
597    /// * `entry_points` - The map of component ids to their entry points to insert.
598    ///
599    /// Note: This function ignores conflicts on inserts.
600    async fn insert_entry_points(
601        &self,
602        entry_points: &HashMap<ComponentId, HashSet<EntryPoint>>,
603    ) -> Result<(), StorageError>;
604
605    /// Inserts a list of entry points with their tracing params into the database.
606    ///
607    /// # Arguments
608    /// * `entry_points_params` - The map of entry points to their tracing params to insert and
609    ///   component id for the component linked to the params.
610    ///
611    /// Note: This function ignores conflicts on inserts.
612    async fn insert_entry_point_tracing_params(
613        &self,
614        entry_points_params: &HashMap<EntryPointId, HashSet<(TracingParams, ComponentId)>>,
615    ) -> Result<(), StorageError>;
616
617    /// Retrieves a map of component ids to a set of entry points from the database.
618    ///
619    /// # Arguments
620    /// * `filter` - The EntryPointFilter to apply to the query.
621    /// * `pagination_params` - The pagination parameters to apply to the query, if None, all
622    ///   results are returned.
623    ///
624    /// # Returns
625    /// A map of component ids to a set of entry points.
626    async fn get_entry_points(
627        &self,
628        filter: EntryPointFilter,
629        pagination_params: Option<&PaginationParams>,
630    ) -> Result<WithTotal<HashMap<ComponentId, HashSet<EntryPoint>>>, StorageError>;
631
632    /// Retrieves a map of component ids to a set of entry points with their tracing data from the
633    /// database.
634    ///
635    /// # Arguments
636    /// * `filter` - The EntryPointFilter to apply to the query.
637    /// * `pagination_params` - The pagination parameters to apply to the query, if None, all
638    ///   results are returned.
639    ///
640    /// # Returns
641    /// A map of component ids to a set of entry points with their tracing params.
642    async fn get_entry_points_tracing_params(
643        &self,
644        filter: EntryPointFilter,
645        pagination_params: Option<&PaginationParams>,
646    ) -> Result<WithTotal<HashMap<ComponentId, HashSet<EntryPointWithTracingParams>>>, StorageError>;
647
648    /// Upserts a list of traced entry points into the database. Updates the result if it already
649    /// exists for the same entry point and tracing params.
650    ///
651    /// # Arguments
652    /// * `traced_entry_points` - The list of traced entry points to upsert.
653    async fn upsert_traced_entry_points(
654        &self,
655        traced_entry_points: &[TracedEntryPoint],
656    ) -> Result<(), StorageError>;
657
658    /// Retrieves all tracing results for a set of entry points from the database.
659    ///
660    /// # Arguments
661    /// * `entry_points` - The set of entry points to retrieve tracing results for.
662    ///
663    /// # Returns
664    /// A map of entry point ids to a map of tracing params to tracing results.
665    async fn get_traced_entry_points(
666        &self,
667        entry_points: &HashSet<EntryPointId>,
668    ) -> Result<HashMap<EntryPointId, HashMap<TracingParams, TracingResult>>, StorageError>;
669
670    /// Retrieves the traced entry points of a set of components from the database.
671    ///
672    /// # Arguments
673    /// * `filter` - The EntryPointFilter to apply to the query.
674    /// * `pagination_params` - The pagination parameters to apply to the query, if None, all
675    ///   results are returned.
676    ///
677    /// # Returns
678    /// A map of component ids to the entry points with the tracing params linked to the
679    /// component, and their tracing results. Params without a tracing result are not included.
680    async fn get_traced_entry_points_by_component(
681        &self,
682        filter: EntryPointFilter,
683        pagination_params: Option<&PaginationParams>,
684    ) -> Result<WithTotal<TracedEntryPoints>, StorageError>;
685}
686
687/// Manage contracts and their state in storage.
688///
689/// Specifies how to retrieve, add and update contracts in storage.
690#[async_trait]
691pub trait ContractStateGateway {
692    /// Get a contracts state from storage
693    ///
694    /// This method retrieves a single contract from the database.
695    ///
696    /// # Parameters
697    /// - `id` The identifier for the contract.
698    /// - `version` Version at which to retrieve state for. None retrieves the latest state.
699    /// - `include_slots`: Flag to determine whether to include slot changes. If set to `true`, it
700    ///   includes storage slot.
701    async fn get_contract(
702        &self,
703        id: &ContractId,
704        version: Option<&Version>,
705        include_slots: bool,
706    ) -> Result<Account, StorageError>;
707
708    /// Get multiple contracts' states from storage.
709    ///
710    /// This method retrieves balance and code, and optionally storage, of
711    /// multiple contracts in a chain. It can optionally filter by given
712    /// addresses and retrieve state for specific versions.
713    ///
714    /// # Parameters:
715    /// - `chain`: The blockchain where the contracts reside.
716    /// - `addresses`: Filter for specific addresses. If set to `None`, it retrieves all indexed
717    ///   contracts in the chain.
718    /// - `version`: Version at which to retrieve state for. If set to `None`, it retrieves the
719    ///   latest state.
720    /// - `include_slots`: Flag to determine whether to include slot changes. If set to `true`, it
721    ///   includes storage slot.
722    /// - `pagination_params`: Optional pagination parameters to control the number of results.
723    ///
724    /// # Returns:
725    /// A `Result` with a list of contract states if the operation is
726    /// successful, or a `StorageError` if the operation fails.
727    async fn get_contracts(
728        &self,
729        chain: &Chain,
730        addresses: Option<&[Address]>,
731        version: Option<&Version>,
732        include_slots: bool,
733        pagination_params: Option<&PaginationParams>,
734    ) -> Result<WithTotal<Vec<Account>>, StorageError>;
735
736    /// Inserts a new contract into the database.
737    ///
738    /// Inserts only the static values of the contract. To insert the contract slots, balance and
739    /// code please use the `update_contracts` method.
740    ///
741    /// # Arguments
742    /// - `new`: A reference to the new contract state to be inserted.
743    ///
744    /// # Returns
745    /// - A Result with Ok if the operation was successful, and an Err containing `StorageError` if
746    ///   there was an issue inserting the contract into the database. E.g. if the contract already
747    ///   existed.
748    async fn insert_contract(&self, new: &Account) -> Result<(), StorageError>;
749
750    /// Update multiple contracts
751    ///
752    /// Given contract deltas, this method will batch all updates to contracts across a single
753    /// chain.
754    ///
755    /// As changes are versioned by transaction, each changeset needs to be associated with a
756    /// transaction hash. All references transaction are assumed to be already persisted.
757    ///
758    /// # Arguments
759    ///
760    /// - `new`: A reference to a slice of tuples where each tuple has a transaction hash (`TxHash`)
761    ///   and a reference to the state delta (`&Self::Delta`) for that transaction.
762    ///
763    /// # Returns
764    ///
765    /// A Result with `Ok` if the operation was successful, and an `Err` containing
766    /// `StorageError` if there was an issue updating the contracts in the database. E.g. if a
767    /// transaction can't be located by it's reference or accounts refer to a different chain then
768    /// the one specified.
769    async fn update_contracts(&self, new: &[(TxHash, AccountDelta)]) -> Result<(), StorageError>;
770
771    /// Mark a contract as deleted
772    ///
773    /// Issues a soft delete of the contract.
774    ///
775    /// # Parameters
776    /// - `id` The identifier for the contract.
777    /// - `at_tx` The transaction hash which deleted the contract. This transaction is assumed to be
778    ///   in storage already. None retrieves the latest state.
779    ///
780    /// # Returns
781    /// Ok if the deletion was successful, might Err if:
782    ///  - Contract is not present in storage.
783    ///  - Deletion transaction is not present in storage.
784    ///  - Contract was already deleted.
785    async fn delete_contract(&self, id: &ContractId, at_tx: &TxHash) -> Result<(), StorageError>;
786
787    /// Retrieve a account delta between two versions.
788    ///
789    /// Given start version V1 and end version V2, this method will return the
790    /// changes necessary to move from V1 to V2. So if V1 < V2, it will contain
791    /// the changes of all accounts that changed between the two versions with the
792    /// values corresponding to V2. If V2 < V1 then it will contain all the
793    /// slots that changed between the two versions with the values corresponding to V1.
794    ///
795    /// This method is mainly meant to handle reverts, but can also be used to create delta changes
796    /// between two historical version thus providing the basis for creating a backtestable stream
797    /// of messages.
798    ///
799    /// # Parameters
800    ///
801    /// - `chain` The chain for which to generate the delta changes.
802    /// - `start_version` The deltas start version, given a block uses VersionKind::Last behaviour.
803    ///   If None the latest version is assumed.
804    /// - `end_version` The deltas end version, given a block uses VersionKind::Last behaviour.
805    ///
806    /// # Note
807    ///
808    /// A choice to utilize `BlockOrTimestamp` has been made intentionally in
809    /// this scenario as passing a `Version` by user isn't quite logical.
810    /// Support for deltas is limited to the states at the start or end of
811    /// blocks because blockchain reorganization at the transaction level is not
812    /// common.
813    ///
814    /// The decision to use either the beginning or end state of a block is
815    /// automatically determined by the underlying logic. For example, if we are
816    /// tracing back, `VersionKind::First` retrieval mode will be used.
817    /// Conversely, if we're progressing forward, we would apply the
818    /// `VersionKind::Last` semantics.
819    ///
820    /// # Returns
821    /// A map containing the necessary changes to update a state from start_version to end_version.
822    /// Errors if:
823    ///     - The versions can't be located in storage.
824    ///     - There was an error with the database
825    async fn get_accounts_delta(
826        &self,
827        chain: &Chain,
828        start_version: Option<&BlockOrTimestamp>,
829        end_version: &BlockOrTimestamp,
830    ) -> Result<Vec<AccountDelta>, StorageError>;
831
832    /// Saves multiple account balances to storage.
833    ///
834    /// # Parameters
835    /// - `account_balances` The account balances to insert.
836    ///
837    /// # Return
838    /// Ok if all account balances could be inserted, Err if at least one token failed to insert.
839    async fn add_account_balances(
840        &self,
841        account_balances: &[AccountBalance],
842    ) -> Result<(), StorageError>;
843
844    /// Retrieve account balances
845    ///
846    /// # Parameters
847    /// - `chain` The chain of the account balances
848    /// - `accounts` The accounts to query for. If set to `None`, it retrieves balances for all
849    ///   indexed
850    ///  accounts in the chain.
851    /// - `version` Version at which to retrieve balances for. If set to `None`, it retrieves the
852    ///   latest balances.
853    async fn get_account_balances(
854        &self,
855        chain: &Chain,
856        accounts: Option<&[Address]>,
857        version: Option<&Version>,
858    ) -> Result<HashMap<Address, HashMap<Address, AccountBalance>>, StorageError>;
859}
860
861pub trait Gateway:
862    ChainGateway
863    + ContractStateGateway
864    + ExtractionStateGateway
865    + ProtocolGateway
866    + ContractStateGateway
867    + EntryPointGateway
868    + Send
869    + Sync
870{
871}
872
873/// When a value was written: the timestamp of the writing block.
874///
875/// This is the unit of the database's `valid_from`, so the cache orders writes the way the
876/// database versions them. Block timestamps are unique per chain: the extractor adds a
877/// microsecond to a block that shares its second with the previous block. A block header supplies
878/// the timestamp; a snapshot row takes it from its `valid_from`.
879#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
880pub struct WriteTimestamp(NaiveDateTime);
881
882impl WriteTimestamp {
883    pub fn new(block_ts: NaiveDateTime) -> Self {
884        Self(block_ts)
885    }
886
887    pub fn block_ts(&self) -> NaiveDateTime {
888        self.0
889    }
890}
891
892impl From<&Block> for WriteTimestamp {
893    fn from(block: &Block) -> Self {
894        Self::new(block.ts)
895    }
896}
897
898/// Write timestamps of one account's values, one per database row.
899#[derive(Debug, Clone, PartialEq)]
900pub struct AccountWriteTimestamps {
901    pub slots: HashMap<StoreKey, WriteTimestamp>,
902    pub native_balance: WriteTimestamp,
903    pub code: WriteTimestamp,
904    pub token_balances: HashMap<Address, WriteTimestamp>,
905}
906
907impl AccountWriteTimestamps {
908    /// One timestamp for every value of `account`.
909    pub fn uniform(account: &Account, at: WriteTimestamp) -> Self {
910        Self {
911            slots: account
912                .slots
913                .keys()
914                .map(|key| (key.clone(), at))
915                .collect(),
916            native_balance: at,
917            code: at,
918            token_balances: account
919                .token_balances
920                .keys()
921                .map(|token| (token.clone(), at))
922                .collect(),
923        }
924    }
925}
926
927/// One account's live state and the write timestamp of every value: the row's `valid_from`.
928#[derive(Debug, Clone, PartialEq)]
929pub struct AccountSnapshot {
930    pub account: Account,
931    pub written_at: AccountWriteTimestamps,
932}
933
934/// One component's live state, timestamped with the newest `valid_from` among its rows or, for a
935/// component without rows, its `created_at`.
936#[derive(Debug, Clone, PartialEq)]
937pub struct ComponentSnapshot {
938    pub system: ProtocolSystem,
939    pub state: ProtocolComponentState,
940    pub updated_at: WriteTimestamp,
941}
942
943/// The stream cursor an extractor saved last, and the block that cursor points to. The extractor
944/// resumes after that block.
945#[derive(Debug, Clone, PartialEq)]
946pub struct ExtractorCursor {
947    pub cursor: Vec<u8>,
948    pub block: Block,
949}
950
951/// A point in the database's commit order, taken when a read starts. Every row version that the
952/// read cannot see carries this transaction id or a newer one.
953///
954/// "Snapshot" here is the Postgres transaction snapshot, the set of transactions a read can see
955/// (`pg_current_snapshot()`), not a [`StateSnapshot`]. The watermark is the `xmin` of that
956/// transaction snapshot, the oldest transaction that was still running when the read started, as
957/// a 64-bit transaction id.
958///
959/// The watermark also holds the block each extractor had committed in the same read. A later
960/// catch-up uses these blocks to find the oldest rows it must read through an index, instead of
961/// a scan of every row.
962#[derive(Debug, Clone, PartialEq, Eq)]
963pub struct CommitWatermark {
964    transaction_id: u64,
965    committed_blocks: HashMap<String, u64>,
966}
967
968impl CommitWatermark {
969    /// A watermark without committed blocks. A catch-up from it scans every row.
970    pub fn new(transaction_id: u64) -> Self {
971        Self { transaction_id, committed_blocks: HashMap::new() }
972    }
973
974    /// Sets the number of the block each extractor had committed when the read started, by
975    /// extractor name.
976    pub fn with_committed_blocks(mut self, committed_blocks: HashMap<String, u64>) -> Self {
977        self.committed_blocks = committed_blocks;
978        self
979    }
980
981    pub fn transaction_id(&self) -> u64 {
982        self.transaction_id
983    }
984
985    /// The number of the block each extractor had committed when the read started, keyed by
986    /// extractor name. An extractor that had committed nothing has no entry.
987    pub fn committed_blocks(&self) -> &HashMap<String, u64> {
988        &self.committed_blocks
989    }
990}
991
992/// All live contracts and components of one chain, and the cursor of each extractor, read from
993/// one transaction snapshot.
994#[derive(Debug, Clone, PartialEq)]
995pub struct StateSnapshot {
996    pub accounts: Vec<AccountSnapshot>,
997    pub components: Vec<ComponentSnapshot>,
998    /// The cursor of each extractor, keyed by extractor name. An extractor that has committed
999    /// nothing has no entry. The snapshot holds the data of every block of an extractor up to the
1000    /// block of its cursor, and of no later block.
1001    pub cursors: HashMap<String, ExtractorCursor>,
1002    /// Every row written after the snapshot is at or after this watermark.
1003    pub watermark: CommitWatermark,
1004}
1005
1006/// The values of one account written after a watermark, each timestamped with the block that
1007/// wrote its row. A deleted slot has an empty value.
1008#[derive(Debug, Clone, Default, PartialEq)]
1009pub struct AccountChanges {
1010    pub slots: HashMap<StoreKey, (StoreVal, WriteTimestamp)>,
1011    pub native_balance: Option<(Balance, WriteTimestamp)>,
1012    pub token_balances: HashMap<Address, (AccountBalance, WriteTimestamp)>,
1013    pub code: Option<(Code, CodeHash, WriteTimestamp)>,
1014}
1015
1016/// What a catch-up of the entity cache reads in one transaction. It holds the account rows of a
1017/// chain written after a watermark, and the full current state of the components of one protocol
1018/// system.
1019///
1020/// The account part can hold more than was written after the watermark, never less.
1021#[derive(Debug, Clone, PartialEq)]
1022pub struct CatchUpRead {
1023    /// The full state of each account whose own row was written after the watermark, which is
1024    /// each contract created since. Later changes to a contract go to its value rows, not to its
1025    /// account row. Deleted accounts and accounts without code are left out, as in a
1026    /// [`StateSnapshot`].
1027    pub accounts: Vec<AccountSnapshot>,
1028    /// The live values written after the watermark, keyed by account address. Covers every
1029    /// account of the chain, including the accounts in `accounts`.
1030    pub changes: HashMap<Address, AccountChanges>,
1031    /// Every live component of the requested protocol system with its full state, whether it
1032    /// changed after the watermark or not.
1033    pub components: Vec<ComponentSnapshot>,
1034    /// The cursor of each extractor, as in [`StateSnapshot::cursors`].
1035    pub cursors: HashMap<String, ExtractorCursor>,
1036    /// Every row written after this read is at or after this watermark.
1037    pub watermark: CommitWatermark,
1038}
1039
1040/// Reads the live contracts and components of a chain, each call from one transaction snapshot.
1041#[async_trait]
1042pub trait StateSnapshotGateway {
1043    /// All live accounts and components of `chain`, every value timestamped with the block
1044    /// that wrote its row, and the cursor of each extractor of `chain`.
1045    ///
1046    /// Implementations must read everything from one transaction snapshot: a row committed after
1047    /// the read starts is invisible to every part of the result. In SQL terms, a read-only
1048    /// `REPEATABLE READ` transaction or stricter.
1049    async fn state_snapshot(&self, chain: &Chain) -> Result<StateSnapshot, StorageError>;
1050
1051    /// The account rows of `chain` written at or after `since`, every live component of
1052    /// `system`, and the cursor of each extractor of `chain`. Read from one transaction snapshot,
1053    /// as [`Self::state_snapshot`].
1054    async fn catch_up_read(
1055        &self,
1056        chain: &Chain,
1057        since: CommitWatermark,
1058        system: &str,
1059    ) -> Result<CatchUpRead, StorageError>;
1060}