@secondlayer/subgraphs 3.19.10 → 3.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -124,18 +124,45 @@ interface ContractDeployFilter {
124
124
  deployer?: string;
125
125
  contractName?: string;
126
126
  }
127
+ /**
128
+ * One declared field of a print payload.
129
+ *
130
+ * A bare {@link ColumnType} is a required scalar (`amount: "uint"`). The
131
+ * composite forms exist because real print payloads are not flat: BNS-V2
132
+ * emits `name` as a NESTED tuple, and a `prints` vocabulary that could only
133
+ * say `"jsonb"` is why a handler reading flat `data.name` type-checked,
134
+ * deployed, and then decoded to null on every event.
135
+ *
136
+ * - `{ type: F, optional: true }` — the KEY becomes optional on `event.data`
137
+ * (mirrors `always_present: false` in the inferred schema).
138
+ * - `{ tuple: { … } }` — a nested tuple, typed all the way down.
139
+ * - `{ list: F }` — a list of `F`.
140
+ */
141
+ type PrintField = ColumnType | {
142
+ type: PrintField
143
+ optional: true
144
+ } | {
145
+ tuple: Record<string, PrintField>
146
+ } | {
147
+ list: PrintField
148
+ };
127
149
  interface PrintEventFilter extends TraitScope {
128
150
  type: "print_event";
129
151
  contractId?: string;
130
152
  topic?: string;
131
153
  /**
132
- * Optional per-topic field schema. When declared, the handler's `event` is
133
- * a discriminated union keyed by `topic` and `event.data` is typed per topic
154
+ * Per-topic field schema. When declared, the handler's `event` is a
155
+ * discriminated union keyed by `topic` and `event.data` is typed per topic
134
156
  * (e.g. `{ "completed-deposit": { amount: "uint", sender: "principal" } }`).
135
- * Uses the same `ColumnType` vocab as `schema`; nested fields use `"jsonb"`.
136
- * Type-level only — not validated at runtime.
157
+ * Nested tuples, lists, and optional fields are expressible — see
158
+ * {@link PrintField}.
159
+ *
160
+ * Declaring `prints` also opts the source into RUNTIME validation: an
161
+ * event whose decoded payload does not match is skipped and logged rather
162
+ * than written as nulls (and the deploy-time field lint is promoted from
163
+ * a warning to an error).
137
164
  */
138
- prints?: Record<string, Record<string, ColumnType>>;
165
+ prints?: Record<string, Record<string, PrintField>>;
139
166
  }
140
167
  /** All subgraph filter types — discriminated on `type` */
141
168
  type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter;
@@ -396,6 +423,10 @@ type EventRecord = {
396
423
  interface RunResult {
397
424
  processed: number;
398
425
  errors: number;
426
+ /** Print events skipped because their decoded payload did not match the
427
+ * source's declared `prints` schema. Never an error: skipping keeps the
428
+ * block committable, which the checkpoint model requires. */
429
+ skipped?: number;
399
430
  }
400
431
  /**
401
432
  * Build the named, ABI-decoded `event.input` for a contract_call source that
@@ -40,6 +40,87 @@ import {
40
40
  deserializeCV as deserializeCV2,
41
41
  toCamelCase
42
42
  } from "@secondlayer/stacks/clarity";
43
+
44
+ // src/runtime/print-validate.ts
45
+ var COLUMN_TYPES = new Set([
46
+ "text",
47
+ "uint",
48
+ "int",
49
+ "principal",
50
+ "boolean",
51
+ "timestamp",
52
+ "jsonb"
53
+ ]);
54
+ function isColumnType(field) {
55
+ return typeof field === "string" && COLUMN_TYPES.has(field);
56
+ }
57
+ function matchesField(field, value) {
58
+ if (isColumnType(field)) {
59
+ switch (field) {
60
+ case "uint":
61
+ case "int":
62
+ return typeof value === "bigint" || typeof value === "number";
63
+ case "boolean":
64
+ return typeof value === "boolean";
65
+ case "text":
66
+ case "principal":
67
+ case "timestamp":
68
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
69
+ case "jsonb":
70
+ return value !== undefined;
71
+ }
72
+ }
73
+ if (typeof field !== "object" || field === null)
74
+ return false;
75
+ if ("optional" in field) {
76
+ return value === undefined || value === null || matchesField(field.type, value);
77
+ }
78
+ if ("tuple" in field) {
79
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
80
+ return false;
81
+ }
82
+ return matchesTopic(field.tuple, value).ok;
83
+ }
84
+ if ("list" in field) {
85
+ return Array.isArray(value) && value.every((item) => matchesField(field.list, item));
86
+ }
87
+ return false;
88
+ }
89
+ function matchesTopic(declared, data) {
90
+ for (const [name, field] of Object.entries(declared)) {
91
+ const present = name in data;
92
+ const optional = typeof field === "object" && field !== null && "optional" in field;
93
+ if (!present) {
94
+ if (optional)
95
+ continue;
96
+ return { ok: false, reason: `missing declared field "${name}"` };
97
+ }
98
+ if (!matchesField(field, data[name])) {
99
+ return {
100
+ ok: false,
101
+ reason: `field "${name}" does not match its declared type (got ${describe(data[name])})`
102
+ };
103
+ }
104
+ }
105
+ return { ok: true };
106
+ }
107
+ function describe(value) {
108
+ if (value === null)
109
+ return "null";
110
+ if (Array.isArray(value))
111
+ return "array";
112
+ return typeof value;
113
+ }
114
+ function validatePrintPayload(prints, topic, data) {
115
+ if (!prints)
116
+ return { ok: true };
117
+ const declared = prints[topic];
118
+ if (!declared)
119
+ return { ok: true };
120
+ return matchesTopic(declared, data);
121
+ }
122
+
123
+ // src/runtime/runner.ts
43
124
  var DEFAULT_ERROR_THRESHOLD = 50;
44
125
  function camelCase(str) {
45
126
  return str.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
@@ -284,6 +365,7 @@ function buildEventPayload(filter, tx, event) {
284
365
  async function runHandlers(subgraph, matched, ctx, opts) {
285
366
  let processed = 0;
286
367
  let errors = 0;
368
+ let skipped = 0;
287
369
  const threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;
288
370
  const filterLookup = new Map;
289
371
  if (!Array.isArray(subgraph.sources)) {
@@ -308,7 +390,7 @@ async function runHandlers(subgraph, matched, ctx, opts) {
308
390
  errors,
309
391
  threshold
310
392
  });
311
- return { processed, errors };
393
+ return { processed, errors, ...skipped > 0 ? { skipped } : {} };
312
394
  }
313
395
  const handler = subgraph.handlers[sourceName] ?? subgraph.handlers["*"] ?? null;
314
396
  if (!handler) {
@@ -364,6 +446,21 @@ async function runHandlers(subgraph, matched, ctx, opts) {
364
446
  if (event !== null && filter?.type === "print_event" && filter.topic && payload.topic !== filter.topic) {
365
447
  continue;
366
448
  }
449
+ if (event !== null && filter?.type === "print_event" && filter.prints) {
450
+ const printPayload = payload;
451
+ const verdict = validatePrintPayload(filter.prints, printPayload.topic ?? "", printPayload.data ?? {});
452
+ if (!verdict.ok) {
453
+ skipped++;
454
+ logger.warn("Print payload does not match declared prints schema", {
455
+ subgraph: subgraph.name,
456
+ sourceName,
457
+ topic: printPayload.topic,
458
+ txId: tx.tx_id,
459
+ reason: verdict.reason
460
+ });
461
+ continue;
462
+ }
463
+ }
367
464
  await handler(payload, ctx);
368
465
  processed++;
369
466
  } catch (err) {
@@ -378,7 +475,7 @@ async function runHandlers(subgraph, matched, ctx, opts) {
378
475
  });
379
476
  }
380
477
  }
381
- return { processed, errors };
478
+ return { processed, errors, ...skipped > 0 ? { skipped } : {} };
382
479
  }
383
480
  export {
384
481
  runHandlers,
@@ -386,5 +483,5 @@ export {
386
483
  buildContractCallInput
387
484
  };
388
485
 
389
- //# debugId=611CAFE15DEA08D764756E2164756E21
486
+ //# debugId=5FE61480B3DD60C064756E2164756E21
390
487
  //# sourceMappingURL=runner.js.map
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/runtime/clarity.ts", "../src/runtime/runner.ts"],
3
+ "sources": ["../src/runtime/clarity.ts", "../src/runtime/runner.ts", "../src/runtime/print-validate.ts"],
4
4
  "sourcesContent": [
5
5
  "import { cvToValue, deserializeCV } from \"@secondlayer/stacks/clarity\";\n\n/**\n * Decode a hex-encoded Clarity value to a JS object.\n * Returns original value on failure.\n */\nexport function decodeClarityValue(hex: string): unknown {\n\ttry {\n\t\tconst cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\tconst cv = deserializeCV(cleanHex);\n\t\treturn cvToValue(cv);\n\t} catch {\n\t\treturn hex;\n\t}\n}\n\n/**\n * Recursively decode all hex-encoded Clarity values in an object.\n * Any string starting with \"0x\" and longer than 10 chars is attempted.\n */\nexport function decodeEventData(data: unknown): unknown {\n\tif (typeof data === \"string\" && data.startsWith(\"0x\") && data.length > 10) {\n\t\treturn decodeClarityValue(data);\n\t}\n\n\tif (Array.isArray(data)) {\n\t\treturn data.map(decodeEventData);\n\t}\n\n\tif (typeof data === \"object\" && data !== null) {\n\t\tconst decoded: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(data)) {\n\t\t\tdecoded[key] = decodeEventData(value);\n\t\t}\n\t\treturn decoded;\n\t}\n\n\treturn data;\n}\n\n/**\n * Decode function args array (hex-encoded Clarity values).\n */\nexport function decodeFunctionArgs(args: string[]): unknown[] {\n\treturn args.map(decodeClarityValue);\n}\n",
6
- "import { getErrorMessage } from \"@secondlayer/shared\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport {\n\tclarityValueToJS,\n\tdeserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport type {\n\tContractCallFilter,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n} from \"../types.ts\";\nimport { decodeClarityValue, decodeEventData } from \"./clarity.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport type { MatchedTx } from \"./source-matcher.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n\tprocessed: number;\n\terrors: number;\n}\n\n/** Convert kebab-case to camelCase: \"bitcoin-txid\" → \"bitcoinTxid\" */\nfunction camelCase(str: string): string {\n\treturn str.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());\n}\n\n/** Recursively camelize all object keys */\nfunction camelizeKeys(obj: unknown): unknown {\n\tif (obj === null || obj === undefined) return obj;\n\tif (typeof obj !== \"object\") return obj;\n\tif (Array.isArray(obj)) return obj.map(camelizeKeys);\n\tconst result: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n\t\tresult[camelCase(k)] = camelizeKeys(v);\n\t}\n\treturn result;\n}\n\n/**\n * Decode function_args (hex-encoded ClarityValues) to an array of JS values.\n * Returns decoded values via cvToValue.\n *\n * postgres.js returns JSONB columns as JSON strings rather than parsed objects —\n * parse the string first before checking Array.isArray.\n */\nfunction decodeFunctionArgs(args: unknown): unknown[] {\n\tlet parsed = args;\n\tif (typeof parsed === \"string\") {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.map((arg) => {\n\t\tif (typeof arg === \"string\") return decodeClarityValue(arg);\n\t\treturn arg;\n\t});\n}\n\n/**\n * Decode raw_result (hex-encoded Clarity return value) to JS value.\n */\nfunction decodeRawResult(raw: unknown): unknown {\n\tif (typeof raw === \"string\" && raw.length > 2) {\n\t\treturn decodeClarityValue(raw);\n\t}\n\treturn null;\n}\n\n/** Safely convert a value to BigInt. Handles string, number, bigint. Returns 0n on failure. */\nfunction safeBigInt(val: unknown): bigint {\n\tif (typeof val === \"bigint\") return val;\n\tif (typeof val === \"number\") return BigInt(val);\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn BigInt(val);\n\t\t} catch {\n\t\t\treturn 0n;\n\t\t}\n\t}\n\treturn 0n;\n}\n\n/**\n * Build the named, ABI-decoded `event.input` for a contract_call source that\n * declares an `abi`. Each function arg is decoded via `clarityValueToJS` so the\n * values match the types `ExtractFunctionArgs` promises (Uint8Array buffers,\n * camelCase tuple keys, wrapped responses). Returns undefined when no abi /\n * function match, leaving handlers with the positional `args` only.\n */\nexport function buildContractCallInput(\n\tfilter: ContractCallFilter,\n\ttx: MatchedTx[\"tx\"],\n): Record<string, unknown> | undefined {\n\tconst abi = filter.abi;\n\tconst fnName = tx.function_name;\n\tif (!abi || !fnName) return undefined;\n\tconst fn = abi.functions?.find((f) => f.name === fnName);\n\tif (!fn || !Array.isArray(fn.args)) return undefined;\n\n\tlet rawArgs: unknown = tx.function_args;\n\tif (typeof rawArgs === \"string\") {\n\t\ttry {\n\t\t\trawArgs = JSON.parse(rawArgs);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (!Array.isArray(rawArgs)) return undefined;\n\n\t// Call through a non-generic cast: clarityValueToJS<T> instantiates the deep\n\t// AbiToTS<T> conditional (TS2589) at runtime call sites. The static types\n\t// come from ContractCallPayload; here we only need its runtime reshaping.\n\tconst decodeArg = clarityValueToJS as unknown as (\n\t\ttype: unknown,\n\t\tcv: unknown,\n\t) => unknown;\n\tconst input: Record<string, unknown> = {};\n\tfn.args.forEach((arg, i) => {\n\t\tconst hex = rawArgs[i];\n\t\tif (typeof hex !== \"string\") return;\n\t\ttry {\n\t\t\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\t\tinput[toCamelCase(arg.name)] = decodeArg(arg.type, deserializeCV(clean));\n\t\t} catch {\n\t\t\t// Skip args that fail to decode rather than dropping the whole event.\n\t\t}\n\t});\n\treturn input;\n}\n\n/**\n * Build a typed event payload based on the source filter type.\n * Returns the payload the handler will receive.\n */\nexport function buildEventPayload(\n\tfilter: SubgraphFilter,\n\ttx: MatchedTx[\"tx\"],\n\tevent: MatchedTx[\"events\"][0] | null,\n): Record<string, unknown> {\n\tconst txMeta = {\n\t\ttxId: tx.tx_id,\n\t\tsender: tx.sender,\n\t\ttype: tx.type,\n\t\tstatus: tx.status,\n\t\tcontractId: tx.contract_id ?? null,\n\t\tfunctionName: tx.function_name ?? null,\n\t};\n\n\t// Decoded function args + result for contract_call payloads\n\tconst decodedArgs = decodeFunctionArgs(tx.function_args);\n\tconst decodedResult = decodeRawResult(tx.raw_result);\n\n\t// No event — tx-level match (contract_call or contract_deploy)\n\tif (!event) {\n\t\tswitch (filter.type) {\n\t\t\tcase \"contract_call\": {\n\t\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"contract_call\",\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\targs: decodedArgs,\n\t\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\t\tresult: decodedResult,\n\t\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"contract_deploy\":\n\t\t\t\treturn {\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tdeployer: tx.sender,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn { tx: txMeta };\n\t\t}\n\t}\n\n\t// Decode event data (Clarity values auto-unwrapped via cvToValue)\n\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\n\tswitch (filter.type) {\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── NFT events ──\n\t\t// tokenId decodes from the canonical hex (`raw_value`), not the node's\n\t\t// verbose serde-tagged `value` (`{UInt:223}`). The hex is source-\n\t\t// independent — present in both the DB tap and the Index API — so a\n\t\t// subgraph yields the same clean tokenId (e.g. 223n) on either source.\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tmemo: decoded.memo ?? \"\",\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\tlockedAddress: decoded.locked_address as string,\n\t\t\t\tlockedAmount: safeBigInt(decoded.locked_amount),\n\t\t\t\tunlockHeight: safeBigInt(decoded.unlock_height),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\t// Decode the print value from the canonical hex (`raw_value`) so it's\n\t\t\t// source-independent and clean — the node's verbose serde-tagged\n\t\t\t// `value` (e.g. `{Optional:{data:null}}`) is not reproducible from the\n\t\t\t// Index API and is no longer used (same rationale as nft tokenId).\n\t\t\t// decodeEventData skips hex ≤10 chars, so decode `raw_value` directly.\n\t\t\tconst rawHex = (event.data as Record<string, unknown> | null)?.raw_value;\n\t\t\tconst rawValue =\n\t\t\t\ttypeof rawHex === \"string\" && rawHex.startsWith(\"0x\")\n\t\t\t\t\t? decodeClarityValue(rawHex)\n\t\t\t\t\t: decoded.value;\n\t\t\t// Extract topic from decoded Clarity value (not raw event topic which is always \"print\")\n\t\t\tconst clarityObj =\n\t\t\t\trawValue && typeof rawValue === \"object\" && !Array.isArray(rawValue)\n\t\t\t\t\t? (rawValue as Record<string, unknown>)\n\t\t\t\t\t: null;\n\t\t\tconst topic = clarityObj?.topic\n\t\t\t\t? String(clarityObj.topic)\n\t\t\t\t: ((decoded.topic as string) ?? \"\");\n\t\t\t// Camelize remaining keys for developer convenience\n\t\t\tconst { topic: _, ...rest } = clarityObj ?? {};\n\t\t\tconst data =\n\t\t\t\tObject.keys(rest).length > 0\n\t\t\t\t\t? (camelizeKeys(rest) as Record<string, unknown>)\n\t\t\t\t\t: rawValue && typeof rawValue !== \"object\"\n\t\t\t\t\t\t? rawValue\n\t\t\t\t\t\t: {};\n\t\t\treturn {\n\t\t\t\tcontractId:\n\t\t\t\t\t(decoded.contract_identifier as string) ?? tx.contract_id ?? \"\",\n\t\t\t\ttopic,\n\t\t\t\tdata: data ?? {},\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract call (with events) ──\n\t\tcase \"contract_call\": {\n\t\t\t// Normalize the spread event Clarity `value` to the decoded canonical\n\t\t\t// (from `raw_value`), so it's identical whether the event came from the\n\t\t\t// DB tap or the Index API — the node's serde-tagged `value` is not\n\t\t\t// reproducible from Index (same rationale as nft tokenId / print).\n\t\t\tconst ccRawHex = (event.data as Record<string, unknown> | null)\n\t\t\t\t?.raw_value;\n\t\t\tconst normalized =\n\t\t\t\ttypeof ccRawHex === \"string\" && ccRawHex.startsWith(\"0x\")\n\t\t\t\t\t? { ...decoded, value: decodeClarityValue(ccRawHex) }\n\t\t\t\t\t: decoded;\n\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\treturn {\n\t\t\t\t...normalized,\n\t\t\t\ttype: \"contract_call\",\n\t\t\t\t_eventType: event.type,\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\tsender: tx.sender,\n\t\t\t\targs: decodedArgs,\n\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\tresult: decodedResult,\n\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\":\n\t\t\treturn {\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tdeployer: tx.sender,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\tdefault:\n\t\t\t// Fallback: spread decoded data with tx metadata\n\t\t\treturn {\n\t\t\t\t...decoded,\n\t\t\t\t_eventType: event.type,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t}\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceName from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n\tsubgraph: SubgraphDefinition,\n\tmatched: MatchedTx[],\n\tctx: SubgraphContext,\n\topts?: { errorThreshold?: number },\n): Promise<RunResult> {\n\tlet processed = 0;\n\tlet errors = 0;\n\tconst threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n\t// Build filter lookup from sources (supports both array and named object)\n\tconst filterLookup = new Map<string, SubgraphFilter>();\n\tif (!Array.isArray(subgraph.sources)) {\n\t\tfor (const [name, filter] of Object.entries(\n\t\t\tsubgraph.sources as Record<string, SubgraphFilter>,\n\t\t)) {\n\t\t\tfilterLookup.set(name, filter);\n\t\t}\n\t}\n\n\t// Flatten matches to per-event dispatch units and sort into CHAIN order\n\t// (tx_index, then event_index; tx-level matches first within their tx).\n\t// The matcher groups results by source, so without this a block's mints\n\t// all run before (or after) its transfers — a debit could apply before\n\t// the same block's funding credit, which on-chain ordering forbids. Chain\n\t// order makes per-statement invariants (e.g. uint CHECK >= 0) sound.\n\ttype DispatchUnit = {\n\t\ttx: MatchedTx[\"tx\"];\n\t\tsourceName: string;\n\t\tevent: MatchedTx[\"events\"][0] | null;\n\t};\n\tconst units: DispatchUnit[] = [];\n\tfor (const { tx, events, sourceName } of matched) {\n\t\tif (events.length === 0) {\n\t\t\tunits.push({ tx, sourceName, event: null });\n\t\t} else {\n\t\t\tfor (const event of events) units.push({ tx, sourceName, event });\n\t\t}\n\t}\n\tunits.sort(\n\t\t(a, b) =>\n\t\t\t(a.tx.tx_index ?? 0) - (b.tx.tx_index ?? 0) ||\n\t\t\t(a.event?.event_index ?? -1) - (b.event?.event_index ?? -1),\n\t);\n\n\tfor (const { tx, event, sourceName } of units) {\n\t\tif (errors >= threshold) {\n\t\t\tlogger.error(\n\t\t\t\t\"Subgraph error threshold reached, skipping remaining events\",\n\t\t\t\t{\n\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\terrors,\n\t\t\t\t\tthreshold,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { processed, errors };\n\t\t}\n\n\t\tconst handler =\n\t\t\tsubgraph.handlers[sourceName] ?? subgraph.handlers[\"*\"] ?? null;\n\t\tif (!handler) {\n\t\t\tlogger.warn(\"No handler found for source\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tctx.setTx({\n\t\t\ttxId: tx.tx_id,\n\t\t\tsender: tx.sender,\n\t\t\ttype: tx.type,\n\t\t\tstatus: tx.status,\n\t\t\tcontractId: tx.contract_id ?? null,\n\t\t\tfunctionName: tx.function_name ?? null,\n\t\t});\n\n\t\tconst filter = filterLookup.get(sourceName);\n\n\t\t// Checkpoint the ops queue: a handler that throws mid-way must\n\t\t// contribute nothing — a partial flush (e.g. a debit without its\n\t\t// credit) silently corrupts accumulator tables (fix-f040 B6).\n\t\tconst checkpoint = ctx.opsCheckpoint();\n\t\ttry {\n\t\t\tlet payload: Record<string, unknown>;\n\t\t\tif (event === null) {\n\t\t\t\t// Tx-level match (contract_call / contract_deploy)\n\t\t\t\tpayload = filter\n\t\t\t\t\t? buildEventPayload(filter, tx, null)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttx: {\n\t\t\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t} else if (filter) {\n\t\t\t\tpayload = buildEventPayload(filter, tx, event);\n\t\t\t} else {\n\t\t\t\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\t\t\t\tpayload = {\n\t\t\t\t\t...decoded,\n\t\t\t\t\t_eventId: event.id,\n\t\t\t\t\t_eventType: event.type,\n\t\t\t\t\t_eventIndex: event.event_index,\n\t\t\t\t\ttx: {\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Post-decode topic filter for print_event — source-matcher defers this\n\t\t\t// because data.value is raw hex at match time; apply it now after decode.\n\t\t\tif (\n\t\t\t\tevent !== null &&\n\t\t\t\tfilter?.type === \"print_event\" &&\n\t\t\t\tfilter.topic &&\n\t\t\t\tpayload.topic !== filter.topic\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tawait handler(payload, ctx);\n\t\t\tprocessed++;\n\t\t} catch (err) {\n\t\t\tctx.rollbackTo(checkpoint);\n\t\t\terrors++;\n\t\t\tlogger.error(\"Subgraph handler error\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t...(event !== null ? { eventId: event.id, eventType: event.type } : {}),\n\t\t\t\terror: getErrorMessage(err),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { processed, errors };\n}\n"
6
+ "import { getErrorMessage } from \"@secondlayer/shared\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport {\n\tclarityValueToJS,\n\tdeserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport type {\n\tContractCallFilter,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n} from \"../types.ts\";\nimport { decodeClarityValue, decodeEventData } from \"./clarity.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport { validatePrintPayload } from \"./print-validate.ts\";\nimport type { MatchedTx } from \"./source-matcher.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n\tprocessed: number;\n\terrors: number;\n\t/** Print events skipped because their decoded payload did not match the\n\t * source's declared `prints` schema. Never an error: skipping keeps the\n\t * block committable, which the checkpoint model requires. */\n\tskipped?: number;\n}\n\n/** Convert kebab-case to camelCase: \"bitcoin-txid\" → \"bitcoinTxid\" */\nfunction camelCase(str: string): string {\n\treturn str.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());\n}\n\n/** Recursively camelize all object keys */\nfunction camelizeKeys(obj: unknown): unknown {\n\tif (obj === null || obj === undefined) return obj;\n\tif (typeof obj !== \"object\") return obj;\n\tif (Array.isArray(obj)) return obj.map(camelizeKeys);\n\tconst result: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n\t\tresult[camelCase(k)] = camelizeKeys(v);\n\t}\n\treturn result;\n}\n\n/**\n * Decode function_args (hex-encoded ClarityValues) to an array of JS values.\n * Returns decoded values via cvToValue.\n *\n * postgres.js returns JSONB columns as JSON strings rather than parsed objects —\n * parse the string first before checking Array.isArray.\n */\nfunction decodeFunctionArgs(args: unknown): unknown[] {\n\tlet parsed = args;\n\tif (typeof parsed === \"string\") {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.map((arg) => {\n\t\tif (typeof arg === \"string\") return decodeClarityValue(arg);\n\t\treturn arg;\n\t});\n}\n\n/**\n * Decode raw_result (hex-encoded Clarity return value) to JS value.\n */\nfunction decodeRawResult(raw: unknown): unknown {\n\tif (typeof raw === \"string\" && raw.length > 2) {\n\t\treturn decodeClarityValue(raw);\n\t}\n\treturn null;\n}\n\n/** Safely convert a value to BigInt. Handles string, number, bigint. Returns 0n on failure. */\nfunction safeBigInt(val: unknown): bigint {\n\tif (typeof val === \"bigint\") return val;\n\tif (typeof val === \"number\") return BigInt(val);\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn BigInt(val);\n\t\t} catch {\n\t\t\treturn 0n;\n\t\t}\n\t}\n\treturn 0n;\n}\n\n/**\n * Build the named, ABI-decoded `event.input` for a contract_call source that\n * declares an `abi`. Each function arg is decoded via `clarityValueToJS` so the\n * values match the types `ExtractFunctionArgs` promises (Uint8Array buffers,\n * camelCase tuple keys, wrapped responses). Returns undefined when no abi /\n * function match, leaving handlers with the positional `args` only.\n */\nexport function buildContractCallInput(\n\tfilter: ContractCallFilter,\n\ttx: MatchedTx[\"tx\"],\n): Record<string, unknown> | undefined {\n\tconst abi = filter.abi;\n\tconst fnName = tx.function_name;\n\tif (!abi || !fnName) return undefined;\n\tconst fn = abi.functions?.find((f) => f.name === fnName);\n\tif (!fn || !Array.isArray(fn.args)) return undefined;\n\n\tlet rawArgs: unknown = tx.function_args;\n\tif (typeof rawArgs === \"string\") {\n\t\ttry {\n\t\t\trawArgs = JSON.parse(rawArgs);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (!Array.isArray(rawArgs)) return undefined;\n\n\t// Call through a non-generic cast: clarityValueToJS<T> instantiates the deep\n\t// AbiToTS<T> conditional (TS2589) at runtime call sites. The static types\n\t// come from ContractCallPayload; here we only need its runtime reshaping.\n\tconst decodeArg = clarityValueToJS as unknown as (\n\t\ttype: unknown,\n\t\tcv: unknown,\n\t) => unknown;\n\tconst input: Record<string, unknown> = {};\n\tfn.args.forEach((arg, i) => {\n\t\tconst hex = rawArgs[i];\n\t\tif (typeof hex !== \"string\") return;\n\t\ttry {\n\t\t\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\t\tinput[toCamelCase(arg.name)] = decodeArg(arg.type, deserializeCV(clean));\n\t\t} catch {\n\t\t\t// Skip args that fail to decode rather than dropping the whole event.\n\t\t}\n\t});\n\treturn input;\n}\n\n/**\n * Build a typed event payload based on the source filter type.\n * Returns the payload the handler will receive.\n */\nexport function buildEventPayload(\n\tfilter: SubgraphFilter,\n\ttx: MatchedTx[\"tx\"],\n\tevent: MatchedTx[\"events\"][0] | null,\n): Record<string, unknown> {\n\tconst txMeta = {\n\t\ttxId: tx.tx_id,\n\t\tsender: tx.sender,\n\t\ttype: tx.type,\n\t\tstatus: tx.status,\n\t\tcontractId: tx.contract_id ?? null,\n\t\tfunctionName: tx.function_name ?? null,\n\t};\n\n\t// Decoded function args + result for contract_call payloads\n\tconst decodedArgs = decodeFunctionArgs(tx.function_args);\n\tconst decodedResult = decodeRawResult(tx.raw_result);\n\n\t// No event — tx-level match (contract_call or contract_deploy)\n\tif (!event) {\n\t\tswitch (filter.type) {\n\t\t\tcase \"contract_call\": {\n\t\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"contract_call\",\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\targs: decodedArgs,\n\t\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\t\tresult: decodedResult,\n\t\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"contract_deploy\":\n\t\t\t\treturn {\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tdeployer: tx.sender,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn { tx: txMeta };\n\t\t}\n\t}\n\n\t// Decode event data (Clarity values auto-unwrapped via cvToValue)\n\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\n\tswitch (filter.type) {\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── NFT events ──\n\t\t// tokenId decodes from the canonical hex (`raw_value`), not the node's\n\t\t// verbose serde-tagged `value` (`{UInt:223}`). The hex is source-\n\t\t// independent — present in both the DB tap and the Index API — so a\n\t\t// subgraph yields the same clean tokenId (e.g. 223n) on either source.\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tmemo: decoded.memo ?? \"\",\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\tlockedAddress: decoded.locked_address as string,\n\t\t\t\tlockedAmount: safeBigInt(decoded.locked_amount),\n\t\t\t\tunlockHeight: safeBigInt(decoded.unlock_height),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\t// Decode the print value from the canonical hex (`raw_value`) so it's\n\t\t\t// source-independent and clean — the node's verbose serde-tagged\n\t\t\t// `value` (e.g. `{Optional:{data:null}}`) is not reproducible from the\n\t\t\t// Index API and is no longer used (same rationale as nft tokenId).\n\t\t\t// decodeEventData skips hex ≤10 chars, so decode `raw_value` directly.\n\t\t\tconst rawHex = (event.data as Record<string, unknown> | null)?.raw_value;\n\t\t\tconst rawValue =\n\t\t\t\ttypeof rawHex === \"string\" && rawHex.startsWith(\"0x\")\n\t\t\t\t\t? decodeClarityValue(rawHex)\n\t\t\t\t\t: decoded.value;\n\t\t\t// Extract topic from decoded Clarity value (not raw event topic which is always \"print\")\n\t\t\tconst clarityObj =\n\t\t\t\trawValue && typeof rawValue === \"object\" && !Array.isArray(rawValue)\n\t\t\t\t\t? (rawValue as Record<string, unknown>)\n\t\t\t\t\t: null;\n\t\t\tconst topic = clarityObj?.topic\n\t\t\t\t? String(clarityObj.topic)\n\t\t\t\t: ((decoded.topic as string) ?? \"\");\n\t\t\t// Camelize remaining keys for developer convenience\n\t\t\tconst { topic: _, ...rest } = clarityObj ?? {};\n\t\t\tconst data =\n\t\t\t\tObject.keys(rest).length > 0\n\t\t\t\t\t? (camelizeKeys(rest) as Record<string, unknown>)\n\t\t\t\t\t: rawValue && typeof rawValue !== \"object\"\n\t\t\t\t\t\t? rawValue\n\t\t\t\t\t\t: {};\n\t\t\treturn {\n\t\t\t\tcontractId:\n\t\t\t\t\t(decoded.contract_identifier as string) ?? tx.contract_id ?? \"\",\n\t\t\t\ttopic,\n\t\t\t\tdata: data ?? {},\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract call (with events) ──\n\t\tcase \"contract_call\": {\n\t\t\t// Normalize the spread event Clarity `value` to the decoded canonical\n\t\t\t// (from `raw_value`), so it's identical whether the event came from the\n\t\t\t// DB tap or the Index API — the node's serde-tagged `value` is not\n\t\t\t// reproducible from Index (same rationale as nft tokenId / print).\n\t\t\tconst ccRawHex = (event.data as Record<string, unknown> | null)\n\t\t\t\t?.raw_value;\n\t\t\tconst normalized =\n\t\t\t\ttypeof ccRawHex === \"string\" && ccRawHex.startsWith(\"0x\")\n\t\t\t\t\t? { ...decoded, value: decodeClarityValue(ccRawHex) }\n\t\t\t\t\t: decoded;\n\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\treturn {\n\t\t\t\t...normalized,\n\t\t\t\ttype: \"contract_call\",\n\t\t\t\t_eventType: event.type,\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\tsender: tx.sender,\n\t\t\t\targs: decodedArgs,\n\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\tresult: decodedResult,\n\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\":\n\t\t\treturn {\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tdeployer: tx.sender,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\tdefault:\n\t\t\t// Fallback: spread decoded data with tx metadata\n\t\t\treturn {\n\t\t\t\t...decoded,\n\t\t\t\t_eventType: event.type,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t}\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceName from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n\tsubgraph: SubgraphDefinition,\n\tmatched: MatchedTx[],\n\tctx: SubgraphContext,\n\topts?: { errorThreshold?: number },\n): Promise<RunResult> {\n\tlet processed = 0;\n\tlet errors = 0;\n\tlet skipped = 0;\n\tconst threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n\t// Build filter lookup from sources (supports both array and named object)\n\tconst filterLookup = new Map<string, SubgraphFilter>();\n\tif (!Array.isArray(subgraph.sources)) {\n\t\tfor (const [name, filter] of Object.entries(\n\t\t\tsubgraph.sources as Record<string, SubgraphFilter>,\n\t\t)) {\n\t\t\tfilterLookup.set(name, filter);\n\t\t}\n\t}\n\n\t// Flatten matches to per-event dispatch units and sort into CHAIN order\n\t// (tx_index, then event_index; tx-level matches first within their tx).\n\t// The matcher groups results by source, so without this a block's mints\n\t// all run before (or after) its transfers — a debit could apply before\n\t// the same block's funding credit, which on-chain ordering forbids. Chain\n\t// order makes per-statement invariants (e.g. uint CHECK >= 0) sound.\n\ttype DispatchUnit = {\n\t\ttx: MatchedTx[\"tx\"];\n\t\tsourceName: string;\n\t\tevent: MatchedTx[\"events\"][0] | null;\n\t};\n\tconst units: DispatchUnit[] = [];\n\tfor (const { tx, events, sourceName } of matched) {\n\t\tif (events.length === 0) {\n\t\t\tunits.push({ tx, sourceName, event: null });\n\t\t} else {\n\t\t\tfor (const event of events) units.push({ tx, sourceName, event });\n\t\t}\n\t}\n\tunits.sort(\n\t\t(a, b) =>\n\t\t\t(a.tx.tx_index ?? 0) - (b.tx.tx_index ?? 0) ||\n\t\t\t(a.event?.event_index ?? -1) - (b.event?.event_index ?? -1),\n\t);\n\n\tfor (const { tx, event, sourceName } of units) {\n\t\tif (errors >= threshold) {\n\t\t\tlogger.error(\n\t\t\t\t\"Subgraph error threshold reached, skipping remaining events\",\n\t\t\t\t{\n\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\terrors,\n\t\t\t\t\tthreshold,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n\t\t}\n\n\t\tconst handler =\n\t\t\tsubgraph.handlers[sourceName] ?? subgraph.handlers[\"*\"] ?? null;\n\t\tif (!handler) {\n\t\t\tlogger.warn(\"No handler found for source\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tctx.setTx({\n\t\t\ttxId: tx.tx_id,\n\t\t\tsender: tx.sender,\n\t\t\ttype: tx.type,\n\t\t\tstatus: tx.status,\n\t\t\tcontractId: tx.contract_id ?? null,\n\t\t\tfunctionName: tx.function_name ?? null,\n\t\t});\n\n\t\tconst filter = filterLookup.get(sourceName);\n\n\t\t// Checkpoint the ops queue: a handler that throws mid-way must\n\t\t// contribute nothing — a partial flush (e.g. a debit without its\n\t\t// credit) silently corrupts accumulator tables (fix-f040 B6).\n\t\tconst checkpoint = ctx.opsCheckpoint();\n\t\ttry {\n\t\t\tlet payload: Record<string, unknown>;\n\t\t\tif (event === null) {\n\t\t\t\t// Tx-level match (contract_call / contract_deploy)\n\t\t\t\tpayload = filter\n\t\t\t\t\t? buildEventPayload(filter, tx, null)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttx: {\n\t\t\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t} else if (filter) {\n\t\t\t\tpayload = buildEventPayload(filter, tx, event);\n\t\t\t} else {\n\t\t\t\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\t\t\t\tpayload = {\n\t\t\t\t\t...decoded,\n\t\t\t\t\t_eventId: event.id,\n\t\t\t\t\t_eventType: event.type,\n\t\t\t\t\t_eventIndex: event.event_index,\n\t\t\t\t\ttx: {\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Post-decode topic filter for print_event — source-matcher defers this\n\t\t\t// because data.value is raw hex at match time; apply it now after decode.\n\t\t\tif (\n\t\t\t\tevent !== null &&\n\t\t\t\tfilter?.type === \"print_event\" &&\n\t\t\t\tfilter.topic &&\n\t\t\t\tpayload.topic !== filter.topic\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Declared `prints` is the developer's stated payload shape, so a\n\t\t\t// mismatch is a real defect (a contract upgrade, or a declaration\n\t\t\t// that never matched — the bns-names class, where every event\n\t\t\t// decoded to null for an entire deploy). Skip + log rather than\n\t\t\t// write nulls; never throw, which would wedge the block.\n\t\t\tif (event !== null && filter?.type === \"print_event\" && filter.prints) {\n\t\t\t\tconst printPayload = payload as {\n\t\t\t\t\ttopic?: string;\n\t\t\t\t\tdata?: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst verdict = validatePrintPayload(\n\t\t\t\t\tfilter.prints,\n\t\t\t\t\tprintPayload.topic ?? \"\",\n\t\t\t\t\tprintPayload.data ?? {},\n\t\t\t\t);\n\t\t\t\tif (!verdict.ok) {\n\t\t\t\t\tskipped++;\n\t\t\t\t\tlogger.warn(\"Print payload does not match declared prints schema\", {\n\t\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\ttopic: printPayload.topic,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: verdict.reason,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait handler(payload, ctx);\n\t\t\tprocessed++;\n\t\t} catch (err) {\n\t\t\tctx.rollbackTo(checkpoint);\n\t\t\terrors++;\n\t\t\tlogger.error(\"Subgraph handler error\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t...(event !== null ? { eventId: event.id, eventType: event.type } : {}),\n\t\t\t\terror: getErrorMessage(err),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n}\n",
7
+ "import type { ColumnType, PrintField } from \"../types.ts\";\n\n/**\n * Runtime validation of a decoded print payload against a source's declared\n * `prints` schema.\n *\n * Declaring `prints` is the opt-in that makes strictness safe: the developer\n * has stated the shape, so a mismatch is a real defect (a contract upgrade,\n * or a hand-written declaration that never matched — the bns-names class of\n * bug, where a handler read flat `data.name` while BNS-V2 emitted a nested\n * tuple, and every event silently decoded to null for a whole deploy).\n *\n * Failure mode is SKIP + LOG, never throw: throwing would fail the block, and\n * a poisoned block that can never advance is incompatible with the\n * checkpoint model. One bad event is dropped and counted; the rest of the\n * block commits.\n */\n\nconst COLUMN_TYPES = new Set<string>([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\nfunction isColumnType(field: PrintField): field is ColumnType {\n\treturn typeof field === \"string\" && COLUMN_TYPES.has(field);\n}\n\n/** Does a decoded value match one declared field? */\nfunction matchesField(field: PrintField, value: unknown): boolean {\n\tif (isColumnType(field)) {\n\t\tswitch (field) {\n\t\t\tcase \"uint\":\n\t\t\tcase \"int\":\n\t\t\t\treturn typeof value === \"bigint\" || typeof value === \"number\";\n\t\t\tcase \"boolean\":\n\t\t\t\treturn typeof value === \"boolean\";\n\t\t\tcase \"text\":\n\t\t\tcase \"principal\":\n\t\t\tcase \"timestamp\":\n\t\t\t\t// Buffers decode to strings; principals too. Accept any scalar the\n\t\t\t\t// decoder can render, but reject objects/arrays.\n\t\t\t\treturn (\n\t\t\t\t\ttypeof value === \"string\" ||\n\t\t\t\t\ttypeof value === \"number\" ||\n\t\t\t\t\ttypeof value === \"bigint\"\n\t\t\t\t);\n\t\t\tcase \"jsonb\":\n\t\t\t\t// Deliberately permissive: `jsonb` is the \"shape unknown\" escape.\n\t\t\t\treturn value !== undefined;\n\t\t}\n\t}\n\tif (typeof field !== \"object\" || field === null) return false;\n\tif (\"optional\" in field) {\n\t\treturn (\n\t\t\tvalue === undefined || value === null || matchesField(field.type, value)\n\t\t);\n\t}\n\tif (\"tuple\" in field) {\n\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn matchesTopic(field.tuple, value as Record<string, unknown>).ok;\n\t}\n\tif (\"list\" in field) {\n\t\treturn (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.every((item) => matchesField(field.list, item))\n\t\t);\n\t}\n\treturn false;\n}\n\nexport type PrintValidationResult =\n\t| { ok: true }\n\t| { ok: false; reason: string };\n\n/** Validate a decoded payload object against one topic's declared fields. */\nexport function matchesTopic(\n\tdeclared: Record<string, PrintField>,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tfor (const [name, field] of Object.entries(declared)) {\n\t\tconst present = name in data;\n\t\tconst optional =\n\t\t\ttypeof field === \"object\" && field !== null && \"optional\" in field;\n\t\tif (!present) {\n\t\t\tif (optional) continue;\n\t\t\treturn { ok: false, reason: `missing declared field \"${name}\"` };\n\t\t}\n\t\tif (!matchesField(field, data[name])) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: `field \"${name}\" does not match its declared type (got ${describe(data[name])})`,\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction describe(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"array\";\n\treturn typeof value;\n}\n\n/**\n * Validate one decoded print event against a source's `prints` declaration.\n * Returns `{ ok: true }` when no declaration covers this topic (undeclared\n * topics are not the developer's stated contract, so they pass through).\n */\nexport function validatePrintPayload(\n\tprints: Record<string, Record<string, PrintField>> | undefined,\n\ttopic: string,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tif (!prints) return { ok: true };\n\tconst declared = prints[topic];\n\tif (!declared) return { ok: true };\n\treturn matchesTopic(declared, data);\n}\n"
7
8
  ],
8
- "mappings": ";;;;AAAA;AAMO,SAAS,kBAAkB,CAAC,KAAsB;AAAA,EACxD,IAAI;AAAA,IACH,MAAM,WAAW,IAAI,WAAW,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI;AAAA,IACvD,MAAM,KAAK,cAAc,QAAQ;AAAA,IACjC,OAAO,UAAU,EAAE;AAAA,IAClB,MAAM;AAAA,IACP,OAAO;AAAA;AAAA;AAQF,SAAS,eAAe,CAAC,MAAwB;AAAA,EACvD,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,IAAI,KAAK,KAAK,SAAS,IAAI;AAAA,IAC1E,OAAO,mBAAmB,IAAI;AAAA,EAC/B;AAAA,EAEA,IAAI,MAAM,QAAQ,IAAI,GAAG;AAAA,IACxB,OAAO,KAAK,IAAI,eAAe;AAAA,EAChC;AAAA,EAEA,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM;AAAA,IAC9C,MAAM,UAAmC,CAAC;AAAA,IAC1C,YAAY,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;AAAA,MAChD,QAAQ,OAAO,gBAAgB,KAAK;AAAA,IACrC;AAAA,IACA,OAAO;AAAA,EACR;AAAA,EAEA,OAAO;AAAA;AAMD,SAAS,kBAAkB,CAAC,MAA2B;AAAA,EAC7D,OAAO,KAAK,IAAI,kBAAkB;AAAA;;;AC5CnC;AACA;AACA;AAAA;AAAA,mBAEC;AAAA;AAAA;AAaD,IAAM,0BAA0B;AAQhC,SAAS,SAA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G;AAAA,WACL,UAAU,OAAO,EAAE,SAAS,MAAM,IAAI,WAAW,MAAM,KAAK,IAAI,CAAC;AAAA,QACrE,OAAO,gBAAgB,GAAG;AAAA,MAC3B,CAAC;AAAA;AAAA,EAEH;AAAA,EAEA,OAAO,EAAE,WAAW,WAAY,UAAU,IAAI,EAAE,QAAQ,IAAI,CAAC,EAAG;AAAA;",
10
+ "debugId": "5FE61480B3DD60C064756E2164756E21",
10
11
  "names": []
11
12
  }
@@ -88,18 +88,45 @@ interface ContractDeployFilter {
88
88
  deployer?: string;
89
89
  contractName?: string;
90
90
  }
91
+ /**
92
+ * One declared field of a print payload.
93
+ *
94
+ * A bare {@link ColumnType} is a required scalar (`amount: "uint"`). The
95
+ * composite forms exist because real print payloads are not flat: BNS-V2
96
+ * emits `name` as a NESTED tuple, and a `prints` vocabulary that could only
97
+ * say `"jsonb"` is why a handler reading flat `data.name` type-checked,
98
+ * deployed, and then decoded to null on every event.
99
+ *
100
+ * - `{ type: F, optional: true }` — the KEY becomes optional on `event.data`
101
+ * (mirrors `always_present: false` in the inferred schema).
102
+ * - `{ tuple: { … } }` — a nested tuple, typed all the way down.
103
+ * - `{ list: F }` — a list of `F`.
104
+ */
105
+ type PrintField = ColumnType | {
106
+ type: PrintField
107
+ optional: true
108
+ } | {
109
+ tuple: Record<string, PrintField>
110
+ } | {
111
+ list: PrintField
112
+ };
91
113
  interface PrintEventFilter extends TraitScope {
92
114
  type: "print_event";
93
115
  contractId?: string;
94
116
  topic?: string;
95
117
  /**
96
- * Optional per-topic field schema. When declared, the handler's `event` is
97
- * a discriminated union keyed by `topic` and `event.data` is typed per topic
118
+ * Per-topic field schema. When declared, the handler's `event` is a
119
+ * discriminated union keyed by `topic` and `event.data` is typed per topic
98
120
  * (e.g. `{ "completed-deposit": { amount: "uint", sender: "principal" } }`).
99
- * Uses the same `ColumnType` vocab as `schema`; nested fields use `"jsonb"`.
100
- * Type-level only — not validated at runtime.
121
+ * Nested tuples, lists, and optional fields are expressible — see
122
+ * {@link PrintField}.
123
+ *
124
+ * Declaring `prints` also opts the source into RUNTIME validation: an
125
+ * event whose decoded payload does not match is skipped and logged rather
126
+ * than written as nulls (and the deploy-time field lint is promoted from
127
+ * a warning to an error).
101
128
  */
102
- prints?: Record<string, Record<string, ColumnType>>;
129
+ prints?: Record<string, Record<string, PrintField>>;
103
130
  }
104
131
  /** All subgraph filter types — discriminated on `type` */
105
132
  type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter;
@@ -124,18 +124,45 @@ interface ContractDeployFilter {
124
124
  deployer?: string;
125
125
  contractName?: string;
126
126
  }
127
+ /**
128
+ * One declared field of a print payload.
129
+ *
130
+ * A bare {@link ColumnType} is a required scalar (`amount: "uint"`). The
131
+ * composite forms exist because real print payloads are not flat: BNS-V2
132
+ * emits `name` as a NESTED tuple, and a `prints` vocabulary that could only
133
+ * say `"jsonb"` is why a handler reading flat `data.name` type-checked,
134
+ * deployed, and then decoded to null on every event.
135
+ *
136
+ * - `{ type: F, optional: true }` — the KEY becomes optional on `event.data`
137
+ * (mirrors `always_present: false` in the inferred schema).
138
+ * - `{ tuple: { … } }` — a nested tuple, typed all the way down.
139
+ * - `{ list: F }` — a list of `F`.
140
+ */
141
+ type PrintField = ColumnType | {
142
+ type: PrintField
143
+ optional: true
144
+ } | {
145
+ tuple: Record<string, PrintField>
146
+ } | {
147
+ list: PrintField
148
+ };
127
149
  interface PrintEventFilter extends TraitScope {
128
150
  type: "print_event";
129
151
  contractId?: string;
130
152
  topic?: string;
131
153
  /**
132
- * Optional per-topic field schema. When declared, the handler's `event` is
133
- * a discriminated union keyed by `topic` and `event.data` is typed per topic
154
+ * Per-topic field schema. When declared, the handler's `event` is a
155
+ * discriminated union keyed by `topic` and `event.data` is typed per topic
134
156
  * (e.g. `{ "completed-deposit": { amount: "uint", sender: "principal" } }`).
135
- * Uses the same `ColumnType` vocab as `schema`; nested fields use `"jsonb"`.
136
- * Type-level only — not validated at runtime.
157
+ * Nested tuples, lists, and optional fields are expressible — see
158
+ * {@link PrintField}.
159
+ *
160
+ * Declaring `prints` also opts the source into RUNTIME validation: an
161
+ * event whose decoded payload does not match is skipped and logged rather
162
+ * than written as nulls (and the deploy-time field lint is promoted from
163
+ * a warning to an error).
137
164
  */
138
- prints?: Record<string, Record<string, ColumnType>>;
165
+ prints?: Record<string, Record<string, PrintField>>;
139
166
  }
140
167
  /** All subgraph filter types — discriminated on `type` */
141
168
  type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter;
@@ -234,14 +261,34 @@ interface TableDiff {
234
261
  removedTables: string[];
235
262
  /** Per-table column diffs (only for tables present in both) */
236
263
  tables: Record<string, ColumnDiff>;
264
+ /** Per-table uniqueKeys / composite-index diffs (tables present in both) */
265
+ constraints: Record<string, ConstraintDiff>;
237
266
  }
238
267
  interface ColumnDiff {
239
268
  added: string[];
240
269
  removed: string[];
270
+ /** Data-shape changes (type/nullable/default) — breaking. */
241
271
  changed: string[];
272
+ /** Only the `indexed`/`search` flags differ — index DDL, never a rebuild. */
273
+ indexChanged: string[];
274
+ }
275
+ interface ConstraintDiff {
276
+ /** New uniqueKeys entries → `ALTER TABLE … ADD CONSTRAINT` (additive). */
277
+ addedUniqueKeys: string[][];
278
+ /** Removed uniqueKeys entries — breaking: handler upserts may target them. */
279
+ removedUniqueKeys: string[][];
280
+ /** New composite `indexes` entries → CREATE INDEX (additive). */
281
+ addedIndexes: string[][];
282
+ /** Removed composite `indexes` entries → DROP INDEX (additive). */
283
+ removedIndexes: string[][];
242
284
  }
243
285
  /**
244
286
  * Compare two multi-table subgraph schemas and return differences.
287
+ *
288
+ * Index-only changes (`indexed`/`search` flags, composite `indexes`) are
289
+ * reported separately from data-shape changes: an index never requires a
290
+ * rebuild, so it must never land in `changed`/breaking — flipping
291
+ * `indexed: true` on a populated column used to cost a full reindex.
245
292
  */
246
293
  declare function diffSchema(existing: SubgraphSchema, incoming: SubgraphSchema): TableDiff;
247
294
  interface DeployDiff {
@@ -249,6 +296,10 @@ interface DeployDiff {
249
296
  removedTables: string[];
250
297
  addedColumns: Record<string, string[]>;
251
298
  breakingChanges: string[];
299
+ /** Columns whose only change was the `indexed`/`search` flag (index DDL applied in place). */
300
+ indexChanges?: Record<string, string[]>;
301
+ /** uniqueKeys added in place via ALTER TABLE … ADD CONSTRAINT. */
302
+ addedUniqueKeys?: Record<string, string[][]>;
252
303
  }
253
304
  /**
254
305
  * Deploy a subgraph schema to the database.
@@ -278,5 +329,7 @@ declare function deploySchema(db: AnyDb, def: SubgraphDefinition, handlerPath: s
278
329
  subgraphId: string
279
330
  version: string
280
331
  diff?: DeployDiff
332
+ /** Non-fatal caveats the caller should surface (e.g. handler grafts at tip). */
333
+ warnings?: string[]
281
334
  }>;
282
335
  export { generateSubgraphSQL, diffSchema, deploySchema, TableDiff, TYPE_MAP, GeneratedSQL, ColumnDiff };