moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Provider traits — Rust port of
//! `@midnight-ntwrk/midnight-js-types/src/providers.ts`.
//!
//! Every interface exported from the TS `midnight-js-types` package
//! has a Rust `trait` equivalent in a dedicated submodule. Concrete
//! implementations that wrap moonproof's existing crates live
//! separately — this module just defines the contract.
//!
//! # Reactivity
//!
//! The TS `PublicDataProvider` exposes `RxJS` observables
//! (`contractStateObservable`, `unshieldedBalancesObservable`). The
//! Rust equivalents return `impl Stream<Item = _> + Send + Unpin`
//! (see [`public_data`]), composable with `StreamExt` and directly
//! driveable from any async runtime. No reactive behavior is dropped
//! — only the `RxJS` library surface.
//!
//! # Async
//!
//! All trait methods that are `async` in TS are `async fn` in Rust.
//! Where the TS surface uses `Promise<T>` directly, the Rust trait
//! method returns a future. Dynamic dispatch (`dyn ProviderTrait`) is
//! supported via `#[moonproof_macros::async_trait]` on the traits that
//! need it for integration points.

pub mod capability;
pub mod contract_module;
pub mod disk_pending_tx;
pub mod disk_private_state;
pub mod disk_tx_history;
pub mod facade_wallet;
pub mod fs_zk_config;
pub mod http_proof;
pub mod http_zk_config;
pub mod in_memory_private_state;
pub mod in_process_proof;
pub mod indexer_public_data;
pub mod logger;
pub mod midnight;
pub mod node_client_midnight;
pub mod private_state;
pub mod proof;
pub mod public_data;
pub mod storage_encryption;
pub mod wallet;
pub mod wallet_disk;
pub mod wallet_store;
pub mod zk_config;
pub mod zk_manifest;

pub use capability::{
    HasContractModules, HasLogger, HasMidnight, HasPrivateState, HasProof, HasPublicData,
    HasWallet, HasZkConfig, Providers,
};
pub use contract_module::{ContractModule, ContractModuleProvider, ContractModuleRegistry};

/// Convenience alias for the type-erased provider bundle. Stored
/// long-lived in places that need a concrete (non-generic) type:
/// FFI surfaces, codegen-generated handles, polymorphic registries.
/// Internal hot paths take `impl HasFoo + ...` and accept the typed
/// generic shape transparently.
pub type DynContractProviders = ErasedProviders;

pub use disk_pending_tx::{DiskPendingTransactionsConfig, DiskPendingTransactionsStorage};
pub use disk_private_state::{
    DiskPrivateStateConfig, DiskPrivateStateProvider, PrivateStoragePassword, StaticPassword,
};
pub use disk_tx_history::{DiskTransactionHistoryConfig, DiskTransactionHistoryStorage};
pub use facade_wallet::FacadeWalletProvider;
pub use fs_zk_config::FileSystemZkConfigProvider;
pub use http_proof::HttpProofProvider;
pub use http_zk_config::HttpZkConfigProvider;
pub use in_memory_private_state::InMemoryPrivateStateProvider;
pub use in_process_proof::InProcessProofProvider;
pub use indexer_public_data::IndexerPublicDataProvider;
pub use logger::LoggerProvider;
pub use midnight::MidnightProvider;
pub use moonproof_node_client::SubmissionStage;
pub use node_client_midnight::NodeClientMidnightProvider;
pub use private_state::{
    ExportPrivateStatesOptions, ImportConflictStrategy, ImportPrivateStatesOptions,
    ImportPrivateStatesResult, PrivateStateExport, PrivateStateProvider, SigningKeyExport,
    MAX_EXPORT_SIGNING_KEYS, MAX_EXPORT_STATES,
};
pub use proof::{ProofProvider, ProveTxConfig};
pub use public_data::{
    BlockInfo, ContractEvent, ContractEventFilter, ContractEventKind, ContractEventType,
    ContractEventsPage, EventAddress, PublicDataProvider,
};
pub use wallet::WalletProvider;
pub use wallet_disk::{default_session_account_id, derive_session_password, WALLET_DB_FILENAME};
pub use wallet_store::{WalletStore, WalletStoreConfig};
pub use zk_config::ZkConfigProvider;
pub use zk_manifest::{ZkArtifactIntegrityMode, ZkConfigIntegrityOptions};

use std::sync::Arc;

/// Set of providers needed for transaction construction and
/// submission. Port of TS `MidnightProviders<PCK, PSI, PS>`.
///
/// Generic over each provider type (`P`, `D`, `Z`, `F`, `W`, `M`) so
/// internal hot paths get static dispatch + full inlining. Concrete
/// type arguments propagate through the system; FFI surfaces and
/// other erasure-needing consumers call [`Self::into_erased`] at
/// the boundary to land an [`ErasedProviders`] (the bag of
/// `Arc<dyn FooProvider>` shapes).
///
/// The logger slot stays erased (`Option<Arc<dyn LoggerProvider>>`)
/// because it's off the per-tx hot path and threading another
/// generic parameter through every bundle constructor isn't worth
/// the vtable hop it would avoid.
///
/// Construction goes through [`bon::Builder`]: required fields are
/// enforced at compile time, optional fields default sensibly,
/// argument order is irrelevant.
#[derive(Clone, ::bon::Builder)]
pub struct ContractProviders<P, D, Z, F, W, M> {
    pub private_state: P,
    pub public_data: D,
    pub zk_config: Z,
    pub proof: F,
    pub wallet: W,
    pub midnight: M,
    /// Optional — matches TS `loggerProvider?: LoggerProvider`.
    pub logger: Option<Arc<dyn LoggerProvider>>,
    /// Optional — matches TS `contractModuleProvider?`. Calls to
    /// circuits that call other contracts need it.
    pub contract_modules: Option<Arc<dyn ContractModuleProvider>>,
}

impl<P, D, Z, F, W, M> ContractProviders<P, D, Z, F, W, M> {
    /// Attach a logger provider to an already-built bundle. Equivalent
    /// to `.logger(...)` on the builder; provided as a post-build
    /// chainable mutator for ergonomics.
    #[must_use]
    pub fn with_logger(mut self, logger: Arc<dyn LoggerProvider>) -> Self {
        self.logger = Some(logger);
        self
    }
}

impl<P, D, Z, F, W, M> ContractProviders<P, D, Z, F, W, M>
where
    P: PrivateStateProvider + 'static,
    D: PublicDataProvider + 'static,
    Z: ZkConfigProvider + 'static,
    F: ProofProvider + 'static,
    W: WalletProvider + 'static,
    M: MidnightProvider + 'static,
{
    /// Erase the typed bundle into [`ErasedProviders`] — the concrete
    /// `Arc<dyn FooProvider>` shape FFI surfaces (`moonproof-ffi`,
    /// `@moonproof/node`) consume. One vtable hop per call after this
    /// point, but the FFI boundary already pays a process-call cost
    /// that dwarfs it.
    pub fn into_erased(self) -> ErasedProviders {
        ErasedProviders::builder()
            .private_state(Arc::new(self.private_state))
            .public_data(Arc::new(self.public_data))
            .zk_config(Arc::new(self.zk_config))
            .proof(Arc::new(self.proof))
            .wallet(Arc::new(self.wallet))
            .midnight(Arc::new(self.midnight))
            .maybe_logger(self.logger)
            .maybe_contract_modules(self.contract_modules)
            .build()
    }
}

impl<P, D, Z, F, W, M> std::fmt::Debug for ContractProviders<P, D, Z, F, W, M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContractProviders")
            .field("logger", &self.logger.is_some())
            .finish_non_exhaustive()
    }
}

// -- Capability impls — typed bundle ------------------------------------
//
// Each `Has*` impl carries the user's concrete generic param as the
// associated type, so consumer code monomorphizes against the actual
// provider type. No vtable, no `Arc::clone` per call.

impl<P, D, Z, F, W, M> HasProof for ContractProviders<P, D, Z, F, W, M>
where
    P: Send + Sync,
    D: Send + Sync,
    Z: Send + Sync,
    F: ProofProvider,
    W: Send + Sync,
    M: Send + Sync,
{
    type Proof = F;
    fn proof(&self) -> &Self::Proof {
        &self.proof
    }
}

impl<P, D, Z, F, W, M> HasWallet for ContractProviders<P, D, Z, F, W, M>
where
    P: Send + Sync,
    D: Send + Sync,
    Z: Send + Sync,
    F: Send + Sync,
    W: WalletProvider,
    M: Send + Sync,
{
    type Wallet = W;
    fn wallet(&self) -> &Self::Wallet {
        &self.wallet
    }
}

impl<P, D, Z, F, W, M> HasMidnight for ContractProviders<P, D, Z, F, W, M>
where
    P: Send + Sync,
    D: Send + Sync,
    Z: Send + Sync,
    F: Send + Sync,
    W: Send + Sync,
    M: MidnightProvider,
{
    type Midnight = M;
    fn midnight(&self) -> &Self::Midnight {
        &self.midnight
    }
}

impl<P, D, Z, F, W, M> HasPublicData for ContractProviders<P, D, Z, F, W, M>
where
    P: Send + Sync,
    D: PublicDataProvider,
    Z: Send + Sync,
    F: Send + Sync,
    W: Send + Sync,
    M: Send + Sync,
{
    type PublicData = D;
    fn public_data(&self) -> &Self::PublicData {
        &self.public_data
    }
}

impl<P, D, Z, F, W, M> HasPrivateState for ContractProviders<P, D, Z, F, W, M>
where
    P: PrivateStateProvider,
    D: Send + Sync,
    Z: Send + Sync,
    F: Send + Sync,
    W: Send + Sync,
    M: Send + Sync,
{
    type PrivateState = P;
    fn private_state(&self) -> &Self::PrivateState {
        &self.private_state
    }
}

impl<P, D, Z, F, W, M> HasZkConfig for ContractProviders<P, D, Z, F, W, M>
where
    P: Send + Sync,
    D: Send + Sync,
    Z: ZkConfigProvider,
    F: Send + Sync,
    W: Send + Sync,
    M: Send + Sync,
{
    type ZkConfig = Z;
    fn zk_config(&self) -> &Self::ZkConfig {
        &self.zk_config
    }
}

impl<P, D, Z, F, W, M> HasLogger for ContractProviders<P, D, Z, F, W, M>
where
    P: Send + Sync,
    D: Send + Sync,
    Z: Send + Sync,
    F: Send + Sync,
    W: Send + Sync,
    M: Send + Sync,
{
    type Logger = dyn LoggerProvider;
    fn logger(&self) -> Option<&Self::Logger> {
        self.logger.as_deref()
    }
}

impl<P, D, Z, F, W, M> HasContractModules for ContractProviders<P, D, Z, F, W, M>
where
    P: Send + Sync,
    D: Send + Sync,
    Z: Send + Sync,
    F: Send + Sync,
    W: Send + Sync,
    M: Send + Sync,
{
    type ContractModules = dyn ContractModuleProvider;
    fn contract_modules(&self) -> Option<&Self::ContractModules> {
        self.contract_modules.as_deref()
    }
}

// -- ErasedProviders — FFI / dyn-storage shape --------------------------
//
// The concrete `Arc<dyn FooProvider>` bag. Construct via
// [`ContractProviders::into_erased`] from a typed bundle, or directly
// via [`ErasedProviders::builder`] when callers already hold pre-erased
// `Arc<dyn ...>` slots (e.g. FFI adapters that wrap foreign callbacks).

#[derive(Clone, ::bon::Builder)]
pub struct ErasedProviders {
    pub private_state: Arc<dyn PrivateStateProvider>,
    pub public_data: Arc<dyn PublicDataProvider>,
    pub zk_config: Arc<dyn ZkConfigProvider>,
    pub proof: Arc<dyn ProofProvider>,
    pub wallet: Arc<dyn WalletProvider>,
    pub midnight: Arc<dyn MidnightProvider>,
    pub logger: Option<Arc<dyn LoggerProvider>>,
    pub contract_modules: Option<Arc<dyn ContractModuleProvider>>,
}

impl ErasedProviders {
    /// Attach a logger to an already-built erased bundle.
    #[must_use]
    pub fn with_logger(mut self, logger: Arc<dyn LoggerProvider>) -> Self {
        self.logger = Some(logger);
        self
    }

    #[must_use]
    pub fn with_contract_modules(mut self, modules: Arc<dyn ContractModuleProvider>) -> Self {
        self.contract_modules = Some(modules);
        self
    }
}

impl std::fmt::Debug for ErasedProviders {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ErasedProviders")
            .field("logger", &self.logger.is_some())
            .finish_non_exhaustive()
    }
}

impl HasProof for ErasedProviders {
    type Proof = dyn ProofProvider;
    fn proof(&self) -> &Self::Proof {
        &*self.proof
    }
}

impl HasWallet for ErasedProviders {
    type Wallet = dyn WalletProvider;
    fn wallet(&self) -> &Self::Wallet {
        &*self.wallet
    }
}

impl HasMidnight for ErasedProviders {
    type Midnight = dyn MidnightProvider;
    fn midnight(&self) -> &Self::Midnight {
        &*self.midnight
    }
}

impl HasPublicData for ErasedProviders {
    type PublicData = dyn PublicDataProvider;
    fn public_data(&self) -> &Self::PublicData {
        &*self.public_data
    }
}

impl HasPrivateState for ErasedProviders {
    type PrivateState = dyn PrivateStateProvider;
    fn private_state(&self) -> &Self::PrivateState {
        &*self.private_state
    }
}

impl HasZkConfig for ErasedProviders {
    type ZkConfig = dyn ZkConfigProvider;
    fn zk_config(&self) -> &Self::ZkConfig {
        &*self.zk_config
    }
}

impl HasLogger for ErasedProviders {
    type Logger = dyn LoggerProvider;
    fn logger(&self) -> Option<&Self::Logger> {
        self.logger.as_deref()
    }
}

impl HasContractModules for ErasedProviders {
    type ContractModules = dyn ContractModuleProvider;
    fn contract_modules(&self) -> Option<&Self::ContractModules> {
        self.contract_modules.as_deref()
    }
}