Skip to content
Merged
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
90 changes: 90 additions & 0 deletions lib/utils/json-safe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* Recursively convert non-JSON-serializable values to safe representations
* before they are written to a JSONB column.
*
* Blockchain data from viem/ethers can contain types that JSON.stringify
* cannot handle, which makes drizzle-orm's PgJsonb.mapToDriverValue throw
* (e.g. "Do not know how to serialize a BigInt"). This normalizes them:
*
* - BigInt -> string (token amounts, block numbers, gas values)
* - Uint8Array/Buffer -> hex string prefixed with 0x
* - Map -> plain object
* - Set -> array
* - Date -> ISO string
* - undefined -> null (explicit, avoids silent drops in arrays)
* - Functions -> omitted
* - Circular references -> "[Circular]"
*
* Only ancestor cycles are treated as circular; the same object reachable via
* two sibling paths (a shared, non-circular reference) is serialized in full.
*/
export function toJsonSafe(obj: unknown, seen = new WeakSet()): unknown {
if (obj === null || obj === undefined) {
return null;
}

if (typeof obj === "bigint") {
return obj.toString();
}

if (typeof obj === "function") {
return;
}

if (
typeof obj === "string" ||
typeof obj === "number" ||
typeof obj === "boolean"
) {
return obj;
}

if (obj instanceof Date) {
return obj.toISOString();
}

if (obj instanceof Uint8Array || Buffer.isBuffer(obj)) {
return `0x${Buffer.from(obj).toString("hex")}`;
}

if (typeof obj !== "object") {
return String(obj);
}

if (seen.has(obj)) {
return "[Circular]";
}
seen.add(obj);

if (obj instanceof Map) {
const mapResult: Record<string, unknown> = {};
for (const [key, value] of obj) {
mapResult[String(key)] = toJsonSafe(value, seen);
}
seen.delete(obj);
return mapResult;
}

if (obj instanceof Set) {
const setResult = [...obj].map((item) => toJsonSafe(item, seen));
seen.delete(obj);
return setResult;
}

if (Array.isArray(obj)) {
const arrayResult = obj.map((item) => toJsonSafe(item, seen));
seen.delete(obj);
return arrayResult;
}

// Plain object (includes ethers.Result, which has numeric + named keys)
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
const safe = toJsonSafe(value, seen);
if (safe !== undefined) {
result[key] = safe;
}
}
seen.delete(obj);
return result;
}
9 changes: 5 additions & 4 deletions lib/workflow/executor/logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { ErrorCategory, logSystemError, logSystemWarn } from "@/lib/logging";
import { getMetricsCollector } from "@/lib/metrics";
import { recordWorkflowExecutionError } from "@/lib/metrics/collectors/prometheus";
import { ANONYMOUS_ORG_SLUG } from "@/lib/metrics/db-metrics";
import { toJsonSafe } from "@/lib/utils/json-safe";
import {
EXCEEDED_MAX_RETRIES_REGEX,
FAILED_AFTER_RETRIES_REGEX,
Expand Down Expand Up @@ -451,7 +452,7 @@ export async function logStepStartDb(
nodeName: params.nodeName,
nodeType: params.nodeType,
status: "running",
input: params.input,
input: toJsonSafe(params.input),
startedAt: new Date(),
iterationIndex: params.iterationIndex ?? null,
forEachNodeId: params.forEachNodeId ?? null,
Expand Down Expand Up @@ -509,8 +510,8 @@ export async function logStepCompleteDb(
.update(workflowExecutionLogs)
.set({
status: params.status,
output: params.output,
outputRaw: params.outputRaw,
output: toJsonSafe(params.output),
outputRaw: toJsonSafe(params.outputRaw),
error: errorValue,
completedAt: new Date(),
duration: duration.toString(),
Expand Down Expand Up @@ -720,7 +721,7 @@ export async function logWorkflowCompleteDb(
.update(workflowExecutions)
.set({
status: resolvedStatus,
output: params.output,
output: toJsonSafe(params.output),
error: resolvedError,
errorCategory: classification?.errorCategory ?? null,
errorType: classification?.errorType ?? null,
Expand Down
2 changes: 1 addition & 1 deletion plugins/web3/steps/batch-read-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ function decodeCallResult(
);
const structured = callMeta.functionAbi
? structureDecodedResult(decoded, callMeta.functionAbi)
: decoded;
: serializeBigInts(decoded);
return { success: true, result: structured };
} catch (error) {
return {
Expand Down
110 changes: 110 additions & 0 deletions tests/unit/json-safe.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { describe, expect, it } from "vitest";

import { toJsonSafe } from "@/lib/utils/json-safe";

describe("toJsonSafe", () => {
it("converts BigInt to string", () => {
expect(toJsonSafe(BigInt(123))).toBe("123");
expect(
toJsonSafe({ gas: BigInt(21_000), value: BigInt(10) ** BigInt(18) })
).toEqual({
gas: "21000",
value: "1000000000000000000",
});
});

it("survives JSON.stringify after conversion (the JSONB write path)", () => {
const stepOutput = {
blockNumber: BigInt(19_000_000),
balances: [BigInt(1), BigInt(2), BigInt(3)],
nested: { fee: BigInt(500) },
};
// Drizzle's PgJsonb.mapToDriverValue calls JSON.stringify, which throws on
// a raw BigInt. After toJsonSafe it must not throw.
expect(() => JSON.stringify(toJsonSafe(stepOutput))).not.toThrow();
expect(JSON.parse(JSON.stringify(toJsonSafe(stepOutput)))).toEqual({
blockNumber: "19000000",
balances: ["1", "2", "3"],
nested: { fee: "500" },
});
});

it("preserves plain JSON-safe primitives and structures", () => {
expect(toJsonSafe("hello")).toBe("hello");
expect(toJsonSafe(42)).toBe(42);
expect(toJsonSafe(true)).toBe(true);
expect(toJsonSafe([1, "a", false])).toEqual([1, "a", false]);
});

it("normalizes Date to ISO string", () => {
const date = new Date("2026-06-05T12:00:00.000Z");
expect(toJsonSafe(date)).toBe("2026-06-05T12:00:00.000Z");
});

it("converts Uint8Array/Buffer to 0x-prefixed hex", () => {
expect(toJsonSafe(new Uint8Array([0xde, 0xad]))).toBe("0xdead");
expect(toJsonSafe(Buffer.from([0xbe, 0xef]))).toBe("0xbeef");
});

it("converts Map to object and Set to array", () => {
expect(toJsonSafe(new Map([["k", BigInt(1)]]))).toEqual({ k: "1" });
expect(toJsonSafe(new Set([BigInt(1), BigInt(2)]))).toEqual(["1", "2"]);
});

it("returns null for null and undefined", () => {
expect(toJsonSafe(null)).toBeNull();
expect(toJsonSafe(undefined)).toBeNull();
});

it("drops functions and normalizes undefined properties to null", () => {
const value = {
keep: 1,
fn: () => "nope",
gone: undefined,
};
expect(toJsonSafe(value)).toEqual({ keep: 1, gone: null });
});

it("handles circular references without throwing", () => {
const a: Record<string, unknown> = { name: "a" };
a.self = a;
expect(toJsonSafe(a)).toEqual({ name: "a", self: "[Circular]" });
});

it("serializes shared (non-circular) references in full", () => {
const shared = { token: "USDC", decimals: 6 };
expect(toJsonSafe({ a: shared, b: shared })).toEqual({
a: { token: "USDC", decimals: 6 },
b: { token: "USDC", decimals: 6 },
});
expect(toJsonSafe([shared, shared])).toEqual([
{ token: "USDC", decimals: 6 },
{ token: "USDC", decimals: 6 },
]);
});

it("serializes a reference shared across Set and Map entries in full", () => {
const shared = { fee: BigInt(500) };
expect(toJsonSafe(new Set([{ shared }, { shared }]))).toEqual([
{ shared: { fee: "500" } },
{ shared: { fee: "500" } },
]);
expect(
toJsonSafe(
new Map<string, unknown>([
["x", shared],
["y", shared],
])
)
).toEqual({ x: { fee: "500" }, y: { fee: "500" } });
});

it("still flags a true cycle even when the node also appears as a sibling", () => {
const node: Record<string, unknown> = { name: "n" };
node.self = node;
expect(toJsonSafe({ first: node, second: node })).toEqual({
first: { name: "n", self: "[Circular]" },
second: { name: "n", self: "[Circular]" },
});
});
});
Loading