use std::fmt::Write as _;
use moonproof_runtime_ir::RuntimeValue;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TraceLevel {
#[default]
Off,
Calls,
Full,
}
impl TraceLevel {
#[must_use]
pub const fn is_enabled(self) -> bool {
!matches!(self, Self::Off)
}
#[must_use]
pub const fn includes_details(self) -> bool {
matches!(self, Self::Full)
}
#[must_use]
pub fn from_env_str(raw: &str) -> Self {
match raw.trim().to_ascii_lowercase().as_str() {
"1" | "2" | "true" | "yes" | "full" | "verbose" | "trace" => Self::Full,
"calls" | "summary" => Self::Calls,
_ => Self::Off,
}
}
#[must_use]
pub fn from_env() -> Self {
std::env::var("MOONPROOF_TRACE").map_or(Self::Off, |v| Self::from_env_str(&v))
}
#[must_use]
pub const fn as_env_str(self) -> &'static str {
match self {
Self::Off => "off",
Self::Calls => "calls",
Self::Full => "full",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TraceEvent {
CircuitEnter {
contract: String,
circuit: String,
args: RuntimeValue,
depth: usize,
},
CircuitExit {
contract: String,
circuit: String,
result: RuntimeValue,
depth: usize,
},
WitnessCall {
contract: String,
circuit: String,
witness: String,
args: RuntimeValue,
observed: RuntimeValue,
depth: usize,
},
LedgerOp {
contract: String,
adt: String,
operation: String,
vm_op_count: usize,
result: Option<RuntimeValue>,
depth: usize,
},
EmitEvent {
contract: String,
version: u32,
tag: u32,
depth: usize,
},
CrossContractCall {
caller: String,
callee: String,
circuit: String,
args: RuntimeValue,
depth: usize,
},
AssertFailed {
contract: String,
circuit: String,
message: String,
depth: usize,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionTrace {
pub events: Vec<TraceEvent>,
}
impl ExecutionTrace {
#[must_use]
pub const fn new() -> Self {
Self { events: Vec::new() }
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn push(&mut self, event: TraceEvent) {
self.events.push(event);
}
pub fn clear(&mut self) {
self.events.clear();
}
pub fn witness_observations(&self) -> impl Iterator<Item = (&str, &str, &str, &RuntimeValue)> {
self.events.iter().filter_map(|ev| match ev {
TraceEvent::WitnessCall {
contract,
circuit,
witness,
observed,
..
} => Some((
contract.as_str(),
circuit.as_str(),
witness.as_str(),
observed,
)),
_ => None,
})
}
#[must_use]
pub fn render(&self) -> String {
let mut out = String::new();
for ev in &self.events {
match ev {
TraceEvent::CircuitEnter {
contract,
circuit,
args,
depth,
} => {
let prefix = indent(*depth);
let _ = writeln!(
out,
"{prefix}{contract}.{circuit}({})",
format_args_compact(args)
);
}
TraceEvent::CircuitExit { result, depth, .. } => {
let prefix = child_indent(*depth);
let _ = writeln!(out, "{prefix}└─ return {}", format_value_compact(result));
}
TraceEvent::WitnessCall {
witness,
args,
observed,
depth,
..
} => {
let prefix = child_indent(*depth);
let _ = writeln!(
out,
"{prefix}├─ witness {witness}({}) => {}",
format_args_compact(args),
format_value_compact(observed)
);
}
TraceEvent::LedgerOp {
adt,
operation,
vm_op_count,
result,
depth,
..
} => {
let prefix = child_indent(*depth);
match result {
Some(val) => {
let _ = writeln!(
out,
"{prefix}├─ ledger {adt}.{operation} ({vm_op_count} vm ops) => {}",
format_value_compact(val)
);
}
None => {
let _ = writeln!(
out,
"{prefix}├─ ledger {adt}.{operation} ({vm_op_count} vm ops)"
);
}
}
}
TraceEvent::EmitEvent {
version,
tag,
depth,
..
} => {
let prefix = child_indent(*depth);
let _ = writeln!(out, "{prefix}├─ emit event(v{version}, tag={tag})");
}
TraceEvent::CrossContractCall {
callee,
circuit,
args,
depth,
..
} => {
let prefix = child_indent(*depth);
let _ = writeln!(
out,
"{prefix}├─ call {callee}.{circuit}({})",
format_args_compact(args)
);
}
TraceEvent::AssertFailed { message, depth, .. } => {
let prefix = child_indent(*depth);
let _ = writeln!(out, "{prefix}└─ [REVERT] assert failed: {message:?}");
}
}
}
out
}
}
fn indent(depth: usize) -> String {
"│ ".repeat(depth)
}
fn child_indent(depth: usize) -> String {
format!("{} ", "│ ".repeat(depth))
}
fn format_args_compact(args: &RuntimeValue) -> String {
match args {
RuntimeValue::Null => String::new(),
RuntimeValue::Array(items) if items.is_empty() => String::new(),
RuntimeValue::Array(items) => items
.iter()
.map(format_value_compact)
.collect::<Vec<_>>()
.join(", "),
other => format_value_compact(other),
}
}
#[must_use]
pub fn format_value_compact(val: &RuntimeValue) -> String {
match val {
RuntimeValue::Null => "()".to_owned(),
RuntimeValue::Bool(b) => b.to_string(),
RuntimeValue::Int(n) => n.to_string(),
RuntimeValue::String(s) => {
if s.len() > 48 {
format!("\"{}…\" ({}B)", &s[..45], s.len())
} else {
format!("{s:?}")
}
}
RuntimeValue::Bytes(bytes) => {
if bytes.len() <= 8 {
format!("0x{}", hex::encode(bytes))
} else {
format!(
"0x{}…{} ({}B)",
hex::encode(&bytes[..4]),
hex::encode(&bytes[bytes.len() - 2..]),
bytes.len()
)
}
}
RuntimeValue::Array(items) => {
if items.is_empty() {
"[]".to_owned()
} else if items.len() <= 4 {
let inner = items
.iter()
.map(format_value_compact)
.collect::<Vec<_>>()
.join(", ");
format!("[{inner}]")
} else {
format!(
"[{}, … ({} items)]",
format_value_compact(&items[0]),
items.len()
)
}
}
RuntimeValue::Object(map) => {
let mut parts = Vec::new();
for (i, (k, v)) in map.iter().enumerate() {
if i >= 4 {
parts.push(format!("… ({} fields)", map.len()));
break;
}
parts.push(format!("{k}: {}", format_value_compact(v)));
}
format!("{{{}}}", parts.join(", "))
}
}
}
#[must_use]
pub(crate) fn short_address(
addr: &moonproof_ledger::coin_structure::contract::ContractAddress,
) -> String {
let hex_str = crate::state::contract_address_to_hex(addr);
if hex_str.len() > 10 {
format!("0x{}…{}", &hex_str[..6], &hex_str[hex_str.len() - 4..])
} else {
format!("0x{hex_str}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trace_level_env_parsing() {
assert_eq!(TraceLevel::from_env_str(""), TraceLevel::Off);
assert_eq!(TraceLevel::from_env_str("0"), TraceLevel::Off);
assert_eq!(TraceLevel::from_env_str("off"), TraceLevel::Off);
assert_eq!(TraceLevel::from_env_str("calls"), TraceLevel::Calls);
assert_eq!(TraceLevel::from_env_str("1"), TraceLevel::Full);
assert_eq!(TraceLevel::from_env_str("full"), TraceLevel::Full);
assert_eq!(TraceLevel::from_env_str("2"), TraceLevel::Full);
}
#[test]
fn render_nested_call_tree_and_revert() {
let mut trace = ExecutionTrace::new();
trace.push(TraceEvent::CircuitEnter {
contract: "vault".into(),
circuit: "withdraw".into(),
args: RuntimeValue::Int(100),
depth: 0,
});
trace.push(TraceEvent::WitnessCall {
contract: "vault".into(),
circuit: "withdraw".into(),
witness: "secret_key".into(),
args: RuntimeValue::Null,
observed: RuntimeValue::Bytes(vec![0xab; 32]),
depth: 0,
});
trace.push(TraceEvent::LedgerOp {
contract: "vault".into(),
adt: "Counter".into(),
operation: "increment".into(),
vm_op_count: 3,
result: None,
depth: 0,
});
trace.push(TraceEvent::AssertFailed {
contract: "vault".into(),
circuit: "withdraw".into(),
message: "insufficient balance".into(),
depth: 0,
});
let rendered = trace.render();
assert!(rendered.contains("vault.withdraw(100)"));
assert!(rendered.contains("witness secret_key() => 0xabababab…abab (32B)"));
assert!(rendered.contains("ledger Counter.increment (3 vm ops)"));
assert!(rendered.contains("[REVERT] assert failed: \"insufficient balance\""));
assert_eq!(trace.witness_observations().count(), 1);
}
}