Skip to main content

moonproof_contracts/
types.rs

1//! Lifecycle-side types — finalized tx data, transaction status,
2//! fees, balances, call-result shapes, contract-state stream config.
3//!
4//! Pure-data wasm-friendly types live in
5//! [`crate::types`]. These ones either depend on
6//! [`moonproof_wallet::ProtocolVersion`] (heavy crate) or are only
7//! ever produced by the host's lifecycle pipeline (deploy / call /
8//! sync / submit), so they live here.
9
10use std::collections::BTreeMap;
11
12use moonproof_ledger::base_crypto::fab::AlignedValue;
13use moonproof_ledger::onchain_runtime::state::ContractState;
14use moonproof_ledger::storage::db::InMemoryDB;
15use serde::{Deserialize, Serialize};
16
17// Re-export the wasm-friendly runtime-side types so host consumers can
18// use a single `crate::types::*` prefix.
19pub use moonproof_runtime::types::{
20    BlockHash, CircuitId, CoinPublicKey, ContractAddress, EncPublicKey, PrivateStateId, ProverKey,
21    TransactionHash, TransactionId, VerifierKey, ZkConfig, Zkir,
22};
23
24use moonproof_runtime::CompactZswapLocalState;
25
26// =====================================================================
27// Transaction status
28// =====================================================================
29
30/// The status of a transaction as returned by the node after execution.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32pub enum TxStatus {
33    FailEntirely,
34    FailFallible,
35    SucceedEntirely,
36}
37
38impl TxStatus {
39    #[inline]
40    #[must_use]
41    pub fn is_success(&self) -> bool {
42        matches!(self, TxStatus::SucceedEntirely)
43    }
44}
45
46/// Per-segment application status inside a transaction.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
48pub enum SegmentStatus {
49    Success,
50    Fail,
51}
52
53// =====================================================================
54// Fees / unshielded balances
55// =====================================================================
56
57/// Port of TS `Fees`. String-encoded `u128` for round-trip safety.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct Fees {
60    pub paid_fees: String,
61    pub estimated_fees: String,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct UnshieldedBalance {
66    pub balance: u128,
67    pub token_type: [u8; 32],
68}
69
70pub type UnshieldedBalances = Vec<UnshieldedBalance>;
71
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct UnshieldedUtxo {
74    pub owner: moonproof_ledger::coin_structure::contract::ContractAddress,
75    pub intent_hash: [u8; 32],
76    pub token_type: [u8; 32],
77    pub value: u128,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Default)]
81pub struct UnshieldedUtxos {
82    pub created: Vec<UnshieldedUtxo>,
83    pub spent: Vec<UnshieldedUtxo>,
84}
85
86// =====================================================================
87// Finalized transaction data
88// =====================================================================
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct FinalizedTxData {
92    pub tx_id: TransactionId,
93    pub identifiers: Vec<TransactionId>,
94    pub tx_hash: TransactionHash,
95    pub block_hash: BlockHash,
96    pub block_height: u64,
97    pub block_timestamp_ms: i64,
98    pub block_author: Option<String>,
99    pub indexer_id: i64,
100    pub protocol_version: moonproof_wallet::ProtocolVersion,
101    pub status: TxStatus,
102    pub segment_status_map: Option<BTreeMap<u16, SegmentStatus>>,
103    pub fees: Fees,
104    pub unshielded: UnshieldedUtxos,
105    pub tx_bytes: Vec<u8>,
106}
107
108// =====================================================================
109// Contract-state observable configuration
110// =====================================================================
111
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum ContractStateStreamStart {
114    All,
115    Latest,
116    TxId {
117        tx_id: TransactionId,
118        inclusive: bool,
119    },
120    BlockHeight {
121        height: u64,
122        inclusive: bool,
123    },
124    BlockHash {
125        hash: BlockHash,
126        inclusive: bool,
127    },
128}
129
130impl ContractStateStreamStart {
131    #[must_use]
132    pub fn tx_id(tx_id: TransactionId) -> Self {
133        Self::TxId {
134            tx_id,
135            inclusive: true,
136        }
137    }
138    #[must_use]
139    pub fn block_height(height: u64) -> Self {
140        Self::BlockHeight {
141            height,
142            inclusive: true,
143        }
144    }
145    #[must_use]
146    pub fn block_hash(hash: BlockHash) -> Self {
147        Self::BlockHash {
148            hash,
149            inclusive: true,
150        }
151    }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum ContractStateQueryAt {
156    BlockHeight(u64),
157    BlockHash(BlockHash),
158}
159
160// =====================================================================
161// Call result — output of executing a circuit off-chain
162// =====================================================================
163
164/// One event a call emitted, with the contract that emitted it.
165#[derive(Debug, Clone)]
166pub struct CallEvent {
167    pub contract_address: ContractAddress,
168    pub event: moonproof_runtime::ir::interp::EmittedEvent,
169}
170
171#[derive(Debug, Clone)]
172pub struct CallResultPublic {
173    pub next_contract_state: ContractState<InMemoryDB>,
174    pub public_transcript: PartitionedTranscriptWire,
175    pub partitioned_transcript: PartitionedTranscript,
176    /// Every event the execution emitted, in emission order (midnight-js
177    /// 5's `CallResultPublic.events`).
178    pub events: Vec<CallEvent>,
179}
180
181#[derive(Debug, Clone)]
182pub struct CallResultPrivate {
183    pub input: AlignedValue,
184    pub output: AlignedValue,
185    pub private_transcript_outputs: Vec<AlignedValue>,
186    pub result: moonproof_runtime_ir::RuntimeValue,
187    pub next_private_state: moonproof_runtime_ir::RuntimeValue,
188    pub next_zswap_local_state: CompactZswapLocalState,
189}
190
191#[derive(Debug, Clone)]
192pub struct CallResult {
193    pub public: CallResultPublic,
194    pub private: CallResultPrivate,
195    /// Every cross-contract call the circuit made, callees before their
196    /// callers (midnight-js 5's `calls`, less the root's own entry,
197    /// which `public` and `private` describe).
198    pub callees: Vec<moonproof_runtime::CalleeCall>,
199}
200
201pub type PartitionedTranscript = (
202    Option<moonproof_ledger::onchain_runtime::transcript::Transcript<InMemoryDB>>,
203    Option<moonproof_ledger::onchain_runtime::transcript::Transcript<InMemoryDB>>,
204);
205
206pub type PartitionedTranscriptWire = Vec<
207    moonproof_ledger::onchain_runtime::ops::Op<
208        moonproof_ledger::onchain_runtime::result_mode::ResultModeGather,
209        InMemoryDB,
210    >,
211>;
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn tx_status_success_predicate() {
219        assert!(TxStatus::SucceedEntirely.is_success());
220        assert!(!TxStatus::FailEntirely.is_success());
221        assert!(!TxStatus::FailFallible.is_success());
222    }
223
224    #[test]
225    fn contract_state_stream_start_helpers_default_to_inclusive() {
226        match ContractStateStreamStart::tx_id(TransactionId::new("0x1")) {
227            ContractStateStreamStart::TxId { inclusive, .. } => assert!(inclusive),
228            _ => panic!(),
229        }
230        match ContractStateStreamStart::block_height(42) {
231            ContractStateStreamStart::BlockHeight { inclusive, .. } => assert!(inclusive),
232            _ => panic!(),
233        }
234        match ContractStateStreamStart::block_hash(BlockHash::new("0xabc")) {
235            ContractStateStreamStart::BlockHash { inclusive, .. } => assert!(inclusive),
236            _ => panic!(),
237        }
238    }
239
240    #[test]
241    fn unshielded_utxos_default_is_empty() {
242        let u = UnshieldedUtxos::default();
243        assert_eq!(u.created, [] as [UnshieldedUtxo; 0]);
244        assert_eq!(u.spent, [] as [UnshieldedUtxo; 0]);
245    }
246}