moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! [`ContractRuntimeState`] — the per-contract client-side view.
//!
//! Holds a plain read-only snapshot the caller owns by value. Private
//! state is the caller's responsibility — see the crate-level `lib.rs`
//! docs for the witness-bytes-at-call-time contract.
//!
//! # What lives here
//!
//! - [`ContractRuntimeState`] — a bundle of the [`ContractAddress`],
//!   the latest observed [`ContractState<InMemoryDB>`], and the
//!   transaction id + block height of the indexer tick that produced
//!   the current snapshot.
//! - [`contract_address_to_hex`] / [`decode_contract_address`] /
//!   [`encode_contract_state`] / [`decode_contract_state`] — small
//!   pure-compute hex codecs the indexer-driven fold uses.
//!
//! The indexer-driven fold helper (`fold_contract_actions`) lives in
//! [`moonproof_contracts::state_fold`] — it consumes
//! [`moonproof_indexer_client::ContractActionTickRaw`] which would pull
//! a heavy network dep into this wasm-friendly crate.

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::{ChargedState, ContractState};
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::storage::db::InMemoryDB;

use crate::error::{ContractRuntimeError, Result};

/// The client-side view of a single deployed contract.
#[derive(Debug, Clone)]
pub struct ContractRuntimeState {
    address: ContractAddress,
    current_state: ContractState<InMemoryDB>,
    last_observed_tx_id: Option<i64>,
    last_observed_block_height: Option<i64>,
}

impl ContractRuntimeState {
    /// Construct a new runtime state with the given address and
    /// initial contract state.
    #[must_use]
    pub fn new(address: ContractAddress, current_state: ContractState<InMemoryDB>) -> Self {
        Self {
            address,
            current_state,
            last_observed_tx_id: None,
            last_observed_block_height: None,
        }
    }

    /// Construct a state pre-populated with observation markers, used
    /// by the indexer-driven fold helper in `moonproof_contracts::state_fold`.
    #[must_use]
    pub fn with_observed(
        address: ContractAddress,
        current_state: ContractState<InMemoryDB>,
        last_observed_tx_id: Option<i64>,
        last_observed_block_height: Option<i64>,
    ) -> Self {
        Self {
            address,
            current_state,
            last_observed_tx_id,
            last_observed_block_height,
        }
    }

    /// Replace the current state and advance the observation markers
    /// monotonically. Used by the fold helper when applying a new tick.
    pub fn apply_observed(
        &mut self,
        current_state: ContractState<InMemoryDB>,
        tx_id: i64,
        block_height: i64,
    ) {
        self.current_state = current_state;
        self.last_observed_tx_id = Some(match self.last_observed_tx_id {
            Some(prev) => prev.max(tx_id),
            None => tx_id,
        });
        self.last_observed_block_height = Some(match self.last_observed_block_height {
            Some(prev) => prev.max(block_height),
            None => block_height,
        });
    }

    /// The [`ContractAddress`] this state lives at.
    #[inline]
    #[must_use]
    pub fn address(&self) -> &ContractAddress {
        &self.address
    }

    #[must_use]
    pub fn address_hex(&self) -> String {
        contract_address_to_hex(&self.address)
    }

    #[inline]
    #[must_use]
    pub fn current_state(&self) -> &ContractState<InMemoryDB> {
        &self.current_state
    }

    #[inline]
    #[must_use]
    pub fn charged_state(&self) -> &ChargedState<InMemoryDB> {
        &self.current_state.data
    }

    #[inline]
    #[must_use]
    pub fn last_observed_tx_id(&self) -> Option<i64> {
        self.last_observed_tx_id
    }

    #[inline]
    #[must_use]
    pub fn last_observed_block_height(&self) -> Option<i64> {
        self.last_observed_block_height
    }
}

/// Hex-encode a [`ContractAddress`] in the same lower-case-64-char
/// convention the indexer uses on the wire.
#[must_use]
pub fn contract_address_to_hex(address: &ContractAddress) -> String {
    hex::encode(address.0 .0)
}

/// Parse a 64-hex-char address into a [`ContractAddress`].
pub fn decode_contract_address(hex_str: &str) -> Result<ContractAddress> {
    let bytes = hex::decode(hex_str)?;
    if bytes.len() != 32 {
        return Err(ContractRuntimeError::Deserialize {
            context: "decode_contract_address: expected 32 bytes",
            source: std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("got {} bytes", bytes.len()),
            ),
        });
    }
    let mut hash_bytes = [0u8; 32];
    hash_bytes.copy_from_slice(&bytes);
    Ok(ContractAddress(
        moonproof_ledger::base_crypto::hash::HashOutput(hash_bytes),
    ))
}

/// Parse a hex-encoded tagged [`ContractState`] blob into a
/// [`ContractState<InMemoryDB>`].
pub fn decode_contract_state(hex_str: &str) -> Result<ContractState<InMemoryDB>> {
    let bytes = hex::decode(hex_str)?;
    tagged_deserialize::<ContractState<InMemoryDB>>(&mut bytes.as_slice()).map_err(|e| {
        ContractRuntimeError::Deserialize {
            context: "tagged_deserialize(ContractState)",
            source: e,
        }
    })
}

/// Tagged-serialize a [`ContractState<InMemoryDB>`] to hex — inverse
/// of [`decode_contract_state`].
pub fn encode_contract_state(state: &ContractState<InMemoryDB>) -> Result<String> {
    let mut buf = Vec::new();
    tagged_serialize(state, &mut buf).map_err(|e| ContractRuntimeError::Serialize {
        context: "tagged_serialize(ContractState)",
        source: e,
    })?;
    Ok(hex::encode(buf))
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::hash::{HashOutput, PERSISTENT_HASH_BYTES};
    use moonproof_ledger::onchain_runtime::state::ContractState;

    fn dummy_contract_state() -> ContractState<InMemoryDB> {
        use moonproof_ledger::onchain_runtime::state::{
            ContractMaintenanceAuthority, EntryPointBuf,
        };
        use moonproof_ledger::storage::storage::HashMap;
        let op_key: EntryPointBuf = b"noop"[..].into();
        ContractState::<InMemoryDB>::new(
            moonproof_ledger::onchain_runtime::state::StateValue::Null,
            HashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
            ContractMaintenanceAuthority::default(),
        )
    }

    fn dummy_address(byte: u8) -> ContractAddress {
        ContractAddress(HashOutput([byte; PERSISTENT_HASH_BYTES]))
    }

    #[test]
    fn new_stores_address_and_state() {
        let addr = dummy_address(0x01);
        let state = ContractRuntimeState::new(addr, dummy_contract_state());
        assert_eq!(state.address(), &addr);
        assert_eq!(state.address_hex().len(), 64);
        assert!(state.last_observed_tx_id().is_none());
        assert!(state.last_observed_block_height().is_none());
        assert_eq!(
            state.address_hex(),
            "0101010101010101010101010101010101010101010101010101010101010101",
        );
    }

    #[test]
    fn charged_state_is_current_state_data() {
        let state = ContractRuntimeState::new(dummy_address(0x02), dummy_contract_state());
        let charged = state.charged_state();
        let from_full = &state.current_state().data;
        assert!(std::ptr::eq(charged, from_full));
    }

    #[test]
    fn contract_address_roundtrips_through_hex() {
        let addr = dummy_address(0xab);
        let hex = contract_address_to_hex(&addr);
        let back = decode_contract_address(&hex).unwrap();
        assert_eq!(addr, back);
    }

    #[test]
    fn decode_contract_address_rejects_short_input() {
        let err = decode_contract_address("deadbeef").unwrap_err();
        matches!(err, ContractRuntimeError::Deserialize { .. });
    }

    #[test]
    fn decode_contract_address_rejects_invalid_hex() {
        let err = decode_contract_address("not-hex").unwrap_err();
        matches!(err, ContractRuntimeError::HexDecode(_));
    }

    #[test]
    fn contract_state_roundtrips_through_hex() {
        let cs = dummy_contract_state();
        let hex = encode_contract_state(&cs).unwrap();
        let back = decode_contract_state(&hex).unwrap();
        let reencoded = encode_contract_state(&back).unwrap();
        assert_eq!(hex, reencoded);
    }

    #[test]
    fn decode_contract_state_rejects_malformed_hex() {
        let err = decode_contract_state("zzzz").unwrap_err();
        matches!(err, ContractRuntimeError::HexDecode(_));
    }

    #[test]
    fn decode_contract_state_rejects_truncated_payload() {
        let err = decode_contract_state("aa").unwrap_err();
        matches!(err, ContractRuntimeError::Deserialize { .. });
    }

    #[test]
    fn apply_observed_advances_markers() {
        let addr = dummy_address(0x03);
        let mut state = ContractRuntimeState::new(addr, dummy_contract_state());
        state.apply_observed(dummy_contract_state(), 7, 42);
        assert_eq!(state.last_observed_tx_id(), Some(7));
        assert_eq!(state.last_observed_block_height(), Some(42));

        // Monotonic — older tick must not regress.
        state.apply_observed(dummy_contract_state(), 3, 10);
        assert_eq!(state.last_observed_tx_id(), Some(7));
        assert_eq!(state.last_observed_block_height(), Some(42));
    }
}