moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Port of `@midnight-ntwrk/midnight-js-contracts/src/get-states.ts`.
//!
//! Helpers that fetch the current public (and optionally private)
//! states of a deployed contract. Used by [`crate::unproven_call_tx`]
//! and [`crate::find_deployed_contract`] to seed circuit execution +
//! verifier-key validation.

#[cfg(test)]
use std::sync::Arc;

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::ContractState;
use moonproof_ledger::storage::db::InMemoryDB;

use crate::error::{ContractRuntimeError, Result};
use crate::providers::{HasPublicData, PrivateStateProvider, PublicDataProvider};
use crate::types::{ContractStateQueryAt, PrivateStateId};

/// Fetch the contract's current on-chain `ContractState` in one
/// async round-trip. Use the runtime's sync `walker::*` +
/// `ledger::field_at` to project individual fields without further
/// network calls.
///
/// ```ignore
/// let state = query_full(&providers, &address).await?;
/// let cell = moonproof_runtime::ledger::field_at(&state, 0)?;
/// let buf  = moonproof_runtime::ledger::counter_atoms(&cell)?;
/// ```
///
/// # Errors
///
/// - [`ContractRuntimeError::NotFound`] if no contract is deployed
///   at `address`.
/// - Any error the public-data provider raises.
pub async fn query_full<C: HasPublicData + ?Sized>(
    providers: &C,
    address: &ContractAddress,
) -> Result<ContractState<InMemoryDB>> {
    providers
        .public_data()
        .query_contract_state(address, None)
        .await?
        .ok_or_else(|| {
            ContractRuntimeError::NotFound(format!(
                "no contract deployed at {}",
                moonproof_runtime::contract_address_to_hex(address),
            ))
        })
}

/// Publicly visible states of a contract. Port of TS
/// `PublicContractStates`.
///
/// The zswap chain state + ledger parameters are opaque tagged-
/// serialized bytes; callers that need typed access deserialize on
/// demand. Kept as bytes to avoid pulling deep zswap / ledger
/// parameter types through the public runtime API surface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicContractStates {
    pub zswap_chain_state_bytes: Vec<u8>,
    pub contract_state: ContractState<InMemoryDB>,
    pub ledger_parameters_bytes: Vec<u8>,
}

/// Public + private states of a contract. Port of TS
/// `ContractStates<PS>`. Generic on the private-state payload —
/// callers that use `PS = Vec<u8>` keep the bytes opaque; callers
/// that want typed access wrap this with a typed adapter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractStates<PS> {
    pub zswap_chain_state_bytes: Vec<u8>,
    pub contract_state: ContractState<InMemoryDB>,
    pub ledger_parameters_bytes: Vec<u8>,
    pub private_state: PS,
}

/// Fetch just the public states at `contract_address` from the
/// public-data provider. Port of TS `getPublicStates`.
///
/// # Errors
///
/// - [`ContractRuntimeError::NotFound`] when the provider returns
///   `None` for `query_zswap_and_contract_state`, matching the TS
///   `assertDefined(... 'No public state found at contract address')`
///   behaviour.
/// - Any provider error propagates unchanged.
pub async fn query_public<D: PublicDataProvider + ?Sized>(
    public_data: &D,
    contract_address: &ContractAddress,
) -> Result<PublicContractStates> {
    query_public_at(public_data, contract_address, None).await
}

/// [`query_public`] at a given block, or the latest when `at` is `None`.
/// TS `getPublicStates` takes the block as an optional argument.
pub async fn query_public_at<D: PublicDataProvider + ?Sized>(
    public_data: &D,
    contract_address: &ContractAddress,
    at: Option<ContractStateQueryAt>,
) -> Result<PublicContractStates> {
    let bundle = public_data
        .query_zswap_and_contract_state(contract_address, at)
        .await?
        .ok_or_else(|| {
            ContractRuntimeError::NotFound(format!(
                "No public state found at contract address {}",
                moonproof_runtime::state::contract_address_to_hex(contract_address),
            ))
        })?;
    Ok(PublicContractStates {
        zswap_chain_state_bytes: bundle.zswap_chain_state_bytes,
        contract_state: bundle.contract_state,
        ledger_parameters_bytes: bundle.ledger_parameters_bytes,
    })
}

/// Fetch the public states AND the private state stored at
/// `private_state_id`. Port of TS `getStates<PS>`.
///
/// The private-state provider returns `Vec<u8>` — the Rust version of
/// TS's opaque `PS`. Callers that want a typed private state
/// deserialize at their boundary. This keeps the provider trait
/// object-safe.
///
/// # Errors
///
/// - [`ContractRuntimeError::NotFound`] for missing public state OR
///   missing private state. The error message distinguishes the two.
pub async fn query_with_private_state<D, P>(
    public_data: &D,
    private_state: &P,
    contract_address: &ContractAddress,
    private_state_id: &PrivateStateId,
) -> Result<ContractStates<Vec<u8>>>
where
    D: PublicDataProvider + ?Sized,
    P: PrivateStateProvider + ?Sized,
{
    query_with_private_state_at(
        public_data,
        private_state,
        contract_address,
        private_state_id,
        None,
    )
    .await
}

/// [`query_with_private_state`] with the public states read at a given
/// block, or the latest when `at` is `None`.
pub async fn query_with_private_state_at<D, P>(
    public_data: &D,
    private_state: &P,
    contract_address: &ContractAddress,
    private_state_id: &PrivateStateId,
    at: Option<ContractStateQueryAt>,
) -> Result<ContractStates<Vec<u8>>>
where
    D: PublicDataProvider + ?Sized,
    P: PrivateStateProvider + ?Sized,
{
    let public = query_public_at(public_data, contract_address, at).await?;
    let ps_bytes = private_state.get(private_state_id).await?.ok_or_else(|| {
        ContractRuntimeError::NotFound(format!(
            "No private state found at private state ID '{private_state_id}'"
        ))
    })?;
    Ok(ContractStates {
        zswap_chain_state_bytes: public.zswap_chain_state_bytes,
        contract_state: public.contract_state,
        ledger_parameters_bytes: public.ledger_parameters_bytes,
        private_state: ps_bytes,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::public_data::{PublicDataStream, ZSwapAndContractState};
    use crate::providers::{PrivateStateProvider, PublicDataProvider};
    use crate::types::{
        ContractStateQueryAt, ContractStateStreamStart, FinalizedTxData, TransactionId,
        UnshieldedBalances,
    };
    use async_trait::async_trait;
    use moonproof_ledger::base_crypto::hash::HashOutput;
    use moonproof_ledger::onchain_runtime::state::{
        ContractMaintenanceAuthority, ContractState, StateValue,
    };
    use moonproof_ledger::signatures::SigningKey;
    use moonproof_ledger::storage::storage::HashMap as StorageHashMap;

    fn dummy_contract_state() -> ContractState<InMemoryDB> {
        ContractState::<InMemoryDB>::new(
            StateValue::Null,
            StorageHashMap::new(),
            ContractMaintenanceAuthority::default(),
        )
    }

    fn dummy_address() -> ContractAddress {
        ContractAddress(HashOutput([0x55u8; 32]))
    }

    #[derive(Debug)]
    struct FakePublicData {
        zswap_bundle: Option<ZSwapAndContractState>,
    }
    #[async_trait]
    impl PublicDataProvider for FakePublicData {
        async fn query_contract_state(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<ContractState<InMemoryDB>>> {
            unimplemented!()
        }
        async fn query_zswap_and_contract_state(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<ZSwapAndContractState>> {
            Ok(self.zswap_bundle.clone())
        }
        async fn query_deploy_contract_state(
            &self,
            _address: &ContractAddress,
        ) -> Result<Option<ContractState<InMemoryDB>>> {
            unimplemented!()
        }
        async fn query_unshielded_balances(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<UnshieldedBalances>> {
            unimplemented!()
        }
        async fn watch_for_deploy_tx_data(
            &self,
            _address: &ContractAddress,
        ) -> Result<FinalizedTxData> {
            unimplemented!()
        }
        async fn watch_for_tx_data(&self, _tx_id: &TransactionId) -> Result<FinalizedTxData> {
            unimplemented!()
        }
        async fn watch_for_contract_state(
            &self,
            _address: &ContractAddress,
        ) -> Result<ContractState<InMemoryDB>> {
            unimplemented!()
        }
        async fn watch_for_unshielded_balances(
            &self,
            _address: &ContractAddress,
        ) -> Result<UnshieldedBalances> {
            unimplemented!()
        }
        async fn contract_state_stream(
            &self,
            _address: &ContractAddress,
            _start: ContractStateStreamStart,
        ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
            unimplemented!()
        }
        async fn unshielded_balances_stream(
            &self,
            _address: &ContractAddress,
            _start: ContractStateStreamStart,
        ) -> Result<PublicDataStream<UnshieldedBalances>> {
            unimplemented!()
        }
    }

    #[derive(Debug)]
    struct FakePrivateState {
        stored: Option<Vec<u8>>,
    }
    #[async_trait]
    impl PrivateStateProvider for FakePrivateState {
        async fn set_contract_address(&self, _address: &ContractAddress) -> Result<()> {
            Ok(())
        }
        async fn set(&self, _: &PrivateStateId, _: Vec<u8>) -> Result<()> {
            Ok(())
        }
        async fn get(&self, _: &PrivateStateId) -> Result<Option<Vec<u8>>> {
            Ok(self.stored.clone())
        }
        async fn remove(&self, _: &PrivateStateId) -> Result<()> {
            Ok(())
        }
        async fn clear(&self) -> Result<()> {
            Ok(())
        }
        async fn set_signing_key(&self, _: &ContractAddress, _: SigningKey) -> Result<()> {
            Ok(())
        }
        async fn get_signing_key(&self, _: &ContractAddress) -> Result<Option<SigningKey>> {
            Ok(None)
        }
        async fn remove_signing_key(&self, _: &ContractAddress) -> Result<()> {
            Ok(())
        }
        async fn clear_signing_keys(&self) -> Result<()> {
            Ok(())
        }
        async fn export_private_states(
            &self,
            _options: &crate::providers::ExportPrivateStatesOptions,
        ) -> Result<crate::providers::PrivateStateExport> {
            unimplemented!()
        }
        async fn import_private_states(
            &self,
            _export: &crate::providers::PrivateStateExport,
            _options: &crate::providers::ImportPrivateStatesOptions,
        ) -> Result<crate::providers::ImportPrivateStatesResult> {
            unimplemented!()
        }
        async fn export_signing_keys(
            &self,
            _options: &crate::providers::private_state::ExportSigningKeysOptions,
        ) -> Result<crate::providers::SigningKeyExport> {
            unimplemented!()
        }
        async fn import_signing_keys(
            &self,
            _export: &crate::providers::SigningKeyExport,
            _options: &crate::providers::private_state::ImportSigningKeysOptions,
        ) -> Result<crate::providers::private_state::ImportSigningKeysResult> {
            unimplemented!()
        }
    }

    fn arc_pd(bundle: Option<ZSwapAndContractState>) -> Arc<dyn PublicDataProvider> {
        Arc::new(FakePublicData {
            zswap_bundle: bundle,
        })
    }

    fn arc_ps(stored: Option<Vec<u8>>) -> Arc<dyn PrivateStateProvider> {
        Arc::new(FakePrivateState { stored })
    }

    /// ports: `get-states.test.ts::getPublicStates::should successfully retrieve public states`
    #[tokio::test]
    async fn get_public_states_returns_all_three_bundle_fields() {
        let bundle = ZSwapAndContractState {
            zswap_chain_state_bytes: vec![0xAA, 0xBB],
            contract_state: dummy_contract_state(),
            ledger_parameters_bytes: vec![0xCC, 0xDD],
        };
        let pd = arc_pd(Some(bundle));
        let got = query_public(&pd, &dummy_address()).await.unwrap();
        assert_eq!(got.zswap_chain_state_bytes, vec![0xAA, 0xBB]);
        assert_eq!(got.ledger_parameters_bytes, vec![0xCC, 0xDD]);
    }

    #[tokio::test]
    async fn get_public_states_errors_when_provider_returns_none() {
        let pd = arc_pd(None);
        let err = query_public(&pd, &dummy_address()).await.unwrap_err();
        matches!(err, ContractRuntimeError::NotFound(_));
        let msg = format!("{err}");
        assert!(
            msg.contains("No public state found"),
            "expected the TS message, got `{msg}`",
        );
    }

    /// ports: `get-states.test.ts::getStates::should successfully retrieve all states`
    #[tokio::test]
    async fn get_states_fetches_both_public_and_private_state() {
        let bundle = ZSwapAndContractState {
            zswap_chain_state_bytes: vec![1, 2, 3],
            contract_state: dummy_contract_state(),
            ledger_parameters_bytes: vec![4, 5, 6],
        };
        let pd = arc_pd(Some(bundle));
        let ps = arc_ps(Some(b"private!".to_vec()));
        let got = query_with_private_state(&pd, &ps, &dummy_address(), &PrivateStateId::new("x"))
            .await
            .unwrap();
        assert_eq!(got.private_state, b"private!".to_vec());
        assert_eq!(got.zswap_chain_state_bytes, vec![1, 2, 3]);
    }

    #[tokio::test]
    async fn get_states_errors_when_private_state_missing() {
        let bundle = ZSwapAndContractState {
            zswap_chain_state_bytes: vec![1],
            contract_state: dummy_contract_state(),
            ledger_parameters_bytes: vec![2],
        };
        let pd = arc_pd(Some(bundle));
        let ps = arc_ps(None); // provider returns None for the id
        let err =
            query_with_private_state(&pd, &ps, &dummy_address(), &PrivateStateId::new("missing"))
                .await
                .unwrap_err();
        matches!(err, ContractRuntimeError::NotFound(_));
        let msg = format!("{err}");
        assert!(
            msg.contains("No private state found"),
            "expected the TS message, got `{msg}`",
        );
    }

    #[tokio::test]
    async fn get_states_propagates_public_state_missing_error_without_hitting_private_provider() {
        let pd = arc_pd(None);
        let ps = arc_ps(Some(b"ignored".to_vec()));
        let err = query_with_private_state(&pd, &ps, &dummy_address(), &PrivateStateId::new("x"))
            .await
            .unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("No public state"), "{msg}");
    }
}