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