Skip to main content

degenbot_cli_core/
pool.rs

1//! The `pool` command arms (ADR-051 D1;).
2//!
3//! Ports `cli/pool.py` arm for arm:
4//!
5//! - `pool update` — the chunk-loop hand-off to
6//!   [`run_pool_update`](degenbot_pool_updater::run_pool_update), with the
7//!   `--chunk` / `--to-block` / `--verify-chunk` / `--verify-all` /
8//!   `--verify-all-interval` flags 1:1. Progress stays a no-op sink here
9//!   (ADR-051 D9: the bin paints it); a cooperative cancel returns a friendly
10//!   cancelled report (exit 0), matching the Python `RuntimeError` guard.
11//! - `pool verify` — the read-only, ad-hoc sibling: fetch the COMMITTED
12//!   liquidity map, compare against on-chain truth at `--block`, and render
13//!   GREEN / the named divergence list.
14
15use std::future::Future;
16use std::path::Path;
17use std::str::FromStr;
18use std::sync::atomic::{AtomicU64, Ordering};
19use std::sync::Arc;
20
21use alloy::primitives::{Address, B256};
22use degenbot_core::runtime::get_runtime;
23use degenbot_db::{ComputedLiquidityUpdate, DegenbotDb};
24use degenbot_pool_updater::{
25    run_pool_update, verify_v3_liquidity_map_on_chain, verify_v4_liquidity_map_on_chain,
26    NoProgress, RunError,
27};
28
29use crate::block::{parse_to_block, resolve_to_block};
30use crate::cancel::CancelHandle;
31use crate::context::CliContext;
32use crate::error::{CliError, ExchangeResumeState, PoolUpdateFailure};
33use crate::prompt::{PromptPlan, Prompter};
34use crate::report::PoolReport;
35
36/// The RPC retry budget the verify arm's spot reads use.
37const RPC_MAX_RETRIES: u32 = 5;
38
39/// The pool family `--family` selects.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum PoolFamily {
42    /// V3 (`ticks()`/`tickBitmap()`).
43    V3,
44    /// V4 (`PoolManager` `extsload`).
45    V4,
46}
47
48impl PoolFamily {
49    /// The wire spelling (`v3` / `v4`).
50    #[must_use]
51    pub const fn as_str(self) -> &'static str {
52        match self {
53            Self::V3 => "v3",
54            Self::V4 => "v4",
55        }
56    }
57}
58
59/// The `pool` command group.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum PoolCommand {
62    /// Advance every active exchange's liquidity state to `to_block`.
63    Update {
64        /// Max blocks per chunk before committing.
65        chunk_size: u64,
66        /// The widest block range a single `eth_getLogs` request may
67        /// span (independent of `chunk_size`).
68        max_block_range: u64,
69        /// The raw `--to-block` identifier (tag / tag:offset / integer).
70        to_block: String,
71        /// Run the pre-commit per-chunk on-chain-truth gate.
72        verify_chunk: bool,
73        /// Run the pre-commit market-wide verification at the interval + completion.
74        verify_all: bool,
75        /// The block interval for the `--verify-all` gate.
76        verify_all_interval: u64,
77    },
78    /// Verify a committed pool's liquidity map against on-chain truth.
79    Verify {
80        /// The HTTP RPC endpoint.
81        rpc_url: String,
82        /// The chain the pool lives on.
83        chain_id: i64,
84        /// The block number to read on-chain truth at.
85        block_number: u64,
86        /// V3 pool address, or V4 `PoolId` (bytes32 hex).
87        pool: String,
88        /// The pool family.
89        family: PoolFamily,
90        /// (V4 only) the `PoolManager` singleton.
91        pool_manager: Option<String>,
92    },
93}
94
95impl PoolCommand {
96    /// The arm's confirmation policy: neither pool arm prompts.
97    #[must_use]
98    pub const fn prompt_plan(&self, _ctx: &CliContext<'_>) -> PromptPlan {
99        PromptPlan::None
100    }
101}
102
103/// The resolved verify target for a family.
104enum VerifyTarget {
105    /// A V3 pool contract address.
106    V3(Address),
107    /// A V4 `PoolManager` + `PoolId`.
108    V4 { manager: Address, pool_id: B256 },
109}
110
111/// Execute a `pool` command.
112///
113/// # Errors
114///
115/// [`CliError::InvalidBlockTag`] / [`CliError::InvalidArgument`] /
116/// [`CliError::InvalidAddress`] for malformed inputs, [`CliError::Config`] for
117/// an unresolved driver-domain value, and [`CliError::PoolUpdate`] for a core
118/// failure.
119pub(crate) fn execute(
120    command: &PoolCommand,
121    ctx: &CliContext<'_>,
122    _prompter: &dyn Prompter,
123    cancel: &CancelHandle,
124) -> Result<PoolReport, CliError> {
125    match command {
126        PoolCommand::Update {
127            chunk_size,
128            max_block_range,
129            to_block,
130            verify_chunk,
131            verify_all,
132            verify_all_interval,
133        } => update(
134            ctx,
135            cancel,
136            *chunk_size,
137            *max_block_range,
138            to_block,
139            *verify_chunk,
140            *verify_all,
141            *verify_all_interval,
142        ),
143        PoolCommand::Verify {
144            rpc_url,
145            chain_id,
146            block_number,
147            pool,
148            family,
149            pool_manager,
150        } => verify(
151            ctx,
152            rpc_url,
153            *chain_id,
154            *block_number,
155            pool,
156            *family,
157            pool_manager.as_deref(),
158        ),
159    }
160}
161
162/// `pool update`.
163#[expect(clippy::too_many_arguments)]
164fn update(
165    ctx: &CliContext<'_>,
166    cancel: &CancelHandle,
167    chunk_size: u64,
168    max_block_range: u64,
169    to_block: &str,
170    verify_chunk: bool,
171    verify_all: bool,
172    verify_all_interval: u64,
173) -> Result<PoolReport, CliError> {
174    let database_path = ctx.database_path()?.value;
175    let chain_id = ctx.chain_id()?.value;
176    let rpc_url = ctx.node_request_uri()?.value;
177    // Self-serve registration: every supported exchange pair not found in the
178    // DB registers inactive, so the update never depends on prior CREATEs.
179    crate::registrations::ensure_supported_registrations(&database_path)?;
180    let resolved = resolve_to_block(parse_to_block(to_block)?, &rpc_url)?;
181    let chain = i64::try_from(chain_id)
182        .map_err(|_| CliError::InvalidArgument(format!("chain id {chain_id} is out of range")))?;
183    let interval = if verify_all {
184        Some(verify_all_interval)
185    } else {
186        None
187    };
188    // The pre-run resume snapshot, for the failure line's requested-range
189    // bound: it mirrors the core's own `initial_start_block` (the minimum
190    // `last_update_block + 1` across the active exchanges). Read-only, so a
191    // failed diagnostic read must not fail the run — it degrades to the
192    // requested target.
193    let cursors = read_exchange_cursors(database_path.as_path(), chain).unwrap_or_default();
194    let from_block = initial_run_start_block(&cursors, resolved);
195    // The thin live-provider wrapper (ADR-068 D5): the CLI owns the transport
196    // construction — ONE build per run on the shared runtime, exactly where
197    // the core's old internal `AlloyProvider::new` site sat — and the core
198    // only injects it. A build failure flows through the SAME
199    // [`PoolUpdateFailure`] report as a mid-run failure (endpoint + chain +
200    // the committed resume cursors), since it IS the run's transport dying.
201    let run = match shared_runtime_block_on(async {
202        degenbot_rpc::provider::AlloyProvider::new(&rpc_url, RPC_MAX_RETRIES).await
203    }) {
204        Ok(Ok(provider)) => run_pool_update(
205            &database_path,
206            chain,
207            resolved,
208            chunk_size,
209            max_block_range,
210            provider,
211            cancel.flag(),
212            Arc::new(NoProgress),
213            verify_chunk,
214            interval,
215            verify_all,
216        ),
217        Ok(Err(err)) => Err(RunError::from(err)),
218        Err(cli_err) => return Err(cli_err),
219    };
220    match run {
221        Ok(report) => Ok(PoolReport::Updated {
222            chain_id: report.chain_id,
223            from_block: report.from_block,
224            to_block: report.to_block,
225            chunks_committed: report.chunks_committed,
226            total_pools_written: report.total_pools_written,
227            total_liquidity_applies: report.total_liquidity_applies,
228        }),
229        Err(RunError::Cancelled) => Ok(PoolReport::UpdateCancelled { chain_id: chain }),
230        Err(err) => {
231            // Post-failure resume snapshot: the committed per-chunk progress
232            // (a chunk-boundary commit advances the exchange cursor), read
233            // only — the outstanding work a rerun resumes from. `None` when
234            // the snapshot read itself failed; the rendering says so.
235            let resume = read_exchange_cursors(database_path.as_path(), chain).ok();
236            Err(CliError::PoolUpdate(Box::new(PoolUpdateFailure {
237                error: err,
238                rpc_url: rpc_url.clone(),
239                chain_id: chain,
240                from_block,
241                to_block: resolved,
242                resume,
243            })))
244        }
245    }
246}
247
248/// The read-only per-exchange cursor snapshot for `chain_id` — the resume
249/// state a mid-run failure leaves committed. Plain `SELECT`, so it writes
250/// nothing; `None` cursors are the never-updated exchanges.
251fn read_exchange_cursors(
252    database_path: &Path,
253    chain_id: i64,
254) -> Result<Vec<ExchangeResumeState>, rusqlite::Error> {
255    let conn = rusqlite::Connection::open_with_flags(
256        database_path,
257        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
258    )?;
259    let mut statement = conn.prepare(
260        "SELECT name, last_update_block FROM exchanges \
261         WHERE chain_id = ?1 AND active = 1 ORDER BY name",
262    )?;
263    let rows = statement.query_map([chain_id], |row| {
264        Ok(ExchangeResumeState {
265            name: row.get(0)?,
266            last_update_block: row.get(1)?,
267        })
268    })?;
269    rows.collect()
270}
271
272/// The run's intended start block, mirroring the core's own
273/// `initial_start_block`: the minimum `last_update_block + 1` across the
274/// active exchanges (a never-updated exchange starts at 1). An empty
275/// registration set falls back to the requested target.
276fn initial_run_start_block(cursors: &[ExchangeResumeState], to_block: Option<u64>) -> u64 {
277    cursors
278        .iter()
279        .map(|row| {
280            row.last_update_block
281                .map_or(1, |block| u64::try_from(block).unwrap_or(0) + 1)
282        })
283        .min()
284        .unwrap_or_else(|| to_block.unwrap_or(1))
285        .max(1)
286}
287
288/// `pool verify`.
289fn verify(
290    ctx: &CliContext<'_>,
291    rpc_url: &str,
292    chain_id: i64,
293    block_number: u64,
294    pool: &str,
295    family: PoolFamily,
296    pool_manager: Option<&str>,
297) -> Result<PoolReport, CliError> {
298    let database_path = ctx.database_path()?.value;
299    let (computed, target) = {
300        let (db, _state) = DegenbotDb::open(&database_path)?;
301        let conn = db.lock();
302        fetch_verify_state(&conn, chain_id, pool, family, pool_manager)?
303    };
304    // The arm verifies a row stored for `chain_id` against the node, so the
305    // provider is bound to that chain: an endpoint serving another chain is
306    // refused before any on-chain comparison reports phantom divergences.
307    let chain = u64::try_from(chain_id).map_err(|_| {
308        CliError::InvalidArgument(format!("chain id {chain_id} is not a valid chain"))
309    })?;
310    // ONE chain-verified provider for the whole arm, on the process-wide
311    // shared runtime — the pattern `run_pool_update` uses for its chunk
312    // loop — NOT a fresh runtime + transport built inside `block::block_on`
313    // per target family (a per-family, per-verification build with its
314    // connection tasks destroyed alongside the ad-hoc runtime is the churn
315    // that intermittently surfaces as alloy's
316    // `TransportErrorKind::BackendGone`). The construction is lazy (the
317    // node is dialed only after the committed row above is resolved), the
318    // chain binding still runs exactly once (`for_chain` refuses a
319    // foreign-chain endpoint before any comparison), and no retry layer is
320    // added: a transport failure surfaces as the typed run failure.
321    let divergences = shared_runtime_block_on(async {
322        note_verify_provider_build();
323        let provider =
324            degenbot_rpc::provider::AlloyProvider::for_chain(rpc_url, chain, RPC_MAX_RETRIES)
325                .await
326                .map_err(|err| CliError::BlockResolution(err.to_string()))?;
327        match target {
328            VerifyTarget::V3(address) => {
329                verify_v3_liquidity_map_on_chain(&provider, address, &computed, block_number)
330                    .await
331                    .map_err(|err| {
332                        CliError::PoolUpdate(Box::new(PoolUpdateFailure {
333                            error: err,
334                            rpc_url: rpc_url.to_string(),
335                            chain_id,
336                            from_block: block_number,
337                            to_block: Some(block_number),
338                            resume: None,
339                        }))
340                    })
341            }
342            VerifyTarget::V4 { manager, pool_id } => verify_v4_liquidity_map_on_chain(
343                &provider,
344                manager,
345                pool_id,
346                &computed,
347                block_number,
348            )
349            .await
350            .map_err(|err| {
351                CliError::PoolUpdate(Box::new(PoolUpdateFailure {
352                    error: err,
353                    rpc_url: rpc_url.to_string(),
354                    chain_id,
355                    from_block: block_number,
356                    to_block: Some(block_number),
357                    resume: None,
358                }))
359            }),
360        }
361    })??;
362    Ok(PoolReport::Verified {
363        pool: pool.to_string(),
364        family,
365        block_number,
366        divergences,
367    })
368}
369
370/// Drive `fut` on the process-wide shared runtime — the `&'static`
371/// `degenbot_core::runtime::get_runtime()` singleton the updater cores
372/// drive — instead of building a throwaway `Builder` runtime per call.
373/// Same nesting constraint as [`crate::block::block_on`]: the arm must not
374/// run from inside another runtime.
375///
376/// # Errors
377///
378/// [`CliError::RuntimeNested`] when called from inside an existing runtime.
379pub(crate) fn shared_runtime_block_on<F: Future>(fut: F) -> Result<F::Output, CliError> {
380    if tokio::runtime::Handle::try_current().is_ok() {
381        return Err(CliError::RuntimeNested);
382    }
383    Ok(get_runtime().block_on(fut))
384}
385
386/// The process-lifetime count of `pool verify` transport builds (the
387/// `for_chain` site above). The lifecycle contract to pin: ONE build per
388/// verify run — zero when the arm fails before the node is needed, and
389/// never one per target family. The companion counter lives at the chunk
390/// loop's own build site (`degenbot-pool-updater`'s
391/// `run_provider_build_count`).
392static VERIFY_PROVIDER_BUILDS: AtomicU64 = AtomicU64::new(0);
393
394fn note_verify_provider_build() {
395    VERIFY_PROVIDER_BUILDS.fetch_add(1, Ordering::Relaxed);
396}
397
398/// The instrumented transport-build count — a test-visible seam so the
399/// one-build-per-run contract is pinnable offline (see the crate's
400/// `pool_verify_lifecycle` test).
401#[doc(hidden)]
402#[must_use]
403pub fn verify_provider_build_count() -> u64 {
404    VERIFY_PROVIDER_BUILDS.load(Ordering::Relaxed)
405}
406
407/// Reset the transport-build counter to zero, returning the previous value.
408#[doc(hidden)]
409#[must_use]
410pub fn reset_verify_provider_build_count() -> u64 {
411    VERIFY_PROVIDER_BUILDS.swap(0, Ordering::Relaxed)
412}
413
414/// Fetch the pool's committed liquidity map + resolve the verify target.
415fn fetch_verify_state(
416    conn: &rusqlite::Connection,
417    chain_id: i64,
418    pool: &str,
419    family: PoolFamily,
420    pool_manager: Option<&str>,
421) -> Result<(ComputedLiquidityUpdate, VerifyTarget), CliError> {
422    match family {
423        PoolFamily::V3 => {
424            let address: Address = pool
425                .parse()
426                .map_err(|_| CliError::InvalidAddress(pool.to_string()))?;
427            let key = address.to_checksum(None);
428            let state = DegenbotDb::fetch_v3_pool_update_state_on_conn(conn, chain_id, &key)?
429                .ok_or_else(|| {
430                    CliError::InvalidArgument(format!(
431                        "v3 pool {key} not found on chain {chain_id}"
432                    ))
433                })?;
434            let tick_data = DegenbotDb::fetch_v3_liquidity_map_on_conn(
435                conn,
436                state.pool_id,
437                state.snapshot_block(),
438            )?;
439            Ok((
440                ComputedLiquidityUpdate {
441                    pool_id: state.pool_id,
442                    tick_spacing: state.tick_spacing,
443                    tick_data,
444                    last_event: None,
445                },
446                VerifyTarget::V3(address),
447            ))
448        }
449        PoolFamily::V4 => {
450            let manager = pool_manager.ok_or_else(|| {
451                CliError::InvalidArgument(
452                    "--pool-manager is required for --family v4 (the PoolManager singleton)."
453                        .to_string(),
454                )
455            })?;
456            let manager: Address = manager
457                .parse()
458                .map_err(|_| CliError::InvalidAddress(manager.to_string()))?;
459            let pool_id = B256::from_str(pool.strip_prefix("0x").unwrap_or(pool))
460                .map_err(|_| CliError::InvalidAddress(pool.to_string()))?;
461            let state = DegenbotDb::fetch_v4_pool_update_state_on_conn(conn, pool, chain_id)?
462                .ok_or_else(|| {
463                    CliError::InvalidArgument(format!(
464                        "v4 pool {pool} not found on chain {chain_id}"
465                    ))
466                })?;
467            let tick_data = DegenbotDb::fetch_v4_liquidity_map_on_conn(
468                conn,
469                state.pool_id,
470                state.snapshot_block(),
471            )?;
472            Ok((
473                ComputedLiquidityUpdate {
474                    pool_id: state.pool_id,
475                    tick_spacing: state.tick_spacing,
476                    tick_data,
477                    last_event: None,
478                },
479                VerifyTarget::V4 { manager, pool_id },
480            ))
481        }
482    }
483}