1use ethnum::I256;
8use indexmap::IndexMap;
9use serde::de::{self, Visitor};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use crate::RuntimeValue;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
30pub struct IntLit(pub I256);
31
32impl IntLit {
33 pub const ZERO: Self = Self(I256::ZERO);
34 pub const ONE: Self = Self(I256::ONE);
35
36 #[must_use]
37 pub fn from_i128(v: i128) -> Self {
38 Self(I256::from(v))
39 }
40
41 #[must_use]
42 pub fn from_u128(v: u128) -> Self {
43 Self(I256::from(v))
44 }
45
46 #[must_use]
48 pub fn as_u256(&self) -> Option<ethnum::U256> {
49 if self.0 < I256::ZERO {
50 return None;
51 }
52 Some(ethnum::U256::from_le_bytes(self.0.to_le_bytes()))
53 }
54
55 #[must_use]
57 pub fn as_u128(&self) -> Option<u128> {
58 if self.0 < I256::ZERO {
59 return None;
60 }
61 let (hi, lo) = self.0.into_words();
62 if hi != 0 {
63 return None;
64 }
65 Some(u128::from_ne_bytes(lo.to_ne_bytes()))
66 }
67
68 #[must_use]
70 pub fn as_i128(&self) -> Option<i128> {
71 let min = I256::from(i128::MIN);
72 let max = I256::from(i128::MAX);
73 if self.0 < min || self.0 > max {
74 return None;
75 }
76 let (_hi, lo) = self.0.into_words();
77 Some(lo)
78 }
79
80 #[must_use]
82 pub fn as_u32(&self) -> Option<u32> {
83 self.as_u128().and_then(|v| u32::try_from(v).ok())
84 }
85
86 #[must_use]
88 pub fn as_u64(&self) -> Option<u64> {
89 self.as_u128().and_then(|v| u64::try_from(v).ok())
90 }
91}
92
93impl std::fmt::Display for TypeDescriptor {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 let joined = |types: &[TypeDescriptor]| {
98 types
99 .iter()
100 .map(ToString::to_string)
101 .collect::<Vec<_>>()
102 .join(", ")
103 };
104 match self {
105 Self::Boolean => f.write_str("Boolean"),
106 Self::Field => f.write_str("Field"),
107 Self::JubjubScalar => f.write_str("JubjubScalar"),
108 Self::Secp256k1Base => f.write_str("Secp256k1Base"),
109 Self::Secp256k1Scalar => f.write_str("Secp256k1Scalar"),
110 Self::Secp256r1Base => f.write_str("Secp256r1Base"),
111 Self::Secp256r1Scalar => f.write_str("Secp256r1Scalar"),
112 Self::Curve25519Base => f.write_str("Curve25519Base"),
113 Self::Curve25519Scalar => f.write_str("Curve25519Scalar"),
114 Self::JubjubPoint => f.write_str("JubjubPoint"),
115 Self::Secp256k1Point => f.write_str("Secp256k1Point"),
116 Self::Secp256r1Point => f.write_str("Secp256r1Point"),
117 Self::Curve25519Point => f.write_str("Curve25519Point"),
118 Self::Uint { maxval, .. } => write!(f, "Uint<0..{maxval}>"),
119 Self::Bytes { length } => write!(f, "Bytes<{length}>"),
120 Self::Opaque { ts_type } => write!(f, "Opaque<{ts_type}>"),
121 Self::Tuple { types } => write!(f, "Tuple<{}>", joined(types)),
122 Self::Vector { length, elt_type } => write!(f, "Vector<{length}, {elt_type}>"),
123 Self::Set { of } => write!(f, "Set<{of}>"),
124 Self::List { of } => write!(f, "List<{of}>"),
125 Self::Map { key, value } => write!(f, "Map<{key}, {value}>"),
126 Self::MerkleTree { depth, of } => write!(f, "MerkleTree<{depth}, {of}>"),
127 Self::HistoricMerkleTree { depth, of } => {
128 write!(f, "HistoricMerkleTree<{depth}, {of}>")
129 }
130 Self::Counter => f.write_str("Counter"),
131 Self::Cell { of } => write!(f, "Cell<{of}>"),
132 Self::Struct { name, .. } => write!(f, "Struct<{name}>"),
133 Self::Enum { name, .. } => write!(f, "Enum<{name}>"),
134 Self::Alias { name, .. } => write!(f, "Alias<{name}>"),
135 Self::Contract { name, .. } => write!(f, "Contract<{name}>"),
136 Self::Unknown => f.write_str("Unknown"),
137 }
138 }
139}
140
141impl std::fmt::Display for IntLit {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 write!(f, "{}", self.0)
144 }
145}
146
147impl Serialize for IntLit {
148 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
149 match self.as_i128().and_then(|v| i64::try_from(v).ok()) {
150 Some(v) => s.serialize_i64(v),
152 None => s.serialize_str(&self.0.to_string()),
153 }
154 }
155}
156
157impl<'de> Deserialize<'de> for IntLit {
158 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
159 struct V;
160 impl Visitor<'_> for V {
161 type Value = IntLit;
162 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163 f.write_str("an integer (JSON number or decimal string)")
164 }
165 fn visit_u64<E: de::Error>(self, v: u64) -> Result<IntLit, E> {
166 Ok(IntLit(I256::from(v)))
167 }
168 fn visit_i64<E: de::Error>(self, v: i64) -> Result<IntLit, E> {
169 Ok(IntLit(I256::from(v)))
170 }
171 fn visit_u128<E: de::Error>(self, v: u128) -> Result<IntLit, E> {
172 Ok(IntLit(I256::from(v)))
173 }
174 fn visit_i128<E: de::Error>(self, v: i128) -> Result<IntLit, E> {
175 Ok(IntLit(I256::from(v)))
176 }
177 fn visit_str<E: de::Error>(self, v: &str) -> Result<IntLit, E> {
178 v.parse::<I256>()
179 .map(IntLit)
180 .map_err(|e| E::custom(format!("invalid integer literal '{v}': {e}")))
181 }
182 fn visit_string<E: de::Error>(self, v: String) -> Result<IntLit, E> {
183 self.visit_str(&v)
184 }
185 }
186 d.deserialize_any(V)
187 }
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct MoonIr {
196 #[serde(rename = "schema-version")]
197 pub schema_version: u32,
198 #[serde(rename = "compiler-version")]
199 pub compiler_version: String,
200 #[serde(rename = "language-version")]
201 pub language_version: String,
202 #[serde(rename = "runtime-version")]
203 pub runtime_version: String,
204
205 #[serde(default)]
210 pub contracts: Vec<TypeDescriptor>,
211 #[serde(default)]
212 pub ledger: Vec<LedgerField>,
213 #[serde(default)]
214 pub witnesses: Vec<Witness>,
215 #[serde(default)]
216 pub natives: Vec<Native>,
217 #[serde(default)]
218 pub circuits: Vec<CircuitBody>,
219 #[serde(default)]
220 pub descriptors: IndexMap<String, TypeDescriptor>,
221 pub constructor: Constructor,
222 #[serde(rename = "external-contracts", default)]
223 pub external_contracts: Vec<RuntimeValue>,
224 #[serde(rename = "pure-circuits", default)]
225 pub pure_circuits: Vec<RuntimeValue>,
226
227 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub frontend: Option<FrontendMeta>,
230 #[serde(
232 rename = "debug-info",
233 default,
234 skip_serializing_if = "Option::is_none"
235 )]
236 pub debug_info: Option<DebugInfo>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub capabilities: Option<CapabilitiesMeta>,
240 #[serde(default, skip_serializing_if = "Vec::is_empty")]
242 pub workflows: Vec<WorkflowMeta>,
243 #[serde(default, skip_serializing_if = "Option::is_none")]
245 pub privacy: Option<PrivacyMeta>,
246 #[serde(
249 rename = "type-roles",
250 default,
251 skip_serializing_if = "IndexMap::is_empty"
252 )]
253 pub type_roles: IndexMap<String, SemanticTypeRole>,
254}
255
256impl MoonIr {
257 #[must_use]
260 pub fn new_v3(
261 compiler_version: impl Into<String>,
262 language_version: impl Into<String>,
263 runtime_version: impl Into<String>,
264 ) -> Self {
265 Self {
266 schema_version: crate::loader::SUPPORTED_SCHEMA_VERSION,
267 compiler_version: compiler_version.into(),
268 language_version: language_version.into(),
269 runtime_version: runtime_version.into(),
270 contracts: Vec::new(),
271 ledger: Vec::new(),
272 witnesses: Vec::new(),
273 natives: Vec::new(),
274 circuits: Vec::new(),
275 descriptors: IndexMap::new(),
276 constructor: Constructor::default(),
277 external_contracts: Vec::new(),
278 pure_circuits: Vec::new(),
279 frontend: None,
280 debug_info: None,
281 capabilities: None,
282 workflows: Vec::new(),
283 privacy: None,
284 type_roles: IndexMap::new(),
285 }
286 }
287
288 #[must_use]
289 pub fn with_frontend(mut self, frontend: FrontendMeta) -> Self {
290 self.frontend = Some(frontend);
291 self
292 }
293
294 #[must_use]
295 pub fn with_debug_info(mut self, debug_info: DebugInfo) -> Self {
296 self.debug_info = Some(debug_info);
297 self
298 }
299
300 #[must_use]
301 pub fn with_capabilities(mut self, capabilities: CapabilitiesMeta) -> Self {
302 self.capabilities = Some(capabilities);
303 self
304 }
305
306 #[must_use]
307 pub fn with_workflows(mut self, workflows: Vec<WorkflowMeta>) -> Self {
308 self.workflows = workflows;
309 self
310 }
311
312 #[must_use]
313 pub fn with_privacy(mut self, privacy: PrivacyMeta) -> Self {
314 self.privacy = Some(privacy);
315 self
316 }
317
318 #[must_use]
319 pub fn with_type_roles(mut self, type_roles: IndexMap<String, SemanticTypeRole>) -> Self {
320 self.type_roles = type_roles;
321 self
322 }
323
324 #[must_use]
325 pub fn with_type_role(
326 mut self,
327 descriptor_key: impl Into<String>,
328 role: SemanticTypeRole,
329 ) -> Self {
330 self.type_roles.insert(descriptor_key.into(), role);
331 self
332 }
333
334 #[must_use]
335 pub fn with_constructor(mut self, constructor: Constructor) -> Self {
336 self.constructor = constructor;
337 self
338 }
339
340 pub fn add_ledger_field(&mut self, field: LedgerField) -> &mut Self {
341 self.ledger.push(field);
342 self
343 }
344
345 pub fn add_witness(&mut self, witness: Witness) -> &mut Self {
346 self.witnesses.push(witness);
347 self
348 }
349
350 pub fn add_native(&mut self, native: Native) -> &mut Self {
351 self.natives.push(native);
352 self
353 }
354
355 pub fn add_circuit(&mut self, circuit: CircuitBody) -> &mut Self {
356 self.circuits.push(circuit);
357 self
358 }
359
360 pub fn add_descriptor(
361 &mut self,
362 key: impl Into<String>,
363 descriptor: TypeDescriptor,
364 ) -> &mut Self {
365 self.descriptors.insert(key.into(), descriptor);
366 self
367 }
368
369 pub fn add_workflow(&mut self, workflow: WorkflowMeta) -> &mut Self {
370 self.workflows.push(workflow);
371 self
372 }
373}
374
375#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
381#[serde(rename_all = "kebab-case")]
382pub enum FrontendLanguage {
383 Compact,
384 Pact5,
385 Custom(String),
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390pub struct FrontendMeta {
391 pub language: FrontendLanguage,
392 #[serde(rename = "frontend-version")]
393 pub frontend_version: String,
394 #[serde(
395 rename = "source-module",
396 default,
397 skip_serializing_if = "Option::is_none"
398 )]
399 pub source_module: Option<String>,
400 #[serde(
401 rename = "source-hash",
402 default,
403 skip_serializing_if = "Option::is_none"
404 )]
405 pub source_hash: Option<String>,
406 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
407 pub metadata: IndexMap<String, String>,
408}
409
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
412pub struct SourceSpan {
413 #[serde(default, skip_serializing_if = "Option::is_none")]
414 pub file: Option<String>,
415 #[serde(rename = "start-line")]
416 pub start_line: u32,
417 #[serde(rename = "start-col")]
418 pub start_col: u32,
419 #[serde(rename = "end-line")]
420 pub end_line: u32,
421 #[serde(rename = "end-col")]
422 pub end_col: u32,
423}
424
425#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
427pub struct DebugInfo {
428 #[serde(default, skip_serializing_if = "Vec::is_empty")]
429 pub sources: Vec<String>,
430 #[serde(
431 rename = "circuit-spans",
432 default,
433 skip_serializing_if = "IndexMap::is_empty"
434 )]
435 pub circuit_spans: IndexMap<String, SourceSpan>,
436 #[serde(
437 rename = "field-spans",
438 default,
439 skip_serializing_if = "IndexMap::is_empty"
440 )]
441 pub field_spans: IndexMap<String, SourceSpan>,
442}
443
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(tag = "kind", rename_all = "kebab-case")]
447pub enum GovernanceSpec {
448 Keyset { name: String },
449 Capability { name: String },
450 Custom { description: String },
451}
452
453#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
455#[serde(rename_all = "kebab-case")]
456pub enum CapabilityKind {
457 Basic,
458 Managed,
459 Event,
460}
461
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
464pub struct CapabilityDef {
465 pub name: String,
466 pub kind: CapabilityKind,
467 #[serde(default, skip_serializing_if = "Vec::is_empty")]
468 pub arguments: Vec<Argument>,
469 #[serde(
470 rename = "managed-param",
471 default,
472 skip_serializing_if = "Option::is_none"
473 )]
474 pub managed_param: Option<String>,
475 #[serde(
476 rename = "manager-circuit",
477 default,
478 skip_serializing_if = "Option::is_none"
479 )]
480 pub manager_circuit: Option<String>,
481 #[serde(default, skip_serializing_if = "Vec::is_empty")]
482 pub composes: Vec<String>,
483}
484
485#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
487pub struct CircuitCapUsage {
488 #[serde(default, skip_serializing_if = "Vec::is_empty")]
489 pub acquires: Vec<String>,
490 #[serde(default, skip_serializing_if = "Vec::is_empty")]
491 pub requires: Vec<String>,
492 #[serde(default, skip_serializing_if = "Vec::is_empty")]
493 pub emits: Vec<String>,
494}
495
496#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
498pub struct CapabilitiesMeta {
499 #[serde(default, skip_serializing_if = "Option::is_none")]
500 pub governance: Option<GovernanceSpec>,
501 #[serde(default, skip_serializing_if = "Vec::is_empty")]
502 pub capabilities: Vec<CapabilityDef>,
503 #[serde(
504 rename = "circuit-usage",
505 default,
506 skip_serializing_if = "IndexMap::is_empty"
507 )]
508 pub circuit_usage: IndexMap<String, CircuitCapUsage>,
509}
510
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
513pub struct WorkflowStepMeta {
514 pub index: u32,
515 pub circuit: String,
516 #[serde(
517 rename = "rollback-circuit",
518 default,
519 skip_serializing_if = "Option::is_none"
520 )]
521 pub rollback_circuit: Option<String>,
522 #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub entity: Option<String>,
524 #[serde(default, skip_serializing_if = "Vec::is_empty")]
525 pub yields: Vec<String>,
526}
527
528#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530pub struct WorkflowMeta {
531 pub name: String,
532 #[serde(default, skip_serializing_if = "Vec::is_empty")]
533 pub steps: Vec<WorkflowStepMeta>,
534}
535
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
538#[serde(rename_all = "kebab-case")]
539pub enum PrivacyClass {
540 Public,
541 Private,
542 Shielded,
543 Disclosed,
544}
545
546#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
548#[serde(rename_all = "kebab-case")]
549pub enum FieldRole {
550 State,
551 Commitment,
552 Nullifier,
553 Ciphertext,
554 Authority,
555 Balance,
556}
557
558#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
560pub struct CircuitBoundsMeta {
561 #[serde(
562 rename = "max-constraints",
563 default,
564 skip_serializing_if = "Option::is_none"
565 )]
566 pub max_constraints: Option<u64>,
567 #[serde(
568 rename = "max-public-inputs",
569 default,
570 skip_serializing_if = "Option::is_none"
571 )]
572 pub max_public_inputs: Option<u32>,
573 #[serde(
574 rename = "max-witness-elements",
575 default,
576 skip_serializing_if = "Option::is_none"
577 )]
578 pub max_witness_elements: Option<u32>,
579}
580
581#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
583pub struct PrivacyMeta {
584 #[serde(
585 rename = "field-classes",
586 default,
587 skip_serializing_if = "IndexMap::is_empty"
588 )]
589 pub field_classes: IndexMap<String, PrivacyClass>,
590 #[serde(
591 rename = "field-roles",
592 default,
593 skip_serializing_if = "IndexMap::is_empty"
594 )]
595 pub field_roles: IndexMap<String, FieldRole>,
596 #[serde(
597 rename = "circuit-bounds",
598 default,
599 skip_serializing_if = "IndexMap::is_empty"
600 )]
601 pub circuit_bounds: IndexMap<String, CircuitBoundsMeta>,
602}
603
604#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
607#[serde(tag = "role", rename_all = "kebab-case")]
608pub enum SemanticTypeRole {
609 FixedDecimal {
610 scale: u8,
611 signed: bool,
612 },
613 SignedInt {
614 bits: u16,
615 },
616 BoundedList {
617 #[serde(rename = "max-len")]
618 max_len: u32,
619 },
620 Guard,
621 Timestamp,
622}
623
624#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
635pub enum FieldType {
636 Field,
637 JubjubScalar,
638 Secp256k1Base,
639 Secp256k1Scalar,
640 Secp256r1Base,
641 Secp256r1Scalar,
642 Curve25519Base,
643 Curve25519Scalar,
644}
645
646impl FieldType {
647 #[must_use]
649 pub fn descriptor(self) -> TypeDescriptor {
650 match self {
651 FieldType::Field => TypeDescriptor::Field,
652 FieldType::JubjubScalar => TypeDescriptor::JubjubScalar,
653 FieldType::Secp256k1Base => TypeDescriptor::Secp256k1Base,
654 FieldType::Secp256k1Scalar => TypeDescriptor::Secp256k1Scalar,
655 FieldType::Secp256r1Base => TypeDescriptor::Secp256r1Base,
656 FieldType::Secp256r1Scalar => TypeDescriptor::Secp256r1Scalar,
657 FieldType::Curve25519Base => TypeDescriptor::Curve25519Base,
658 FieldType::Curve25519Scalar => TypeDescriptor::Curve25519Scalar,
659 }
660 }
661
662 #[must_use]
666 pub fn of_descriptor(descriptor: &TypeDescriptor) -> Option<FieldType> {
667 Some(match descriptor {
668 TypeDescriptor::Field => FieldType::Field,
669 TypeDescriptor::JubjubScalar => FieldType::JubjubScalar,
670 TypeDescriptor::Secp256k1Base => FieldType::Secp256k1Base,
671 TypeDescriptor::Secp256k1Scalar => FieldType::Secp256k1Scalar,
672 TypeDescriptor::Secp256r1Base => FieldType::Secp256r1Base,
673 TypeDescriptor::Secp256r1Scalar => FieldType::Secp256r1Scalar,
674 TypeDescriptor::Curve25519Base => FieldType::Curve25519Base,
675 TypeDescriptor::Curve25519Scalar => FieldType::Curve25519Scalar,
676 _ => return None,
677 })
678 }
679}
680
681#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
682#[serde(tag = "type-name")]
683pub enum TypeDescriptor {
684 Boolean,
685 Field,
686 JubjubScalar,
691 Secp256k1Base,
696 Secp256k1Scalar,
699 Secp256r1Base,
702 Secp256r1Scalar,
705 Curve25519Base,
708 Curve25519Scalar,
711 JubjubPoint,
713 Secp256k1Point,
716 Secp256r1Point,
719 Curve25519Point,
722 Unknown,
727 Uint {
728 maxval: IntLit,
729 #[serde(default, rename = "alignment-bytes")]
730 alignment_bytes: Option<u32>,
731 },
732 Bytes {
733 length: u32,
734 },
735 Opaque {
736 #[serde(rename = "tsType")]
737 ts_type: String,
738 },
739 Vector {
740 length: u32,
741 #[serde(rename = "type")]
742 elt_type: Box<TypeDescriptor>,
743 },
744 Tuple {
745 types: Vec<TypeDescriptor>,
746 },
747 Struct {
748 name: String,
749 elements: Vec<StructField>,
750 },
751 Enum {
752 name: String,
753 elements: Vec<String>,
754 },
755 Alias {
756 name: String,
757 #[serde(rename = "type")]
758 of: Box<TypeDescriptor>,
759 },
760 Contract {
761 name: String,
762 circuits: Vec<ContractCircuitSig>,
763 },
764 Cell {
765 #[serde(rename = "type")]
766 of: Box<TypeDescriptor>,
767 },
768 Counter,
769 Map {
770 key: Box<TypeDescriptor>,
771 value: Box<TypeDescriptor>,
772 },
773 Set {
774 #[serde(rename = "type")]
775 of: Box<TypeDescriptor>,
776 },
777 List {
778 #[serde(rename = "type")]
779 of: Box<TypeDescriptor>,
780 },
781 MerkleTree {
782 depth: IntLit,
783 #[serde(rename = "type")]
784 of: Box<TypeDescriptor>,
785 },
786 HistoricMerkleTree {
787 depth: IntLit,
788 #[serde(rename = "type")]
789 of: Box<TypeDescriptor>,
790 },
791}
792
793impl TypeDescriptor {
794 #[must_use]
799 pub fn contract_address() -> Self {
800 TypeDescriptor::Struct {
801 name: "ContractAddress".to_owned(),
802 elements: vec![StructField {
803 name: "bytes".to_owned(),
804 field_type: TypeDescriptor::Bytes { length: 32 },
805 }],
806 }
807 }
808}
809
810#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
811pub struct StructField {
812 pub name: String,
813 #[serde(rename = "type")]
814 pub field_type: TypeDescriptor,
815}
816
817#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
818pub struct ContractCircuitSig {
819 pub name: String,
820 #[serde(rename = "argument-types")]
821 pub argument_types: Vec<TypeDescriptor>,
822 #[serde(rename = "result-type")]
823 pub result_type: TypeDescriptor,
824}
825
826#[derive(Debug, Clone, Serialize, Deserialize)]
831pub struct LedgerField {
832 pub name: String,
833 #[serde(
846 deserialize_with = "deserialize_field_index",
847 serialize_with = "serialize_field_index"
848 )]
849 pub index: Vec<u32>,
850 pub exported: bool,
851 #[serde(flatten)]
852 pub storage: Storage,
853}
854
855impl LedgerField {
856 #[must_use]
859 pub fn leaf_index(&self) -> u32 {
860 self.index.last().copied().unwrap_or(0)
861 }
862}
863
864fn serialize_field_index<S>(v: &[u32], s: S) -> Result<S::Ok, S::Error>
865where
866 S: serde::Serializer,
867{
868 use serde::ser::SerializeSeq;
869 if v.len() == 1 {
870 s.serialize_u32(v[0])
871 } else {
872 let mut seq = s.serialize_seq(Some(v.len()))?;
873 for n in v {
874 seq.serialize_element(n)?;
875 }
876 seq.end()
877 }
878}
879
880fn deserialize_field_index<'de, D>(d: D) -> Result<Vec<u32>, D::Error>
881where
882 D: serde::Deserializer<'de>,
883{
884 use serde::de::{self, Error, SeqAccess, Visitor};
885 use std::fmt;
886
887 struct V;
888 impl<'de> Visitor<'de> for V {
889 type Value = Vec<u32>;
890 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891 f.write_str("a non-negative integer or an array of non-negative integers")
892 }
893 fn visit_u64<E: Error>(self, v: u64) -> Result<Vec<u32>, E> {
894 u32::try_from(v)
895 .map(|n| vec![n])
896 .map_err(|_| Error::custom(format!("ledger field index {v} exceeds u32::MAX")))
897 }
898 fn visit_i64<E: Error>(self, v: i64) -> Result<Vec<u32>, E> {
899 u32::try_from(v)
900 .map(|n| vec![n])
901 .map_err(|_| Error::custom(format!("ledger field index {v} not in u32 range")))
902 }
903 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
904 let mut out: Vec<u32> = Vec::new();
905 while let Some(elem) = seq.next_element::<i64>()? {
906 let n = u32::try_from(elem).map_err(|_| {
907 de::Error::custom(format!(
908 "ledger field index path entry {elem} not in u32 range"
909 ))
910 })?;
911 out.push(n);
912 }
913 Ok(out)
914 }
915 }
916 d.deserialize_any(V)
917}
918
919#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
938#[serde(tag = "storage")]
939pub enum Storage {
940 Counter,
941 Cell {
942 #[serde(rename = "type")]
943 of: TypeDescriptor,
944 },
945 Map {
946 key: TypeDescriptor,
947 value: TypeDescriptor,
948 },
949 Set {
950 #[serde(rename = "type")]
951 of: TypeDescriptor,
952 },
953 List {
954 #[serde(rename = "type")]
955 of: TypeDescriptor,
956 },
957 MerkleTree {
958 #[serde(rename = "type")]
959 of: TypeDescriptor,
960 },
961 HistoricMerkleTree {
962 #[serde(rename = "type")]
963 of: TypeDescriptor,
964 },
965}
966
967impl Storage {
968 #[must_use]
971 pub fn kind(&self) -> &'static str {
972 match self {
973 Self::Counter => "Counter",
974 Self::Cell { .. } => "Cell",
975 Self::Map { .. } => "Map",
976 Self::Set { .. } => "Set",
977 Self::List { .. } => "List",
978 Self::MerkleTree { .. } => "MerkleTree",
979 Self::HistoricMerkleTree { .. } => "HistoricMerkleTree",
980 }
981 }
982}
983
984#[derive(Debug, Clone, Serialize, Deserialize)]
985pub struct Witness {
986 pub name: String,
987 #[serde(default)]
988 pub arguments: Vec<Argument>,
989 #[serde(rename = "result-type")]
990 pub result_type: TypeDescriptor,
991}
992
993#[derive(Debug, Clone, Serialize, Deserialize)]
994pub struct Native {
995 pub name: String,
996 #[serde(rename = "internal-uniq", default)]
1000 pub internal_uniq: Option<u64>,
1001 #[serde(rename = "host-symbol")]
1002 pub host_symbol: String,
1003 #[serde(default, skip_serializing_if = "Option::is_none")]
1007 pub intrinsic: Option<String>,
1008 pub class: String,
1009 #[serde(default)]
1010 pub arguments: Vec<Argument>,
1011 #[serde(rename = "result-type")]
1012 pub result_type: TypeDescriptor,
1013}
1014
1015impl Native {
1016 #[must_use]
1019 pub fn new_intrinsic(
1020 name: impl Into<String>,
1021 intrinsic: impl Into<String>,
1022 class: impl Into<String>,
1023 arguments: Vec<Argument>,
1024 result_type: TypeDescriptor,
1025 ) -> Self {
1026 let intr = intrinsic.into();
1027 Self {
1028 name: name.into(),
1029 internal_uniq: None,
1030 host_symbol: intr.clone(),
1031 intrinsic: Some(intr),
1032 class: class.into(),
1033 arguments,
1034 result_type,
1035 }
1036 }
1037
1038 #[must_use]
1044 pub fn resolve_intrinsic(&self) -> &str {
1045 if let Some(ref intrinsic) = self.intrinsic {
1046 intrinsic.as_str()
1047 } else {
1048 self.host_symbol
1049 .strip_prefix("__compactRuntime.")
1050 .unwrap_or(&self.host_symbol)
1051 }
1052 }
1053}
1054
1055#[must_use]
1060pub fn canonical_intrinsic_name(raw: &str) -> &str {
1061 let trimmed = raw.strip_prefix("__compactRuntime.").unwrap_or(raw);
1062 match trimmed {
1063 "mp:hash/persistent" => "persistentHash",
1065 "mp:hash/transient" | "mp:hash/poseidon" => "transientHash",
1066 "mp:commit/persistent" | "mp:hash/persistent-commit" => "persistentCommit",
1067 "mp:commit/transient" | "mp:hash/transient-commit" => "transientCommit",
1068 "mp:hash/degrade-to-transient" => "degradeToTransient",
1069 "mp:hash/upgrade-from-transient" => "upgradeFromTransient",
1070 "mp:hash/keccak256" => "keccak256",
1071 "mp:hash/sha512" => "sha512",
1072 "mp:hash/to-curve" | "mp:curve/hash-to-curve" => "hashToCurve",
1073
1074 "mp:coin/commitment" | "mp:zswap/coin-commitment" => "coinCommitment",
1076 "mp:coin/token-type" | "mp:zswap/token-type" => "tokenType",
1077 "mp:context/own-public-key"
1078 | "mp:zswap/own-public-key"
1079 | "mp:auth/own-public-key"
1080 | "mp:ledger/own-public-key" => "ownPublicKey",
1081 "mp:zswap/create-output" => "createZswapOutput",
1082 "mp:zswap/create-input" => "createZswapInput",
1083
1084 "mp:curve/jubjub-point-x" | "mp:ec/jubjub-point-x" => "jubjubPointX",
1086 "mp:curve/jubjub-point-y" | "mp:ec/jubjub-point-y" => "jubjubPointY",
1087 "mp:curve/jubjub-construct" | "mp:ec/jubjub-construct" => "constructJubjubPoint",
1088 "mp:curve/jubjub-add" | "mp:ec/add" | "mp:ec/jubjub-add" => "ecAdd",
1089 "mp:curve/jubjub-mul" | "mp:ec/mul" | "mp:ec/jubjub-mul" => "ecMul",
1090 "mp:curve/jubjub-mul-generator" | "mp:ec/mul-generator" | "mp:ec/jubjub-mul-generator" => {
1091 "ecMulGenerator"
1092 }
1093 "mp:curve/jubjub-neg" | "mp:ec/neg" | "mp:ec/jubjub-neg" => "ecNeg",
1094 "mp:curve/jubjub-scalar-from-native"
1095 | "mp:ec/jubjub-scalar-from-native"
1096 | "reduceModJubjubOrder" => "jubjubScalarFromNative",
1097 "mp:curve/secp256k1-add" | "mp:ec/secp256k1-add" => "secp256k1Add",
1098 "mp:curve/secp256r1-add" | "mp:ec/secp256r1-add" => "secp256r1Add",
1099 "mp:curve/curve25519-add" | "mp:ec/curve25519-add" => "curve25519Add",
1100 "mp:curve/secp256k1-mul" | "mp:ec/secp256k1-mul" => "secp256k1Mul",
1101 "mp:curve/secp256r1-mul" | "mp:ec/secp256r1-mul" => "secp256r1Mul",
1102 "mp:curve/curve25519-mul" | "mp:ec/curve25519-mul" => "curve25519Mul",
1103 "mp:curve/secp256k1-mul-generator" | "mp:ec/secp256k1-mul-generator" => {
1104 "secp256k1MulGenerator"
1105 }
1106 "mp:curve/secp256r1-mul-generator" | "mp:ec/secp256r1-mul-generator" => {
1107 "secp256r1MulGenerator"
1108 }
1109 "mp:curve/curve25519-mul-generator" | "mp:ec/curve25519-mul-generator" => {
1110 "curve25519MulGenerator"
1111 }
1112
1113 "mp:merkle/path-root" => "merkleTreePathRoot",
1115 "mp:merkle/path-root-no-leaf-hash" => "merkleTreePathRootNoLeafHash",
1116
1117 "mp:crypto/ed25519-verify" | "mp:sig/ed25519-verify" => "ed25519Verify",
1119 "mp:crypto/secp256r1-ecdsa-verify"
1120 | "mp:sig/secp256r1-ecdsa-verify"
1121 | "mp:crypto/ecdsa-p256-verify" => "secp256r1EcdsaVerify",
1122 "mp:crypto/secp256k1-ecdsa-verify"
1123 | "mp:sig/secp256k1-ecdsa-verify"
1124 | "mp:crypto/ecdsa-secp256k1-verify" => "secp256k1EcdsaVerify",
1125
1126 other => other,
1127 }
1128}
1129
1130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1131pub struct Argument {
1132 pub name: String,
1133 #[serde(rename = "type")]
1134 pub arg_type: TypeDescriptor,
1135}
1136
1137#[derive(Debug, Clone, Serialize, Deserialize)]
1142pub struct Constructor {
1143 #[serde(default)]
1144 pub arguments: Vec<Argument>,
1145 #[serde(rename = "initial-state")]
1146 pub initial_state: StateValue,
1147 #[serde(rename = "init-ops", default)]
1148 pub init_ops: Vec<Expression>,
1149 #[serde(rename = "register-operations", default)]
1150 pub register_operations: Vec<String>,
1151 pub body: Statement,
1152}
1153
1154impl Default for Constructor {
1155 fn default() -> Self {
1156 Self {
1157 arguments: Vec::new(),
1158 initial_state: StateValue::Null,
1159 init_ops: Vec::new(),
1160 register_operations: Vec::new(),
1161 body: Statement::Noop,
1162 }
1163 }
1164}
1165
1166#[derive(Debug, Clone, Serialize, Deserialize)]
1171pub struct CircuitBody {
1172 pub name: String,
1173 #[serde(rename = "internal-name")]
1174 pub internal_name: String,
1175 #[serde(rename = "internal-uniq", default)]
1179 pub internal_uniq: Option<u64>,
1180 pub exported: bool,
1181 pub pure: bool,
1182 pub proof: bool,
1183 #[serde(default)]
1184 pub arguments: Vec<Argument>,
1185 #[serde(rename = "result-type")]
1186 pub result_type: TypeDescriptor,
1187 pub body: Statement,
1188}
1189
1190#[derive(Debug, Clone, Serialize, Deserialize)]
1195#[serde(tag = "stmt", rename_all = "kebab-case")]
1196pub enum Statement {
1197 Seq {
1198 items: Vec<Statement>,
1199 },
1200 If {
1201 cond: Expression,
1202 then: Box<Statement>,
1203 #[serde(default)]
1204 r#else: Option<Box<Statement>>,
1205 },
1206 Const {
1207 binding: BindingTarget,
1208 value: Expression,
1209 },
1210 ConstDestructure {
1211 bindings: Vec<BindingTarget>,
1212 },
1213 Expr {
1214 value: Expression,
1215 },
1216 Unimplemented,
1219 Noop,
1221}
1222
1223#[derive(Debug, Clone, Serialize, Deserialize)]
1224pub struct BindingTarget {
1225 pub name: String,
1226 #[serde(rename = "type")]
1227 pub binding_type: TypeDescriptor,
1228}
1229
1230#[derive(Debug, Clone, Serialize, Deserialize)]
1235#[serde(tag = "expr", rename_all = "kebab-case")]
1236pub enum Expression {
1237 Literal {
1238 value: crate::value::RuntimeValue,
1239 },
1240 Var {
1241 name: String,
1242 },
1243 Default {
1244 #[serde(rename = "type")]
1245 of_type: TypeDescriptor,
1246 },
1247 If {
1248 cond: Box<Expression>,
1249 then: Box<Expression>,
1250 r#else: Box<Expression>,
1251 },
1252 EltRef {
1253 value: Box<Expression>,
1254 field: String,
1255 index: IntLit,
1256 },
1257 EnumRef {
1258 #[serde(rename = "type")]
1259 of_type: TypeDescriptor,
1260 variant: String,
1261 },
1262 Tuple {
1263 items: Vec<TupleItem>,
1264 },
1265 Vector {
1266 items: Vec<TupleItem>,
1267 },
1268 TupleRef {
1269 value: Box<Expression>,
1270 index: IntLit,
1271 },
1272 TupleSlice {
1273 value: Box<Expression>,
1274 start: IntLit,
1275 length: IntLit,
1276 #[serde(rename = "result-type")]
1277 result_type: TypeDescriptor,
1278 },
1279 VectorRef {
1280 value: Box<Expression>,
1281 index: Box<Expression>,
1282 #[serde(rename = "result-type")]
1283 result_type: TypeDescriptor,
1284 },
1285 VectorSlice {
1286 value: Box<Expression>,
1287 start: Box<Expression>,
1288 length: IntLit,
1289 #[serde(rename = "result-type")]
1290 result_type: TypeDescriptor,
1291 },
1292 BytesRef {
1293 value: Box<Expression>,
1294 index: Box<Expression>,
1295 #[serde(rename = "result-type")]
1296 result_type: TypeDescriptor,
1297 },
1298 BytesSlice {
1299 value: Box<Expression>,
1300 start: Box<Expression>,
1301 length: IntLit,
1302 #[serde(rename = "result-type")]
1303 result_type: TypeDescriptor,
1304 },
1305 Binop {
1306 op: String,
1307 #[serde(default)]
1309 bits: Option<u32>,
1310 #[serde(rename = "type", default)]
1315 of_type: Option<TypeDescriptor>,
1316 left: Box<Expression>,
1317 right: Box<Expression>,
1318 },
1319 Eq {
1320 #[serde(rename = "type", default)]
1321 of_type: Option<TypeDescriptor>,
1322 left: Box<Expression>,
1323 right: Box<Expression>,
1324 },
1325 Neq {
1326 #[serde(rename = "type", default)]
1327 of_type: Option<TypeDescriptor>,
1328 left: Box<Expression>,
1329 right: Box<Expression>,
1330 },
1331 And {
1332 left: Box<Expression>,
1333 right: Box<Expression>,
1334 },
1335 Or {
1336 left: Box<Expression>,
1337 right: Box<Expression>,
1338 },
1339 Not {
1340 value: Box<Expression>,
1341 },
1342 Assign {
1343 name: String,
1344 value: Box<Expression>,
1345 },
1346 Call {
1347 function: String,
1348 #[serde(rename = "function-uniq", default)]
1355 function_uniq: Option<u64>,
1356 arguments: Vec<Expression>,
1357 },
1358 New {
1359 #[serde(rename = "type")]
1360 of_type: TypeDescriptor,
1361 arguments: Vec<Expression>,
1362 },
1363 Seq {
1364 items: Vec<Expression>,
1365 },
1366 Cast {
1367 to: TypeDescriptor,
1368 value: Box<Expression>,
1369 },
1370 SafeCast {
1371 to: TypeDescriptor,
1372 from: TypeDescriptor,
1373 value: Box<Expression>,
1374 },
1375 DowncastUnsigned {
1383 #[serde(rename = "from-bits")]
1384 from_bits: Option<IntLit>,
1385 #[serde(rename = "to-bits")]
1386 to_bits: IntLit,
1387 value: Box<Expression>,
1388 },
1389 #[serde(rename = "field->bytes")]
1390 FieldToBytes {
1391 length: u32,
1392 #[serde(rename = "field-type", default)]
1395 field_type: Option<FieldType>,
1396 value: Box<Expression>,
1397 },
1398 #[serde(rename = "cast-to-field")]
1401 CastToField {
1402 #[serde(rename = "field-type")]
1403 field_type: FieldType,
1404 from: TypeDescriptor,
1405 value: Box<Expression>,
1406 },
1407 #[serde(rename = "cast-from-field")]
1410 CastFromField {
1411 maxval: IntLit,
1412 #[serde(rename = "field-type")]
1413 field_type: FieldType,
1414 value: Box<Expression>,
1415 },
1416 Emit {
1420 #[serde(rename = "event-version")]
1421 event_version: u32,
1422 #[serde(rename = "event-tag")]
1423 event_tag: u32,
1424 #[serde(rename = "payload-length")]
1425 payload_length: u32,
1426 payload: Box<Expression>,
1427 #[serde(rename = "vm-ops", default)]
1428 vm_ops: Vec<VmInstr>,
1429 },
1430 #[serde(rename = "cast-from-bytes")]
1431 CastFromBytes {
1432 to: TypeDescriptor,
1433 length: u32,
1434 value: Box<Expression>,
1435 },
1436 #[serde(rename = "vector->bytes")]
1437 VectorToBytes {
1438 length: u32,
1439 value: Box<Expression>,
1440 },
1441 #[serde(rename = "bytes->vector")]
1442 BytesToVector {
1443 length: u32,
1444 value: Box<Expression>,
1445 },
1446 CastFromEnum {
1447 from: TypeDescriptor,
1448 to: TypeDescriptor,
1449 value: Box<Expression>,
1450 },
1451 CastToEnum {
1452 from: TypeDescriptor,
1453 to: TypeDescriptor,
1454 value: Box<Expression>,
1455 },
1456 Assert {
1457 cond: Box<Expression>,
1458 message: String,
1459 },
1460 Map {
1461 length: IntLit,
1462 function: crate::value::RuntimeValue,
1463 arguments: Vec<crate::value::RuntimeValue>,
1464 },
1465 Fold {
1466 length: IntLit,
1467 function: crate::value::RuntimeValue,
1468 initial: crate::value::RuntimeValue,
1469 arguments: Vec<crate::value::RuntimeValue>,
1470 },
1471 AdtOp(AdtOpInvocation),
1472 ContractCall {
1473 circuit: String,
1474 address: Box<Expression>,
1475 #[serde(rename = "address-type")]
1476 address_type: TypeDescriptor,
1477 arguments: Vec<Expression>,
1478 },
1479 Unimplemented,
1481}
1482
1483#[derive(Debug, Clone, Serialize, Deserialize)]
1484pub struct TupleItem {
1485 pub kind: String, #[serde(default)]
1487 pub length: Option<IntLit>,
1488 pub value: Expression,
1489}
1490
1491#[derive(Debug, Clone, Serialize, Deserialize)]
1496pub struct AdtOpInvocation {
1497 pub adt: String,
1498 pub operation: String,
1499 #[serde(rename = "op-class")]
1500 pub op_class: String,
1501 #[serde(rename = "op-class-coin-index", default)]
1509 pub op_class_coin_index: Option<u32>,
1510 #[serde(rename = "op-class-recipient-index", default)]
1514 pub op_class_recipient_index: Option<u32>,
1515 #[serde(default)]
1516 pub field: Option<String>,
1517 #[serde(rename = "field-path", default)]
1518 pub field_path: Vec<PathElement>,
1519 #[serde(default)]
1520 pub arguments: Vec<Expression>,
1521 #[serde(rename = "result-type")]
1522 pub result_type: TypeDescriptor,
1523 #[serde(rename = "vm-ops")]
1524 pub vm_ops: Vec<VmInstr>,
1525}
1526
1527#[derive(Debug, Clone, Serialize, Deserialize)]
1528#[serde(tag = "kind", rename_all = "kebab-case")]
1529pub enum PathElement {
1530 Literal {
1531 index: u32,
1532 },
1533 Expr {
1534 #[serde(rename = "type")]
1535 of_type: TypeDescriptor,
1536 value: Box<Expression>,
1540 },
1541}
1542
1543#[derive(Debug, Clone, Serialize, Deserialize)]
1552pub struct VmInstr(pub std::collections::BTreeMap<String, crate::value::RuntimeValue>);
1553
1554impl VmInstr {
1555 #[must_use]
1556 pub fn op(&self) -> Option<&str> {
1557 self.0
1558 .get("op")
1559 .and_then(crate::value::RuntimeValue::as_str)
1560 }
1561}
1562
1563pub type VmOp = crate::value::RuntimeValue;
1569
1570#[derive(Debug, Clone, Serialize, Deserialize)]
1575#[serde(tag = "kind", rename_all = "kebab-case")]
1576pub enum StateValue {
1577 Null,
1578 Cell {
1579 #[serde(default)]
1580 descriptor: Option<String>,
1581 value: crate::value::RuntimeValue,
1582 },
1583 CellExpr {
1584 #[serde(default)]
1585 descriptor: Option<String>,
1586 value: Box<Expression>,
1588 },
1589 Array {
1590 items: Vec<StateValue>,
1591 },
1592 Map {
1593 entries: Vec<MapEntry>,
1594 },
1595 MerkleTree {
1596 depth: IntLit,
1597 #[serde(default)]
1598 entries: Vec<MapEntry>,
1599 },
1600}
1601
1602#[derive(Debug, Clone, Serialize, Deserialize)]
1603pub struct MapEntry {
1604 pub key: StateValue,
1605 pub value: StateValue,
1606}