moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Long-lived sync loop over
//! [`moonproof_indexer_client::subscribe_contract_actions`].
//!
//! Subscribes to the indexer's `contractActions(address, offset)`
//! stream for a single contract and advances an in-memory
//! [`ContractRuntimeState`] each tick via
//! [`moonproof_runtime::state::fold_contract_actions`]. Exposes the latest state
//! to callers via a [`tokio::sync::watch::Receiver`] — the canonical
//! "subscribe once, observe many" pattern.
//!
//! # Lifecycle
//!
//! - [`spawn`] returns a [`Watcher`] carrying:
//!   - a `watch::Receiver<ContractRuntimeState>` for consumers, and
//!   - a [`moonproof_utils::rt::Task`] for the driver task.
//! - The driver task runs until the subscription ends (server
//!   `complete`, network error, or caller cancelling via
//!   [`Watcher::abort`]).
//! - Errors from the indexer subscription are surfaced via the
//!   driver's [`Watcher::join`] result — consumers can either
//!   consult it or let the task run until it errors, whichever fits
//!   their app.

use futures::StreamExt;
use moonproof_indexer_client::{subscribe_contract_actions, BlockOffset};
use moonproof_utils::rt::{spawn_task, Task};
use moonproof_utils::StateCell;
use tokio::sync::watch;

use crate::error::{ContractRuntimeError, Result};
use crate::state_fold::fold_contract_actions;
use moonproof_runtime::state::{contract_address_to_hex, ContractRuntimeState};

/// Handle returned by [`spawn`] — consumers pull state updates via
/// `watch()` and can abort the driver via `abort()`.
///
/// State storage + change broadcast are delegated to the shared
/// [`moonproof_utils::StateCell`] primitive (same one
/// [`moonproof_wallet::runtime::WalletRuntime`] uses for facade
/// state). The runtime-specific addition is the [`Task`] driving the
/// indexer subscription loop.
pub struct Watcher {
    state: StateCell<ContractRuntimeState>,
    task: Task<Result<()>>,
}

impl Watcher {
    /// Latest observed runtime state. Cheaply cloneable; use
    /// [`Self::watch`] to observe changes.
    pub async fn current(&self) -> ContractRuntimeState {
        self.state.current().await
    }

    /// Borrow the underlying watch receiver for change notifications.
    #[must_use]
    pub fn watch(&self) -> watch::Receiver<ContractRuntimeState> {
        self.state.changes()
    }

    /// Wait for the driver task to finish. Returns the driver's exit
    /// status — `Ok(())` on a clean `complete` from the server,
    /// [`ContractRuntimeError::Indexer`] on transport errors.
    ///
    /// # Errors
    ///
    /// - [`ContractRuntimeError::Provider`] if the task was aborted.
    pub async fn join(self) -> Result<()> {
        self.task
            .join()
            .await
            .map_err(|e| ContractRuntimeError::Provider {
                provider: "sync::Watcher::join",
                message: format!("driver task join failed: {e}"),
            })?
    }

    /// Abort the driver task. The watch receiver stays valid — its
    /// last observed state is retained.
    pub fn abort(&self) {
        self.task.abort();
    }
}

/// Spawn a long-lived driver that replays + tails the indexer's
/// `contractActions(address)` stream and advances
/// `initial_state` in-place. Returns a [`Watcher`] carrying the
/// latest state and the driver's join handle.
///
/// `indexer_http_url` is the same URL passed to
/// [`crate::providers::IndexerPublicDataProvider::new`] — the
/// helper derives the WebSocket form via
/// `moonproof_indexer_client::graphql_ws_url`.
///
/// `start_offset = None` replays from the beginning and then tails
/// live ticks. Callers that already have a state synced up to some
/// block pass `Some(BlockOffset::Height(last_known_height + 1))` to
/// skip the historic replay.
///
/// # Errors
///
/// - The initial subscription open errors (bad URL, server down) are
///   surfaced as [`ContractRuntimeError::Indexer`] from this
///   function.
/// - Errors observed while the stream is running are propagated
///   through [`Watcher::join`].
pub async fn spawn(
    indexer_http_url: impl Into<String>,
    initial_state: ContractRuntimeState,
    start_offset: Option<BlockOffset>,
) -> Result<Watcher> {
    let url = indexer_http_url.into();
    let address_hex = initial_state.address_hex();
    let address = *initial_state.address();
    // Open the subscription BEFORE spawning so the caller sees any
    // "can't connect" errors synchronously.
    let subscription = subscribe_contract_actions(&url, &address_hex, start_offset)
        .await
        .map_err(|e| {
            ContractRuntimeError::Indexer(format!(
                "open contractActions subscription for {}: {e}",
                contract_address_to_hex(&address),
            ))
        })?;

    let cell = StateCell::new(initial_state);
    let driver_cell = cell.clone();
    let task: Task<Result<()>> = spawn_task(async move {
        let mut stream = subscription;
        while let Some(tick_res) = stream.next().await {
            let tick = tick_res.map_err(|e| {
                ContractRuntimeError::Indexer(format!("contractActions stream error: {e}"))
            })?;
            driver_cell
                .apply::<_, ContractRuntimeError>(|old| fold_contract_actions(old, [tick]))
                .await?;
        }
        Ok(())
    });

    Ok(Watcher { state: cell, task })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn watcher_exposes_current_state_and_joins_its_task() {
        // Construct a watch channel locally to sanity-check the
        // Watcher's accessor shape. Full driver behaviour is covered
        // by the live-harness integration test — mocking the
        // `subscribe_contract_actions` WebSocket handshake is
        // higher-friction than it's worth for a shape-only check.
        use moonproof_ledger::base_crypto::hash::HashOutput;
        use moonproof_ledger::coin_structure::contract::ContractAddress;
        use moonproof_ledger::onchain_runtime::state::{
            ContractMaintenanceAuthority, ContractState, EntryPointBuf, StateValue,
        };
        use moonproof_ledger::storage::db::InMemoryDB;
        use moonproof_ledger::storage::storage::HashMap as StorageHashMap;

        let op_key: EntryPointBuf = b"noop"[..].into();
        let state = ContractState::<InMemoryDB>::new(
            StateValue::Null,
            StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
            ContractMaintenanceAuthority::default(),
        );
        let address = ContractAddress(HashOutput([0xabu8; 32]));
        let runtime_state = ContractRuntimeState::new(address, state);
        let task = spawn_task(async { Ok(()) as Result<()> });
        let watcher = Watcher {
            state: StateCell::new(runtime_state),
            task,
        };
        assert_eq!(watcher.watch().borrow().address(), &address);
        watcher.join().await.unwrap();
    }
}