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
//! Indexer-driven [`ContractRuntimeState`] fold.
//!
//! Lives in the host crate because it consumes
//! [`moonproof_indexer_client::ContractActionTickRaw`] — pulling the
//! indexer dep into the wasm-friendly runtime crate is what we want
//! to avoid. The struct itself + the hex codecs live in
//! [`moonproof_runtime::state`].

use moonproof_indexer_client::ContractActionTickRaw;
use moonproof_runtime::state::{
    contract_address_to_hex, decode_contract_address, decode_contract_state, ContractRuntimeState,
};

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

/// Construct a runtime state by parsing a [`ContractActionTickRaw`] —
/// typically the first tick returned by `find_deployed_contract`'s
/// `contractAction` query.
///
/// The tick's `address` field must decode to the same expected
/// [`moonproof_ledger::coin_structure::contract::ContractAddress`] supplied by
/// the caller — we compare against the value carried in the tick to
/// guard against mis-routed replies.
///
/// # Errors
///
/// - [`ContractRuntimeError::HexDecode`] if the tick's `address` or
///   `state` hex fails to decode.
/// - [`ContractRuntimeError::Deserialize`] if the state bytes aren't a
///   well-formed tagged `ContractState` blob.
/// - [`ContractRuntimeError::AddressMismatch`] if `expected` doesn't
///   match the tick's address.
pub fn from_observed(
    expected: moonproof_ledger::coin_structure::contract::ContractAddress,
    tick: &ContractActionTickRaw,
) -> Result<ContractRuntimeState> {
    let tick_address = decode_contract_address(&tick.address)?;
    if tick_address != expected {
        return Err(ContractRuntimeError::AddressMismatch {
            expected: contract_address_to_hex(&expected),
            got: tick.address.clone(),
        });
    }
    let current_state = decode_contract_state(&tick.state)?;
    Ok(ContractRuntimeState::with_observed(
        expected,
        current_state,
        Some(tick.transaction_id),
        Some(tick.block.height),
    ))
}

/// Replay a batch of [`ContractActionTickRaw`] ticks into a
/// [`ContractRuntimeState`].
///
/// Ticks whose `address` doesn't match the state's address are
/// skipped. For matching ticks, the tick's `state` blob replaces the
/// runtime state's `current_state` regardless of action kind — the
/// indexer always sends the post-action full state, not a delta.
/// Observation markers advance monotonically.
///
/// # Errors
///
/// - [`ContractRuntimeError::HexDecode`] / [`ContractRuntimeError::Deserialize`]
///   if a tick's `state` hex is malformed.
pub fn fold_contract_actions<I>(
    state: ContractRuntimeState,
    ticks: I,
) -> Result<ContractRuntimeState>
where
    I: IntoIterator<Item = ContractActionTickRaw>,
{
    let mut state = state;
    let expected_hex = state.address_hex();
    for tick in ticks {
        if tick.address != expected_hex {
            continue;
        }
        let new_contract_state = decode_contract_state(&tick.state)?;
        state.apply_observed(new_contract_state, tick.transaction_id, tick.block.height);
    }
    Ok(state)
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_indexer_client::{BlockRef, ContractActionKind};
    use moonproof_ledger::base_crypto::hash::{HashOutput, PERSISTENT_HASH_BYTES};
    use moonproof_ledger::coin_structure::contract::ContractAddress;
    use moonproof_ledger::onchain_runtime::state::ContractState;
    use moonproof_ledger::storage::db::InMemoryDB;
    use moonproof_runtime::state::encode_contract_state;

    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]))
    }

    fn tick(
        kind: ContractActionKind,
        address: &str,
        state_hex: String,
        tx_id: i64,
        height: i64,
    ) -> ContractActionTickRaw {
        ContractActionTickRaw {
            kind,
            address: address.to_owned(),
            state: state_hex,
            zswap_state: String::new(),
            unshielded_balances: Vec::new(),
            entry_point: None,
            transaction_id: tx_id,
            transaction_hash: "0xdeadbeef".to_owned(),
            block: BlockRef {
                hash: "0xcafebabe".to_owned(),
                height,
            },
        }
    }

    #[test]
    fn from_observed_populates_observation_markers() {
        let addr = dummy_address(0x03);
        let state_hex = encode_contract_state(&dummy_contract_state()).unwrap();
        let t = tick(
            ContractActionKind::Deploy,
            &contract_address_to_hex(&addr),
            state_hex,
            7,
            42,
        );
        let built = from_observed(addr, &t).unwrap();
        assert_eq!(built.address(), &addr);
        assert_eq!(built.last_observed_tx_id(), Some(7));
        assert_eq!(built.last_observed_block_height(), Some(42));
    }

    #[test]
    fn from_observed_rejects_address_mismatch() {
        let addr = dummy_address(0x04);
        let other = dummy_address(0x05);
        let state_hex = encode_contract_state(&dummy_contract_state()).unwrap();
        let t = tick(
            ContractActionKind::Deploy,
            &contract_address_to_hex(&other),
            state_hex,
            1,
            1,
        );
        let err = from_observed(addr, &t).unwrap_err();
        matches!(err, ContractRuntimeError::AddressMismatch { .. });
    }

    #[test]
    fn fold_empty_ticks_is_identity() {
        let addr = dummy_address(0x06);
        let state = ContractRuntimeState::new(addr, dummy_contract_state());
        let out = fold_contract_actions(state.clone(), std::iter::empty::<_>()).unwrap();
        assert_eq!(state.address(), out.address());
        assert_eq!(state.last_observed_tx_id(), out.last_observed_tx_id());
    }

    #[test]
    fn fold_advances_on_matching_tick() {
        let addr = dummy_address(0x07);
        let addr_hex = contract_address_to_hex(&addr);
        let state_hex = encode_contract_state(&dummy_contract_state()).unwrap();
        let state = ContractRuntimeState::new(addr, dummy_contract_state());
        let out = fold_contract_actions(
            state,
            [
                tick(
                    ContractActionKind::Deploy,
                    &addr_hex,
                    state_hex.clone(),
                    10,
                    100,
                ),
                tick(ContractActionKind::Call, &addr_hex, state_hex, 12, 102),
            ],
        )
        .unwrap();
        assert_eq!(out.last_observed_tx_id(), Some(12));
        assert_eq!(out.last_observed_block_height(), Some(102));
    }

    #[test]
    fn fold_ignores_non_matching_tick() {
        let addr = dummy_address(0x08);
        let other = dummy_address(0x09);
        let other_hex = contract_address_to_hex(&other);
        let state_hex = encode_contract_state(&dummy_contract_state()).unwrap();
        let state = ContractRuntimeState::new(addr, dummy_contract_state());
        let out = fold_contract_actions(
            state,
            [tick(
                ContractActionKind::Deploy,
                &other_hex,
                state_hex,
                5,
                50,
            )],
        )
        .unwrap();
        assert!(out.last_observed_tx_id().is_none());
        assert!(out.last_observed_block_height().is_none());
    }

    #[test]
    fn fold_tracks_monotonic_observation_markers() {
        let addr = dummy_address(0x0A);
        let addr_hex = contract_address_to_hex(&addr);
        let state_hex = encode_contract_state(&dummy_contract_state()).unwrap();
        let state = ContractRuntimeState::new(addr, dummy_contract_state());
        let out = fold_contract_actions(
            state,
            [
                tick(
                    ContractActionKind::Call,
                    &addr_hex,
                    state_hex.clone(),
                    20,
                    200,
                ),
                tick(
                    ContractActionKind::Call,
                    &addr_hex,
                    state_hex.clone(),
                    5,
                    50,
                ),
                tick(ContractActionKind::Update, &addr_hex, state_hex, 15, 150),
            ],
        )
        .unwrap();
        assert_eq!(out.last_observed_tx_id(), Some(20));
        assert_eq!(out.last_observed_block_height(), Some(200));
    }

    #[test]
    fn fold_surfaces_malformed_state_hex() {
        let addr = dummy_address(0x0B);
        let addr_hex = contract_address_to_hex(&addr);
        let state = ContractRuntimeState::new(addr, dummy_contract_state());
        let err = fold_contract_actions(
            state,
            [tick(
                ContractActionKind::Call,
                &addr_hex,
                "zzzz".to_owned(),
                1,
                1,
            )],
        )
        .unwrap_err();
        matches!(err, ContractRuntimeError::HexDecode(_));
    }
}