Skip to main content

BlockchainCacheDatabase

Struct BlockchainCacheDatabase 

Source
pub struct BlockchainCacheDatabase { /* private fields */ }
Expand description

Database interface for persisting and retrieving blockchain entities and domain objects.

Implementations§

Source§

impl BlockchainCacheDatabase

Source

pub async fn init(pg_options: PgConnectOptions) -> Self

Initializes a new database instance by establishing a connection to PostgreSQL.

§Panics

Panics if unable to connect to PostgreSQL with the provided options.

Source

pub async fn connect(pg_options: PgConnectOptions) -> Result<Self>

Establishes a connection to PostgreSQL and returns a new database instance.

§Errors

Returns an error if a connection cannot be established with the provided options.

Source

pub async fn seed_chain(&self, chain: &Chain) -> Result<()>

Seeds the database with a blockchain chain record.

§Errors

Returns an error if the database operation fails.

Source

pub async fn create_block_partition(&self, chain: &Chain) -> Result<String>

Creates a table partition for the block table specific to the given chain by calling the existing PostgreSQL function create_block_partition.

§Errors

Returns an error if the database operation fails.

Source

pub async fn create_token_partition(&self, chain: &Chain) -> Result<String>

Creates a table partition for the token table specific to the given chain by calling the existing PostgreSQL function create_token_partition.

§Errors

Returns an error if the database operation fails.

Source

pub async fn get_block_consistency_status( &self, chain: &Chain, ) -> Result<CachedBlocksConsistencyStatus>

Returns the highest block number that maintains data continuity in the database.

§Errors

Returns an error if the database query fails.

Source

pub async fn add_block(&self, chain_id: u32, block: &Block) -> Result<()>

Inserts or updates a block record in the database.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_blocks_batch( &self, chain_id: u32, blocks: &[Block], ) -> Result<()>

Inserts multiple blocks in a single database operation using UNNEST for optimal performance.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_event_blocks_batch( &self, chain_id: u32, blocks: &[Block], ) -> Result<()>

Inserts block timestamps observed while streaming pool events.

§Errors

Returns an error if the database operation fails.

Source

pub async fn ensure_pool_event_block_hash_schema(&self) -> Result<()>

Adds block-hash storage to databases created before hash-bound profiler checkpoints.

§Errors

Returns an error if the schema update fails.

Source

pub async fn add_blocks_copy( &self, chain_id: u32, blocks: &[Block], ) -> Result<()>

Inserts blocks using PostgreSQL COPY BINARY for maximum performance.

This method is significantly faster than INSERT for bulk operations as it bypasses SQL parsing and uses PostgreSQL’s native binary protocol.

§Errors

Returns an error if the COPY operation fails.

Source

pub async fn add_tokens_copy( &self, chain_id: u32, tokens: &[Token], ) -> Result<()>

Inserts tokens using PostgreSQL COPY BINARY for maximum performance.

§Errors

Returns an error if the COPY operation fails.

Source

pub async fn add_pools_copy(&self, chain_id: u32, pools: &[Pool]) -> Result<()>

Inserts pools using PostgreSQL COPY BINARY for maximum performance.

§Errors

Returns an error if the COPY operation fails.

Source

pub async fn add_pool_swaps_copy( &self, chain_id: u32, swaps: &[PoolSwap], ) -> Result<()>

Inserts pool swaps using PostgreSQL COPY BINARY for maximum performance.

This method is significantly faster than INSERT for bulk operations as it bypasses SQL parsing and uses PostgreSQL’s native binary protocol.

§Errors

Returns an error if the COPY operation fails.

Source

pub async fn add_pool_liquidity_updates_copy( &self, chain_id: u32, updates: &[PoolLiquidityUpdate], ) -> Result<()>

Inserts pool liquidity updates using PostgreSQL COPY BINARY for maximum performance.

This method is significantly faster than INSERT for bulk operations as it bypasses SQL parsing and uses PostgreSQL’s native binary protocol.

§Errors

Returns an error if the COPY operation fails.

Source

pub async fn copy_pool_fee_collects_batch( &self, chain_id: u32, collects: &[PoolFeeCollect], ) -> Result<()>

Inserts pool fee collect events using PostgreSQL COPY BINARY for maximum performance.

This method is significantly faster than INSERT for bulk operations as it bypasses SQL parsing and most database validation checks.

§Errors

Returns an error if the COPY operation fails.

Source

pub async fn load_block_timestamps( &self, chain: SharedChain, from_block: u64, ) -> Result<Vec<BlockTimestampRow>>

Retrieves block timestamps for a given chain starting from a specific block number.

§Errors

Returns an error if the database query fails.

Source

pub async fn add_dex(&self, dex: SharedDex) -> Result<()>

Adds or updates a DEX (Decentralized Exchange) record in the database.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool(&self, pool: &Pool) -> Result<()>

Adds or updates a liquidity pool/pair record in the database.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pools_batch(&self, pools: &[Pool]) -> Result<()>

Inserts multiple pools in a single database operation using UNNEST for optimal performance.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_swaps_batch( &self, chain_id: u32, swaps: &[PoolSwap], ) -> Result<()>

Inserts multiple pool swaps in a single database operation using UNNEST for optimal performance.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_liquidity_updates_batch( &self, chain_id: u32, updates: &[PoolLiquidityUpdate], ) -> Result<()>

Inserts multiple pool liquidity updates in a single database operation using UNNEST for optimal performance.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_token(&self, token: &Token) -> Result<()>

Adds or updates a token record in the database.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_invalid_token( &self, chain_id: u32, address: &Address, error_string: &str, ) -> Result<()>

Records an invalid token address with associated error information.

§Errors

Returns an error if the database insertion fails.

Source

pub async fn add_swap(&self, chain_id: u32, swap: &PoolSwap) -> Result<()>

Persists a token swap transaction event to the pool_swap table.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_liquidity_update( &self, chain_id: u32, liquidity_update: &PoolLiquidityUpdate, ) -> Result<()>

Persists a liquidity position change (mint/burn) event to the pool_liquidity table.

§Errors

Returns an error if the database operation fails.

Source

pub async fn load_tokens(&self, chain: SharedChain) -> Result<Vec<Token>>

Retrieves all valid token records for the given chain and converts them into Token domain objects.

Only returns tokens that do not contain error information, filtering out invalid tokens that were previously recorded with error details.

§Errors

Returns an error if the database query fails.

Source

pub async fn load_invalid_token_addresses( &self, chain_id: u32, ) -> Result<Vec<Address>>

Retrieves all invalid token addresses for a given chain.

§Errors

Returns an error if the database query fails or address validation fails.

Source

pub async fn load_pools( &self, chain: SharedChain, dex_id: &str, ) -> Result<Vec<PoolRow>>

Loads pool data from the database for the specified chain and DEX.

§Errors

Returns an error if the database query fails, the connection to the database is lost, or the query parameters are invalid.

Source

pub async fn load_pool( &self, chain: SharedChain, dex_id: &str, pool_identifier: &PoolIdentifier, ) -> Result<Option<PoolRow>>

Loads a single pool row by its identifier.

Returns None when the pool is not present in the database. Lets per-pool tools load only the pool they analyze instead of the whole DEX pool set (see load_pools).

§Errors

Returns an error if the database query fails.

Source

pub async fn toggle_perf_sync_settings(&self, enable: bool) -> Result<()>

Toggles performance optimization settings for sync operations.

When enabled (true), applies settings for maximum write performance:

  • synchronous_commit = OFF
  • work_mem increased for bulk operations

When disabled (false), restores default safe settings:

  • synchronous_commit = ON (data safety)
  • work_mem back to default
§Errors

Returns an error if the database operations fail.

Source

pub async fn update_dex_last_synced_block( &self, chain_id: u32, dex: &DexType, block_number: u64, ) -> Result<()>

Saves the checkpoint block number indicating the last completed pool synchronization for a specific DEX.

§Errors

Returns an error if the database operation fails.

Source

pub async fn update_pool_last_synced_block( &self, chain_id: u32, dex: &DexType, pool_identifier: &PoolIdentifier, block_number: u64, ) -> Result<()>

Updates the last synced block number for a pool.

§Errors

Returns an error if the database update fails.

Source

pub async fn get_dex_last_synced_block( &self, chain_id: u32, dex: &DexType, ) -> Result<Option<u64>>

Retrieves the saved checkpoint block number from the last completed pool synchronization for a specific DEX.

§Errors

Returns an error if the database query fails.

Source

pub async fn get_pool_last_synced_block( &self, chain_id: u32, dex: &DexType, pool_identifier: &PoolIdentifier, ) -> Result<Option<u64>>

Retrieves the last synced block number for a pool.

§Errors

Returns an error if the database query fails.

Source

pub async fn get_table_last_block( &self, chain_id: u32, table_name: &str, pool_identifier: &PoolIdentifier, ) -> Result<Option<u64>>

Retrieves the maximum block number from a specific table for a given pool. This is useful to detect orphaned data where events were inserted but progress wasn’t updated.

§Errors

Returns an error if the database query fails.

Source

pub async fn add_pool_collects_batch( &self, chain_id: u32, collects: &[PoolFeeCollect], ) -> Result<()>

Adds a batch of pool fee collect events to the database using batch operations.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_flash_batch( &self, chain_id: u32, flash_events: &[PoolFlash], ) -> Result<()>

Inserts multiple pool flash events in a single database operation using UNNEST for optimal performance.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_fee_protocol_updates_batch( &self, chain_id: u32, updates: &[PoolFeeProtocolUpdate], ) -> Result<()>

Inserts multiple pool fee-protocol update events in a single database operation using UNNEST.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_fee_protocol_collect_batch( &self, chain_id: u32, collects: &[PoolFeeProtocolCollect], ) -> Result<()>

Inserts multiple pool protocol-fee withdrawal events in a single database operation using UNNEST.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_snapshot( &self, chain_id: u32, dex_name: &DexType, pool_identifier: &PoolIdentifier, snapshot: &PoolSnapshot, ) -> Result<()>

Adds a pool snapshot to the database.

§Errors

Returns an error if the database insert fails.

Source

pub async fn add_pool_positions_batch( &self, chain_id: u32, snapshot_block: u64, snapshot_transaction_index: u32, snapshot_log_index: u32, positions: &[(PoolIdentifier, PoolPosition)], ) -> Result<()>

Inserts multiple pool positions in a single database operation using UNNEST for optimal performance.

§Errors

Returns an error if the database operation fails.

Source

pub async fn add_pool_ticks_batch( &self, chain_id: u32, snapshot_block: u64, snapshot_transaction_index: u32, snapshot_log_index: u32, ticks: &[(PoolIdentifier, &PoolTick)], ) -> Result<()>

Inserts multiple pool ticks in a single database operation using UNNEST for optimal performance.

§Errors

Returns an error if the database operation fails.

Source

pub async fn update_pool_initial_price_tick( &self, chain_id: u32, initialize_event: &InitializeEvent, ) -> Result<()>

Updates the initial price and tick for a pool.

§Errors

Returns an error if the database update fails.

Source

pub async fn load_latest_valid_pool_snapshot( &self, chain_id: u32, pool_identifier: &PoolIdentifier, ) -> Result<Option<PoolSnapshot>>

Loads the latest usable pool snapshot from the database.

Returns the most recent snapshot usable as a replay start point: on-chain validated or replay-derived. Snapshots that failed on-chain validation are excluded.

§Errors

Returns an error if the database query fails.

Source

pub async fn load_latest_pool_snapshot( &self, chain_id: u32, pool_identifier: &PoolIdentifier, max_block: Option<u64>, require_valid: bool, ) -> Result<Option<PoolSnapshot>>

Loads the latest pool snapshot from the database, optionally bounded by block.

When max_block is Some, only snapshots at or before that block are considered, so a backtest can restore pool state as of a replay start. When require_valid is true, snapshots that failed on-chain validation are excluded (both on-chain validated and replay-derived snapshots are returned).

§Errors

Returns an error if the database query fails.

Source

pub async fn set_pool_snapshot_validation_state( &self, chain_id: u32, pool_identifier: &PoolIdentifier, block: u64, transaction_index: u32, log_index: u32, state: &str, ) -> Result<()>

Sets the validation state of a pool snapshot after a validation attempt.

state is one of on_chain (hydrated and matched), replay (replay-derived, not checked), or invalid (hydrated and mismatched).

§Errors

Returns an error if the database operation fails.

Source

pub async fn get_pool_snapshot_validation_state( &self, chain_id: u32, pool_identifier: &PoolIdentifier, block: u64, transaction_index: u32, log_index: u32, ) -> Result<Option<String>>

Reads the stored validation_state for the snapshot at the given watermark.

Returns None when no snapshot row exists at that position. Used to report the persisted verdict (rather than re-deriving replay) when on-chain validation cannot reach the block.

§Errors

Returns an error if the database query fails.

Source

pub async fn load_pool_positions_for_snapshot( &self, chain_id: u32, pool_identifier: &PoolIdentifier, snapshot_block: u64, snapshot_transaction_index: u32, snapshot_log_index: u32, ) -> Result<Vec<PoolPosition>>

Loads all positions for a specific snapshot.

§Errors

Returns an error if the database query fails.

Source

pub async fn load_pool_ticks_for_snapshot( &self, chain_id: u32, pool_identifier: &PoolIdentifier, snapshot_block: u64, snapshot_transaction_index: u32, snapshot_log_index: u32, ) -> Result<Vec<PoolTick>>

Loads all ticks for a specific snapshot.

§Errors

Returns an error if the database query fails.

Source

pub fn stream_pool_events<'a>( &'a self, chain: SharedChain, dex: SharedDex, instrument_id: InstrumentId, pool_identifier: PoolIdentifier, from_position: Option<BlockPosition>, to_block: Option<u64>, ) -> Pin<Box<dyn Stream<Item = Result<DexPoolData, Error>> + Send + 'a>>

Streams pool events from all event tables (swap, liquidity, collect) for a specific pool.

Creates a unified stream of pool events from multiple tables, ordering them chronologically by block number, transaction index, and log index. Optionally resumes from a specific block position and stops at a maximum block.

§Returns

A stream of DexPoolData events in chronological order.

§Errors

Returns an error if the database query fails or if event transformation fails.

Source

pub async fn add_execution_transaction( &self, chain_id: u32, wallet_address: &str, nonce: u64, transaction_hash: &str, purpose: &str, status: &str, client_order_id: Option<&str>, ) -> Result<()>

Persists an execution transaction record to the execution_transaction table.

Records are written before broadcast so a signed transaction is never forgotten; the unique (chain_id, transaction_hash) constraint makes an exact re-insertion idempotent. Signer nonce ownership and order IDs are unique before broadcast. Order submission records carry the client order ID; operator transactions (wrap, approve) store NULL.

§Errors

Returns an error if the database operation fails.

Source

pub async fn ensure_execution_transaction_schema(&self) -> Result<()>

Installs execution schema version 2 without changing existing transaction rows.

The migration locks the legacy transaction table, refuses unresolved version 1 rows, installs the versioned intent and hash-history tables, and fences older writers before releasing the lock. This prevents a mixed-version process from bypassing the new signer ownership constraints.

§Errors

Returns an error if the database operation fails.

Source

pub async fn reserve_execution_intent( &self, intent: &ExecutionIntentInsert, ) -> Result<ExecutionIntentRow>

Reserves durable ownership of a signer slot and optional client order before signing.

§Errors

Returns a stage-classified error if the signer or client order is already owned, or persistence fails. A commit-stage error does not prove the transaction rolled back.

Source

pub async fn assign_execution_intent_nonce( &self, intent_id: i64, nonce: u64, ) -> Result<()>

Assigns the signer nonce to a prepared execution intent.

Repeating the same assignment is idempotent. A different nonce or non-prepared state fails closed.

§Errors

Returns an error if the intent cannot own the nonce or persistence fails.

Source

pub async fn mark_execution_intent_recoverable( &self, intent_id: i64, ) -> Result<()>

Releases an intent when no broadcast attempt can have occurred.

§Errors

Returns an error if the intent advanced to broadcast or persistence fails.

Source

pub async fn add_execution_transaction_hash( &self, intent_id: i64, chain_id: u32, transaction_hash: &str, raw_transaction: &[u8], ) -> Result<ExecutionTransactionHashRow>

Persists a signed transaction and advances its intent before broadcast.

§Errors

Returns an error if the intent is not prepared, lacks a nonce, conflicts with a stored hash, or persistence fails.

Source

pub async fn record_execution_status( &self, intent_id: i64, transaction_hash: &str, status: TransactionStatus, block_number: Option<u64>, block_hash: Option<&str>, receipt_success: Option<bool>, gas_used: Option<u64>, effective_gas_price: Option<&str>, ) -> Result<()>

Records an idempotent transaction observation and advances its intent state.

§Errors

Returns an error if the transition is invalid, the hash is unknown, or persistence fails.

Source

pub async fn get_active_execution_intent( &self, chain_id: u32, wallet_address: &str, ) -> Result<Option<ExecutionIntentRow>>

Loads the active intent owned by a signer after any concurrent reservation completes.

§Errors

Returns an error if the query fails.

Source

pub async fn has_recoverable_signed_execution( &self, chain_id: u32, wallet_address: &str, ) -> Result<bool>

Reports whether a released legacy intent still retains a broadcastable signature.

§Errors

Returns an error if the query fails.

Source

pub async fn get_execution_transaction_hashes( &self, intent_id: i64, ) -> Result<Vec<ExecutionTransactionHashRow>>

Loads all transaction hashes for an intent in insertion order.

§Errors

Returns an error if the query fails.

Source

pub async fn mark_execution_event_emitted( &self, intent_id: i64, event: &str, ) -> Result<()>

Marks one order event as emitted after dispatch.

§Errors

Returns an error if the event kind is unknown, the intent is absent, the opposing terminal marker is already set, or persistence fails.

Source

pub async fn update_execution_transaction_status( &self, chain_id: u32, transaction_hash: &str, status: &str, ) -> Result<()>

Updates the status of a persisted execution transaction record.

§Errors

Returns an error if the database operation fails.

Source

pub async fn get_execution_transaction( &self, chain_id: u32, transaction_hash: &str, ) -> Result<Option<ExecutionTransactionRow>>

Loads an execution transaction record by chain ID and transaction hash.

§Errors

Returns an error if the database operation fails.

Trait Implementations§

Source§

impl Clone for BlockchainCacheDatabase

Source§

fn clone(&self) -> BlockchainCacheDatabase

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BlockchainCacheDatabase

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Ungil for T
where T: Send,

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more