@secondlayer/subgraphs 0.5.2 → 0.5.4

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.
@@ -3,7 +3,7 @@
3
3
  "sources": ["../src/types.ts", "../src/validate.ts", "../src/runtime/context.ts", "../src/runtime/source-matcher.ts", "../src/runtime/clarity.ts", "../src/runtime/runner.ts", "../src/runtime/block-processor.ts", "../src/schema/utils.ts", "../src/runtime/stats.ts", "../src/runtime/reindex.ts", "../src/schema/generator.ts", "../src/define.ts", "../src/schema/deployer.ts"],
4
4
  "sourcesContent": [
5
5
  "/** Supported column types for subgraph schemas */\nexport type ColumnType =\n | \"text\"\n | \"uint\"\n | \"int\"\n | \"principal\"\n | \"boolean\"\n | \"timestamp\"\n | \"jsonb\";\n\n/** Column definition in a subgraph table */\nexport interface SubgraphColumn {\n type: ColumnType;\n nullable?: boolean;\n indexed?: boolean;\n search?: boolean;\n default?: string | number | boolean;\n}\n\n/** Table definition within a subgraph schema */\nexport interface SubgraphTable {\n columns: Record<string, SubgraphColumn>;\n /** Composite indexes (each entry is an array of column names) */\n indexes?: string[][];\n /** Unique key constraints (each entry is an array of column names). Required for upsert. */\n uniqueKeys?: string[][];\n}\n\n/** Subgraph schema — maps table names to table definitions */\nexport type SubgraphSchema = Record<string, SubgraphTable>;\n\n/** Source filter for what blockchain data this subgraph processes */\nexport interface SubgraphSource {\n /** Contract principal (e.g., SP000...::contract-name). Supports * wildcards. */\n contract?: string;\n /** Event name/topic to filter on */\n event?: string;\n /** Function name to filter on */\n function?: string;\n /** Transaction type filter (e.g., \"stx_transfer\", \"contract_call\") */\n type?: string;\n /** Minimum amount filter (for stx_transfer sources) */\n minAmount?: bigint;\n}\n\n/** Context passed to subgraph handlers during event processing */\nexport interface SubgraphContext {\n block: { height: number; hash: string; timestamp: number; burnBlockHeight: number };\n tx: { txId: string; sender: string; type: string; status: string };\n insert(table: string, row: Record<string, unknown>): void;\n update(table: string, where: Record<string, unknown>, set: Record<string, unknown>): void;\n upsert(table: string, key: Record<string, unknown>, row: Record<string, unknown>): void;\n delete(table: string, where: Record<string, unknown>): void;\n findOne(table: string, where: Record<string, unknown>): Promise<Record<string, unknown> | null>;\n findMany(table: string, where: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n}\n\n/** Handler function that processes events and writes to the subgraph */\nexport type SubgraphHandler = (\n event: Record<string, unknown>,\n ctx: SubgraphContext,\n) => Promise<void> | void;\n\n/**\n * Derive the source key used to look up handlers.\n * - { contract: \"SP123.market\", function: \"list\" } → \"SP123.market::list\"\n * - { contract: \"SP123.market\", event: \"sale\" } → \"SP123.market::sale\"\n * - { contract: \"SP123.market\" } → \"SP123.market\"\n * - { type: \"stx_transfer\" } → \"stx_transfer\"\n */\nexport function sourceKey(source: SubgraphSource): string {\n if (source.contract) {\n if (source.function) return `${source.contract}::${source.function}`;\n if (source.event) return `${source.contract}::${source.event}`;\n return source.contract;\n }\n if (source.type) return source.type;\n return \"*\";\n}\n\n/** Complete subgraph definition */\nexport interface SubgraphDefinition {\n /** Unique subgraph name (lowercase, alphanumeric + hyphens) */\n name: string;\n /** Semantic version */\n version?: string;\n /** Human description */\n description?: string;\n /** What blockchain data to process — one or more source filters */\n sources: SubgraphSource[];\n /** Tables in this subgraph */\n schema: SubgraphSchema;\n /** Keyed handler functions — keys match sourceKey() output, \"*\" is catch-all */\n handlers: Record<string, SubgraphHandler>;\n}\n",
6
- "import { z } from \"zod\";\nimport type { ColumnType, SubgraphColumn, SubgraphTable, SubgraphSource, SubgraphDefinition } from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n .string()\n .min(1)\n .max(63)\n .regex(\n /^[a-z][a-z0-9-]*$/,\n \"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n );\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n \"text\",\n \"uint\",\n \"int\",\n \"principal\",\n \"boolean\",\n \"timestamp\",\n \"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n type: ColumnTypeSchema,\n nullable: z.boolean().optional(),\n indexed: z.boolean().optional(),\n search: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n columns: z\n .record(z.string(), SubgraphColumnSchema)\n .refine((c) => Object.keys(c).length > 0, \"Table must have at least one column\"),\n indexes: z.array(z.array(z.string())).optional(),\n uniqueKeys: z.array(z.array(z.string())).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n .record(z.string(), SubgraphTableSchema)\n .refine((s) => Object.keys(s).length > 0, \"Schema must have at least one table\") as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const SubgraphSourceSchema: z.ZodType<SubgraphSource> = z\n .object({\n contract: z.string().optional(),\n event: z.string().optional(),\n function: z.string().optional(),\n type: z.string().optional(),\n minAmount: z.bigint().optional(),\n })\n .refine(\n (s) => s.contract || s.type,\n \"Source must specify at least 'contract' or 'type'\",\n ) as z.ZodType<SubgraphSource>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object({\n name: SubgraphNameSchema,\n version: z.string().optional(),\n description: z.string().optional(),\n sources: z.array(SubgraphSourceSchema).min(1, \"Must have at least one source\"),\n schema: SubgraphSchemaSchema,\n handlers: z.record(z.string(), z.function()),\n}) 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 return SubgraphDefinitionSchema.parse(def);\n}\n",
6
+ "import { z } from \"zod\";\nimport type { ColumnType, SubgraphColumn, SubgraphTable, SubgraphSource, SubgraphDefinition } from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n .string()\n .min(1)\n .max(63)\n .regex(\n /^[a-z][a-z0-9-]*$/,\n \"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n );\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n \"text\",\n \"uint\",\n \"int\",\n \"principal\",\n \"boolean\",\n \"timestamp\",\n \"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n type: ColumnTypeSchema,\n nullable: z.boolean().optional(),\n indexed: z.boolean().optional(),\n search: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n columns: z\n .record(z.string(), SubgraphColumnSchema)\n .refine((c) => Object.keys(c).length > 0, \"Table must have at least one column\"),\n indexes: z.array(z.array(z.string())).optional(),\n uniqueKeys: z.array(z.array(z.string())).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n .record(z.string(), SubgraphTableSchema)\n .refine((s) => Object.keys(s).length > 0, \"Schema must have at least one table\") as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const SubgraphSourceSchema: z.ZodType<SubgraphSource> = z\n .object({\n contract: z.string().optional(),\n event: z.string().optional(),\n function: z.string().optional(),\n type: z.string().optional(),\n minAmount: z.bigint().optional(),\n })\n .refine(\n (s) => s.contract || s.type,\n \"Source must specify at least 'contract' or 'type'\",\n ) as z.ZodType<SubgraphSource>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object({\n name: SubgraphNameSchema,\n version: z.string().optional(),\n description: z.string().optional(),\n sources: z.array(SubgraphSourceSchema).min(1, \"Must have at least one source\"),\n schema: SubgraphSchemaSchema,\n handlers: z.record(z.string(), z.function()),\n}) 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 return SubgraphDefinitionSchema.parse(def);\n}\n",
7
7
  "import { sql, type Kysely, type Transaction } from \"kysely\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphSchema } from \"../types.ts\";\n\ntype AnyDb = Kysely<Database> | Transaction<Database>;\n\ninterface WriteOp {\n kind: \"insert\" | \"update\" | \"delete\";\n table: string;\n data: Record<string, unknown>;\n /** For update: SET clause */\n set?: Record<string, unknown>;\n}\n\nexport interface BlockMeta {\n height: number;\n hash: string;\n timestamp: number;\n burnBlockHeight: number;\n}\n\nexport interface TxMeta {\n txId: string;\n sender: string;\n type: string;\n status: string;\n}\n\n/** Validate that a column name is safe for SQL identifiers */\nfunction validateColumnName(name: string): void {\n if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {\n throw new Error(`Invalid column name: ${name}`);\n }\n}\n\n/**\n * Runtime context passed to subgraph handlers.\n * Batches writes and flushes them atomically at the end of a block.\n * Reads execute immediately against the DB (pre-flush state).\n */\nexport class SubgraphContext {\n readonly block: BlockMeta;\n private _tx: TxMeta;\n private readonly db: AnyDb;\n private readonly pgSchemaName: string;\n private readonly subgraphSchema: SubgraphSchema;\n private readonly ops: WriteOp[] = [];\n\n constructor(\n db: AnyDb,\n pgSchemaName: string,\n subgraphSchema: SubgraphSchema,\n block: BlockMeta,\n tx: TxMeta,\n ) {\n this.db = db;\n this.pgSchemaName = pgSchemaName;\n this.subgraphSchema = subgraphSchema;\n this.block = block;\n this._tx = tx;\n }\n\n get tx(): TxMeta {\n return this._tx;\n }\n\n /** Update the current transaction context (used by runner between events) */\n setTx(tx: TxMeta): void {\n this._tx = tx;\n }\n\n // --- Write operations (batched) ---\n\n insert(table: string, row: Record<string, unknown>): void {\n this.validateTable(table);\n this.ops.push({ kind: \"insert\", table, data: row });\n }\n\n update(\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n ): void {\n this.validateTable(table);\n this.ops.push({ kind: \"update\", table, data: where, set });\n }\n\n upsert(\n table: string,\n key: Record<string, unknown>,\n row: Record<string, unknown>,\n ): void {\n this.validateTable(table);\n const tableDef = this.subgraphSchema[table]!;\n const keyColumns = Object.keys(key);\n\n // Check if there's a matching uniqueKeys constraint\n const hasUniqueConstraint = tableDef.uniqueKeys?.some(\n (uk) => uk.length === keyColumns.length && uk.every((c) => keyColumns.includes(c)),\n );\n\n if (hasUniqueConstraint) {\n // Use ON CONFLICT for proper upsert\n this.ops.push({ kind: \"insert\", table, data: { ...key, ...row, _upsert_keys: keyColumns } });\n } else {\n // Fallback: log warning, use findOne + conditional insert/update\n logger.warn(\"upsert called without matching uniqueKeys constraint, using fallback\", {\n table,\n keys: keyColumns,\n });\n this.ops.push({ kind: \"insert\", table, data: { ...key, ...row, _upsert_fallback_keys: keyColumns, _upsert_fallback_set: row } });\n }\n }\n\n delete(table: string, where: Record<string, unknown>): void {\n this.validateTable(table);\n this.ops.push({ kind: \"delete\", table, data: where });\n }\n\n // --- Read operations (immediate) ---\n\n async findOne(\n table: string,\n where: Record<string, unknown>,\n ): Promise<Record<string, unknown> | null> {\n this.validateTable(table);\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n const { clause } = buildWhereClause(where);\n const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause} LIMIT 1`;\n const { rows } = await sql.raw(query).execute(this.db);\n const row = (rows as Record<string, unknown>[])[0] ?? null;\n return row ? this.coerceRow(table, row) : null;\n }\n\n async findMany(\n table: string,\n where: Record<string, unknown>,\n ): Promise<Record<string, unknown>[]> {\n this.validateTable(table);\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n const { clause } = buildWhereClause(where);\n const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause}`;\n const { rows } = await sql.raw(query).execute(this.db);\n return (rows as Record<string, unknown>[]).map((r) => this.coerceRow(table, r));\n }\n\n /** Coerce string values from Postgres back to BigInt for uint/int columns */\n private coerceRow(table: string, row: Record<string, unknown>): Record<string, unknown> {\n const tableDef = this.subgraphSchema[table];\n if (!tableDef) return row;\n const result = { ...row };\n for (const [col, def] of Object.entries(tableDef.columns)) {\n if ((def.type === \"uint\" || def.type === \"int\") && typeof result[col] === \"string\") {\n result[col] = BigInt(result[col] as string);\n }\n }\n return result;\n }\n\n // --- Flush ---\n\n /** Number of pending write operations */\n get pendingOps(): number {\n return this.ops.length;\n }\n\n /**\n * Execute all batched writes in a single transaction.\n * Auto-populates _block_height, _tx_id, _created_at on inserts.\n */\n async flush(): Promise<number> {\n if (this.ops.length === 0) return 0;\n\n const opsToFlush = [...this.ops];\n this.ops.length = 0;\n\n const statements = this.buildStatements(opsToFlush);\n\n // If db is already a transaction, execute directly\n if (\"isTransaction\" in this.db) {\n for (const stmt of statements) {\n await sql.raw(stmt).execute(this.db);\n }\n } else {\n await (this.db as Kysely<Database>).transaction().execute(async (tx) => {\n for (const stmt of statements) {\n await sql.raw(stmt).execute(tx);\n }\n });\n }\n\n return opsToFlush.length;\n }\n\n /** Build SQL statements from write ops */\n private buildStatements(ops: WriteOp[]): string[] {\n const statements: string[] = [];\n\n for (const op of ops) {\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${op.table}\"`;\n\n switch (op.kind) {\n case \"insert\": {\n const upsertKeys = op.data._upsert_keys as string[] | undefined;\n const fallbackKeys = op.data._upsert_fallback_keys as string[] | undefined;\n const fallbackSet = op.data._upsert_fallback_set as Record<string, unknown> | undefined;\n const data = { ...op.data };\n delete data._upsert_keys;\n delete data._upsert_fallback_keys;\n delete data._upsert_fallback_set;\n\n // Auto-populate meta columns\n data._block_height = this.block.height;\n data._tx_id = this._tx.txId;\n data._created_at = \"NOW()\";\n\n const cols = Object.keys(data);\n cols.forEach(validateColumnName);\n const vals = cols.map((c) =>\n data[c] === \"NOW()\" ? \"NOW()\" : escapeLiteral(data[c]),\n );\n let stmt = `INSERT INTO ${qualifiedTable} (${cols.map((c) => `\"${c}\"`).join(\", \")}) VALUES (${vals.join(\", \")})`;\n\n if (upsertKeys && upsertKeys.length > 0) {\n const updateCols = cols.filter((c) => !upsertKeys.includes(c) && !c.startsWith(\"_\"));\n if (updateCols.length > 0) {\n const setClauses = updateCols.map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`);\n stmt += ` ON CONFLICT (${upsertKeys.map((k) => `\"${k}\"`).join(\", \")}) DO UPDATE SET ${setClauses.join(\", \")}`;\n } else {\n stmt += ` ON CONFLICT (${upsertKeys.map((k) => `\"${k}\"`).join(\", \")}) DO NOTHING`;\n }\n } else if (fallbackKeys && fallbackSet) {\n // Fallback upsert: use ON CONFLICT DO UPDATE but without a declared constraint\n // This will just be a plain INSERT — if it conflicts, PG will raise an error.\n // The caller was already warned. This is the best we can do without a unique constraint.\n }\n\n statements.push(stmt);\n break;\n }\n case \"update\": {\n const setEntries = Object.entries(op.set!);\n setEntries.forEach(([k]) => validateColumnName(k));\n const setClauses = setEntries.map(\n ([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`,\n );\n const { clause } = buildWhereClause(op.data);\n statements.push(\n `UPDATE ${qualifiedTable} SET ${setClauses.join(\", \")} WHERE ${clause}`,\n );\n break;\n }\n case \"delete\": {\n const { clause } = buildWhereClause(op.data);\n statements.push(`DELETE FROM ${qualifiedTable} WHERE ${clause}`);\n break;\n }\n }\n }\n\n return statements;\n }\n\n private validateTable(table: string): void {\n if (!this.subgraphSchema[table]) {\n throw new Error(\n `Table \"${table}\" not found in subgraph schema. Available: [${Object.keys(this.subgraphSchema).join(\", \")}]`,\n );\n }\n }\n}\n\n// --- Helpers ---\n\nfunction escapeLiteral(value: unknown): string {\n if (value === null || value === undefined) return \"NULL\";\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"object\") return `'${JSON.stringify(value).replace(/'/g, \"''\")}'::jsonb`;\n // String — escape single quotes\n return `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\nfunction buildWhereClause(where: Record<string, unknown>): {\n clause: string;\n values: unknown[];\n} {\n const entries = Object.entries(where);\n if (entries.length === 0) return { clause: \"TRUE\", values: [] };\n\n entries.forEach(([k]) => validateColumnName(k));\n const parts = entries.map(([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`);\n return { clause: parts.join(\" AND \"), values: [] };\n}\n",
8
8
  "import { type SubgraphSource, sourceKey } from \"../types.ts\";\n\nexport interface MatchedTx {\n tx: { tx_id: string; type: string; sender: string; status: string; contract_id?: string | null; function_name?: string | null };\n events: { id: string; tx_id: string; type: string; event_index: number; data: unknown }[];\n /** Which source produced this match — used for handler dispatch */\n sourceKey: string;\n}\n\n/**\n * Check if a string matches a pattern with `*` wildcard support.\n */\nfunction matchPattern(value: string, pattern: string): boolean {\n if (!pattern.includes(\"*\")) return value === pattern;\n const regex = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*/g, \".*\");\n return new RegExp(`^${regex}$`).test(value);\n}\n\ntype TxRecord = { tx_id: string; type: string; sender: string; status: string; contract_id?: string | null; function_name?: string | null };\ntype EventRecord = { id: string; tx_id: string; type: string; event_index: number; data: unknown };\n\n/**\n * Match a single source against transactions and events.\n */\nfunction matchSource(\n source: SubgraphSource,\n transactions: TxRecord[],\n eventsByTx: Map<string, EventRecord[]>,\n): MatchedTx[] {\n const results: MatchedTx[] = [];\n const key = sourceKey(source);\n\n for (const tx of transactions) {\n // Type-based matching (e.g., token_transfer → matches tx.type)\n if (source.type) {\n if (!matchPattern(tx.type, source.type)) continue;\n\n const txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\n // Collect all events for this tx (type-based sources match the whole tx)\n let matchedEvents = txEvents;\n\n // minAmount filter — check events with an amount field\n if (source.minAmount !== undefined) {\n const amountEvents = matchedEvents.filter((e) => {\n const data = e.data as Record<string, unknown> | null;\n const rawAmount = data?.amount as string | number | undefined;\n if (rawAmount === undefined) return false;\n const amount = BigInt(rawAmount);\n return amount >= source.minAmount!;\n });\n if (amountEvents.length === 0) continue;\n matchedEvents = amountEvents;\n }\n\n results.push({ tx, events: matchedEvents, sourceKey: key });\n continue;\n }\n\n // Contract-based matching\n if (source.contract) {\n const txContractMatch = tx.contract_id && matchPattern(tx.contract_id, source.contract);\n\n // Function filter\n if (source.function && tx.function_name) {\n if (!matchPattern(tx.function_name, source.function)) continue;\n } else if (source.function && !tx.function_name) {\n continue;\n }\n\n const txEvents = eventsByTx.get(tx.tx_id) ?? [];\n let matchedEvents = txEvents;\n\n if (!txContractMatch) {\n // Check if any events match the contract\n matchedEvents = txEvents.filter((e) => {\n const data = e.data as Record<string, unknown> | null;\n const contractIdentifier = data?.contract_identifier as string | undefined;\n return contractIdentifier && matchPattern(contractIdentifier, source.contract!);\n });\n if (matchedEvents.length === 0) continue;\n }\n\n // Event type / topic filter\n if (source.event) {\n matchedEvents = matchedEvents.filter((e) => {\n if (matchPattern(e.type, source.event!)) return true;\n const data = e.data as Record<string, unknown> | null;\n const topic = data?.topic as string | undefined;\n return topic ? matchPattern(topic, source.event!) : false;\n });\n }\n\n if (txContractMatch || matchedEvents.length > 0) {\n results.push({ tx, events: matchedEvents, sourceKey: key });\n }\n }\n }\n\n return results;\n}\n\n/**\n * Match all sources against a block's transactions and events.\n * Deduplicates by (txId, sourceKey) — each handler key fires at most once per tx.\n */\nexport function matchSources(\n sources: SubgraphSource[],\n transactions: TxRecord[],\n events: EventRecord[],\n): MatchedTx[] {\n // Index events by txId\n const eventsByTx = new Map<string, EventRecord[]>();\n for (const event of events) {\n const list = eventsByTx.get(event.tx_id) ?? [];\n list.push(event);\n eventsByTx.set(event.tx_id, list);\n }\n\n const seen = new Set<string>();\n const results: MatchedTx[] = [];\n\n for (const source of sources) {\n const matches = matchSource(source, transactions, eventsByTx);\n for (const match of matches) {\n const dedupeKey = `${match.tx.tx_id}:${match.sourceKey}`;\n if (!seen.has(dedupeKey)) {\n seen.add(dedupeKey);\n results.push(match);\n }\n }\n }\n\n return results;\n}\n",
9
9
  "import { cvToJSON, 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 try {\n const cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n const cv = deserializeCV(cleanHex);\n return cvToJSON(cv);\n } catch {\n return hex;\n }\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 if (typeof data === \"string\" && data.startsWith(\"0x\") && data.length > 10) {\n return decodeClarityValue(data);\n }\n\n if (Array.isArray(data)) {\n return data.map(decodeEventData);\n }\n\n if (typeof data === \"object\" && data !== null) {\n const decoded: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n decoded[key] = decodeEventData(value);\n }\n return decoded;\n }\n\n return data;\n}\n\n/**\n * Decode function args array (hex-encoded Clarity values).\n */\nexport function decodeFunctionArgs(args: string[]): unknown[] {\n return args.map(decodeClarityValue);\n}\n",
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/validate.ts", "../src/schema/utils.ts", "../src/schema/generator.ts", "../src/schema/deployer.ts"],
4
4
  "sourcesContent": [
5
- "import { z } from \"zod\";\nimport type { ColumnType, SubgraphColumn, SubgraphTable, SubgraphSource, SubgraphDefinition } from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n .string()\n .min(1)\n .max(63)\n .regex(\n /^[a-z][a-z0-9-]*$/,\n \"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n );\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n \"text\",\n \"uint\",\n \"int\",\n \"principal\",\n \"boolean\",\n \"timestamp\",\n \"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n type: ColumnTypeSchema,\n nullable: z.boolean().optional(),\n indexed: z.boolean().optional(),\n search: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n columns: z\n .record(z.string(), SubgraphColumnSchema)\n .refine((c) => Object.keys(c).length > 0, \"Table must have at least one column\"),\n indexes: z.array(z.array(z.string())).optional(),\n uniqueKeys: z.array(z.array(z.string())).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n .record(z.string(), SubgraphTableSchema)\n .refine((s) => Object.keys(s).length > 0, \"Schema must have at least one table\") as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const SubgraphSourceSchema: z.ZodType<SubgraphSource> = z\n .object({\n contract: z.string().optional(),\n event: z.string().optional(),\n function: z.string().optional(),\n type: z.string().optional(),\n minAmount: z.bigint().optional(),\n })\n .refine(\n (s) => s.contract || s.type,\n \"Source must specify at least 'contract' or 'type'\",\n ) as z.ZodType<SubgraphSource>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object({\n name: SubgraphNameSchema,\n version: z.string().optional(),\n description: z.string().optional(),\n sources: z.array(SubgraphSourceSchema).min(1, \"Must have at least one source\"),\n schema: SubgraphSchemaSchema,\n handlers: z.record(z.string(), z.function()),\n}) 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 return SubgraphDefinitionSchema.parse(def);\n}\n",
5
+ "import { z } from \"zod\";\nimport type { ColumnType, SubgraphColumn, SubgraphTable, SubgraphSource, SubgraphDefinition } from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n .string()\n .min(1)\n .max(63)\n .regex(\n /^[a-z][a-z0-9-]*$/,\n \"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n );\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n \"text\",\n \"uint\",\n \"int\",\n \"principal\",\n \"boolean\",\n \"timestamp\",\n \"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n type: ColumnTypeSchema,\n nullable: z.boolean().optional(),\n indexed: z.boolean().optional(),\n search: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n columns: z\n .record(z.string(), SubgraphColumnSchema)\n .refine((c) => Object.keys(c).length > 0, \"Table must have at least one column\"),\n indexes: z.array(z.array(z.string())).optional(),\n uniqueKeys: z.array(z.array(z.string())).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n .record(z.string(), SubgraphTableSchema)\n .refine((s) => Object.keys(s).length > 0, \"Schema must have at least one table\") as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const SubgraphSourceSchema: z.ZodType<SubgraphSource> = z\n .object({\n contract: z.string().optional(),\n event: z.string().optional(),\n function: z.string().optional(),\n type: z.string().optional(),\n minAmount: z.bigint().optional(),\n })\n .refine(\n (s) => s.contract || s.type,\n \"Source must specify at least 'contract' or 'type'\",\n ) as z.ZodType<SubgraphSource>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object({\n name: SubgraphNameSchema,\n version: z.string().optional(),\n description: z.string().optional(),\n sources: z.array(SubgraphSourceSchema).min(1, \"Must have at least one source\"),\n schema: SubgraphSchemaSchema,\n handlers: z.record(z.string(), z.function()),\n}) 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 return SubgraphDefinitionSchema.parse(def);\n}\n",
6
6
  "// Re-export canonical pgSchemaName from shared\nexport { pgSchemaName } from \"@secondlayer/shared/db/queries/subgraphs\";\n",
7
7
  "import type { ColumnType, SubgraphDefinition } from \"../types.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\nexport const TYPE_MAP: Record<ColumnType, string> = {\n text: \"TEXT\",\n uint: \"NUMERIC\",\n int: \"NUMERIC\",\n principal: \"TEXT\",\n boolean: \"BOOLEAN\",\n timestamp: \"TIMESTAMPTZ\",\n jsonb: \"JSONB\",\n};\n\nexport interface GeneratedSQL {\n statements: string[];\n hash: string;\n}\n\nfunction escapeLiteralDefault(value: unknown): string {\n if (value === null || value === undefined) return \"NULL\";\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n return `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Generates PostgreSQL DDL statements for a subgraph definition.\n * Creates a dedicated schema `subgraph_<name>` with one table per schema entry,\n * each with auto-columns and indexes.\n */\nexport function generateSubgraphSQL(def: SubgraphDefinition, schemaNameOverride?: string): GeneratedSQL {\n const schemaName = schemaNameOverride ?? pgSchemaName(def.name);\n const statements: string[] = [];\n\n // Check if any column uses search (trigram)\n const needsTrgm = Object.values(def.schema).some((table) =>\n Object.values(table.columns).some((col) => col.search),\n );\n\n if (needsTrgm) {\n statements.push(`CREATE EXTENSION IF NOT EXISTS pg_trgm`);\n }\n\n // Schema namespace\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);\n\n // One table per schema entry\n for (const [tableName, tableDef] of Object.entries(def.schema)) {\n const qualifiedName = `${schemaName}.${tableName}`;\n\n // Auto-columns + user columns\n const columnDefs: string[] = [\n `_id BIGSERIAL PRIMARY KEY`,\n `_block_height BIGINT NOT NULL`,\n `_tx_id TEXT NOT NULL`,\n `_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()`,\n ];\n\n for (const [colName, col] of Object.entries(tableDef.columns)) {\n const sqlType = TYPE_MAP[col.type];\n const nullable = col.nullable ? \"\" : \" NOT NULL\";\n let colDef = `${colName} ${sqlType}${nullable}`;\n if (col.default !== undefined) {\n colDef += ` DEFAULT ${escapeLiteralDefault(col.default)}`;\n }\n columnDefs.push(colDef);\n }\n\n statements.push(\n `CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${columnDefs.join(\",\\n \")}\\n)`,\n );\n\n // Auto-indexes on meta columns\n statements.push(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`,\n );\n statements.push(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`,\n );\n\n // Single-column indexes\n for (const [colName, col] of Object.entries(tableDef.columns)) {\n if (col.indexed) {\n statements.push(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n );\n }\n }\n\n // Trigram GIN indexes for search columns\n for (const [colName, col] of Object.entries(tableDef.columns)) {\n if (col.search) {\n statements.push(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n );\n }\n }\n\n // Composite indexes\n if (tableDef.indexes) {\n for (let i = 0; i < tableDef.indexes.length; i++) {\n const cols = tableDef.indexes[i]!;\n const idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n statements.push(\n `CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.join(\", \")})`,\n );\n }\n }\n\n // Unique constraints (required for upsert ON CONFLICT)\n if (tableDef.uniqueKeys) {\n for (let i = 0; i < tableDef.uniqueKeys.length; i++) {\n const cols = tableDef.uniqueKeys[i]!;\n const constraintName = `uq_${schemaName}_${tableName}_${cols.join(\"_\")}`;\n statements.push(\n `ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.join(\", \")})`,\n );\n }\n }\n }\n\n // Hash based on schema structure (excludes handler)\n const hashInput = JSON.stringify({\n name: def.name,\n version: def.version,\n schema: def.schema,\n sources: def.sources,\n }, (_key, value) => typeof value === \"bigint\" ? value.toString() : value);\n const hash = String(Bun.hash(hashInput));\n\n return { statements, hash };\n}\n",
8
8
  "import { sql, type Kysely } from \"kysely\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { validateSubgraphDefinition } from \"../validate.ts\";\nimport { generateSubgraphSQL, TYPE_MAP } from \"./generator.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\nimport type { SubgraphDefinition, SubgraphSchema } from \"../types.ts\";\n\ntype AnyDb = Kysely<Database>;\n\n/** Deep-clone an object, converting BigInts to strings for JSON serialization. */\nfunction toJsonSafe(obj: unknown): unknown {\n return JSON.parse(JSON.stringify(obj, (_key, value) =>\n typeof value === \"bigint\" ? value.toString() : value\n ));\n}\n\nexport interface TableDiff {\n /** Tables added to the schema */\n addedTables: string[];\n /** Tables removed from the schema */\n removedTables: string[];\n /** Per-table column diffs (only for tables present in both) */\n tables: Record<string, ColumnDiff>;\n}\n\nexport interface ColumnDiff {\n added: string[];\n removed: string[];\n changed: string[];\n}\n\n/**\n * Compare two multi-table subgraph schemas and return differences.\n */\nexport function diffSchema(existing: SubgraphSchema, incoming: SubgraphSchema): TableDiff {\n const existingTables = new Set(Object.keys(existing));\n const incomingTables = new Set(Object.keys(incoming));\n\n const addedTables = [...incomingTables].filter((t) => !existingTables.has(t));\n const removedTables = [...existingTables].filter((t) => !incomingTables.has(t));\n\n const tables: Record<string, ColumnDiff> = {};\n for (const tableName of incomingTables) {\n if (!existingTables.has(tableName)) continue;\n const existingCols = existing[tableName]!.columns;\n const incomingCols = incoming[tableName]!.columns;\n\n const existingKeys = new Set(Object.keys(existingCols));\n const incomingKeys = new Set(Object.keys(incomingCols));\n\n tables[tableName] = {\n added: [...incomingKeys].filter((k) => !existingKeys.has(k)),\n removed: [...existingKeys].filter((k) => !incomingKeys.has(k)),\n changed: [...incomingKeys].filter((k) => {\n if (!existingKeys.has(k)) return false;\n return JSON.stringify(existingCols[k]) !== JSON.stringify(incomingCols[k]);\n }),\n };\n }\n\n return { addedTables, removedTables, tables };\n}\n\n/**\n * Returns true if the diff contains any breaking changes\n * (removed tables, removed columns, or changed column types).\n */\nfunction hasBreakingChanges(diff: TableDiff): { breaking: boolean; reasons: string[] } {\n const reasons: string[] = [];\n if (diff.removedTables.length > 0) {\n reasons.push(`removed tables: [${diff.removedTables.join(\", \")}]`);\n }\n for (const [table, colDiff] of Object.entries(diff.tables)) {\n if (colDiff.removed.length > 0) {\n reasons.push(`${table}: removed columns [${colDiff.removed.join(\", \")}]`);\n }\n if (colDiff.changed.length > 0) {\n reasons.push(`${table}: changed columns [${colDiff.changed.join(\", \")}]`);\n }\n }\n return { breaking: reasons.length > 0, reasons };\n}\n\n/**\n * Deploy a subgraph schema to the database.\n * - New subgraph → CREATE SCHEMA + tables + register\n * - Same hash → no-op\n * - Additive change → ALTER TABLE ADD COLUMN / CREATE TABLE for new tables\n * - Breaking change → throws error\n */\nexport async function deploySchema(\n db: AnyDb,\n def: SubgraphDefinition,\n handlerPath: string,\n opts?: { forceReindex?: boolean; apiKeyId?: string; schemaName?: string },\n): Promise<{ action: \"created\" | \"unchanged\" | \"updated\" | \"reindexed\"; subgraphId: string }> {\n validateSubgraphDefinition(def);\n\n const { statements, hash } = generateSubgraphSQL(def, opts?.schemaName);\n const { getSubgraph, registerSubgraph } = await import(\"@secondlayer/shared/db/queries/subgraphs\");\n\n const existing = await getSubgraph(db, def.name, opts?.apiKeyId);\n\n const schemaName = opts?.schemaName ?? pgSchemaName(def.name);\n const regData = {\n name: def.name,\n version: def.version || \"1.0.0\",\n definition: toJsonSafe({ name: def.name, version: def.version, description: def.description, sources: def.sources, schema: def.schema }) as Record<string, unknown>,\n schemaHash: hash,\n handlerPath,\n apiKeyId: opts?.apiKeyId,\n schemaName,\n };\n\n if (existing) {\n if (existing.schema_hash === hash && !opts?.forceReindex) {\n // Update handler path in case file moved\n const { updateSubgraphHandlerPath } = await import(\"@secondlayer/shared/db/queries/subgraphs\");\n await updateSubgraphHandlerPath(db, def.name, handlerPath);\n return { action: \"unchanged\", subgraphId: existing.id };\n }\n\n if (existing.schema_hash === hash && opts?.forceReindex) {\n // Same schema but force reindex requested — drop and recreate\n await sql.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`).execute(db);\n for (const stmt of statements) {\n await sql.raw(stmt).execute(db);\n }\n const sg = await registerSubgraph(db, regData);\n return { action: \"reindexed\", subgraphId: sg.id };\n }\n\n const existingDef = existing.definition as { schema?: SubgraphSchema };\n if (existingDef.schema) {\n const diff = diffSchema(existingDef.schema, def.schema);\n const { breaking, reasons } = hasBreakingChanges(diff);\n\n if (breaking) {\n if (!opts?.forceReindex) {\n throw new Error(\n `Breaking schema change detected (${reasons.join(\"; \")}). ` +\n `Use --reindex to force rebuild, or delete the subgraph first.`,\n );\n }\n\n // Force reindex: drop schema, recreate, register, caller triggers reindex\n await sql.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`).execute(db);\n for (const stmt of statements) {\n await sql.raw(stmt).execute(db);\n }\n const sg = await registerSubgraph(db, regData);\n return { action: \"reindexed\", subgraphId: sg.id };\n }\n\n // Create new tables\n for (const tableName of diff.addedTables) {\n const tableDef = def.schema[tableName]!;\n const qualifiedName = `${schemaName}.${tableName}`;\n const colDefs = [\n `_id BIGSERIAL PRIMARY KEY`,\n `_block_height BIGINT NOT NULL`,\n `_tx_id TEXT NOT NULL`,\n `_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()`,\n ];\n for (const [colName, col] of Object.entries(tableDef.columns)) {\n const nullable = col.nullable ? \"\" : \" NOT NULL\";\n colDefs.push(`${colName} ${TYPE_MAP[col.type]!}${nullable}`);\n }\n await sql.raw(\n `CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${colDefs.join(\",\\n \")}\\n)`,\n ).execute(db);\n await sql.raw(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`,\n ).execute(db);\n await sql.raw(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`,\n ).execute(db);\n for (const [colName, col] of Object.entries(tableDef.columns)) {\n if (col.indexed) {\n await sql.raw(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n ).execute(db);\n }\n if (col.search) {\n await sql.raw(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n ).execute(db);\n }\n }\n }\n\n // Add columns to existing tables\n for (const [tableName, colDiff] of Object.entries(diff.tables)) {\n if (colDiff.added.length === 0) continue;\n const qualifiedName = `${schemaName}.${tableName}`;\n const tableDef = def.schema[tableName]!;\n for (const colName of colDiff.added) {\n const col = tableDef.columns[colName]!;\n const sqlType = TYPE_MAP[col.type]!;\n const nullable = col.nullable ? \"\" : \" NOT NULL DEFAULT \" + getDefault(col.type);\n await sql.raw(\n `ALTER TABLE ${qualifiedName} ADD COLUMN ${colName} ${sqlType}${nullable}`,\n ).execute(db);\n if (col.indexed) {\n await sql.raw(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n ).execute(db);\n }\n if (col.search) {\n await sql.raw(\n `CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n ).execute(db);\n }\n }\n }\n }\n\n const sg = await registerSubgraph(db, regData);\n return { action: \"updated\", subgraphId: sg.id };\n }\n\n // New subgraph — execute all DDL\n for (const stmt of statements) {\n await sql.raw(stmt).execute(db);\n }\n\n const sg = await registerSubgraph(db, regData);\n return { action: \"created\", subgraphId: sg.id };\n}\n\nfunction getDefault(type: string): string {\n switch (type) {\n case \"text\":\n case \"principal\":\n return \"''\";\n case \"uint\":\n case \"int\":\n return \"0\";\n case \"boolean\":\n return \"false\";\n case \"timestamp\":\n return \"NOW()\";\n case \"jsonb\":\n return \"'{}'\";\n default:\n return \"''\";\n }\n}\n"
@@ -0,0 +1,12 @@
1
+ interface SubgraphTemplate {
2
+ id: string;
3
+ name: string;
4
+ description: string;
5
+ category: "defi" | "nft" | "token" | "infrastructure";
6
+ code: string;
7
+ prompt: string;
8
+ }
9
+ declare const templates: SubgraphTemplate[];
10
+ declare function getTemplateById(id: string): SubgraphTemplate | undefined;
11
+ declare function getTemplatesByCategory(category: string): SubgraphTemplate[];
12
+ export { templates, getTemplatesByCategory, getTemplateById, SubgraphTemplate };
@@ -0,0 +1,267 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
4
+ // src/templates.ts
5
+ var templates = [
6
+ {
7
+ id: "dex-swaps",
8
+ name: "DEX Swap Tracking",
9
+ description: "Track swap events from ALEX or any AMM pool. Indexes token pairs, amounts, and traders.",
10
+ category: "defi",
11
+ code: `import { defineSubgraph } from '@secondlayer/subgraphs';
12
+
13
+ export default defineSubgraph({
14
+ name: 'dex-swaps',
15
+ sources: [
16
+ { contract: 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01', event: 'swap' },
17
+ ],
18
+ schema: {
19
+ swaps: {
20
+ columns: {
21
+ sender: { type: 'principal', indexed: true },
22
+ token_x: { type: 'text' },
23
+ token_y: { type: 'text' },
24
+ amount_x: { type: 'uint' },
25
+ amount_y: { type: 'uint' },
26
+ },
27
+ indexes: [['sender', 'token_x']],
28
+ },
29
+ },
30
+ handlers: {
31
+ 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01::swap': (event, ctx) => {
32
+ ctx.insert('swaps', {
33
+ sender: ctx.tx.sender,
34
+ token_x: event.tokenX,
35
+ token_y: event.tokenY,
36
+ amount_x: event.dx,
37
+ amount_y: event.dy,
38
+ });
39
+ },
40
+ },
41
+ });
42
+ `,
43
+ prompt: "Create a Secondlayer subgraph that tracks DEX swap events from ALEX AMM pool. Index sender, token pairs, and amounts."
44
+ },
45
+ {
46
+ id: "nft-marketplace",
47
+ name: "NFT Marketplace",
48
+ description: "Index NFT listings, sales, and cancellations. Track prices and ownership changes.",
49
+ category: "nft",
50
+ code: `import { defineSubgraph } from '@secondlayer/subgraphs';
51
+
52
+ export default defineSubgraph({
53
+ name: 'nft-marketplace',
54
+ sources: [
55
+ { contract: 'SP...marketplace', event: 'list-item' },
56
+ { contract: 'SP...marketplace', event: 'unlist-item' },
57
+ { contract: 'SP...marketplace', event: 'purchase' },
58
+ ],
59
+ schema: {
60
+ listings: {
61
+ columns: {
62
+ nft_id: { type: 'uint', indexed: true },
63
+ seller: { type: 'principal', indexed: true },
64
+ price: { type: 'uint' },
65
+ status: { type: 'text' },
66
+ },
67
+ uniqueKeys: [['nft_id']],
68
+ },
69
+ sales: {
70
+ columns: {
71
+ nft_id: { type: 'uint', indexed: true },
72
+ seller: { type: 'principal' },
73
+ buyer: { type: 'principal', indexed: true },
74
+ price: { type: 'uint' },
75
+ },
76
+ },
77
+ },
78
+ handlers: {
79
+ 'SP...marketplace::list-item': (event, ctx) => {
80
+ ctx.upsert('listings', { nft_id: event.nftId }, {
81
+ nft_id: event.nftId,
82
+ seller: ctx.tx.sender,
83
+ price: event.price,
84
+ status: 'active',
85
+ });
86
+ },
87
+ 'SP...marketplace::unlist-item': (event, ctx) => {
88
+ ctx.update('listings', { nft_id: event.nftId }, { status: 'cancelled' });
89
+ },
90
+ 'SP...marketplace::purchase': (event, ctx) => {
91
+ ctx.update('listings', { nft_id: event.nftId }, { status: 'sold' });
92
+ ctx.insert('sales', {
93
+ nft_id: event.nftId,
94
+ seller: event.seller,
95
+ buyer: ctx.tx.sender,
96
+ price: event.price,
97
+ });
98
+ },
99
+ },
100
+ });
101
+ `,
102
+ prompt: "Create a Secondlayer subgraph for an NFT marketplace. Track listings, cancellations, and sales with prices."
103
+ },
104
+ {
105
+ id: "token-transfers",
106
+ name: "Token Transfers",
107
+ description: "Track fungible token transfers with running balance computation per address.",
108
+ category: "token",
109
+ code: `import { defineSubgraph } from '@secondlayer/subgraphs';
110
+
111
+ export default defineSubgraph({
112
+ name: 'token-transfers',
113
+ sources: [
114
+ { contract: 'SP...token', event: 'transfer' },
115
+ ],
116
+ schema: {
117
+ transfers: {
118
+ columns: {
119
+ from_addr: { type: 'principal', indexed: true },
120
+ to_addr: { type: 'principal', indexed: true },
121
+ amount: { type: 'uint' },
122
+ },
123
+ },
124
+ balances: {
125
+ columns: {
126
+ address: { type: 'principal', indexed: true },
127
+ balance: { type: 'uint' },
128
+ },
129
+ uniqueKeys: [['address']],
130
+ },
131
+ },
132
+ handlers: {
133
+ 'SP...token::transfer': async (event, ctx) => {
134
+ ctx.insert('transfers', {
135
+ from_addr: event.sender,
136
+ to_addr: event.recipient,
137
+ amount: event.amount,
138
+ });
139
+
140
+ // Update sender balance
141
+ const senderBal = await ctx.findOne('balances', { address: event.sender });
142
+ const senderPrev = senderBal ? BigInt(senderBal.balance as string) : 0n;
143
+ ctx.upsert('balances', { address: event.sender }, {
144
+ address: event.sender,
145
+ balance: senderPrev - BigInt(event.amount as string),
146
+ });
147
+
148
+ // Update recipient balance
149
+ const recipBal = await ctx.findOne('balances', { address: event.recipient });
150
+ const recipPrev = recipBal ? BigInt(recipBal.balance as string) : 0n;
151
+ ctx.upsert('balances', { address: event.recipient }, {
152
+ address: event.recipient,
153
+ balance: recipPrev + BigInt(event.amount as string),
154
+ });
155
+ },
156
+ },
157
+ });
158
+ `,
159
+ prompt: "Create a Secondlayer subgraph that tracks token transfers and computes running balances per address."
160
+ },
161
+ {
162
+ id: "bns-names",
163
+ name: "BNS Names",
164
+ description: "Index BNS name registrations and transfers. Search names by owner or namespace.",
165
+ category: "infrastructure",
166
+ code: `import { defineSubgraph } from '@secondlayer/subgraphs';
167
+
168
+ export default defineSubgraph({
169
+ name: 'bns-names',
170
+ sources: [
171
+ { contract: 'SP000000000000000000002Q6VF78.bns', function: 'name-register' },
172
+ { contract: 'SP000000000000000000002Q6VF78.bns', function: 'name-transfer' },
173
+ ],
174
+ schema: {
175
+ names: {
176
+ columns: {
177
+ name: { type: 'text', indexed: true, search: true },
178
+ namespace: { type: 'text', indexed: true },
179
+ owner: { type: 'principal', indexed: true },
180
+ },
181
+ uniqueKeys: [['name', 'namespace']],
182
+ },
183
+ transfers: {
184
+ columns: {
185
+ name: { type: 'text' },
186
+ namespace: { type: 'text' },
187
+ from_addr: { type: 'principal' },
188
+ to_addr: { type: 'principal' },
189
+ },
190
+ },
191
+ },
192
+ handlers: {
193
+ 'SP000000000000000000002Q6VF78.bns::name-register': (event, ctx) => {
194
+ ctx.upsert('names', { name: event.name, namespace: event.namespace }, {
195
+ name: event.name,
196
+ namespace: event.namespace,
197
+ owner: ctx.tx.sender,
198
+ });
199
+ },
200
+ 'SP000000000000000000002Q6VF78.bns::name-transfer': (event, ctx) => {
201
+ ctx.update('names', { name: event.name, namespace: event.namespace }, {
202
+ owner: event.newOwner,
203
+ });
204
+ ctx.insert('transfers', {
205
+ name: event.name,
206
+ namespace: event.namespace,
207
+ from_addr: event.sender,
208
+ to_addr: event.newOwner,
209
+ });
210
+ },
211
+ },
212
+ });
213
+ `,
214
+ prompt: "Create a Secondlayer subgraph for BNS name registrations and transfers on Stacks."
215
+ },
216
+ {
217
+ id: "stx-whales",
218
+ name: "STX Whale Alerts",
219
+ description: "Track large STX transfers above a configurable threshold. Great for monitoring whale activity.",
220
+ category: "token",
221
+ code: `import { defineSubgraph } from '@secondlayer/subgraphs';
222
+
223
+ const WHALE_THRESHOLD = 100_000_000_000; // 100k STX in microSTX
224
+
225
+ export default defineSubgraph({
226
+ name: 'stx-whales',
227
+ sources: [{ type: 'stx_transfer' }],
228
+ schema: {
229
+ whale_transfers: {
230
+ columns: {
231
+ sender: { type: 'principal', indexed: true },
232
+ receiver: { type: 'principal', indexed: true },
233
+ amount: { type: 'uint' },
234
+ },
235
+ },
236
+ },
237
+ handlers: {
238
+ stx_transfer: (event, ctx) => {
239
+ const amount = BigInt(event.amount as string);
240
+ if (amount >= BigInt(WHALE_THRESHOLD)) {
241
+ ctx.insert('whale_transfers', {
242
+ sender: event.sender,
243
+ receiver: event.recipient,
244
+ amount: event.amount,
245
+ });
246
+ }
247
+ },
248
+ },
249
+ });
250
+ `,
251
+ prompt: "Create a Secondlayer subgraph that tracks STX transfers above 100k STX as whale alerts."
252
+ }
253
+ ];
254
+ function getTemplateById(id) {
255
+ return templates.find((t) => t.id === id);
256
+ }
257
+ function getTemplatesByCategory(category) {
258
+ return templates.filter((t) => t.category === category);
259
+ }
260
+ export {
261
+ templates,
262
+ getTemplatesByCategory,
263
+ getTemplateById
264
+ };
265
+
266
+ //# debugId=C475457B59EBDAC964756E2164756E21
267
+ //# sourceMappingURL=templates.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/templates.ts"],
4
+ "sourcesContent": [
5
+ "export interface SubgraphTemplate {\n id: string;\n name: string;\n description: string;\n category: \"defi\" | \"nft\" | \"token\" | \"infrastructure\";\n code: string;\n prompt: string;\n}\n\nexport const templates: SubgraphTemplate[] = [\n {\n id: \"dex-swaps\",\n name: \"DEX Swap Tracking\",\n description: \"Track swap events from ALEX or any AMM pool. Indexes token pairs, amounts, and traders.\",\n category: \"defi\",\n code: `import { defineSubgraph } from '@secondlayer/subgraphs';\n\nexport default defineSubgraph({\n name: 'dex-swaps',\n sources: [\n { contract: 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01', event: 'swap' },\n ],\n schema: {\n swaps: {\n columns: {\n sender: { type: 'principal', indexed: true },\n token_x: { type: 'text' },\n token_y: { type: 'text' },\n amount_x: { type: 'uint' },\n amount_y: { type: 'uint' },\n },\n indexes: [['sender', 'token_x']],\n },\n },\n handlers: {\n 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01::swap': (event, ctx) => {\n ctx.insert('swaps', {\n sender: ctx.tx.sender,\n token_x: event.tokenX,\n token_y: event.tokenY,\n amount_x: event.dx,\n amount_y: event.dy,\n });\n },\n },\n});\n`,\n prompt: \"Create a Secondlayer subgraph that tracks DEX swap events from ALEX AMM pool. Index sender, token pairs, and amounts.\",\n },\n {\n id: \"nft-marketplace\",\n name: \"NFT Marketplace\",\n description: \"Index NFT listings, sales, and cancellations. Track prices and ownership changes.\",\n category: \"nft\",\n code: `import { defineSubgraph } from '@secondlayer/subgraphs';\n\nexport default defineSubgraph({\n name: 'nft-marketplace',\n sources: [\n { contract: 'SP...marketplace', event: 'list-item' },\n { contract: 'SP...marketplace', event: 'unlist-item' },\n { contract: 'SP...marketplace', event: 'purchase' },\n ],\n schema: {\n listings: {\n columns: {\n nft_id: { type: 'uint', indexed: true },\n seller: { type: 'principal', indexed: true },\n price: { type: 'uint' },\n status: { type: 'text' },\n },\n uniqueKeys: [['nft_id']],\n },\n sales: {\n columns: {\n nft_id: { type: 'uint', indexed: true },\n seller: { type: 'principal' },\n buyer: { type: 'principal', indexed: true },\n price: { type: 'uint' },\n },\n },\n },\n handlers: {\n 'SP...marketplace::list-item': (event, ctx) => {\n ctx.upsert('listings', { nft_id: event.nftId }, {\n nft_id: event.nftId,\n seller: ctx.tx.sender,\n price: event.price,\n status: 'active',\n });\n },\n 'SP...marketplace::unlist-item': (event, ctx) => {\n ctx.update('listings', { nft_id: event.nftId }, { status: 'cancelled' });\n },\n 'SP...marketplace::purchase': (event, ctx) => {\n ctx.update('listings', { nft_id: event.nftId }, { status: 'sold' });\n ctx.insert('sales', {\n nft_id: event.nftId,\n seller: event.seller,\n buyer: ctx.tx.sender,\n price: event.price,\n });\n },\n },\n});\n`,\n prompt: \"Create a Secondlayer subgraph for an NFT marketplace. Track listings, cancellations, and sales with prices.\",\n },\n {\n id: \"token-transfers\",\n name: \"Token Transfers\",\n description: \"Track fungible token transfers with running balance computation per address.\",\n category: \"token\",\n code: `import { defineSubgraph } from '@secondlayer/subgraphs';\n\nexport default defineSubgraph({\n name: 'token-transfers',\n sources: [\n { contract: 'SP...token', event: 'transfer' },\n ],\n schema: {\n transfers: {\n columns: {\n from_addr: { type: 'principal', indexed: true },\n to_addr: { type: 'principal', indexed: true },\n amount: { type: 'uint' },\n },\n },\n balances: {\n columns: {\n address: { type: 'principal', indexed: true },\n balance: { type: 'uint' },\n },\n uniqueKeys: [['address']],\n },\n },\n handlers: {\n 'SP...token::transfer': async (event, ctx) => {\n ctx.insert('transfers', {\n from_addr: event.sender,\n to_addr: event.recipient,\n amount: event.amount,\n });\n\n // Update sender balance\n const senderBal = await ctx.findOne('balances', { address: event.sender });\n const senderPrev = senderBal ? BigInt(senderBal.balance as string) : 0n;\n ctx.upsert('balances', { address: event.sender }, {\n address: event.sender,\n balance: senderPrev - BigInt(event.amount as string),\n });\n\n // Update recipient balance\n const recipBal = await ctx.findOne('balances', { address: event.recipient });\n const recipPrev = recipBal ? BigInt(recipBal.balance as string) : 0n;\n ctx.upsert('balances', { address: event.recipient }, {\n address: event.recipient,\n balance: recipPrev + BigInt(event.amount as string),\n });\n },\n },\n});\n`,\n prompt: \"Create a Secondlayer subgraph that tracks token transfers and computes running balances per address.\",\n },\n {\n id: \"bns-names\",\n name: \"BNS Names\",\n description: \"Index BNS name registrations and transfers. Search names by owner or namespace.\",\n category: \"infrastructure\",\n code: `import { defineSubgraph } from '@secondlayer/subgraphs';\n\nexport default defineSubgraph({\n name: 'bns-names',\n sources: [\n { contract: 'SP000000000000000000002Q6VF78.bns', function: 'name-register' },\n { contract: 'SP000000000000000000002Q6VF78.bns', function: 'name-transfer' },\n ],\n schema: {\n names: {\n columns: {\n name: { type: 'text', indexed: true, search: true },\n namespace: { type: 'text', indexed: true },\n owner: { type: 'principal', indexed: true },\n },\n uniqueKeys: [['name', 'namespace']],\n },\n transfers: {\n columns: {\n name: { type: 'text' },\n namespace: { type: 'text' },\n from_addr: { type: 'principal' },\n to_addr: { type: 'principal' },\n },\n },\n },\n handlers: {\n 'SP000000000000000000002Q6VF78.bns::name-register': (event, ctx) => {\n ctx.upsert('names', { name: event.name, namespace: event.namespace }, {\n name: event.name,\n namespace: event.namespace,\n owner: ctx.tx.sender,\n });\n },\n 'SP000000000000000000002Q6VF78.bns::name-transfer': (event, ctx) => {\n ctx.update('names', { name: event.name, namespace: event.namespace }, {\n owner: event.newOwner,\n });\n ctx.insert('transfers', {\n name: event.name,\n namespace: event.namespace,\n from_addr: event.sender,\n to_addr: event.newOwner,\n });\n },\n },\n});\n`,\n prompt: \"Create a Secondlayer subgraph for BNS name registrations and transfers on Stacks.\",\n },\n {\n id: \"stx-whales\",\n name: \"STX Whale Alerts\",\n description: \"Track large STX transfers above a configurable threshold. Great for monitoring whale activity.\",\n category: \"token\",\n code: `import { defineSubgraph } from '@secondlayer/subgraphs';\n\nconst WHALE_THRESHOLD = 100_000_000_000; // 100k STX in microSTX\n\nexport default defineSubgraph({\n name: 'stx-whales',\n sources: [{ type: 'stx_transfer' }],\n schema: {\n whale_transfers: {\n columns: {\n sender: { type: 'principal', indexed: true },\n receiver: { type: 'principal', indexed: true },\n amount: { type: 'uint' },\n },\n },\n },\n handlers: {\n stx_transfer: (event, ctx) => {\n const amount = BigInt(event.amount as string);\n if (amount >= BigInt(WHALE_THRESHOLD)) {\n ctx.insert('whale_transfers', {\n sender: event.sender,\n receiver: event.recipient,\n amount: event.amount,\n });\n }\n },\n },\n});\n`,\n prompt: \"Create a Secondlayer subgraph that tracks STX transfers above 100k STX as whale alerts.\",\n },\n];\n\nexport function getTemplateById(id: string): SubgraphTemplate | undefined {\n return templates.find((t) => t.id === id);\n}\n\nexport function getTemplatesByCategory(category: string): SubgraphTemplate[] {\n return templates.filter((t) => t.category === category);\n}\n"
6
+ ],
7
+ "mappings": ";;;;AASO,IAAM,YAAgC;AAAA,EAC3C;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgCN,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAoDN,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAkDN,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgDN,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IA8BN,QAAQ;AAAA,EACV;AACF;AAEO,SAAS,eAAe,CAAC,IAA0C;AAAA,EACxE,OAAO,UAAU,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE;AAAA;AAGnC,SAAS,sBAAsB,CAAC,UAAsC;AAAA,EAC3E,OAAO,UAAU,OAAO,CAAC,MAAM,EAAE,aAAa,QAAQ;AAAA;",
8
+ "debugId": "C475457B59EBDAC964756E2164756E21",
9
+ "names": []
10
+ }
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/validate.ts"],
4
4
  "sourcesContent": [
5
- "import { z } from \"zod\";\nimport type { ColumnType, SubgraphColumn, SubgraphTable, SubgraphSource, SubgraphDefinition } from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n .string()\n .min(1)\n .max(63)\n .regex(\n /^[a-z][a-z0-9-]*$/,\n \"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n );\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n \"text\",\n \"uint\",\n \"int\",\n \"principal\",\n \"boolean\",\n \"timestamp\",\n \"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n type: ColumnTypeSchema,\n nullable: z.boolean().optional(),\n indexed: z.boolean().optional(),\n search: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n columns: z\n .record(z.string(), SubgraphColumnSchema)\n .refine((c) => Object.keys(c).length > 0, \"Table must have at least one column\"),\n indexes: z.array(z.array(z.string())).optional(),\n uniqueKeys: z.array(z.array(z.string())).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n .record(z.string(), SubgraphTableSchema)\n .refine((s) => Object.keys(s).length > 0, \"Schema must have at least one table\") as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const SubgraphSourceSchema: z.ZodType<SubgraphSource> = z\n .object({\n contract: z.string().optional(),\n event: z.string().optional(),\n function: z.string().optional(),\n type: z.string().optional(),\n minAmount: z.bigint().optional(),\n })\n .refine(\n (s) => s.contract || s.type,\n \"Source must specify at least 'contract' or 'type'\",\n ) as z.ZodType<SubgraphSource>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object({\n name: SubgraphNameSchema,\n version: z.string().optional(),\n description: z.string().optional(),\n sources: z.array(SubgraphSourceSchema).min(1, \"Must have at least one source\"),\n schema: SubgraphSchemaSchema,\n handlers: z.record(z.string(), z.function()),\n}) 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 return SubgraphDefinitionSchema.parse(def);\n}\n"
5
+ "import { z } from \"zod\";\nimport type { ColumnType, SubgraphColumn, SubgraphTable, SubgraphSource, SubgraphDefinition } from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n .string()\n .min(1)\n .max(63)\n .regex(\n /^[a-z][a-z0-9-]*$/,\n \"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n );\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n \"text\",\n \"uint\",\n \"int\",\n \"principal\",\n \"boolean\",\n \"timestamp\",\n \"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n type: ColumnTypeSchema,\n nullable: z.boolean().optional(),\n indexed: z.boolean().optional(),\n search: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n columns: z\n .record(z.string(), SubgraphColumnSchema)\n .refine((c) => Object.keys(c).length > 0, \"Table must have at least one column\"),\n indexes: z.array(z.array(z.string())).optional(),\n uniqueKeys: z.array(z.array(z.string())).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n .record(z.string(), SubgraphTableSchema)\n .refine((s) => Object.keys(s).length > 0, \"Schema must have at least one table\") as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const SubgraphSourceSchema: z.ZodType<SubgraphSource> = z\n .object({\n contract: z.string().optional(),\n event: z.string().optional(),\n function: z.string().optional(),\n type: z.string().optional(),\n minAmount: z.bigint().optional(),\n })\n .refine(\n (s) => s.contract || s.type,\n \"Source must specify at least 'contract' or 'type'\",\n ) as z.ZodType<SubgraphSource>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object({\n name: SubgraphNameSchema,\n version: z.string().optional(),\n description: z.string().optional(),\n sources: z.array(SubgraphSourceSchema).min(1, \"Must have at least one source\"),\n schema: SubgraphSchemaSchema,\n handlers: z.record(z.string(), z.function()),\n}) 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 return SubgraphDefinitionSchema.parse(def);\n}\n"
6
6
  ],
7
7
  "mappings": ";;;;AAAA;AAGO,IAAM,qBAAwC,EAClD,OAAO,EACP,IAAI,CAAC,EACL,IAAI,EAAE,EACN,MACC,qBACA,mFACF;AAEK,IAAM,mBAA0C,EAAE,KAAK;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,uBAAkD,EAAE,OAAO;AAAA,EACtE,MAAM;AAAA,EACN,UAAU,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC/B,SAAS,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC9B,QAAQ,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC7B,SAAS,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,EAAE,SAAS;AACnE,CAAC;AAEM,IAAM,sBAAgD,EAAE,OAAO;AAAA,EACpE,SAAS,EACN,OAAO,EAAE,OAAO,GAAG,oBAAoB,EACvC,OAAO,CAAC,MAAM,OAAO,KAAK,CAAC,EAAE,SAAS,GAAG,qCAAqC;AAAA,EACjF,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS;AAAA,EAC/C,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS;AACpD,CAAC;AAEM,IAAM,uBAAiE,EAC3E,OAAO,EAAE,OAAO,GAAG,mBAAmB,EACtC,OAAO,CAAC,MAAM,OAAO,KAAK,CAAC,EAAE,SAAS,GAAG,qCAAqC;AAE1E,IAAM,uBAAkD,EAC5D,OAAO;AAAA,EACN,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9B,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,EAC3B,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9B,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,WAAW,EAAE,OAAO,EAAE,SAAS;AACjC,CAAC,EACA,OACC,CAAC,MAAM,EAAE,YAAY,EAAE,MACvB,mDACF;AAEK,IAAM,2BAA0D,EAAE,OAAO;AAAA,EAC9E,MAAM;AAAA,EACN,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,SAAS,EAAE,MAAM,oBAAoB,EAAE,IAAI,GAAG,+BAA+B;AAAA,EAC7E,QAAQ;AAAA,EACR,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,SAAS,CAAC;AAC7C,CAAC;AAKM,SAAS,0BAA0B,CAAC,KAAkC;AAAA,EAC3E,OAAO,yBAAyB,MAAM,GAAG;AAAA;",
8
8
  "debugId": "56E43D8408C71C4064756E2164756E21",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secondlayer/subgraphs",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -20,6 +20,10 @@
20
20
  "./validate": {
21
21
  "types": "./dist/src/validate.d.ts",
22
22
  "import": "./dist/src/validate.js"
23
+ },
24
+ "./templates": {
25
+ "types": "./dist/src/templates.d.ts",
26
+ "import": "./dist/src/templates.js"
23
27
  }
24
28
  },
25
29
  "files": [
@@ -37,7 +41,7 @@
37
41
  "@secondlayer/stacks": "^0.2.0",
38
42
  "kysely": "^0.28.10",
39
43
  "postgres": "^3.4.6",
40
- "zod": "^3.24.1"
44
+ "zod": "^4.3.6"
41
45
  },
42
46
  "devDependencies": {
43
47
  "@types/bun": "latest",