Skip to main content

moonproof_contracts/
sync.rs

1//! Long-lived sync loop over
2//! [`moonproof_indexer_client::subscribe_contract_actions`].
3//!
4//! Subscribes to the indexer's `contractActions(address, offset)`
5//! stream for a single contract and advances an in-memory
6//! [`ContractRuntimeState`] each tick via
7//! [`moonproof_runtime::state::fold_contract_actions`]. Exposes the latest state
8//! to callers via a [`tokio::sync::watch::Receiver`] — the canonical
9//! "subscribe once, observe many" pattern.
10//!
11//! # Lifecycle
12//!
13//! - [`spawn`] returns a [`Watcher`] carrying:
14//!   - a `watch::Receiver<ContractRuntimeState>` for consumers, and
15//!   - a [`moonproof_utils::rt::Task`] for the driver task.
16//! - The driver task runs until the subscription ends (server
17//!   `complete`, network error, or caller cancelling via
18//!   [`Watcher::abort`]).
19//! - Errors from the indexer subscription are surfaced via the
20//!   driver's [`Watcher::join`] result — consumers can either
21//!   consult it or let the task run until it errors, whichever fits
22//!   their app.
23
24use futures::StreamExt;
25use moonproof_indexer_client::{subscribe_contract_actions, BlockOffset};
26use moonproof_utils::rt::{spawn_task, Task};
27use moonproof_utils::StateCell;
28use tokio::sync::watch;
29
30use crate::error::{ContractRuntimeError, Result};
31use crate::state_fold::fold_contract_actions;
32use moonproof_runtime::state::{contract_address_to_hex, ContractRuntimeState};
33
34/// Handle returned by [`spawn`] — consumers pull state updates via
35/// `watch()` and can abort the driver via `abort()`.
36///
37/// State storage + change broadcast are delegated to the shared
38/// [`moonproof_utils::StateCell`] primitive (same one
39/// [`moonproof_wallet::runtime::WalletRuntime`] uses for facade
40/// state). The runtime-specific addition is the [`Task`] driving the
41/// indexer subscription loop.
42pub struct Watcher {
43    state: StateCell<ContractRuntimeState>,
44    task: Task<Result<()>>,
45}
46
47impl Watcher {
48    /// Latest observed runtime state. Cheaply cloneable; use
49    /// [`Self::watch`] to observe changes.
50    pub async fn current(&self) -> ContractRuntimeState {
51        self.state.current().await
52    }
53
54    /// Borrow the underlying watch receiver for change notifications.
55    #[must_use]
56    pub fn watch(&self) -> watch::Receiver<ContractRuntimeState> {
57        self.state.changes()
58    }
59
60    /// Wait for the driver task to finish. Returns the driver's exit
61    /// status — `Ok(())` on a clean `complete` from the server,
62    /// [`ContractRuntimeError::Indexer`] on transport errors.
63    ///
64    /// # Errors
65    ///
66    /// - [`ContractRuntimeError::Provider`] if the task was aborted.
67    pub async fn join(self) -> Result<()> {
68        self.task
69            .join()
70            .await
71            .map_err(|e| ContractRuntimeError::Provider {
72                provider: "sync::Watcher::join",
73                message: format!("driver task join failed: {e}"),
74            })?
75    }
76
77    /// Abort the driver task. The watch receiver stays valid — its
78    /// last observed state is retained.
79    pub fn abort(&self) {
80        self.task.abort();
81    }
82}
83
84/// Spawn a long-lived driver that replays + tails the indexer's
85/// `contractActions(address)` stream and advances
86/// `initial_state` in-place. Returns a [`Watcher`] carrying the
87/// latest state and the driver's join handle.
88///
89/// `indexer_http_url` is the same URL passed to
90/// [`crate::providers::IndexerPublicDataProvider::new`] — the
91/// helper derives the WebSocket form via
92/// `moonproof_indexer_client::graphql_ws_url`.
93///
94/// `start_offset = None` replays from the beginning and then tails
95/// live ticks. Callers that already have a state synced up to some
96/// block pass `Some(BlockOffset::Height(last_known_height + 1))` to
97/// skip the historic replay.
98///
99/// # Errors
100///
101/// - The initial subscription open errors (bad URL, server down) are
102///   surfaced as [`ContractRuntimeError::Indexer`] from this
103///   function.
104/// - Errors observed while the stream is running are propagated
105///   through [`Watcher::join`].
106pub async fn spawn(
107    indexer_http_url: impl Into<String>,
108    initial_state: ContractRuntimeState,
109    start_offset: Option<BlockOffset>,
110) -> Result<Watcher> {
111    let url = indexer_http_url.into();
112    let address_hex = initial_state.address_hex();
113    let address = *initial_state.address();
114    // Open the subscription BEFORE spawning so the caller sees any
115    // "can't connect" errors synchronously.
116    let subscription = subscribe_contract_actions(&url, &address_hex, start_offset)
117        .await
118        .map_err(|e| {
119            ContractRuntimeError::Indexer(format!(
120                "open contractActions subscription for {}: {e}",
121                contract_address_to_hex(&address),
122            ))
123        })?;
124
125    let cell = StateCell::new(initial_state);
126    let driver_cell = cell.clone();
127    let task: Task<Result<()>> = spawn_task(async move {
128        let mut stream = subscription;
129        while let Some(tick_res) = stream.next().await {
130            let tick = tick_res.map_err(|e| {
131                ContractRuntimeError::Indexer(format!("contractActions stream error: {e}"))
132            })?;
133            driver_cell
134                .apply::<_, ContractRuntimeError>(|old| fold_contract_actions(old, [tick]))
135                .await?;
136        }
137        Ok(())
138    });
139
140    Ok(Watcher { state: cell, task })
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[tokio::test]
148    async fn watcher_exposes_current_state_and_joins_its_task() {
149        // Construct a watch channel locally to sanity-check the
150        // Watcher's accessor shape. Full driver behaviour is covered
151        // by the live-harness integration test — mocking the
152        // `subscribe_contract_actions` WebSocket handshake is
153        // higher-friction than it's worth for a shape-only check.
154        use moonproof_ledger::base_crypto::hash::HashOutput;
155        use moonproof_ledger::coin_structure::contract::ContractAddress;
156        use moonproof_ledger::onchain_runtime::state::{
157            ContractMaintenanceAuthority, ContractState, EntryPointBuf, StateValue,
158        };
159        use moonproof_ledger::storage::db::InMemoryDB;
160        use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
161
162        let op_key: EntryPointBuf = b"noop"[..].into();
163        let state = ContractState::<InMemoryDB>::new(
164            StateValue::Null,
165            StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
166            ContractMaintenanceAuthority::default(),
167        );
168        let address = ContractAddress(HashOutput([0xabu8; 32]));
169        let runtime_state = ContractRuntimeState::new(address, state);
170        let task = spawn_task(async { Ok(()) as Result<()> });
171        let watcher = Watcher {
172            state: StateCell::new(runtime_state),
173            task,
174        };
175        assert_eq!(watcher.watch().borrow().address(), &address);
176        watcher.join().await.unwrap();
177    }
178}