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
//! Public-data provider trait — port of
//! `@midnight-ntwrk/midnight-js-types/src/public-data-provider.ts`.
//!
//! The TS interface exposes a mix of one-shot queries (`queryContractState`)
//! and reactive observables (`contractStateObservable`). The Rust port
//! keeps both kinds — one-shots are `async fn`, reactive streams return
//! `impl Stream<Item = _>`. `RxJS` is not dropped; it's swapped for
//! Rust-native async streams with the same semantics.
//!
//! # Stream lifecycle
//!
//! Streams returned by this provider are expected to:
//!
//! - yield every relevant update after their start point (matches the
//!   TS observable contract),
//! - signal stream completion via the `Stream` trait's natural
//!   termination (a `None` after some sequence of `Some(Ok(..))`), and
//! - surface errors as `Err(ContractRuntimeError)` within the stream
//!   item type.

use std::pin::Pin;

use futures::stream::Stream;
use moonproof_macros::async_trait;

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::ContractState;
use moonproof_ledger::storage::db::InMemoryDB;

use crate::error::Result;
use crate::types::{
    ContractStateQueryAt, ContractStateStreamStart, FinalizedTxData, TransactionId,
    UnshieldedBalances,
};

/// Boxed `Stream` item alias used by the reactive methods of
/// [`PublicDataProvider`]. Each tick is either a successful update or
/// an error.
#[cfg(not(target_arch = "wasm32"))]
pub type PublicDataStream<T> = Pin<Box<dyn Stream<Item = Result<T>> + Send>>;

/// A stream of public data; a browser's socket stays on its thread.
#[cfg(target_arch = "wasm32")]
pub type PublicDataStream<T> = Pin<Box<dyn Stream<Item = Result<T>>>>;

/// Port of TS `[ZswapChainState, ContractState, LedgerParameters]` —
/// the triple returned by `queryZSwapAndContractState`. The zswap
/// state and ledger parameters are passed through as their
/// tagged-serialized bytes because moonproof-wallet already has
/// deserializers for both shapes; the runtime surface stays free of
/// deep wallet-crate type dependencies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZSwapAndContractState {
    pub zswap_chain_state_bytes: Vec<u8>,
    pub contract_state: ContractState<InMemoryDB>,
    pub ledger_parameters_bytes: Vec<u8>,
}

pub use moonproof_indexer_client::events::{
    ContractEvent, ContractEventFilter, ContractEventKind, ContractEventType, EventAddress,
};

/// A block's identity and the protocol version it was produced under.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockInfo {
    pub hash: String,
    pub height: u64,
    pub protocol_version: u32,
}

/// One page of a [`PublicDataProvider::query_contract_events`] result.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ContractEventsPage {
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// The error a provider returns for a capability it does not serve,
/// as midnight-js does for providers predating it.
fn unserved(what: &str) -> crate::error::ContractRuntimeError {
    crate::error::ContractRuntimeError::Provider {
        provider: "public_data",
        message: format!("this PublicDataProvider does not serve {what}"),
    }
}

/// Rust port of TS `PublicDataProvider`.
///
/// The block and contract-event methods default to an "unserved"
/// error, so providers implemented over host callbacks keep compiling
/// and report the gap instead of a wrong answer.
#[async_trait]
pub trait PublicDataProvider: Send + Sync + std::fmt::Debug {
    /// The block at `at`, or the latest when `None`.
    async fn query_block(&self, at: Option<ContractStateQueryAt>) -> Result<Option<BlockInfo>> {
        let _ = at;
        Err(unserved("queryBlock"))
    }

    /// The protocol version of the latest block.
    async fn query_latest_protocol_version(&self) -> Result<u32> {
        Err(unserved("queryLatestProtocolVersion"))
    }

    /// Contract events matching `filter`, oldest first.
    async fn query_contract_events(
        &self,
        filter: &ContractEventFilter,
        page: ContractEventsPage,
    ) -> Result<Vec<ContractEvent>> {
        let _ = (filter, page);
        Err(unserved("contract events"))
    }

    /// Live contract events matching `filter`, resuming after event
    /// `after_id` when given.
    async fn contract_events_stream(
        &self,
        filter: &ContractEventFilter,
        after_id: Option<u64>,
    ) -> Result<PublicDataStream<ContractEvent>> {
        let _ = (filter, after_id);
        Err(unserved("contract event subscriptions"))
    }

    // --- One-shot queries -------------------------------------------

    /// Retrieves the on-chain state of the contract at `address`. If
    /// `at` is `None`, returns the latest state.
    ///
    /// Returns `Ok(None)` when no matching data exists — port of the
    /// TS "immediately returns null" behaviour for missing data.
    async fn query_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ContractState<InMemoryDB>>>;

    /// Single-round-trip query for zswap chain state, contract state,
    /// and ledger parameters. Returns `Ok(None)` if no matching data
    /// exists.
    async fn query_zswap_and_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ZSwapAndContractState>>;

    /// The contract state included in the deploy tx for `address`.
    /// Returns `Ok(None)` if no deploy has been observed.
    async fn query_deploy_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<Option<ContractState<InMemoryDB>>>;

    /// The unshielded balances associated with `address`.
    async fn query_unshielded_balances(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<UnshieldedBalances>>;

    // --- Watch-for (indefinite blocking) ---------------------------

    /// Resolves when a deploy transaction for `address` appears
    /// on-chain. TS explicitly contracts this as "waits indefinitely
    /// until the deployment transaction appears". The Rust port
    /// inherits that behaviour — callers that need a timeout wrap the
    /// returned future with their own timeout primitive.
    async fn watch_for_deploy_tx_data(&self, address: &ContractAddress) -> Result<FinalizedTxData>;

    /// Resolves when the tx with `tx_id` appears on-chain.
    async fn watch_for_tx_data(&self, tx_id: &TransactionId) -> Result<FinalizedTxData>;

    /// Resolves when a contract state appears at `address` (first
    /// deploy OR call that produces an updated state). Matches TS
    /// `watchForContractState`.
    async fn watch_for_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<ContractState<InMemoryDB>>;

    /// Resolves when unshielded balances appear at `address`.
    async fn watch_for_unshielded_balances(
        &self,
        address: &ContractAddress,
    ) -> Result<UnshieldedBalances>;

    // --- Streams ----------------------------------------------------

    /// Stream of contract-state updates for `address`, starting per
    /// `start`. Port of TS `contractStateObservable`.
    ///
    /// Implementations typically build this by subscribing to the
    /// indexer's `subscribe_contract_actions` stream and replaying
    /// historic actions as needed to honour `start.inclusive`.
    async fn contract_state_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<ContractState<InMemoryDB>>>;

    /// Stream of unshielded-balance updates for `address`. Port of TS
    /// `unshieldedBalancesObservable`.
    async fn unshielded_balances_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<UnshieldedBalances>>;
}

#[async_trait]
impl<T: PublicDataProvider + ?Sized> PublicDataProvider for std::sync::Arc<T> {
    async fn query_block(&self, at: Option<ContractStateQueryAt>) -> Result<Option<BlockInfo>> {
        (**self).query_block(at).await
    }
    async fn query_latest_protocol_version(&self) -> Result<u32> {
        (**self).query_latest_protocol_version().await
    }
    async fn query_contract_events(
        &self,
        filter: &ContractEventFilter,
        page: ContractEventsPage,
    ) -> Result<Vec<ContractEvent>> {
        (**self).query_contract_events(filter, page).await
    }
    async fn contract_events_stream(
        &self,
        filter: &ContractEventFilter,
        after_id: Option<u64>,
    ) -> Result<PublicDataStream<ContractEvent>> {
        (**self).contract_events_stream(filter, after_id).await
    }
    async fn query_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        (**self).query_contract_state(address, at).await
    }
    async fn query_zswap_and_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ZSwapAndContractState>> {
        (**self).query_zswap_and_contract_state(address, at).await
    }
    async fn query_deploy_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        (**self).query_deploy_contract_state(address).await
    }
    async fn query_unshielded_balances(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<UnshieldedBalances>> {
        (**self).query_unshielded_balances(address, at).await
    }
    async fn watch_for_deploy_tx_data(&self, address: &ContractAddress) -> Result<FinalizedTxData> {
        (**self).watch_for_deploy_tx_data(address).await
    }
    async fn watch_for_tx_data(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
        (**self).watch_for_tx_data(tx_id).await
    }
    async fn watch_for_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<ContractState<InMemoryDB>> {
        (**self).watch_for_contract_state(address).await
    }
    async fn watch_for_unshielded_balances(
        &self,
        address: &ContractAddress,
    ) -> Result<UnshieldedBalances> {
        (**self).watch_for_unshielded_balances(address).await
    }
    async fn contract_state_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
        (**self).contract_state_stream(address, start).await
    }
    async fn unshielded_balances_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<UnshieldedBalances>> {
        (**self).unshielded_balances_stream(address, start).await
    }
}

#[async_trait]
impl<T: PublicDataProvider + ?Sized> PublicDataProvider for Box<T> {
    async fn query_block(&self, at: Option<ContractStateQueryAt>) -> Result<Option<BlockInfo>> {
        (**self).query_block(at).await
    }
    async fn query_latest_protocol_version(&self) -> Result<u32> {
        (**self).query_latest_protocol_version().await
    }
    async fn query_contract_events(
        &self,
        filter: &ContractEventFilter,
        page: ContractEventsPage,
    ) -> Result<Vec<ContractEvent>> {
        (**self).query_contract_events(filter, page).await
    }
    async fn contract_events_stream(
        &self,
        filter: &ContractEventFilter,
        after_id: Option<u64>,
    ) -> Result<PublicDataStream<ContractEvent>> {
        (**self).contract_events_stream(filter, after_id).await
    }
    async fn query_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        (**self).query_contract_state(address, at).await
    }
    async fn query_zswap_and_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ZSwapAndContractState>> {
        (**self).query_zswap_and_contract_state(address, at).await
    }
    async fn query_deploy_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        (**self).query_deploy_contract_state(address).await
    }
    async fn query_unshielded_balances(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<UnshieldedBalances>> {
        (**self).query_unshielded_balances(address, at).await
    }
    async fn watch_for_deploy_tx_data(&self, address: &ContractAddress) -> Result<FinalizedTxData> {
        (**self).watch_for_deploy_tx_data(address).await
    }
    async fn watch_for_tx_data(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
        (**self).watch_for_tx_data(tx_id).await
    }
    async fn watch_for_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<ContractState<InMemoryDB>> {
        (**self).watch_for_contract_state(address).await
    }
    async fn watch_for_unshielded_balances(
        &self,
        address: &ContractAddress,
    ) -> Result<UnshieldedBalances> {
        (**self).watch_for_unshielded_balances(address).await
    }
    async fn contract_state_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
        (**self).contract_state_stream(address, start).await
    }
    async fn unshielded_balances_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<UnshieldedBalances>> {
        (**self).unshielded_balances_stream(address, start).await
    }
}