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
//! Lifecycle-side types — finalized tx data, transaction status,
//! fees, balances, call-result shapes, contract-state stream config.
//!
//! Pure-data wasm-friendly types live in
//! [`crate::types`]. These ones either depend on
//! [`moonproof_wallet::ProtocolVersion`] (heavy crate) or are only
//! ever produced by the host's lifecycle pipeline (deploy / call /
//! sync / submit), so they live here.

use std::collections::BTreeMap;

use moonproof_ledger::base_crypto::fab::AlignedValue;
use moonproof_ledger::onchain_runtime::state::ContractState;
use moonproof_ledger::storage::db::InMemoryDB;
use serde::{Deserialize, Serialize};

// Re-export the wasm-friendly runtime-side types so host consumers can
// use a single `crate::types::*` prefix.
pub use moonproof_runtime::types::{
    BlockHash, CircuitId, CoinPublicKey, ContractAddress, EncPublicKey, PrivateStateId, ProverKey,
    TransactionHash, TransactionId, VerifierKey, ZkConfig, Zkir,
};

use moonproof_runtime::CompactZswapLocalState;

// =====================================================================
// Transaction status
// =====================================================================

/// The status of a transaction as returned by the node after execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TxStatus {
    FailEntirely,
    FailFallible,
    SucceedEntirely,
}

impl TxStatus {
    #[inline]
    #[must_use]
    pub fn is_success(&self) -> bool {
        matches!(self, TxStatus::SucceedEntirely)
    }
}

/// Per-segment application status inside a transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SegmentStatus {
    Success,
    Fail,
}

// =====================================================================
// Fees / unshielded balances
// =====================================================================

/// Port of TS `Fees`. String-encoded `u128` for round-trip safety.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Fees {
    pub paid_fees: String,
    pub estimated_fees: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnshieldedBalance {
    pub balance: u128,
    pub token_type: [u8; 32],
}

pub type UnshieldedBalances = Vec<UnshieldedBalance>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnshieldedUtxo {
    pub owner: moonproof_ledger::coin_structure::contract::ContractAddress,
    pub intent_hash: [u8; 32],
    pub token_type: [u8; 32],
    pub value: u128,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct UnshieldedUtxos {
    pub created: Vec<UnshieldedUtxo>,
    pub spent: Vec<UnshieldedUtxo>,
}

// =====================================================================
// Finalized transaction data
// =====================================================================

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FinalizedTxData {
    pub tx_id: TransactionId,
    pub identifiers: Vec<TransactionId>,
    pub tx_hash: TransactionHash,
    pub block_hash: BlockHash,
    pub block_height: u64,
    pub block_timestamp_ms: i64,
    pub block_author: Option<String>,
    pub indexer_id: i64,
    pub protocol_version: moonproof_wallet::ProtocolVersion,
    pub status: TxStatus,
    pub segment_status_map: Option<BTreeMap<u16, SegmentStatus>>,
    pub fees: Fees,
    pub unshielded: UnshieldedUtxos,
    pub tx_bytes: Vec<u8>,
}

// =====================================================================
// Contract-state observable configuration
// =====================================================================

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContractStateStreamStart {
    All,
    Latest,
    TxId {
        tx_id: TransactionId,
        inclusive: bool,
    },
    BlockHeight {
        height: u64,
        inclusive: bool,
    },
    BlockHash {
        hash: BlockHash,
        inclusive: bool,
    },
}

impl ContractStateStreamStart {
    #[must_use]
    pub fn tx_id(tx_id: TransactionId) -> Self {
        Self::TxId {
            tx_id,
            inclusive: true,
        }
    }
    #[must_use]
    pub fn block_height(height: u64) -> Self {
        Self::BlockHeight {
            height,
            inclusive: true,
        }
    }
    #[must_use]
    pub fn block_hash(hash: BlockHash) -> Self {
        Self::BlockHash {
            hash,
            inclusive: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContractStateQueryAt {
    BlockHeight(u64),
    BlockHash(BlockHash),
}

// =====================================================================
// Call result — output of executing a circuit off-chain
// =====================================================================

/// One event a call emitted, with the contract that emitted it.
#[derive(Debug, Clone)]
pub struct CallEvent {
    pub contract_address: ContractAddress,
    pub event: moonproof_runtime::ir::interp::EmittedEvent,
}

#[derive(Debug, Clone)]
pub struct CallResultPublic {
    pub next_contract_state: ContractState<InMemoryDB>,
    pub public_transcript: PartitionedTranscriptWire,
    pub partitioned_transcript: PartitionedTranscript,
    /// Every event the execution emitted, in emission order (midnight-js
    /// 5's `CallResultPublic.events`).
    pub events: Vec<CallEvent>,
}

#[derive(Debug, Clone)]
pub struct CallResultPrivate {
    pub input: AlignedValue,
    pub output: AlignedValue,
    pub private_transcript_outputs: Vec<AlignedValue>,
    pub result: moonproof_runtime_ir::RuntimeValue,
    pub next_private_state: moonproof_runtime_ir::RuntimeValue,
    pub next_zswap_local_state: CompactZswapLocalState,
}

#[derive(Debug, Clone)]
pub struct CallResult {
    pub public: CallResultPublic,
    pub private: CallResultPrivate,
    /// Every cross-contract call the circuit made, callees before their
    /// callers (midnight-js 5's `calls`, less the root's own entry,
    /// which `public` and `private` describe).
    pub callees: Vec<moonproof_runtime::CalleeCall>,
}

pub type PartitionedTranscript = (
    Option<moonproof_ledger::onchain_runtime::transcript::Transcript<InMemoryDB>>,
    Option<moonproof_ledger::onchain_runtime::transcript::Transcript<InMemoryDB>>,
);

pub type PartitionedTranscriptWire = Vec<
    moonproof_ledger::onchain_runtime::ops::Op<
        moonproof_ledger::onchain_runtime::result_mode::ResultModeGather,
        InMemoryDB,
    >,
>;

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

    #[test]
    fn tx_status_success_predicate() {
        assert!(TxStatus::SucceedEntirely.is_success());
        assert!(!TxStatus::FailEntirely.is_success());
        assert!(!TxStatus::FailFallible.is_success());
    }

    #[test]
    fn contract_state_stream_start_helpers_default_to_inclusive() {
        match ContractStateStreamStart::tx_id(TransactionId::new("0x1")) {
            ContractStateStreamStart::TxId { inclusive, .. } => assert!(inclusive),
            _ => panic!(),
        }
        match ContractStateStreamStart::block_height(42) {
            ContractStateStreamStart::BlockHeight { inclusive, .. } => assert!(inclusive),
            _ => panic!(),
        }
        match ContractStateStreamStart::block_hash(BlockHash::new("0xabc")) {
            ContractStateStreamStart::BlockHash { inclusive, .. } => assert!(inclusive),
            _ => panic!(),
        }
    }

    #[test]
    fn unshielded_utxos_default_is_empty() {
        let u = UnshieldedUtxos::default();
        assert_eq!(u.created, [] as [UnshieldedUtxo; 0]);
        assert_eq!(u.spent, [] as [UnshieldedUtxo; 0]);
    }
}