Skip to content
Open
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
151 changes: 146 additions & 5 deletions gnd/src/abi.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,93 @@
//! ABI normalization utilities.
//!
//! Handles extraction of bare ABI arrays from various artifact formats
//! (raw arrays, Hardhat/Foundry, Truffle).
//! (raw arrays, Hardhat/Foundry, Truffle), the preprocessing alloy's ABI
//! parser needs (`anonymous` and `param{index}` defaults), and the shared
//! event-signature format the manifest uses.

use anyhow::{Context, Result, anyhow};
use graph::abi::{DynSolType, Event, EventParam};
use serde_json::Value;

/// Resolve an `EventParam`'s declared type to `DynSolType`.
pub fn resolve_event_param_type(param: &EventParam) -> DynSolType {
param
.selector_type()
.parse::<DynSolType>()
.expect("valid ABI type")
}

/// The type an indexed param actually carries in the log.
///
/// A topic is exactly 32 bytes, so reference types (strings, bytes, arrays and
/// tuples) do not fit: the EVM stores `keccak256(encoding)` instead and the
/// value itself is not in the log at all. Value types are stored as-is.
pub fn indexed_input_type(param_type: &DynSolType) -> DynSolType {
match param_type {
DynSolType::String | DynSolType::Bytes | DynSolType::Tuple(_) => DynSolType::FixedBytes(32),
DynSolType::Array(_) | DynSolType::FixedArray(_, _) => DynSolType::FixedBytes(32),
_ => param_type.clone(),
}
}

/// Whether an event param is reduced to a `bytes32` hash by being indexed, so
/// its value cannot be read back out of the log.
///
/// A type that does not parse (a malformed ABI can declare `tuple` with no
/// components) is reported as not hashed: scaffolding must not abort on an ABI
/// that alloy accepted.
pub fn is_hashed_when_indexed(param: &EventParam) -> bool {
if !param.indexed {
return false;
}
match param.selector_type().parse::<DynSolType>() {
Ok(declared) => indexed_input_type(&declared) != declared,
Err(_) => false,
}
}

/// Build a manifest event signature, e.g.
/// `Transfer(indexed address,indexed address,uint256)`.
///
/// The `indexed ` marker is graph-node's own convention: it is stripped before
/// hashing topic0, and only the strict manifest-vs-ABI matcher reads it.
///
/// Types come from `selector_type`, which expands a tuple to its components so
/// the hash covers the real shape. It does not normalize the `uint`/`int`
/// aliases, so an ABI declaring `uint` rather than `uint256` yields a signature
/// that hashes to the wrong topic0 and matches no log. graph-node's matcher
/// builds its comparison string the same way, so such a manifest still
/// validates.
pub fn event_signature_with_indexed(event: &Event) -> String {
let params: Vec<String> = event
.inputs
.iter()
.map(|input| {
let ty = input.selector_type();
if input.indexed {
format!("indexed {}", ty)
} else {
ty.into_owned()
}
})
.collect();

format!("{}({})", event.name, params.join(","))
}

/// 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,8 +113,66 @@ 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.
///
/// An unnamed param reaches us two ways: solc emits `"name": ""` (the key is
/// always present), while a hand-written ABI may omit the key entirely. Both
/// count as unnamed. The index matches the one the codegen counts from, so the
/// generated getter and this name agree.
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() {
let unnamed = obj
.get("name")
.and_then(|n| n.as_str())
.is_none_or(|name| name.is_empty());
if unnamed {
obj.insert("name".to_string(), Value::String(format!("param{}", index)));
}
}
}
}
}

#[cfg(test)]
mod tests {
use serde_json::json;

use super::*;

#[test]
Expand Down Expand Up @@ -98,4 +229,14 @@ mod tests {
.contains("Invalid ABI format")
);
}

#[test]
fn test_is_hashed_when_indexed_tolerates_unparseable_type() {
// alloy accepts a component-less `tuple`, whose selector type is the
// bare word "tuple" and does not parse as a Solidity type. Scaffolding
// must not abort on an ABI that parsed.
let param: EventParam =
serde_json::from_value(json!({"name": "x", "type": "tuple", "indexed": true})).unwrap();
assert!(!is_hashed_when_indexed(&param));
}
}
19 changes: 1 addition & 18 deletions gnd/src/codegen/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use graph::abi::{
use regex::Regex;

use super::typescript::{self as ts, Class, ClassMember, Method, ModuleImports, Param as TsParam};
use crate::abi::{indexed_input_type, resolve_event_param_type};
use crate::shared::{capitalize, handle_reserved_word};

/// Resolve a `Param`'s type to `DynSolType`.
Expand All @@ -23,14 +24,6 @@ fn resolve_param_type(param: &Param) -> DynSolType {
.expect("valid ABI type")
}

/// Resolve an `EventParam`'s type to `DynSolType`.
fn resolve_event_param_type(param: &EventParam) -> DynSolType {
param
.selector_type()
.parse::<DynSolType>()
.expect("valid ABI type")
}

const GRAPH_TS_MODULE: &str = "@graphprotocol/graph-ts";

/// ABI code generator.
Expand Down Expand Up @@ -1363,16 +1356,6 @@ fn is_tuple_matrix_type(param_type: &DynSolType) -> bool {
}
}

/// Handle indexed input type conversion.
fn indexed_input_type(param_type: &DynSolType) -> DynSolType {
// Strings, bytes, and arrays are encoded and hashed to bytes32
match param_type {
DynSolType::String | DynSolType::Bytes | DynSolType::Tuple(_) => DynSolType::FixedBytes(32),
DynSolType::Array(_) | DynSolType::FixedArray(_, _) => DynSolType::FixedBytes(32),
_ => param_type.clone(),
}
}

#[cfg(test)]
mod tests {

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