@secondlayer/subgraphs 7.0.1 → 7.0.3

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.
package/dist/types.d.ts CHANGED
@@ -15,6 +15,7 @@ import { AssetIdentifier } from "@secondlayer/stacks/filters";
15
15
  * first answer forever, so it is opt-in and never inferred.
16
16
  */
17
17
  type ChainReadCacheMode = "per-block" | "contract-constant";
18
+ /** Options for a contract read, such as cache mode. */
18
19
  type ChainReadOptions = {
19
20
  cache?: ChainReadCacheMode;
20
21
  };
@@ -24,6 +25,12 @@ type ChainReadOptions = {
24
25
  * one and handlers get full inference.
25
26
  */
26
27
  interface ErasedChainReadClient {
28
+ /**
29
+ * Reads a contract's read-only functions at the block being processed.
30
+ *
31
+ * Results are untyped here. Call it through `readContractAt` to get typed
32
+ * results from the contract's ABI.
33
+ */
27
34
  contract(contractId: string, abi: unknown, options?: ChainReadOptions): {
28
35
  read: Record<string, (args?: Record<string, unknown>) => Promise<unknown>>;
29
36
  };
@@ -55,7 +62,7 @@ interface SubgraphTable {
55
62
  /** Unique key constraints (each entry is an array of column names). Required for upsert. */
56
63
  uniqueKeys?: readonly (readonly string[])[];
57
64
  }
58
- /** Subgraph schema — maps table names to table definitions */
65
+ /** Maps table names to table definitions. */
59
66
  type SubgraphSchema = Record<string, SubgraphTable>;
60
67
  /** STX event filters */
61
68
  interface StxTransferFilter {
@@ -327,7 +334,7 @@ type UnpinnedPrintEventFilter = PrintEventFields & {
327
334
  * `prints`; trait and unpinned sources may omit it.
328
335
  */
329
336
  type PrintEventFilter = PinnedPrintEventFilter | TraitPrintEventFilter | UnpinnedPrintEventFilter;
330
- /** All subgraph filter types — discriminated on `type` */
337
+ /** A subgraph filter, discriminated on `type`. */
331
338
  type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter | NestedContractCallFilter | VarSetFilter | MapWriteFilter;
332
339
  /** Transaction metadata available in handlers */
333
340
  interface TxMeta {
@@ -16,6 +16,7 @@ import { AssetIdentifier } from "@secondlayer/stacks/filters";
16
16
  * first answer forever, so it is opt-in and never inferred.
17
17
  */
18
18
  type ChainReadCacheMode = "per-block" | "contract-constant";
19
+ /** Options for a contract read, such as cache mode. */
19
20
  type ChainReadOptions = {
20
21
  cache?: ChainReadCacheMode;
21
22
  };
@@ -25,6 +26,12 @@ type ChainReadOptions = {
25
26
  * one and handlers get full inference.
26
27
  */
27
28
  interface ErasedChainReadClient {
29
+ /**
30
+ * Reads a contract's read-only functions at the block being processed.
31
+ *
32
+ * Results are untyped here. Call it through `readContractAt` to get typed
33
+ * results from the contract's ABI.
34
+ */
28
35
  contract(contractId: string, abi: unknown, options?: ChainReadOptions): {
29
36
  read: Record<string, (args?: Record<string, unknown>) => Promise<unknown>>;
30
37
  };
@@ -56,7 +63,7 @@ interface SubgraphTable {
56
63
  /** Unique key constraints (each entry is an array of column names). Required for upsert. */
57
64
  uniqueKeys?: readonly (readonly string[])[];
58
65
  }
59
- /** Subgraph schema — maps table names to table definitions */
66
+ /** Maps table names to table definitions. */
60
67
  type SubgraphSchema = Record<string, SubgraphTable>;
61
68
  /** STX event filters */
62
69
  interface StxTransferFilter {
@@ -287,7 +294,7 @@ type UnpinnedPrintEventFilter = PrintEventFields & {
287
294
  * `prints`; trait and unpinned sources may omit it.
288
295
  */
289
296
  type PrintEventFilter = PinnedPrintEventFilter | TraitPrintEventFilter | UnpinnedPrintEventFilter;
290
- /** All subgraph filter types — discriminated on `type` */
297
+ /** A subgraph filter, discriminated on `type`. */
291
298
  type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter | NestedContractCallFilter | VarSetFilter | MapWriteFilter;
292
299
  /** Transaction metadata available in handlers */
293
300
  interface TxMeta {
@@ -395,14 +402,18 @@ declare const VALID_FILTER_TYPES: readonly ["stx_transfer", "stx_mint", "stx_bur
395
402
  declare const SubgraphFilterSchema: z.ZodType<SubgraphFilter>;
396
403
  declare const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition>;
397
404
  /**
398
- * Validates a subgraph definition, returning the parsed result or throwing on failure.
405
+ * Validates a subgraph definition and returns the parsed result.
406
+ *
407
+ * It throws when the definition is invalid.
399
408
  */
400
409
  declare function validateSubgraphDefinition(def: unknown): SubgraphDefinition;
401
410
  /**
402
- * Per-source-type field vocabulary, DERIVED from
403
- * {@link SubgraphFilterSchema}. Agent-facing surfaces (the MCP filters
404
- * reference) used to hand-maintain a parallel copy of this list; deriving it
405
- * means adding a field to a filter can never leave the documentation behind.
411
+ * Lists the fields each source filter type accepts.
412
+ *
413
+ * The list is derived from {@link SubgraphFilterSchema}. Agent-facing surfaces
414
+ * such as the MCP filters reference used to keep a parallel copy by hand;
415
+ * deriving it means adding a field to a filter can never leave the
416
+ * documentation behind.
406
417
  */
407
418
  declare function filterFieldsByType(): Array<{
408
419
  type: string;
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["src/validate.ts"],
4
4
  "sourcesContent": [
5
- "import { z } from \"zod\";\nimport type {\n\tColumnType,\n\tSubgraphColumn,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n\tSubgraphSchema,\n\tSubgraphTable,\n} from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63)\n\t.regex(\n\t\t/^[a-z][a-z0-9-]*$/,\n\t\t\"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n\t);\n\n/**\n * A safe SQL identifier (table or column name). Mirrors the runtime guard in\n * runtime/context.ts (validateColumnName) so the schema validator can never\n * accept a name the runtime would reject — and closes the deploy-time DDL\n * injection path in schema/generator.ts, which interpolates these names raw.\n */\nexport const SqlIdentifierSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63) // Postgres truncates identifiers > 63 bytes; reject rather than collide.\n\t.regex(\n\t\t/^[a-z_][a-z0-9_]*$/i,\n\t\t\"Must be a valid SQL identifier: start with a letter or underscore, then letters/digits/underscores only\",\n\t);\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\n/**\n * One declared print field: a bare column type, or a composite (optional,\n * nested tuple, list). Recursive — real print payloads nest, and a vocabulary\n * that could only say `\"jsonb\"` is what let a flat-field declaration pass\n * while every event decoded to null.\n */\nexport const PrintFieldSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tColumnTypeSchema,\n\t\tz.object({ type: PrintFieldSchema, optional: z.literal(true) }),\n\t\tz.object({ tuple: z.record(z.string(), PrintFieldSchema) }),\n\t\tz.object({ list: PrintFieldSchema }),\n\t]),\n);\n\n/**\n * A Clarity ABI type: a primitive name, or one of the composite shapes.\n * Recursive, so nested tuples/lists/optionals are checked all the way down.\n */\nconst AbiTypeSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tz.string(),\n\t\tz.object({ buff: z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-ascii\": z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-utf8\": z.object({ length: z.number() }) }),\n\t\tz.object({ optional: AbiTypeSchema }),\n\t\tz.object({\n\t\t\tlist: z.object({ type: AbiTypeSchema, length: z.number() }),\n\t\t}),\n\t\tz.object({\n\t\t\ttuple: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t}),\n\t\tz.object({\n\t\t\tresponse: z.object({ ok: AbiTypeSchema, error: AbiTypeSchema }),\n\t\t}),\n\t]),\n);\n\n/**\n * The canonical `AbiContract` shape, validated at deploy time.\n *\n * This used to be `z.record(z.string(), z.any())`, which accepted a raw\n * Hiro/Clarinet ABI (`read_only` access, `buffer` types, outputs wrapped as\n * `{ type: … }`) and let it through — the deploy succeeded and `event.input`\n * then mis-decoded at RUNTIME, per event, forever. Reject it here instead,\n * and name the fix: run it through `normalizeAbi` from\n * `@secondlayer/stacks/clarity`.\n */\nexport const AbiContractSchema: z.ZodType<unknown> = z.object({\n\tfunctions: z.array(\n\t\tz.object({\n\t\t\tname: z.string(),\n\t\t\taccess: z.enum([\"public\", \"read-only\", \"private\"], {\n\t\t\t\tmessage:\n\t\t\t\t\t\"ABI access must be public | read-only | private — a raw Hiro/Clarinet ABI uses `read_only`. Normalize it first: normalizeAbi() from @secondlayer/stacks/clarity.\",\n\t\t\t}),\n\t\t\targs: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t\t// Canonical shape is a bare AbiType; raw ABIs wrap it as `{ type: … }`.\n\t\t\toutputs: AbiTypeSchema,\n\t\t}),\n\t),\n\tmaps: z.array(z.unknown()).optional(),\n\tvariables: z.array(z.unknown()).optional(),\n\tfungible_tokens: z.array(z.unknown()).optional(),\n\tnon_fungible_tokens: z.array(z.unknown()).optional(),\n\timplemented_traits: z.array(z.unknown()).optional(),\n\tdefined_traits: z.array(z.unknown()).optional(),\n});\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n\ttype: ColumnTypeSchema,\n\tnullable: z.boolean().optional(),\n\tindexed: z.boolean().optional(),\n\tsearch: z.boolean().optional(),\n\tdefault: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n\tcolumns: z\n\t\t.record(SqlIdentifierSchema, SubgraphColumnSchema)\n\t\t.refine(\n\t\t\t(c) => Object.keys(c).length > 0,\n\t\t\t\"Table must have at least one column\",\n\t\t),\n\tindexes: z.array(z.array(SqlIdentifierSchema)).optional(),\n\tuniqueKeys: z.array(z.array(SqlIdentifierSchema)).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n\t.record(SqlIdentifierSchema, SubgraphTableSchema)\n\t.refine(\n\t\t(s) => Object.keys(s).length > 0,\n\t\t\"Schema must have at least one table\",\n\t) as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const VALID_FILTER_TYPES = [\n\t\"stx_transfer\",\n\t\"stx_mint\",\n\t\"stx_burn\",\n\t\"stx_lock\",\n\t\"ft_transfer\",\n\t\"ft_mint\",\n\t\"ft_burn\",\n\t\"nft_transfer\",\n\t\"nft_mint\",\n\t\"nft_burn\",\n\t\"contract_call\",\n\t\"contract_deploy\",\n\t\"print_event\",\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n] as const;\n\n/** A contract id, or a set of them (max 20, matching the Index API cap). */\nconst contractIdField = z.union([\n\tz.string(),\n\tz.array(z.string()).min(1).max(20),\n]);\n\n/** Fields shared by the trait-scopable filters. */\nconst traitScope = { trait: z.string().optional() };\n/** Dynamic address set discovered from another source's events. */\nconst factoryScope = {\n\tfactory: z\n\t\t.object({ from: z.string().min(1), field: z.string().min(1) })\n\t\t.strict()\n\t\t.optional(),\n};\nconst amountRange = {\n\tminAmount: z.bigint().optional(),\n\tmaxAmount: z.bigint().optional(),\n};\n\n/**\n * A REAL discriminated union — one member per source type, each `.strict()`\n * with only the fields that type actually supports.\n *\n * It used to be one flat object with every field optional, so\n * `{ type: \"contract_deploy\", assetIdentifier: \"SP…\", minAmount: 1n }`\n * validated clean at deploy and then matched nothing, forever. The runtime\n * union already knew better; only the validator didn't.\n */\nconst SubgraphFilterUnion = z.discriminatedUnion(\"type\", [\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_transfer\"),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...amountRange,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_mint\"),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_burn\"),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_lock\"),\n\t\t\tlockedAddress: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_call\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tfunctionName: z.string().optional(),\n\t\t\tcaller: z.string().optional(),\n\t\t\tabi: AbiContractSchema.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_deploy\"),\n\t\t\tdeployer: z.string().optional(),\n\t\t\tcontractName: z.string().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"print_event\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\ttopic: z.string().optional(),\n\t\t\tprints: z\n\t\t\t\t.record(z.string(), z.record(z.string(), PrintFieldSchema))\n\t\t\t\t.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nested_contract_call\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tfunctionName: z.string().optional(),\n\t\t\tcaller: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"var_set\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tvarName: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_set\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_insert\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_delete\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n]);\n\n/**\n * `trait` and `contractId` compose rather than conflict: the matcher ANDs\n * them, so the pair means \"contracts conforming to this trait, narrowed to\n * these ids\". (The Index READ API refuses the combination because its query\n * planner picks one index path — that's an API constraint, not a semantic\n * one, and subgraph sources are not bound by it.)\n */\nexport const SubgraphFilterSchema: z.ZodType<SubgraphFilter> =\n\tSubgraphFilterUnion as unknown as z.ZodType<SubgraphFilter>;\n\n/** Pinned contractId: a non-empty string or a non-empty array of ids. */\nfunction hasPinnedContractId(\n\tcontractId: string | readonly string[] | undefined,\n): boolean {\n\tif (typeof contractId === \"string\") return contractId.length > 0;\n\tif (Array.isArray(contractId)) return contractId.length > 0;\n\treturn false;\n}\n\n/**\n * Deploy gates beyond the per-filter union: pinned print_event needs a\n * non-empty `prints` map, contract_call+functionName needs `abi`, and every\n * source needs a handler of the same name.\n */\nfunction refineDeployGates(\n\tdef: {\n\t\tsources: Record<string, SubgraphFilter>;\n\t\thandlers: Record<string, unknown>;\n\t\tschema: SubgraphSchema;\n\t},\n\tctx: z.RefinementCtx,\n): void {\n\tfor (const [name, filter] of Object.entries(def.sources)) {\n\t\tif (filter.type === \"print_event\") {\n\t\t\t// Trait / unpinned (no contractId) may omit prints — no single schema.\n\t\t\tconst pinned = hasPinnedContractId(filter.contractId) && !filter.trait;\n\t\t\tif (pinned) {\n\t\t\t\tconst prints = filter.prints;\n\t\t\t\tif (\n\t\t\t\t\tprints === undefined ||\n\t\t\t\t\ttypeof prints !== \"object\" ||\n\t\t\t\t\tObject.keys(prints).length === 0\n\t\t\t\t) {\n\t\t\t\t\tctx.addIssue({\n\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\tpath: [\"sources\", name, \"prints\"],\n\t\t\t\t\t\tmessage: `print_event source \"${name}\" has no prints map — field names would be untyped and empty tables would typecheck. Declare prints from index_print_schema / create --from-contract.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (filter.type === \"contract_call\" && filter.functionName !== undefined) {\n\t\t\tif (filter.abi === undefined) {\n\t\t\t\tctx.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"sources\", name, \"abi\"],\n\t\t\t\t\tmessage: `contract_call source \"${name}\" has functionName but no abi. \\`secondlayer subgraphs deploy\\` fills it in from the deployed contract; otherwise pass abi (normalizeAbi() from @secondlayer/stacks/clarity).`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const name of Object.keys(def.sources)) {\n\t\tif (def.handlers[name] == null) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"handlers\", name],\n\t\t\t\tmessage: `source \"${name}\" has no handler. Add handlers.${name}, or its events are skipped and the table stays empty.`,\n\t\t\t});\n\t\t}\n\t}\n}\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z\n\t.object({\n\t\tname: SubgraphNameSchema,\n\t\tdescription: z.string().optional(),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\t// 'concurrent' = tip-first deploy: go live at tip immediately, fill\n\t\t// history via a background backfill. Only safe for order-tolerant\n\t\t// handlers (commutative or insert-only writes).\n\t\tbackfillMode: z.enum([\"blocking\", \"concurrent\"]).optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), SubgraphFilterSchema)\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: SubgraphSchemaSchema,\n\t\thandlers: z.record(z.string(), z.any()),\n\t})\n\t.superRefine((def, ctx) => {\n\t\trefineDeployGates(\n\t\t\tdef as {\n\t\t\t\tsources: Record<string, SubgraphFilter>;\n\t\t\t\thandlers: Record<string, unknown>;\n\t\t\t\tschema: SubgraphSchema;\n\t\t\t},\n\t\t\tctx,\n\t\t);\n\t}) as unknown as z.ZodType<SubgraphDefinition>;\n\n/**\n * Validates a subgraph definition, returning the parsed result or throwing on failure.\n */\nexport function validateSubgraphDefinition(def: unknown): SubgraphDefinition {\n\treturn SubgraphDefinitionSchema.parse(def);\n}\n\n/**\n * Per-source-type field vocabulary, DERIVED from\n * {@link SubgraphFilterSchema}. Agent-facing surfaces (the MCP filters\n * reference) used to hand-maintain a parallel copy of this list; deriving it\n * means adding a field to a filter can never leave the documentation behind.\n */\nexport function filterFieldsByType(): Array<{\n\ttype: string;\n\tfields: string[];\n}> {\n\t// Read the UNION directly (SubgraphFilterSchema wraps it in superRefine).\n\t// biome-ignore lint/suspicious/noExplicitAny: reading zod's internal option shapes\n\tconst options = (SubgraphFilterUnion as any)?._def?.options ?? [];\n\tconst out: Array<{ type: string; fields: string[] }> = [];\n\tfor (const option of options) {\n\t\t// `.superRefine()` wraps the union, so unwrap one level when present.\n\t\tconst shape = option?.shape ?? option?._def?.shape;\n\t\tif (!shape) continue;\n\t\tconst literal =\n\t\t\tshape.type?._def?.values?.[0] ?? shape.type?._def?.value ?? undefined;\n\t\tif (typeof literal !== \"string\") continue;\n\t\tout.push({\n\t\t\ttype: literal,\n\t\t\tfields: Object.keys(shape).filter((k) => k !== \"type\"),\n\t\t});\n\t}\n\treturn out;\n}\n"
5
+ "import { z } from \"zod\";\nimport type {\n\tColumnType,\n\tSubgraphColumn,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n\tSubgraphSchema,\n\tSubgraphTable,\n} from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63)\n\t.regex(\n\t\t/^[a-z][a-z0-9-]*$/,\n\t\t\"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n\t);\n\n/**\n * A safe SQL identifier (table or column name). Mirrors the runtime guard in\n * runtime/context.ts (validateColumnName) so the schema validator can never\n * accept a name the runtime would reject — and closes the deploy-time DDL\n * injection path in schema/generator.ts, which interpolates these names raw.\n */\nexport const SqlIdentifierSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63) // Postgres truncates identifiers > 63 bytes; reject rather than collide.\n\t.regex(\n\t\t/^[a-z_][a-z0-9_]*$/i,\n\t\t\"Must be a valid SQL identifier: start with a letter or underscore, then letters/digits/underscores only\",\n\t);\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\n/**\n * One declared print field: a bare column type, or a composite (optional,\n * nested tuple, list). Recursive — real print payloads nest, and a vocabulary\n * that could only say `\"jsonb\"` is what let a flat-field declaration pass\n * while every event decoded to null.\n */\nexport const PrintFieldSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tColumnTypeSchema,\n\t\tz.object({ type: PrintFieldSchema, optional: z.literal(true) }),\n\t\tz.object({ tuple: z.record(z.string(), PrintFieldSchema) }),\n\t\tz.object({ list: PrintFieldSchema }),\n\t]),\n);\n\n/**\n * A Clarity ABI type: a primitive name, or one of the composite shapes.\n * Recursive, so nested tuples/lists/optionals are checked all the way down.\n */\nconst AbiTypeSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tz.string(),\n\t\tz.object({ buff: z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-ascii\": z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-utf8\": z.object({ length: z.number() }) }),\n\t\tz.object({ optional: AbiTypeSchema }),\n\t\tz.object({\n\t\t\tlist: z.object({ type: AbiTypeSchema, length: z.number() }),\n\t\t}),\n\t\tz.object({\n\t\t\ttuple: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t}),\n\t\tz.object({\n\t\t\tresponse: z.object({ ok: AbiTypeSchema, error: AbiTypeSchema }),\n\t\t}),\n\t]),\n);\n\n/**\n * The canonical `AbiContract` shape, validated at deploy time.\n *\n * This used to be `z.record(z.string(), z.any())`, which accepted a raw\n * Hiro/Clarinet ABI (`read_only` access, `buffer` types, outputs wrapped as\n * `{ type: … }`) and let it through — the deploy succeeded and `event.input`\n * then mis-decoded at RUNTIME, per event, forever. Reject it here instead,\n * and name the fix: run it through `normalizeAbi` from\n * `@secondlayer/stacks/clarity`.\n */\nexport const AbiContractSchema: z.ZodType<unknown> = z.object({\n\tfunctions: z.array(\n\t\tz.object({\n\t\t\tname: z.string(),\n\t\t\taccess: z.enum([\"public\", \"read-only\", \"private\"], {\n\t\t\t\tmessage:\n\t\t\t\t\t\"ABI access must be public | read-only | private — a raw Hiro/Clarinet ABI uses `read_only`. Normalize it first: normalizeAbi() from @secondlayer/stacks/clarity.\",\n\t\t\t}),\n\t\t\targs: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t\t// Canonical shape is a bare AbiType; raw ABIs wrap it as `{ type: … }`.\n\t\t\toutputs: AbiTypeSchema,\n\t\t}),\n\t),\n\tmaps: z.array(z.unknown()).optional(),\n\tvariables: z.array(z.unknown()).optional(),\n\tfungible_tokens: z.array(z.unknown()).optional(),\n\tnon_fungible_tokens: z.array(z.unknown()).optional(),\n\timplemented_traits: z.array(z.unknown()).optional(),\n\tdefined_traits: z.array(z.unknown()).optional(),\n});\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n\ttype: ColumnTypeSchema,\n\tnullable: z.boolean().optional(),\n\tindexed: z.boolean().optional(),\n\tsearch: z.boolean().optional(),\n\tdefault: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n\tcolumns: z\n\t\t.record(SqlIdentifierSchema, SubgraphColumnSchema)\n\t\t.refine(\n\t\t\t(c) => Object.keys(c).length > 0,\n\t\t\t\"Table must have at least one column\",\n\t\t),\n\tindexes: z.array(z.array(SqlIdentifierSchema)).optional(),\n\tuniqueKeys: z.array(z.array(SqlIdentifierSchema)).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n\t.record(SqlIdentifierSchema, SubgraphTableSchema)\n\t.refine(\n\t\t(s) => Object.keys(s).length > 0,\n\t\t\"Schema must have at least one table\",\n\t) as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const VALID_FILTER_TYPES = [\n\t\"stx_transfer\",\n\t\"stx_mint\",\n\t\"stx_burn\",\n\t\"stx_lock\",\n\t\"ft_transfer\",\n\t\"ft_mint\",\n\t\"ft_burn\",\n\t\"nft_transfer\",\n\t\"nft_mint\",\n\t\"nft_burn\",\n\t\"contract_call\",\n\t\"contract_deploy\",\n\t\"print_event\",\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n] as const;\n\n/** A contract id, or a set of them (max 20, matching the Index API cap). */\nconst contractIdField = z.union([\n\tz.string(),\n\tz.array(z.string()).min(1).max(20),\n]);\n\n/** Fields shared by the trait-scopable filters. */\nconst traitScope = { trait: z.string().optional() };\n/** Dynamic address set discovered from another source's events. */\nconst factoryScope = {\n\tfactory: z\n\t\t.object({ from: z.string().min(1), field: z.string().min(1) })\n\t\t.strict()\n\t\t.optional(),\n};\nconst amountRange = {\n\tminAmount: z.bigint().optional(),\n\tmaxAmount: z.bigint().optional(),\n};\n\n/**\n * A REAL discriminated union — one member per source type, each `.strict()`\n * with only the fields that type actually supports.\n *\n * It used to be one flat object with every field optional, so\n * `{ type: \"contract_deploy\", assetIdentifier: \"SP…\", minAmount: 1n }`\n * validated clean at deploy and then matched nothing, forever. The runtime\n * union already knew better; only the validator didn't.\n */\nconst SubgraphFilterUnion = z.discriminatedUnion(\"type\", [\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_transfer\"),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...amountRange,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_mint\"),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_burn\"),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_lock\"),\n\t\t\tlockedAddress: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_call\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tfunctionName: z.string().optional(),\n\t\t\tcaller: z.string().optional(),\n\t\t\tabi: AbiContractSchema.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_deploy\"),\n\t\t\tdeployer: z.string().optional(),\n\t\t\tcontractName: z.string().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"print_event\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\ttopic: z.string().optional(),\n\t\t\tprints: z\n\t\t\t\t.record(z.string(), z.record(z.string(), PrintFieldSchema))\n\t\t\t\t.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nested_contract_call\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tfunctionName: z.string().optional(),\n\t\t\tcaller: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"var_set\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tvarName: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_set\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_insert\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_delete\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n]);\n\n/**\n * `trait` and `contractId` compose rather than conflict: the matcher ANDs\n * them, so the pair means \"contracts conforming to this trait, narrowed to\n * these ids\". (The Index READ API refuses the combination because its query\n * planner picks one index path — that's an API constraint, not a semantic\n * one, and subgraph sources are not bound by it.)\n */\nexport const SubgraphFilterSchema: z.ZodType<SubgraphFilter> =\n\tSubgraphFilterUnion as unknown as z.ZodType<SubgraphFilter>;\n\n/** Pinned contractId: a non-empty string or a non-empty array of ids. */\nfunction hasPinnedContractId(\n\tcontractId: string | readonly string[] | undefined,\n): boolean {\n\tif (typeof contractId === \"string\") return contractId.length > 0;\n\tif (Array.isArray(contractId)) return contractId.length > 0;\n\treturn false;\n}\n\n/**\n * Deploy gates beyond the per-filter union: pinned print_event needs a\n * non-empty `prints` map, contract_call+functionName needs `abi`, and every\n * source needs a handler of the same name.\n */\nfunction refineDeployGates(\n\tdef: {\n\t\tsources: Record<string, SubgraphFilter>;\n\t\thandlers: Record<string, unknown>;\n\t\tschema: SubgraphSchema;\n\t},\n\tctx: z.RefinementCtx,\n): void {\n\tfor (const [name, filter] of Object.entries(def.sources)) {\n\t\tif (filter.type === \"print_event\") {\n\t\t\t// Trait / unpinned (no contractId) may omit prints — no single schema.\n\t\t\tconst pinned = hasPinnedContractId(filter.contractId) && !filter.trait;\n\t\t\tif (pinned) {\n\t\t\t\tconst prints = filter.prints;\n\t\t\t\tif (\n\t\t\t\t\tprints === undefined ||\n\t\t\t\t\ttypeof prints !== \"object\" ||\n\t\t\t\t\tObject.keys(prints).length === 0\n\t\t\t\t) {\n\t\t\t\t\tctx.addIssue({\n\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\tpath: [\"sources\", name, \"prints\"],\n\t\t\t\t\t\tmessage: `print_event source \"${name}\" has no prints map — field names would be untyped and empty tables would typecheck. Declare prints from index_print_schema / create --from-contract.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (filter.type === \"contract_call\" && filter.functionName !== undefined) {\n\t\t\tif (filter.abi === undefined) {\n\t\t\t\tctx.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"sources\", name, \"abi\"],\n\t\t\t\t\tmessage: `contract_call source \"${name}\" has functionName but no abi. \\`secondlayer subgraphs deploy\\` fills it in from the deployed contract; otherwise pass abi (normalizeAbi() from @secondlayer/stacks/clarity).`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const name of Object.keys(def.sources)) {\n\t\tif (def.handlers[name] == null) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"handlers\", name],\n\t\t\t\tmessage: `source \"${name}\" has no handler. Add handlers.${name}, or its events are skipped and the table stays empty.`,\n\t\t\t});\n\t\t}\n\t}\n}\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z\n\t.object({\n\t\tname: SubgraphNameSchema,\n\t\tdescription: z.string().optional(),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\t// 'concurrent' = tip-first deploy: go live at tip immediately, fill\n\t\t// history via a background backfill. Only safe for order-tolerant\n\t\t// handlers (commutative or insert-only writes).\n\t\tbackfillMode: z.enum([\"blocking\", \"concurrent\"]).optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), SubgraphFilterSchema)\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: SubgraphSchemaSchema,\n\t\thandlers: z.record(z.string(), z.any()),\n\t})\n\t.superRefine((def, ctx) => {\n\t\trefineDeployGates(\n\t\t\tdef as {\n\t\t\t\tsources: Record<string, SubgraphFilter>;\n\t\t\t\thandlers: Record<string, unknown>;\n\t\t\t\tschema: SubgraphSchema;\n\t\t\t},\n\t\t\tctx,\n\t\t);\n\t}) as unknown as z.ZodType<SubgraphDefinition>;\n\n/**\n * Validates a subgraph definition and returns the parsed result.\n *\n * It throws when the definition is invalid.\n */\nexport function validateSubgraphDefinition(def: unknown): SubgraphDefinition {\n\treturn SubgraphDefinitionSchema.parse(def);\n}\n\n/**\n * Lists the fields each source filter type accepts.\n *\n * The list is derived from {@link SubgraphFilterSchema}. Agent-facing surfaces\n * such as the MCP filters reference used to keep a parallel copy by hand;\n * deriving it means adding a field to a filter can never leave the\n * documentation behind.\n */\nexport function filterFieldsByType(): Array<{\n\ttype: string;\n\tfields: string[];\n}> {\n\t// Read the UNION directly (SubgraphFilterSchema wraps it in superRefine).\n\t// biome-ignore lint/suspicious/noExplicitAny: reading zod's internal option shapes\n\tconst options = (SubgraphFilterUnion as any)?._def?.options ?? [];\n\tconst out: Array<{ type: string; fields: string[] }> = [];\n\tfor (const option of options) {\n\t\t// `.superRefine()` wraps the union, so unwrap one level when present.\n\t\tconst shape = option?.shape ?? option?._def?.shape;\n\t\tif (!shape) continue;\n\t\tconst literal =\n\t\t\tshape.type?._def?.values?.[0] ?? shape.type?._def?.value ?? undefined;\n\t\tif (typeof literal !== \"string\") continue;\n\t\tout.push({\n\t\t\ttype: literal,\n\t\t\tfields: Object.keys(shape).filter((k) => k !== \"type\"),\n\t\t});\n\t}\n\treturn out;\n}\n"
6
6
  ],
7
- "mappings": ";AAAA;AAUO,IAAM,qBAAwC,EACnD,OAAO,EACP,IAAI,CAAC,EACL,IAAI,EA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,CAAC,EAAE,SAAS;AAAA,EAC1D,SAAS,EACP,OAAO,EAAE,OAAO,GAAG,oBAAoB,EACvC,OACA,CAAC,MAAM,OAAO,KAAK,CAAC,EAAE,SAAS,GAC/B,+BACD;AAAA,EACD,QAAQ;AAAA,EACR,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,IAAI,CAAC;AACvC,CAAC,EACA,YAAY,CAAC,KAAK,QAAQ;AAAA,EAC1B,kBACC,KAKA,GACD;AAAA,CACA;AAOK,SAAS,0BAA0B,CAAC,KAAkC;AAAA,EAC5E,OAAO,yBAAyB,MAAM,GAAG;AAAA;AAWnC,SAAS,kBAAkB,GAG/B;AAAA,EAGF,MAAM,UAAW,qBAA6B,MAAM,WAAW,CAAC;AAAA,EAChE,MAAM,MAAiD,CAAC;AAAA,EACxD,WAAW,UAAU,SAAS;AAAA,IAE7B,MAAM,QAAQ,QAAQ,SAAS,QAAQ,MAAM;AAAA,IAC7C,IAAI,CAAC;AAAA,MAAO;AAAA,IACZ,MAAM,UACL,MAAM,MAAM,MAAM,SAAS,MAAM,MAAM,MAAM,MAAM,SAAS;AAAA,IAC7D,IAAI,OAAO,YAAY;AAAA,MAAU;AAAA,IACjC,IAAI,KAAK;AAAA,MACR,MAAM;AAAA,MACN,QAAQ,OAAO,KAAK,KAAK,EAAE,OAAO,CAAC,MAAM,MAAM,MAAM;AAAA,IACtD,CAAC;AAAA,EACF;AAAA,EACA,OAAO;AAAA;",
8
8
  "debugId": "3596CDEC5E862E6064756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -16,6 +16,7 @@ import { AssetIdentifier } from "@secondlayer/stacks/filters";
16
16
  * first answer forever, so it is opt-in and never inferred.
17
17
  */
18
18
  type ChainReadCacheMode = "per-block" | "contract-constant";
19
+ /** Options for a contract read, such as cache mode. */
19
20
  type ChainReadOptions = {
20
21
  cache?: ChainReadCacheMode;
21
22
  };
@@ -25,6 +26,12 @@ type ChainReadOptions = {
25
26
  * one and handlers get full inference.
26
27
  */
27
28
  interface ErasedChainReadClient {
29
+ /**
30
+ * Reads a contract's read-only functions at the block being processed.
31
+ *
32
+ * Results are untyped here. Call it through `readContractAt` to get typed
33
+ * results from the contract's ABI.
34
+ */
28
35
  contract(contractId: string, abi: unknown, options?: ChainReadOptions): {
29
36
  read: Record<string, (args?: Record<string, unknown>) => Promise<unknown>>;
30
37
  };
@@ -56,7 +63,7 @@ interface SubgraphTable {
56
63
  /** Unique key constraints (each entry is an array of column names). Required for upsert. */
57
64
  uniqueKeys?: readonly (readonly string[])[];
58
65
  }
59
- /** Subgraph schema — maps table names to table definitions */
66
+ /** Maps table names to table definitions. */
60
67
  type SubgraphSchema = Record<string, SubgraphTable>;
61
68
  /** STX event filters */
62
69
  interface StxTransferFilter {
@@ -287,7 +294,7 @@ type UnpinnedPrintEventFilter = PrintEventFields & {
287
294
  * `prints`; trait and unpinned sources may omit it.
288
295
  */
289
296
  type PrintEventFilter = PinnedPrintEventFilter | TraitPrintEventFilter | UnpinnedPrintEventFilter;
290
- /** All subgraph filter types — discriminated on `type` */
297
+ /** A subgraph filter, discriminated on `type`. */
291
298
  type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter | NestedContractCallFilter | VarSetFilter | MapWriteFilter;
292
299
  /** Transaction metadata available in handlers */
293
300
  interface TxMeta {
@@ -393,6 +400,7 @@ interface HandlerFinding {
393
400
  /** 1-based. */
394
401
  column: number;
395
402
  }
403
+ /** Formats a handler finding as `file:line:column name: reason`. */
396
404
  declare function formatFinding(f: HandlerFinding): string;
397
405
  /**
398
406
  * Derive how far a subgraph's rows can be checked. Level = the highest any
@@ -403,10 +411,13 @@ declare function formatFinding(f: HandlerFinding): string;
403
411
  */
404
412
  declare function deriveVerification(def: Pick<SubgraphDefinition, "sources" | "backfillMode">, findings?: readonly HandlerFinding[]): SubgraphVerification;
405
413
  /**
406
- * True when the deploy must be refused: the sources are provable (`state`), so
407
- * the determinism contract is enforced, and the scan broke it.
414
+ * Tells whether a deploy must be refused for breaking determinism.
415
+ *
416
+ * It is refused when the sources are provable (`state`), so the determinism
417
+ * contract is enforced, and the scan broke it.
408
418
  */
409
419
  declare function isDeterminismViolation(v: SubgraphVerification): boolean;
420
+ /** What a pin is computed from: schema hash, handler code, network. */
410
421
  interface PinInput {
411
422
  /** Existing `schema_hash` (name + schema + sources). */
412
423
  schemaHash: string;
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
3
3
  // package.json
4
4
  var package_default = {
5
5
  name: "@secondlayer/subgraphs",
6
- version: "7.0.1",
6
+ version: "7.0.3",
7
7
  description: "Describe the Stacks data you want as one TypeScript file; it fills itself and survives reorgs.",
8
8
  license: "MIT",
9
9
  repository: {
@@ -59,12 +59,13 @@ var package_default = {
59
59
  dev: "bunup --watch",
60
60
  test: "bun test",
61
61
  typecheck: "tsc --noEmit",
62
+ openpkg: "bun scripts/sync-openpkg.ts",
62
63
  prepublishOnly: "bun run build"
63
64
  },
64
65
  dependencies: {
65
- "@secondlayer/shared": "^12.0.0",
66
- "@secondlayer/stacks": "^6.2.0",
67
- "@secondlayer/verify": "^0.5.0",
66
+ "@secondlayer/shared": "^12.1.2",
67
+ "@secondlayer/stacks": "^6.2.2",
68
+ "@secondlayer/verify": "^0.5.4",
68
69
  esbuild: "^0.28.2",
69
70
  kysely: "0.28.17",
70
71
  zod: "^4.3.6"
@@ -278,5 +279,5 @@ export {
278
279
  pinPreimage
279
280
  };
280
281
 
281
- //# debugId=F0C43A6F4785B8A464756E2164756E21
282
+ //# debugId=E95A79265B30E4E464756E2164756E21
282
283
  //# sourceMappingURL=verification.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["src/verification.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Verifiable subgraphs: the determinism contract, the derived level and the\n * pin. Pure (node:crypto only) so the bundler's deploy scan, the API and the\n * runtime realm all read the same rules.\n *\n * A subgraph is never configured as verifiable. Its level is derived from\n * its sources plus a scan of the bundled handler, and only a subgraph whose\n * every input is provable today (`state`: named state writes) has the contract\n * enforced. Everything else gets the same findings as advice.\n */\nimport { createHash } from \"node:crypto\";\nimport type { SubgraphVerification } from \"@secondlayer/shared/schemas/subgraphs\";\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport type { SubgraphDefinition, SubgraphFilter } from \"./types.ts\";\n\nexport type { SubgraphVerification };\n\n/** Runtime identity baked into every pin: matcher, decode and flush semantics. */\nexport const SUBGRAPHS_RUNTIME: string = `@secondlayer/subgraphs@${pkg.version}`;\n\n// ── Determinism contract ────────────────────────────────────────────────\n\n/**\n * Globals a handler may not touch, with the reason shown to the developer.\n * The deploy scan reports them; the realm replaces each with a getter that\n * throws `NondeterminismError`.\n */\nexport const FORBIDDEN_GLOBALS: Readonly<Record<string, string>> = {\n\tDate: \"wall-clock time differs per run\",\n\tperformance: \"timers differ per run\",\n\tprocess: \"host environment differs per run\",\n\tfetch: \"network reads are not chain inputs\",\n\tcrypto: \"randomness differs per run\",\n\tsetTimeout: \"scheduling order differs per run\",\n\tsetInterval: \"scheduling order differs per run\",\n\tsetImmediate: \"scheduling order differs per run\",\n\tclearTimeout: \"scheduling order differs per run\",\n\tclearInterval: \"scheduling order differs per run\",\n\tqueueMicrotask: \"scheduling order differs per run\",\n\tWeakRef: \"garbage collection timing differs per run\",\n\tFinalizationRegistry: \"garbage collection timing differs per run\",\n\tAtomics: \"shared memory is not single-threaded\",\n\tSharedArrayBuffer: \"shared memory is not single-threaded\",\n\tIntl: \"locale and time zone data differ per host\",\n\tTemporal: \"locale and time zone data differ per host\",\n\teval: \"generated code hides inputs from the scan\",\n\tWebAssembly: \"compiled code hides inputs from the scan\",\n\tShadowRealm: \"a nested realm escapes the allow-list\",\n\trequire: \"imports must be bundled into the handler\",\n};\n\n/**\n * Globals a handler may use: ECMAScript built-ins whose results are fully\n * specified, plus deterministic host encoders. `Math` is narrowed separately\n * ({@link ALLOWED_MATH}).\n */\nexport const ALLOWED_GLOBALS: readonly string[] = [\n\t\"undefined\",\n\t\"NaN\",\n\t\"Infinity\",\n\t\"globalThis\",\n\t\"isNaN\",\n\t\"isFinite\",\n\t\"parseInt\",\n\t\"parseFloat\",\n\t\"decodeURI\",\n\t\"decodeURIComponent\",\n\t\"encodeURI\",\n\t\"encodeURIComponent\",\n\t\"escape\",\n\t\"unescape\",\n\t\"Object\",\n\t\"Function\",\n\t\"Array\",\n\t\"Number\",\n\t\"Boolean\",\n\t\"String\",\n\t\"Symbol\",\n\t\"BigInt\",\n\t\"Math\",\n\t\"JSON\",\n\t\"Reflect\",\n\t\"Proxy\",\n\t\"Promise\",\n\t\"Map\",\n\t\"Set\",\n\t\"WeakMap\",\n\t\"WeakSet\",\n\t\"RegExp\",\n\t\"Iterator\",\n\t\"DisposableStack\",\n\t\"AsyncDisposableStack\",\n\t\"Error\",\n\t\"AggregateError\",\n\t\"SuppressedError\",\n\t\"EvalError\",\n\t\"RangeError\",\n\t\"ReferenceError\",\n\t\"SyntaxError\",\n\t\"TypeError\",\n\t\"URIError\",\n\t\"ArrayBuffer\",\n\t\"DataView\",\n\t\"Int8Array\",\n\t\"Uint8Array\",\n\t\"Uint8ClampedArray\",\n\t\"Int16Array\",\n\t\"Uint16Array\",\n\t\"Int32Array\",\n\t\"Uint32Array\",\n\t\"Float16Array\",\n\t\"Float32Array\",\n\t\"Float64Array\",\n\t\"BigInt64Array\",\n\t\"BigUint64Array\",\n\t\"TextEncoder\",\n\t\"TextDecoder\",\n\t\"atob\",\n\t\"btoa\",\n\t\"console\",\n];\n\n/** `Math` members whose results are exact on every engine. The rest\n * (`sin`, `pow`, `log`, …) are implementation-approximated. */\nexport const ALLOWED_MATH: readonly string[] = [\n\t\"abs\",\n\t\"min\",\n\t\"max\",\n\t\"floor\",\n\t\"ceil\",\n\t\"trunc\",\n\t\"sign\",\n\t\"round\",\n\t\"E\",\n\t\"LN10\",\n\t\"LN2\",\n\t\"LOG10E\",\n\t\"LOG2E\",\n\t\"PI\",\n\t\"SQRT1_2\",\n\t\"SQRT2\",\n];\n\n/** Methods whose output depends on the host's locale data. */\nexport const LOCALE_METHODS: readonly string[] = [\n\t\"toLocaleString\",\n\t\"toLocaleDateString\",\n\t\"toLocaleTimeString\",\n\t\"toLocaleUpperCase\",\n\t\"toLocaleLowerCase\",\n\t\"localeCompare\",\n];\n\n/**\n * One thing the deploy scan found in a bundled handler.\n *\n * - `nondeterministic`: breaks the determinism contract. Fails the deploy of\n * a state subgraph; advice for everything else.\n * - `needs-events`: deterministic, but reads something only re-execution proofs cover\n * (`ctx.client`). Raises the level instead of failing.\n */\nexport interface HandlerFinding {\n\tkind: \"nondeterministic\" | \"needs-events\";\n\t/** What was used, e.g. `Date`, `Math.random`, `import()`, `ctx.client`. */\n\tname: string;\n\treason: string;\n\t/** Original source file when a sourcemap was available, else the bundle. */\n\tfile: string;\n\t/** 1-based. */\n\tline: number;\n\t/** 1-based. */\n\tcolumn: number;\n}\n\nexport function formatFinding(f: HandlerFinding): string {\n\treturn `${f.file}:${f.line}:${f.column} ${f.name}: ${f.reason}`;\n}\n\n// ── Derived level ───────────────────────────────────────────────────────\n\n/**\n * Sources whose every field is a named state write: provable per block from\n * the header-backed witness plus `state_writes`. Not `map_insert`: storage\n * holds `(some v)` for an insert and a set alike, so telling them apart takes\n * re-execution (event proofs).\n */\nconst STATE_SOURCE_TYPES: ReadonlySet<string> = new Set([\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_delete\",\n]);\n\nconst LEVEL_RANK = { state: 0, events: 1, none: 2 } as const;\n\n/** Handler findings listed in `reasons`; the rest are counted. */\nconst MAX_LISTED_FINDINGS = 10;\n\n/**\n * Derive how far a subgraph's rows can be checked. Level = the highest any\n * source or handler read needs. `reasons` lists everything standing between\n * the subgraph and checkable rows; a `state` subgraph with any reason is\n * refused at deploy, so every stored `state` row has none. Never configured,\n * never a flag.\n */\nexport function deriveVerification(\n\tdef: Pick<SubgraphDefinition, \"sources\" | \"backfillMode\">,\n\tfindings: readonly HandlerFinding[] = [],\n): SubgraphVerification {\n\tlet level: keyof typeof LEVEL_RANK = \"state\";\n\tconst raise = (to: keyof typeof LEVEL_RANK) => {\n\t\tif (LEVEL_RANK[to] > LEVEL_RANK[level]) level = to;\n\t};\n\tconst reasons: string[] = [];\n\n\tfor (const [name, source] of Object.entries(def.sources ?? {})) {\n\t\tconst filter = source as SubgraphFilter & { trait?: string };\n\t\tif (filter.trait) {\n\t\t\traise(\"none\");\n\t\t\treasons.push(\n\t\t\t\t`source \"${name}\": trait scope needs a proven contract registry`,\n\t\t\t);\n\t\t} else if (filter.type === \"map_insert\") {\n\t\t\traise(\"events\");\n\t\t\treasons.push(\n\t\t\t\t`map_insert source \"${name}\": map_insert vs map_set needs event proofs`,\n\t\t\t);\n\t\t} else if (!STATE_SOURCE_TYPES.has(filter.type)) {\n\t\t\traise(\"events\");\n\t\t\treasons.push(`${filter.type} source \"${name}\" needs event proofs`);\n\t\t}\n\t}\n\tif (def.backfillMode === \"concurrent\") {\n\t\traise(\"none\");\n\t\treasons.push(\"backfillMode concurrent: tip-first order is not chain order\");\n\t}\n\tif (findings.some((f) => f.kind === \"needs-events\")) raise(\"events\");\n\t// A large bundled library can trip dozens of findings; list a few.\n\tfor (const f of findings.slice(0, MAX_LISTED_FINDINGS)) {\n\t\treasons.push(\n\t\t\tf.kind === \"needs-events\"\n\t\t\t\t? `${formatFinding(f)} (needs event proofs)`\n\t\t\t\t: formatFinding(f),\n\t\t);\n\t}\n\tif (findings.length > MAX_LISTED_FINDINGS) {\n\t\treasons.push(\n\t\t\t`…and ${findings.length - MAX_LISTED_FINDINGS} more handler findings`,\n\t\t);\n\t}\n\n\treturn {\n\t\tlevel,\n\t\treasons,\n\t\tunproven:\n\t\t\treasons.length === 0\n\t\t\t\t? [\n\t\t\t\t\t\t\"tx attribution of writes: event.tx, _tx_id (needs event proofs)\",\n\t\t\t\t\t\t\"intermediate writes within a block (needs event proofs)\",\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t};\n}\n\n/**\n * True when the deploy must be refused: the sources are provable (`state`), so\n * the determinism contract is enforced, and the scan broke it.\n */\nexport function isDeterminismViolation(v: SubgraphVerification): boolean {\n\treturn v.level === \"state\" && v.reasons.length > 0;\n}\n\n// ── Pin ─────────────────────────────────────────────────────────────────\n\nexport interface PinInput {\n\t/** Existing `schema_hash` (name + schema + sources). */\n\tschemaHash: string;\n\t/** Bundled ESM exactly as stored in `subgraphs.handler_code`. */\n\thandlerCode: string;\n\tstartBlock?: number | null;\n\tnetwork: string;\n\t/** Defaults to {@link SUBGRAPHS_RUNTIME}. */\n\truntime?: string;\n}\n\nfunction sha256(input: string): string {\n\treturn createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\n/** What a pin commits to, as stored in `pin_preimage`. */\nexport interface PinFields {\n\t/** sha256 of the bundled handler, hex. */\n\thandlerHash: string;\n\tnetwork: string;\n\truntime: string;\n\tschemaHash: string;\n\tstartBlock: number | null;\n}\n\n/**\n * The canonical JSON a pin is the sha256 of: fixed key order, primitives\n * only. Stored beside the pin so anyone can recompute it from the served\n * handler code.\n */\nexport function pinPreimage(input: PinInput): string {\n\tconst fields: PinFields = {\n\t\thandlerHash: sha256(input.handlerCode),\n\t\tnetwork: input.network,\n\t\truntime: input.runtime ?? SUBGRAPHS_RUNTIME,\n\t\tschemaHash: input.schemaHash,\n\t\tstartBlock: input.startBlock ?? null,\n\t};\n\treturn JSON.stringify(fields);\n}\n\n/**\n * Content hash over everything that shapes a subgraph's rows. Unlike\n * `schema_hash`, it changes with the handler, `startBlock` and runtime, so\n * two deploys with the same pin produce the same rows from the same chain.\n */\nexport function computePin(input: PinInput): string {\n\treturn sha256(pinPreimage(input));\n}\n"
5
+ "/**\n * Verifiable subgraphs: the determinism contract, the derived level and the\n * pin. Pure (node:crypto only) so the bundler's deploy scan, the API and the\n * runtime realm all read the same rules.\n *\n * A subgraph is never configured as verifiable. Its level is derived from\n * its sources plus a scan of the bundled handler, and only a subgraph whose\n * every input is provable today (`state`: named state writes) has the contract\n * enforced. Everything else gets the same findings as advice.\n */\nimport { createHash } from \"node:crypto\";\nimport type { SubgraphVerification } from \"@secondlayer/shared/schemas/subgraphs\";\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport type { SubgraphDefinition, SubgraphFilter } from \"./types.ts\";\n\nexport type { SubgraphVerification };\n\n/** Runtime identity baked into every pin: matcher, decode and flush semantics. */\nexport const SUBGRAPHS_RUNTIME: string = `@secondlayer/subgraphs@${pkg.version}`;\n\n// ── Determinism contract ────────────────────────────────────────────────\n\n/**\n * Globals a handler may not touch, with the reason shown to the developer.\n * The deploy scan reports them; the realm replaces each with a getter that\n * throws `NondeterminismError`.\n */\nexport const FORBIDDEN_GLOBALS: Readonly<Record<string, string>> = {\n\tDate: \"wall-clock time differs per run\",\n\tperformance: \"timers differ per run\",\n\tprocess: \"host environment differs per run\",\n\tfetch: \"network reads are not chain inputs\",\n\tcrypto: \"randomness differs per run\",\n\tsetTimeout: \"scheduling order differs per run\",\n\tsetInterval: \"scheduling order differs per run\",\n\tsetImmediate: \"scheduling order differs per run\",\n\tclearTimeout: \"scheduling order differs per run\",\n\tclearInterval: \"scheduling order differs per run\",\n\tqueueMicrotask: \"scheduling order differs per run\",\n\tWeakRef: \"garbage collection timing differs per run\",\n\tFinalizationRegistry: \"garbage collection timing differs per run\",\n\tAtomics: \"shared memory is not single-threaded\",\n\tSharedArrayBuffer: \"shared memory is not single-threaded\",\n\tIntl: \"locale and time zone data differ per host\",\n\tTemporal: \"locale and time zone data differ per host\",\n\teval: \"generated code hides inputs from the scan\",\n\tWebAssembly: \"compiled code hides inputs from the scan\",\n\tShadowRealm: \"a nested realm escapes the allow-list\",\n\trequire: \"imports must be bundled into the handler\",\n};\n\n/**\n * Globals a handler may use: ECMAScript built-ins whose results are fully\n * specified, plus deterministic host encoders. `Math` is narrowed separately\n * ({@link ALLOWED_MATH}).\n */\nexport const ALLOWED_GLOBALS: readonly string[] = [\n\t\"undefined\",\n\t\"NaN\",\n\t\"Infinity\",\n\t\"globalThis\",\n\t\"isNaN\",\n\t\"isFinite\",\n\t\"parseInt\",\n\t\"parseFloat\",\n\t\"decodeURI\",\n\t\"decodeURIComponent\",\n\t\"encodeURI\",\n\t\"encodeURIComponent\",\n\t\"escape\",\n\t\"unescape\",\n\t\"Object\",\n\t\"Function\",\n\t\"Array\",\n\t\"Number\",\n\t\"Boolean\",\n\t\"String\",\n\t\"Symbol\",\n\t\"BigInt\",\n\t\"Math\",\n\t\"JSON\",\n\t\"Reflect\",\n\t\"Proxy\",\n\t\"Promise\",\n\t\"Map\",\n\t\"Set\",\n\t\"WeakMap\",\n\t\"WeakSet\",\n\t\"RegExp\",\n\t\"Iterator\",\n\t\"DisposableStack\",\n\t\"AsyncDisposableStack\",\n\t\"Error\",\n\t\"AggregateError\",\n\t\"SuppressedError\",\n\t\"EvalError\",\n\t\"RangeError\",\n\t\"ReferenceError\",\n\t\"SyntaxError\",\n\t\"TypeError\",\n\t\"URIError\",\n\t\"ArrayBuffer\",\n\t\"DataView\",\n\t\"Int8Array\",\n\t\"Uint8Array\",\n\t\"Uint8ClampedArray\",\n\t\"Int16Array\",\n\t\"Uint16Array\",\n\t\"Int32Array\",\n\t\"Uint32Array\",\n\t\"Float16Array\",\n\t\"Float32Array\",\n\t\"Float64Array\",\n\t\"BigInt64Array\",\n\t\"BigUint64Array\",\n\t\"TextEncoder\",\n\t\"TextDecoder\",\n\t\"atob\",\n\t\"btoa\",\n\t\"console\",\n];\n\n/** `Math` members whose results are exact on every engine. The rest\n * (`sin`, `pow`, `log`, …) are implementation-approximated. */\nexport const ALLOWED_MATH: readonly string[] = [\n\t\"abs\",\n\t\"min\",\n\t\"max\",\n\t\"floor\",\n\t\"ceil\",\n\t\"trunc\",\n\t\"sign\",\n\t\"round\",\n\t\"E\",\n\t\"LN10\",\n\t\"LN2\",\n\t\"LOG10E\",\n\t\"LOG2E\",\n\t\"PI\",\n\t\"SQRT1_2\",\n\t\"SQRT2\",\n];\n\n/** Methods whose output depends on the host's locale data. */\nexport const LOCALE_METHODS: readonly string[] = [\n\t\"toLocaleString\",\n\t\"toLocaleDateString\",\n\t\"toLocaleTimeString\",\n\t\"toLocaleUpperCase\",\n\t\"toLocaleLowerCase\",\n\t\"localeCompare\",\n];\n\n/**\n * One thing the deploy scan found in a bundled handler.\n *\n * - `nondeterministic`: breaks the determinism contract. Fails the deploy of\n * a state subgraph; advice for everything else.\n * - `needs-events`: deterministic, but reads something only re-execution proofs cover\n * (`ctx.client`). Raises the level instead of failing.\n */\nexport interface HandlerFinding {\n\tkind: \"nondeterministic\" | \"needs-events\";\n\t/** What was used, e.g. `Date`, `Math.random`, `import()`, `ctx.client`. */\n\tname: string;\n\treason: string;\n\t/** Original source file when a sourcemap was available, else the bundle. */\n\tfile: string;\n\t/** 1-based. */\n\tline: number;\n\t/** 1-based. */\n\tcolumn: number;\n}\n\n/** Formats a handler finding as `file:line:column name: reason`. */\nexport function formatFinding(f: HandlerFinding): string {\n\treturn `${f.file}:${f.line}:${f.column} ${f.name}: ${f.reason}`;\n}\n\n// ── Derived level ───────────────────────────────────────────────────────\n\n/**\n * Sources whose every field is a named state write: provable per block from\n * the header-backed witness plus `state_writes`. Not `map_insert`: storage\n * holds `(some v)` for an insert and a set alike, so telling them apart takes\n * re-execution (event proofs).\n */\nconst STATE_SOURCE_TYPES: ReadonlySet<string> = new Set([\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_delete\",\n]);\n\nconst LEVEL_RANK = { state: 0, events: 1, none: 2 } as const;\n\n/** Handler findings listed in `reasons`; the rest are counted. */\nconst MAX_LISTED_FINDINGS = 10;\n\n/**\n * Derive how far a subgraph's rows can be checked. Level = the highest any\n * source or handler read needs. `reasons` lists everything standing between\n * the subgraph and checkable rows; a `state` subgraph with any reason is\n * refused at deploy, so every stored `state` row has none. Never configured,\n * never a flag.\n */\nexport function deriveVerification(\n\tdef: Pick<SubgraphDefinition, \"sources\" | \"backfillMode\">,\n\tfindings: readonly HandlerFinding[] = [],\n): SubgraphVerification {\n\tlet level: keyof typeof LEVEL_RANK = \"state\";\n\tconst raise = (to: keyof typeof LEVEL_RANK) => {\n\t\tif (LEVEL_RANK[to] > LEVEL_RANK[level]) level = to;\n\t};\n\tconst reasons: string[] = [];\n\n\tfor (const [name, source] of Object.entries(def.sources ?? {})) {\n\t\tconst filter = source as SubgraphFilter & { trait?: string };\n\t\tif (filter.trait) {\n\t\t\traise(\"none\");\n\t\t\treasons.push(\n\t\t\t\t`source \"${name}\": trait scope needs a proven contract registry`,\n\t\t\t);\n\t\t} else if (filter.type === \"map_insert\") {\n\t\t\traise(\"events\");\n\t\t\treasons.push(\n\t\t\t\t`map_insert source \"${name}\": map_insert vs map_set needs event proofs`,\n\t\t\t);\n\t\t} else if (!STATE_SOURCE_TYPES.has(filter.type)) {\n\t\t\traise(\"events\");\n\t\t\treasons.push(`${filter.type} source \"${name}\" needs event proofs`);\n\t\t}\n\t}\n\tif (def.backfillMode === \"concurrent\") {\n\t\traise(\"none\");\n\t\treasons.push(\"backfillMode concurrent: tip-first order is not chain order\");\n\t}\n\tif (findings.some((f) => f.kind === \"needs-events\")) raise(\"events\");\n\t// A large bundled library can trip dozens of findings; list a few.\n\tfor (const f of findings.slice(0, MAX_LISTED_FINDINGS)) {\n\t\treasons.push(\n\t\t\tf.kind === \"needs-events\"\n\t\t\t\t? `${formatFinding(f)} (needs event proofs)`\n\t\t\t\t: formatFinding(f),\n\t\t);\n\t}\n\tif (findings.length > MAX_LISTED_FINDINGS) {\n\t\treasons.push(\n\t\t\t`…and ${findings.length - MAX_LISTED_FINDINGS} more handler findings`,\n\t\t);\n\t}\n\n\treturn {\n\t\tlevel,\n\t\treasons,\n\t\tunproven:\n\t\t\treasons.length === 0\n\t\t\t\t? [\n\t\t\t\t\t\t\"tx attribution of writes: event.tx, _tx_id (needs event proofs)\",\n\t\t\t\t\t\t\"intermediate writes within a block (needs event proofs)\",\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t};\n}\n\n/**\n * Tells whether a deploy must be refused for breaking determinism.\n *\n * It is refused when the sources are provable (`state`), so the determinism\n * contract is enforced, and the scan broke it.\n */\nexport function isDeterminismViolation(v: SubgraphVerification): boolean {\n\treturn v.level === \"state\" && v.reasons.length > 0;\n}\n\n// ── Pin ─────────────────────────────────────────────────────────────────\n\n/** What a pin is computed from: schema hash, handler code, network. */\nexport interface PinInput {\n\t/** Existing `schema_hash` (name + schema + sources). */\n\tschemaHash: string;\n\t/** Bundled ESM exactly as stored in `subgraphs.handler_code`. */\n\thandlerCode: string;\n\tstartBlock?: number | null;\n\tnetwork: string;\n\t/** Defaults to {@link SUBGRAPHS_RUNTIME}. */\n\truntime?: string;\n}\n\nfunction sha256(input: string): string {\n\treturn createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\n/** What a pin commits to, as stored in `pin_preimage`. */\nexport interface PinFields {\n\t/** sha256 of the bundled handler, hex. */\n\thandlerHash: string;\n\tnetwork: string;\n\truntime: string;\n\tschemaHash: string;\n\tstartBlock: number | null;\n}\n\n/**\n * The canonical JSON a pin is the sha256 of: fixed key order, primitives\n * only. Stored beside the pin so anyone can recompute it from the served\n * handler code.\n */\nexport function pinPreimage(input: PinInput): string {\n\tconst fields: PinFields = {\n\t\thandlerHash: sha256(input.handlerCode),\n\t\tnetwork: input.network,\n\t\truntime: input.runtime ?? SUBGRAPHS_RUNTIME,\n\t\tschemaHash: input.schemaHash,\n\t\tstartBlock: input.startBlock ?? null,\n\t};\n\treturn JSON.stringify(fields);\n}\n\n/**\n * Content hash over everything that shapes a subgraph's rows. Unlike\n * `schema_hash`, it changes with the handler, `startBlock` and runtime, so\n * two deploys with the same pin produce the same rows from the same chain.\n */\nexport function computePin(input: PinInput): string {\n\treturn sha256(pinPreimage(input));\n}\n"
6
6
  ],
7
- "mappings": ";AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,QAAQ,KAAK,6DAA6D;AAAA,EAC3E;AAAA,EACA,IAAI,SAAS,KAAK,CAAC,MAAM,EAAE,SAAS,cAAc;AAAA,IAAG,MAAM,QAAQ;AAAA,EAEnE,WAAW,KAAK,SAAS,MAAM,GAAG,mBAAmB,GAAG;AAAA,IACvD,QAAQ,KACP,EAAE,SAAS,iBACR,GAAG,cAAc,CAAC,2BAClB,cAAc,CAAC,CACnB;AAAA,EACD;AAAA,EACA,IAAI,SAAS,SAAS,qBAAqB;AAAA,IAC1C,QAAQ,KACP,QAAQ,SAAS,SAAS,2CAC3B;AAAA,EACD;AAAA,EAEA,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA,UACC,QAAQ,WAAW,IAChB;AAAA,MACA;AAAA,MACA;AAAA,IACD,IACC,CAAC;AAAA,EACN;AAAA;AASM,SAAS,sBAAsB,CAAC,GAAkC;AAAA,EACxE,OAAO,EAAE,UAAU,WAAW,EAAE,QAAQ,SAAS;AAAA;AAiBlD,SAAS,MAAM,CAAC,OAAuB;AAAA,EACtC,OAAO,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK;AAAA;AAkBhD,SAAS,WAAW,CAAC,OAAyB;AAAA,EACpD,MAAM,SAAoB;AAAA,IACzB,aAAa,OAAO,MAAM,WAAW;AAAA,IACrC,SAAS,MAAM;AAAA,IACf,SAAS,MAAM,WAAW;AAAA,IAC1B,YAAY,MAAM;AAAA,IAClB,YAAY,MAAM,cAAc;AAAA,EACjC;AAAA,EACA,OAAO,KAAK,UAAU,MAAM;AAAA;AAQtB,SAAS,UAAU,CAAC,OAAyB;AAAA,EACnD,OAAO,OAAO,YAAY,KAAK,CAAC;AAAA;",
8
+ "debugId": "E95A79265B30E4E464756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -16,6 +16,7 @@ import { AssetIdentifier } from "@secondlayer/stacks/filters";
16
16
  * first answer forever, so it is opt-in and never inferred.
17
17
  */
18
18
  type ChainReadCacheMode = "per-block" | "contract-constant";
19
+ /** Options for a contract read, such as cache mode. */
19
20
  type ChainReadOptions = {
20
21
  cache?: ChainReadCacheMode;
21
22
  };
@@ -25,6 +26,12 @@ type ChainReadOptions = {
25
26
  * one and handlers get full inference.
26
27
  */
27
28
  interface ErasedChainReadClient {
29
+ /**
30
+ * Reads a contract's read-only functions at the block being processed.
31
+ *
32
+ * Results are untyped here. Call it through `readContractAt` to get typed
33
+ * results from the contract's ABI.
34
+ */
28
35
  contract(contractId: string, abi: unknown, options?: ChainReadOptions): {
29
36
  read: Record<string, (args?: Record<string, unknown>) => Promise<unknown>>;
30
37
  };
@@ -56,7 +63,7 @@ interface SubgraphTable {
56
63
  /** Unique key constraints (each entry is an array of column names). Required for upsert. */
57
64
  uniqueKeys?: readonly (readonly string[])[];
58
65
  }
59
- /** Subgraph schema — maps table names to table definitions */
66
+ /** Maps table names to table definitions. */
60
67
  type SubgraphSchema = Record<string, SubgraphTable>;
61
68
  /** STX event filters */
62
69
  interface StxTransferFilter {
@@ -287,7 +294,7 @@ type UnpinnedPrintEventFilter = PrintEventFields & {
287
294
  * `prints`; trait and unpinned sources may omit it.
288
295
  */
289
296
  type PrintEventFilter = PinnedPrintEventFilter | TraitPrintEventFilter | UnpinnedPrintEventFilter;
290
- /** All subgraph filter types — discriminated on `type` */
297
+ /** A subgraph filter, discriminated on `type`. */
291
298
  type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter | NestedContractCallFilter | VarSetFilter | MapWriteFilter;
292
299
  /** Transaction metadata available in handlers */
293
300
  interface TxMeta {
@@ -364,6 +371,7 @@ interface ReplayFailure {
364
371
  /** The source could not serve the input: unchecked, not disproven. */
365
372
  unavailable?: boolean;
366
373
  }
374
+ /** The outcome of a replay: pass or fail, blocks covered, failures. */
367
375
  interface ReplayResult {
368
376
  ok: boolean;
369
377
  /** Set when the range starts after startBlock and a handler read or merged earlier rows. */
@@ -385,6 +393,7 @@ interface ReplayResult {
385
393
  /** The first entry is the first broken link. */
386
394
  failures: ReplayFailure[];
387
395
  }
396
+ /** What to replay: proof source, handler bundle, and block range. */
388
397
  interface ReplayOptions {
389
398
  /** Needs `getStateWrites`: the names are what feed the handlers. */
390
399
  source: ProofSource;
@@ -401,12 +410,15 @@ interface ReplayOptions {
401
410
  /** Verify blocks 512 at a time: the top by one MARF jump, the rest by parent links. */
402
411
  declare const REPLAY_WINDOW = 512;
403
412
  /**
404
- * The contracts a state subgraph's writes come from, or an error when a
405
- * source does not fix one: completeness would need every contract's writes.
413
+ * Lists the contracts a state subgraph's writes come from.
414
+ *
415
+ * It returns an error when a source does not fix one, because completeness
416
+ * would then need every contract's writes.
406
417
  */
407
418
  declare function replayContracts(def: Pick<SubgraphDefinition, "sources">): string[] | {
408
419
  error: string;
409
420
  };
421
+ /** Whether a served pin matches the served bundle. */
410
422
  type PinCheck = {
411
423
  status: "ok";
412
424
  notes: string[];
@@ -419,9 +431,11 @@ type PinCheck = {
419
431
  notes: string[];
420
432
  };
421
433
  /**
422
- * The served pin against the served bundle: the preimage must hash to the
423
- * pin, and name this handler code, this schema and this startBlock. A runtime
424
- * other than this package's is a note: rows can still match.
434
+ * Checks a served pin against the served bundle.
435
+ *
436
+ * The preimage must hash to the pin, and name this handler code, this schema
437
+ * and this `startBlock`. A runtime other than this package's is only a note,
438
+ * since rows can still match.
425
439
  */
426
440
  declare function checkPin(served: {
427
441
  pin: string | null;
@@ -438,14 +452,20 @@ interface ReplayDeps {
438
452
  declare function replayBlocks(deps: ReplayDeps, opts: Omit<ReplayOptions, "source" | "checkpoint"> & {
439
453
  bitcoinCheckpoint?: number;
440
454
  }): Promise<ReplayResult>;
441
- /** Verify every block in `[from, to]` from the checkpoint and recompute the subgraph's tables. */
455
+ /**
456
+ * Verifies every block in a range and recomputes the subgraph's tables.
457
+ *
458
+ * The range is `[from, to]`, and blocks are verified from the checkpoint.
459
+ */
442
460
  declare function replaySubgraph(opts: ReplayOptions): Promise<ReplayResult>;
443
461
  /**
444
- * Evaluate a bundled handler (ESM, as stored in `handler_code`) inside a
445
- * fresh deterministic realm and return its definition with every handler
446
- * wrapped to receive the {@link deterministicContext} facade.
462
+ * Loads a bundled handler into a fresh deterministic realm.
463
+ *
464
+ * The bundle is ESM, as stored in `handler_code`. The returned definition has
465
+ * every handler wrapped to receive the {@link deterministicContext} facade.
447
466
  */
448
467
  declare function loadDeterministicDefinition(handlerCode: string): Promise<SubgraphDefinition>;
468
+ /** A table row as a plain column-to-value record. */
449
469
  type Row = Record<string, unknown>;
450
470
  interface TableComparison {
451
471
  table: string;
@@ -458,14 +478,17 @@ interface TableComparison {
458
478
  /** The same digest over the served rows in the window. */
459
479
  servedDigest: string;
460
480
  }
481
+ /** Replayed tables compared with served tables, and any mismatches. */
461
482
  interface RowComparison {
462
483
  failures: ReplayFailure[];
463
484
  tables: TableComparison[];
464
485
  }
465
486
  /**
466
- * Compare the replayed tables with the served ones over `[from, to]` on
467
- * `_block_height`. Keyed tables (first `uniqueKeys` tuple) compare row by
468
- * row; unkeyed tables as multisets.
487
+ * Compares replayed tables with the served ones over a block range.
488
+ *
489
+ * Rows are matched on `_block_height` within `[from, to]`. Keyed tables, by
490
+ * their first `uniqueKeys` tuple, compare row by row, and unkeyed tables
491
+ * compare as multisets.
469
492
  */
470
493
  declare function compareRows(schema: SubgraphSchema, replayed: {
471
494
  from: number;
@@ -475,7 +475,7 @@ import { createHash } from "node:crypto";
475
475
  // package.json
476
476
  var package_default = {
477
477
  name: "@secondlayer/subgraphs",
478
- version: "7.0.1",
478
+ version: "7.0.3",
479
479
  description: "Describe the Stacks data you want as one TypeScript file; it fills itself and survives reorgs.",
480
480
  license: "MIT",
481
481
  repository: {
@@ -531,12 +531,13 @@ var package_default = {
531
531
  dev: "bunup --watch",
532
532
  test: "bun test",
533
533
  typecheck: "tsc --noEmit",
534
+ openpkg: "bun scripts/sync-openpkg.ts",
534
535
  prepublishOnly: "bun run build"
535
536
  },
536
537
  dependencies: {
537
- "@secondlayer/shared": "^12.0.0",
538
- "@secondlayer/stacks": "^6.2.0",
539
- "@secondlayer/verify": "^0.5.0",
538
+ "@secondlayer/shared": "^12.1.2",
539
+ "@secondlayer/stacks": "^6.2.2",
540
+ "@secondlayer/verify": "^0.5.4",
540
541
  esbuild: "^0.28.2",
541
542
  kysely: "0.28.17",
542
543
  zod: "^4.3.6"
@@ -3345,5 +3346,5 @@ export {
3345
3346
  replaySubgraph
3346
3347
  };
3347
3348
 
3348
- //# debugId=80F9904AA45623E464756E2164756E21
3349
+ //# debugId=319CC0820BB5EC0864756E2164756E21
3349
3350
  //# sourceMappingURL=index.js.map