Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 59 additions & 5 deletions gnd/src/abi.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
//! ABI normalization utilities.
//!
//! Handles extraction of bare ABI arrays from various artifact formats
//! (raw arrays, Hardhat/Foundry, Truffle).
//! (raw arrays, Hardhat/Foundry, Truffle) and the preprocessing alloy's ABI
//! parser needs (`anonymous` and `param{index}` defaults).

use anyhow::{Context, Result, anyhow};
use serde_json::Value;

/// Normalize ABI JSON to extract the actual ABI array from various artifact formats.
pub fn normalize_abi_json(abi_str: &str) -> Result<Value> {
let value: Value = serde_json::from_str(abi_str).context("Failed to parse ABI JSON")?;
normalize_abi_value(value)
}

/// Extract the bare ABI array from a parsed value, unwrapping artifact formats.
///
/// Supports:
/// - Raw ABI array: `[{...}]`
/// - Foundry/Hardhat format: `{"abi": [...], ...}`
/// - Truffle format: `{"compilerOutput": {"abi": [...], ...}, ...}`
pub fn normalize_abi_json(abi_str: &str) -> Result<serde_json::Value> {
let value: serde_json::Value =
serde_json::from_str(abi_str).context("Failed to parse ABI JSON")?;

pub fn normalize_abi_value(value: Value) -> Result<Value> {
// Case 1: Already an array - return as-is
if value.is_array() {
return Ok(value);
Expand All @@ -40,6 +45,55 @@ pub fn normalize_abi_json(abi_str: &str) -> Result<serde_json::Value> {
))
}

/// Normalize a parsed ABI value and add the defaults alloy's parser requires:
/// - `anonymous: false` on events (alloy requires the field)
/// - `param{index}` names for unnamed top-level event parameters (matches
/// graph-cli, so the generated getters and manifest signature agree)
pub fn preprocess_abi_value(value: Value) -> Result<Value> {
let mut abi = normalize_abi_value(value)?;

if let Some(items) = abi.as_array_mut() {
for item in items {
if let Some(obj) = item.as_object_mut() {
let is_event = obj.get("type").and_then(|t| t.as_str()) == Some("event");
if is_event {
if !obj.contains_key("anonymous") {
obj.insert("anonymous".to_string(), Value::Bool(false));
}
if let Some(inputs) = obj.get_mut("inputs") {
add_default_event_param_names(inputs);
}
}
}
}
}

Ok(abi)
}

/// Normalize and preprocess ABI JSON, returning the serialized array string that
/// alloy's `JsonAbi` parser accepts.
pub fn preprocess_abi_json(abi_str: &str) -> Result<String> {
let value: Value = serde_json::from_str(abi_str).context("Failed to parse ABI JSON")?;
let abi = preprocess_abi_value(value)?;
serde_json::to_string(&abi).context("Failed to serialize processed ABI")
}

/// Add `param{index}` names to unnamed event parameters to match graph-cli.
/// Alloy defaults missing names to empty strings, but for events we want
/// `param0`, `param1`, etc.
fn add_default_event_param_names(params: &mut Value) {
if let Some(params_arr) = params.as_array_mut() {
for (index, param) in params_arr.iter_mut().enumerate() {
if let Some(obj) = param.as_object_mut()
&& !obj.contains_key("name")
{
obj.insert("name".to_string(), Value::String(format!("param{}", index)));
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
54 changes: 1 addition & 53 deletions gnd/src/commands/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use graph::abi::JsonAbi;
use graphql_tools::parser::schema as gql;
use semver::Version;

use crate::abi::normalize_abi_json;
use crate::abi::preprocess_abi_json;
use crate::codegen::{
AbiCodeGenerator, Class, GENERATED_FILE_NOTE, ModuleImports, SchemaCodeGenerator,
Template as CodegenTemplate, TemplateCodeGenerator, TemplateKind,
Expand Down Expand Up @@ -237,58 +237,6 @@ fn generate_schema_types(
Ok(true)
}

/// Preprocess ABI JSON to normalize artifact formats and add defaults
/// required by alloy's ABI parser:
/// - `anonymous: false` for events (alloy requires this field)
/// - `param{index}` names for unnamed event parameters (to match graph-cli behavior)
fn preprocess_abi_json(abi_str: &str) -> Result<String> {
// Normalize to get the ABI array from various artifact formats
let mut abi = normalize_abi_json(abi_str)?;

if let Some(items) = abi.as_array_mut() {
for item in items {
if let Some(obj) = item.as_object_mut() {
let is_event = obj
.get("type")
.and_then(|t| t.as_str())
.map(|t| t == "event")
.unwrap_or(false);

if is_event {
// Add anonymous: false for events if missing (alloy requires it)
if !obj.contains_key("anonymous") {
obj.insert("anonymous".to_string(), serde_json::Value::Bool(false));
}

// Add param{index} names for unnamed event parameters
if let Some(inputs) = obj.get_mut("inputs") {
add_default_event_param_names(inputs);
}
}
}
}
}

serde_json::to_string(&abi).context("Failed to serialize processed ABI")
}

/// Add `param{index}` names to unnamed event parameters to match graph-cli behavior.
/// Alloy defaults missing names to empty strings, but for events we want `param0`, `param1`, etc.
fn add_default_event_param_names(params: &mut serde_json::Value) {
if let Some(params_arr) = params.as_array_mut() {
for (index, param) in params_arr.iter_mut().enumerate() {
if let Some(obj) = param.as_object_mut()
&& !obj.contains_key("name")
{
obj.insert(
"name".to_string(),
serde_json::Value::String(format!("param{}", index)),
);
}
}
}
}

/// Generate types from an ABI file.
fn generate_abi_types(name: &str, abi_path: &Path, output_dir: &Path) -> Result<()> {
step(Step::Load, &format!("Load ABI from {}", abi_path.display()));
Expand Down
Loading
Loading