Skip to main content

moonproof_runtime/
compact_types.rs

1//! Typed wrappers + named shapes returned by the Rust source emitted
2//! by `moonproof-codegen`. Mirrors compactc's `compact-types.ts`
3//! type SET; the projection from atom buffers happens through
4//! [`crate::walker`] (single source of truth across every binding
5//! language).
6//!
7//! These live in `moonproof-runtime` so generated code, library code,
8//! and downstream consumers all reach for the same type — there's no
9//! per-language duplicate.
10
11use std::collections::{BTreeMap, BTreeSet};
12
13use moonproof_runtime_ir::value::ValueProjectionError;
14use moonproof_runtime_ir::RuntimeValue;
15use serde::{Deserialize, Serialize};
16
17// ---------------------------------------------------------------------------
18// Multi-element storage views
19// ---------------------------------------------------------------------------
20
21/// Typed wrapper over a `Map<K, V>` ledger snapshot.
22#[derive(Debug, Clone)]
23pub struct CompactMap<K, V> {
24    inner: BTreeMap<K, V>,
25}
26
27impl<K: Ord, V> CompactMap<K, V> {
28    #[must_use]
29    pub fn new(inner: BTreeMap<K, V>) -> Self {
30        Self { inner }
31    }
32    #[must_use]
33    pub fn lookup(&self, k: &K) -> Option<&V> {
34        self.inner.get(k)
35    }
36    #[must_use]
37    pub fn member(&self, k: &K) -> bool {
38        self.inner.contains_key(k)
39    }
40    #[must_use]
41    pub fn size(&self) -> u64 {
42        self.inner.len() as u64
43    }
44    #[must_use]
45    pub fn is_empty(&self) -> bool {
46        self.inner.is_empty()
47    }
48    pub fn iter(&self) -> std::collections::btree_map::Iter<'_, K, V> {
49        self.inner.iter()
50    }
51    #[must_use]
52    pub fn into_inner(self) -> BTreeMap<K, V> {
53        self.inner
54    }
55}
56
57impl<'a, K: Ord, V> IntoIterator for &'a CompactMap<K, V> {
58    type Item = (&'a K, &'a V);
59    type IntoIter = std::collections::btree_map::Iter<'a, K, V>;
60    fn into_iter(self) -> Self::IntoIter {
61        self.iter()
62    }
63}
64
65impl<K: Ord, V> IntoIterator for CompactMap<K, V> {
66    type Item = (K, V);
67    type IntoIter = std::collections::btree_map::IntoIter<K, V>;
68    fn into_iter(self) -> Self::IntoIter {
69        self.inner.into_iter()
70    }
71}
72
73/// Typed wrapper over a `Set<T>` snapshot.
74#[derive(Debug, Clone)]
75pub struct CompactSet<T> {
76    inner: BTreeSet<T>,
77}
78
79impl<T: Ord> CompactSet<T> {
80    #[must_use]
81    pub fn new(elements: Vec<T>) -> Self {
82        Self {
83            inner: elements.into_iter().collect(),
84        }
85    }
86    #[must_use]
87    pub fn member(&self, t: &T) -> bool {
88        self.inner.contains(t)
89    }
90    #[must_use]
91    pub fn size(&self) -> u64 {
92        self.inner.len() as u64
93    }
94    #[must_use]
95    pub fn is_empty(&self) -> bool {
96        self.inner.is_empty()
97    }
98    pub fn iter(&self) -> std::collections::btree_set::Iter<'_, T> {
99        self.inner.iter()
100    }
101}
102
103impl<'a, T: Ord> IntoIterator for &'a CompactSet<T> {
104    type Item = &'a T;
105    type IntoIter = std::collections::btree_set::Iter<'a, T>;
106    fn into_iter(self) -> Self::IntoIter {
107        self.iter()
108    }
109}
110
111/// Typed wrapper over a `List<T>` snapshot.
112#[derive(Debug, Clone)]
113pub struct CompactList<T> {
114    inner: Vec<T>,
115}
116
117impl<T> CompactList<T> {
118    #[must_use]
119    pub fn new(inner: Vec<T>) -> Self {
120        Self { inner }
121    }
122    #[must_use]
123    pub fn head(&self) -> Option<&T> {
124        self.inner.first()
125    }
126    #[must_use]
127    pub fn is_empty(&self) -> bool {
128        self.inner.is_empty()
129    }
130    #[must_use]
131    pub fn length(&self) -> u64 {
132        self.inner.len() as u64
133    }
134    pub fn iter(&self) -> std::slice::Iter<'_, T> {
135        self.inner.iter()
136    }
137    #[must_use]
138    pub fn into_inner(self) -> Vec<T> {
139        self.inner
140    }
141}
142
143impl<'a, T> IntoIterator for &'a CompactList<T> {
144    type Item = &'a T;
145    type IntoIter = std::slice::Iter<'a, T>;
146    fn into_iter(self) -> Self::IntoIter {
147        self.iter()
148    }
149}
150
151// Merkle tree snapshot views live in `crate::ledger` —
152// [`MerkleTreeSnapshot`](crate::ledger::MerkleTreeSnapshot) and
153// [`HistoricMerkleTreeSnapshot`](crate::ledger::HistoricMerkleTreeSnapshot)
154// are the single canonical types; FFI bindings (uniffi / napi / wasm)
155// re-expose them under the same names.
156
157// ---------------------------------------------------------------------------
158// Named scalar / tuple shapes (descriptor projections)
159// ---------------------------------------------------------------------------
160
161/// Point in the embedded elliptic curve. Field elements are little-
162/// endian 32-byte BLS-scalar repr.
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
164pub struct JubjubPoint {
165    pub x: [u8; 32],
166    pub y: [u8; 32],
167}
168
169/// Point on secp256k1. `x` and `y` are little-endian 32-byte values in
170/// the secp256k1 base field; `identity` flags the point at infinity,
171/// which has no coordinate representation.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
173pub struct Secp256k1Point {
174    pub x: [u8; 32],
175    pub y: [u8; 32],
176    pub identity: bool,
177}
178
179/// Point on secp256r1 (P-256), laid out as [`Secp256k1Point`]: `x` and
180/// `y` little-endian in the secp256r1 base field, `identity` flagging
181/// the point at infinity.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
183pub struct Secp256r1Point {
184    pub x: [u8; 32],
185    pub y: [u8; 32],
186    pub identity: bool,
187}
188
189/// Point on Curve25519 in twisted-Edwards form. `x` and `y` are
190/// little-endian 32-byte values in the Curve25519 base field. Unlike
191/// the secp curves there is no identity flag: the identity is the
192/// ordinary point `(0, 1)`.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
194pub struct Curve25519Point {
195    pub x: [u8; 32],
196    pub y: [u8; 32],
197}
198
199// The `RuntimeValue` shape of each point is the object
200// `ir::descriptor::encode_literal` accepts for its descriptor and
201// `decode_aligned_value_full` produces: coordinates as 32-byte
202// little-endian `Bytes`, the secp identity flag as a `Bool`.
203
204fn point_object(
205    value: RuntimeValue,
206    what: &str,
207) -> Result<BTreeMap<String, RuntimeValue>, ValueProjectionError> {
208    match value {
209        RuntimeValue::Object(o) => Ok(o),
210        other => Err(ValueProjectionError::new(format!(
211            "expected Object for {what}, got {}",
212            other.type_label()
213        ))),
214    }
215}
216
217fn point_entry(
218    obj: &mut BTreeMap<String, RuntimeValue>,
219    key: &str,
220    what: &str,
221) -> Result<RuntimeValue, ValueProjectionError> {
222    obj.remove(key)
223        .ok_or_else(|| ValueProjectionError::new(format!("{what} missing field `{key}`")))
224}
225
226macro_rules! edwards_point_value {
227    ($ty:ident) => {
228        impl From<$ty> for RuntimeValue {
229            fn from(p: $ty) -> Self {
230                RuntimeValue::Object(BTreeMap::from([
231                    ("x".to_owned(), RuntimeValue::from(p.x)),
232                    ("y".to_owned(), RuntimeValue::from(p.y)),
233                ]))
234            }
235        }
236
237        impl TryFrom<RuntimeValue> for $ty {
238            type Error = ValueProjectionError;
239            fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
240                let what = stringify!($ty);
241                let mut obj = point_object(value, what)?;
242                Ok(Self {
243                    x: point_entry(&mut obj, "x", what)?.try_into()?,
244                    y: point_entry(&mut obj, "y", what)?.try_into()?,
245                })
246            }
247        }
248    };
249}
250
251macro_rules! weierstrass_point_value {
252    ($ty:ident) => {
253        impl From<$ty> for RuntimeValue {
254            fn from(p: $ty) -> Self {
255                RuntimeValue::Object(BTreeMap::from([
256                    ("x".to_owned(), RuntimeValue::from(p.x)),
257                    ("y".to_owned(), RuntimeValue::from(p.y)),
258                    ("identity".to_owned(), RuntimeValue::Bool(p.identity)),
259                ]))
260            }
261        }
262
263        impl TryFrom<RuntimeValue> for $ty {
264            type Error = ValueProjectionError;
265            fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
266                let what = stringify!($ty);
267                let mut obj = point_object(value, what)?;
268                Ok(Self {
269                    x: point_entry(&mut obj, "x", what)?.try_into()?,
270                    y: point_entry(&mut obj, "y", what)?.try_into()?,
271                    identity: point_entry(&mut obj, "identity", what)?.try_into()?,
272                })
273            }
274        }
275    };
276}
277
278edwards_point_value!(JubjubPoint);
279edwards_point_value!(Curve25519Point);
280weierstrass_point_value!(Secp256k1Point);
281weierstrass_point_value!(Secp256r1Point);
282
283/// Hash value of a Merkle tree.
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
285pub struct MerkleTreeDigest {
286    pub field: [u8; 32],
287}
288
289impl From<MerkleTreeDigest> for RuntimeValue {
290    fn from(v: MerkleTreeDigest) -> Self {
291        RuntimeValue::Object(BTreeMap::from([(
292            "field".to_owned(),
293            RuntimeValue::from(v.field),
294        )]))
295    }
296}
297
298impl TryFrom<RuntimeValue> for MerkleTreeDigest {
299    type Error = ValueProjectionError;
300    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
301        let mut obj = expect_object(value, "MerkleTreeDigest")?;
302        Ok(Self {
303            field: take_field(&mut obj, "field", "MerkleTreeDigest")?,
304        })
305    }
306}
307
308/// Entry in a Merkle path.
309#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
310pub struct MerkleTreePathEntry {
311    pub sibling: MerkleTreeDigest,
312    pub goes_left: bool,
313}
314
315impl From<MerkleTreePathEntry> for RuntimeValue {
316    fn from(v: MerkleTreePathEntry) -> Self {
317        RuntimeValue::Object(BTreeMap::from([
318            ("sibling".to_owned(), RuntimeValue::from(v.sibling)),
319            ("goes_left".to_owned(), RuntimeValue::from(v.goes_left)),
320        ]))
321    }
322}
323
324impl TryFrom<RuntimeValue> for MerkleTreePathEntry {
325    type Error = ValueProjectionError;
326    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
327        let mut obj = expect_object(value, "MerkleTreePathEntry")?;
328        Ok(Self {
329            sibling: take_field(&mut obj, "sibling", "MerkleTreePathEntry")?,
330            goes_left: take_field(&mut obj, "goes_left", "MerkleTreePathEntry")?,
331        })
332    }
333}
334
335/// Path demonstrating inclusion in a Merkle tree.
336#[derive(Debug, Clone, PartialEq, Eq)]
337pub struct MerkleTreePath<A> {
338    pub leaf: A,
339    pub path: Vec<MerkleTreePathEntry>,
340}
341
342/// Coin public-key wrapper.
343#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
344pub struct ZswapCoinPublicKey {
345    pub bytes: [u8; 32],
346}
347
348impl From<ZswapCoinPublicKey> for RuntimeValue {
349    fn from(v: ZswapCoinPublicKey) -> Self {
350        RuntimeValue::Object(BTreeMap::from([(
351            "bytes".to_owned(),
352            RuntimeValue::from(v.bytes),
353        )]))
354    }
355}
356
357impl TryFrom<RuntimeValue> for ZswapCoinPublicKey {
358    type Error = ValueProjectionError;
359    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
360        let mut obj = expect_object(value, "ZswapCoinPublicKey")?;
361        Ok(Self {
362            bytes: take_field(&mut obj, "bytes", "ZswapCoinPublicKey")?,
363        })
364    }
365}
366
367/// Contract-address wrapper (the descriptor-projection shape; distinct
368/// from [`moonproof_ledger::coin_structure::contract::ContractAddress`]).
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
370pub struct ContractAddress {
371    pub bytes: [u8; 32],
372}
373
374impl From<ContractAddress> for RuntimeValue {
375    fn from(v: ContractAddress) -> Self {
376        RuntimeValue::Object(BTreeMap::from([(
377            "bytes".to_owned(),
378            RuntimeValue::from(v.bytes),
379        )]))
380    }
381}
382
383impl TryFrom<RuntimeValue> for ContractAddress {
384    type Error = ValueProjectionError;
385    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
386        let mut obj = expect_object(value, "ContractAddress")?;
387        Ok(Self {
388            bytes: take_field(&mut obj, "bytes", "ContractAddress")?,
389        })
390    }
391}
392
393/// Unshielded user-address wrapper.
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
395pub struct UserAddress {
396    pub bytes: [u8; 32],
397}
398
399impl From<UserAddress> for RuntimeValue {
400    fn from(v: UserAddress) -> Self {
401        RuntimeValue::Object(BTreeMap::from([(
402            "bytes".to_owned(),
403            RuntimeValue::from(v.bytes),
404        )]))
405    }
406}
407
408impl TryFrom<RuntimeValue> for UserAddress {
409    type Error = ValueProjectionError;
410    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
411        let mut obj = expect_object(value, "UserAddress")?;
412        Ok(Self {
413            bytes: take_field(&mut obj, "bytes", "UserAddress")?,
414        })
415    }
416}
417
418/// Canonical `OpenZeppelin` `Either<ZswapCoinPublicKey, ContractAddress>` shape.
419#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
420pub struct OwnerEither {
421    pub is_left: bool,
422    pub left: ZswapCoinPublicKey,
423    pub right: ContractAddress,
424}
425
426impl OwnerEither {
427    /// Construct the `Left(ZswapCoinPublicKey)` variant (e.g. a wallet or account owner).
428    #[must_use]
429    pub const fn coin_public_key(bytes: [u8; 32]) -> Self {
430        Self {
431            is_left: true,
432            left: ZswapCoinPublicKey { bytes },
433            right: ContractAddress { bytes: [0u8; 32] },
434        }
435    }
436
437    /// Construct the `Right(ContractAddress)` variant (e.g. a contract owner).
438    #[must_use]
439    pub const fn contract(bytes: [u8; 32]) -> Self {
440        Self {
441            is_left: false,
442            left: ZswapCoinPublicKey { bytes: [0u8; 32] },
443            right: ContractAddress { bytes },
444        }
445    }
446}
447
448impl From<OwnerEither> for RuntimeValue {
449    fn from(v: OwnerEither) -> Self {
450        RuntimeValue::Object(BTreeMap::from([
451            ("is_left".to_owned(), RuntimeValue::from(v.is_left)),
452            ("left".to_owned(), RuntimeValue::from(v.left)),
453            ("right".to_owned(), RuntimeValue::from(v.right)),
454        ]))
455    }
456}
457
458impl TryFrom<RuntimeValue> for OwnerEither {
459    type Error = ValueProjectionError;
460    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
461        let mut obj = expect_object(value, "Either")?;
462        Ok(Self {
463            is_left: take_field(&mut obj, "is_left", "Either")?,
464            left: take_field(&mut obj, "left", "Either")?,
465            right: take_field(&mut obj, "right", "Either")?,
466        })
467    }
468}
469
470/// Shielded coin descriptor.
471#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
472pub struct ShieldedCoinInfo {
473    pub nonce: [u8; 32],
474    pub color: [u8; 32],
475    pub value: u128,
476}
477
478impl From<ShieldedCoinInfo> for RuntimeValue {
479    fn from(v: ShieldedCoinInfo) -> Self {
480        RuntimeValue::Object(BTreeMap::from([
481            ("nonce".to_owned(), RuntimeValue::from(v.nonce)),
482            ("color".to_owned(), RuntimeValue::from(v.color)),
483            ("value".to_owned(), RuntimeValue::from(v.value)),
484        ]))
485    }
486}
487
488impl TryFrom<RuntimeValue> for ShieldedCoinInfo {
489    type Error = ValueProjectionError;
490    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
491        let mut obj = expect_object(value, "ShieldedCoinInfo")?;
492        Ok(Self {
493            nonce: take_field(&mut obj, "nonce", "ShieldedCoinInfo")?,
494            color: take_field(&mut obj, "color", "ShieldedCoinInfo")?,
495            value: take_field(&mut obj, "value", "ShieldedCoinInfo")?,
496        })
497    }
498}
499
500/// Qualified shielded coin descriptor (coin + Merkle tree index).
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
502pub struct QualifiedShieldedCoinInfo {
503    pub nonce: [u8; 32],
504    pub color: [u8; 32],
505    pub value: u128,
506    pub mt_index: u64,
507}
508
509impl From<QualifiedShieldedCoinInfo> for RuntimeValue {
510    fn from(v: QualifiedShieldedCoinInfo) -> Self {
511        RuntimeValue::Object(BTreeMap::from([
512            ("nonce".to_owned(), RuntimeValue::from(v.nonce)),
513            ("color".to_owned(), RuntimeValue::from(v.color)),
514            ("value".to_owned(), RuntimeValue::from(v.value)),
515            ("mt_index".to_owned(), RuntimeValue::from(v.mt_index)),
516        ]))
517    }
518}
519
520impl TryFrom<RuntimeValue> for QualifiedShieldedCoinInfo {
521    type Error = ValueProjectionError;
522    fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
523        let mut obj = expect_object(value, "QualifiedShieldedCoinInfo")?;
524        Ok(Self {
525            nonce: take_field(&mut obj, "nonce", "QualifiedShieldedCoinInfo")?,
526            color: take_field(&mut obj, "color", "QualifiedShieldedCoinInfo")?,
527            value: take_field(&mut obj, "value", "QualifiedShieldedCoinInfo")?,
528            mt_index: take_field(&mut obj, "mt_index", "QualifiedShieldedCoinInfo")?,
529        })
530    }
531}
532
533/// Recipient of a coin produced by a circuit.
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535pub struct Recipient {
536    pub is_left: bool,
537    pub left: ZswapCoinPublicKey,
538    pub right: ContractAddress,
539}
540
541/// Shielded-coin recipient.
542#[derive(Debug, Clone, Copy, PartialEq, Eq)]
543pub struct ShieldedCoinRecipient {
544    pub is_left: bool,
545    pub left: ZswapCoinPublicKey,
546    pub right: ContractAddress,
547}
548
549// ---------------------------------------------------------------------------
550// Shared projection helpers used by codegen-emitted structs/enums/vectors
551// ---------------------------------------------------------------------------
552
553/// Extract the field map of a `RuntimeValue::Object` or report a typed error.
554pub fn expect_object(
555    value: RuntimeValue,
556    what: &str,
557) -> Result<BTreeMap<String, RuntimeValue>, ValueProjectionError> {
558    point_object(value, what)
559}
560
561/// Remove a raw field from an object map or report a missing-field error.
562pub fn take_raw_field(
563    obj: &mut BTreeMap<String, RuntimeValue>,
564    key: &str,
565    what: &str,
566) -> Result<RuntimeValue, ValueProjectionError> {
567    point_entry(obj, key, what)
568}
569
570/// Remove and project a typed field from an object map.
571pub fn take_field<T: TryFrom<RuntimeValue, Error = ValueProjectionError>>(
572    obj: &mut BTreeMap<String, RuntimeValue>,
573    key: &str,
574    what: &str,
575) -> Result<T, ValueProjectionError> {
576    take_raw_field(obj, key, what)?.try_into()
577}
578
579/// Extract a string from a `RuntimeValue::String` or report a typed error.
580pub fn expect_string(value: RuntimeValue, what: &str) -> Result<String, ValueProjectionError> {
581    match value {
582        RuntimeValue::String(s) => Ok(s),
583        other => Err(ValueProjectionError::new(format!(
584            "expected String for `{what}`, got {}",
585            other.type_label()
586        ))),
587    }
588}
589
590/// Construct an unknown-variant error for an enum projection.
591#[must_use]
592pub fn unknown_variant(variant: &str, what: &str) -> ValueProjectionError {
593    ValueProjectionError::new(format!("unknown variant `{variant}` for `{what}`"))
594}
595
596/// Encode a 32-byte contract address as `{ "bytes": Bytes(...) }`.
597#[must_use]
598pub fn encode_contract_address(bytes: [u8; 32]) -> RuntimeValue {
599    RuntimeValue::Object(BTreeMap::from([(
600        "bytes".to_owned(),
601        RuntimeValue::Bytes(bytes.to_vec()),
602    )]))
603}
604
605/// Decode a contract address from either `{ "bytes": Bytes(32) }` or raw `Bytes(32)`.
606pub fn decode_contract_address(value: RuntimeValue) -> Result<[u8; 32], ValueProjectionError> {
607    let raw = match value {
608        RuntimeValue::Object(mut obj) => obj.remove("bytes").ok_or_else(|| {
609            ValueProjectionError::new("expected `bytes` field in ContractAddress object".to_owned())
610        })?,
611        other @ RuntimeValue::Bytes(_) => other,
612        other => {
613            return Err(ValueProjectionError::new(format!(
614                "expected ContractAddress Object or Bytes, got {}",
615                other.type_label()
616            )));
617        }
618    };
619    <[u8; 32]>::try_from(raw)
620}
621
622/// Encode a fixed-size array into a `RuntimeValue::Array`.
623pub fn encode_array<T, const N: usize, F>(arr: [T; N], mut f: F) -> RuntimeValue
624where
625    F: FnMut(T) -> RuntimeValue,
626{
627    RuntimeValue::Array(arr.into_iter().map(&mut f).collect())
628}
629
630/// Decode a `RuntimeValue::Array` of exact length `N` into `[T; N]`.
631pub fn decode_array<T, const N: usize, F>(
632    value: RuntimeValue,
633    mut f: F,
634) -> Result<[T; N], ValueProjectionError>
635where
636    F: FnMut(RuntimeValue) -> Result<T, ValueProjectionError>,
637{
638    let items = match value {
639        RuntimeValue::Array(a) => a,
640        other => {
641            return Err(ValueProjectionError::new(format!(
642                "expected Vector array, got {}",
643                other.type_label()
644            )));
645        }
646    };
647    if items.len() != N {
648        return Err(ValueProjectionError::new(format!(
649            "Vector expected {N} elements, got {}",
650            items.len()
651        )));
652    }
653    let mut out = Vec::with_capacity(N);
654    for item in items {
655        out.push(f(item)?);
656    }
657    out.try_into().map_err(|_| {
658        ValueProjectionError::new("Vector length mismatch after projection".to_owned())
659    })
660}
661
662/// Define a typed contract front-end struct wrapping `IrExecutable<W>` plus its
663/// standard constructors and accessors (`new`, `with_verifier_keys`, `witnesses`,
664/// `executable`, `initial_state`).
665#[macro_export]
666macro_rules! define_contract_wrapper {
667    (
668        $(#[$meta:meta])*
669        pub struct $name:ident <W: $witness_trait:ident>,
670        cbor = $cbor:ident
671    ) => {
672        $(#[$meta])*
673        pub struct $name<W: $witness_trait> {
674            witnesses: ::std::sync::Arc<W>,
675            executable: ::std::sync::Arc<$crate::IrExecutable<W>>,
676        }
677
678        impl<W: $witness_trait + ::std::clone::Clone + 'static> $name<W> {
679            /// Construct from caller-supplied witnesses using the embedded IR CBOR.
680            pub fn new(witnesses: W) -> $crate::IrResult<Self> {
681                let witnesses = ::std::sync::Arc::new(witnesses);
682                let exec = $crate::IrExecutable::from_cbor_slice($cbor, witnesses.clone())?;
683                Ok(Self {
684                    witnesses,
685                    executable: ::std::sync::Arc::new(exec),
686                })
687            }
688
689            /// Attach verifier keys to the underlying executable.
690            #[must_use]
691            pub fn with_verifier_keys(
692                mut self,
693                keys: ::std::collections::HashMap<$crate::types::CircuitId, $crate::types::VerifierKey>,
694            ) -> Self {
695                let exec = ::std::sync::Arc::make_mut(&mut self.executable);
696                exec.set_verifier_keys(
697                    keys.into_iter()
698                        .map(|(id, vk)| (id.as_str().to_owned(), vk))
699                        .collect(),
700                );
701                self
702            }
703
704            /// Witnesses bundle bound to this contract instance.
705            #[must_use]
706            pub fn witnesses(&self) -> &::std::sync::Arc<W> {
707                &self.witnesses
708            }
709
710            /// Underlying IR executable.
711            #[must_use]
712            pub fn executable(&self) -> &::std::sync::Arc<$crate::IrExecutable<W>> {
713                &self.executable
714            }
715
716            /// Run the contract constructor off-chain.
717            pub async fn initial_state(
718                &self,
719                ctx: $crate::executable::ConstructorContext,
720            ) -> ::std::result::Result<
721                $crate::executable::InitializeResult,
722                $crate::ContractRuntimeError,
723            > {
724                self.executable
725                    .initialize(ctx, $crate::runtime_ir::RuntimeValue::Null)
726                    .await
727            }
728        }
729    };
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735
736    #[test]
737    fn map_view_methods() {
738        let m = CompactMap::new(BTreeMap::from([
739            ("a".to_owned(), 1u64),
740            ("b".to_owned(), 2),
741        ]));
742        assert_eq!(m.size(), 2);
743        assert!(!m.is_empty());
744        assert_eq!(m.lookup(&"a".to_owned()).copied(), Some(1));
745        assert!(m.member(&"b".to_owned()));
746        assert!(!m.member(&"missing".to_owned()));
747    }
748
749    #[test]
750    fn points_round_trip_through_runtime_value() {
751        let (x, y) = ([1u8; 32], [2u8; 32]);
752        for p in [
753            Secp256k1Point {
754                x,
755                y,
756                identity: false,
757            },
758            Secp256k1Point {
759                x,
760                y,
761                identity: true,
762            },
763        ] {
764            assert_eq!(Secp256k1Point::try_from(RuntimeValue::from(p)).unwrap(), p);
765        }
766        let p = Secp256r1Point {
767            x,
768            y,
769            identity: true,
770        };
771        assert_eq!(Secp256r1Point::try_from(RuntimeValue::from(p)).unwrap(), p);
772        let p = Curve25519Point { x, y };
773        assert_eq!(Curve25519Point::try_from(RuntimeValue::from(p)).unwrap(), p);
774        let p = JubjubPoint { x, y };
775        assert_eq!(JubjubPoint::try_from(RuntimeValue::from(p)).unwrap(), p);
776    }
777
778    #[test]
779    fn weierstrass_point_without_identity_flag_is_rejected() {
780        let edwards = RuntimeValue::from(Curve25519Point {
781            x: [1; 32],
782            y: [2; 32],
783        });
784        let err = Secp256r1Point::try_from(edwards).unwrap_err();
785        assert!(err.0.contains("identity"), "{err}");
786    }
787
788    #[test]
789    fn list_view_methods() {
790        let l: CompactList<u64> = CompactList::new(vec![10, 20, 30]);
791        assert_eq!(l.length(), 3);
792        assert_eq!(l.head().copied(), Some(10));
793        assert!(!l.is_empty());
794    }
795}