@secondlayer/subgraphs 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # @secondlayer/subgraphs
2
+
3
+ Typed on-chain indexing for Stacks. Declare event filters + column schema with `defineSubgraph()`; the runtime decodes blocks, matches filters, runs your handlers inside a transactional context, and exposes the result as a Postgres schema you query over REST or SQL.
4
+
5
+ Subgraph rows fan out to HTTP subscribers through a post-flush outbox emitter — signed Standard Webhooks POSTs with retries, circuit breaker, and replay.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add @secondlayer/subgraphs
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import { defineSubgraph } from "@secondlayer/subgraphs";
17
+
18
+ export default defineSubgraph({
19
+ name: "token-transfers",
20
+ version: "1.0.0",
21
+ sources: {
22
+ // Named event sources — the key becomes the handler name.
23
+ transfer: {
24
+ type: "ft_transfer",
25
+ assetIdentifier: "SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173.stx-token::stx",
26
+ },
27
+ },
28
+ schema: {
29
+ transfers: {
30
+ columns: {
31
+ sender: { type: "principal" },
32
+ recipient: { type: "principal" },
33
+ amount: { type: "uint" },
34
+ },
35
+ // Auto-added: _block_height, _tx_id, _created_at
36
+ },
37
+ },
38
+ handlers: {
39
+ async transfer(event, ctx) {
40
+ ctx.insert("transfers", {
41
+ sender: event.sender,
42
+ recipient: event.recipient,
43
+ amount: event.amount,
44
+ });
45
+ },
46
+ },
47
+ });
48
+ ```
49
+
50
+ Deploy via CLI (`sl subgraphs deploy path/to/definition.ts`), SDK (`sl.subgraphs.deploy({...})`), or MCP (`subgraphs_deploy`). The dashboard is read-only — creation always happens through an API surface.
51
+
52
+ ## Exports
53
+
54
+ | Subpath | Description |
55
+ | --- | --- |
56
+ | `.` | `defineSubgraph`, `validateSubgraphDefinition`, `deploySchema`, `diffSchema`, `reindexSubgraph`, `backfillSubgraph`, `generateSubgraphSQL`, `pgSchemaName` |
57
+ | `./types` | All schema + filter + handler types (`SubgraphDefinition`, `SubgraphFilter`, `StxTransferFilter`, etc.) |
58
+ | `./schema` | Generator + deployer internals |
59
+ | `./validate` | Shape + filter validation for deploys |
60
+ | `./runtime/source-matcher` | Pure fn: match txs+events against a `SubgraphFilter` — used by the processor hot path |
61
+ | `./runtime/replay` | `replaySubscription({ accountId, subscriptionId, fromBlock, toBlock })` — re-enqueue historical rows as outbox entries |
62
+
63
+ ## Runtime components
64
+
65
+ The runtime ships behind these entrypoints (import from the package root):
66
+
67
+ - `startSubgraphProcessor(opts?)` — boots the block processor. LISTENs on `indexer:new_block`, matches sources, runs handlers, flushes writes inside a transaction, and emits outbox rows for matching subscriptions. Also boots the emitter worker.
68
+ - `processBlock(subgraph, name, height, opts?)` — single-block entry point used by catch-up, reindex, and tests.
69
+ - `catchUpSubgraph(def, name)` — drains pending blocks up to chain tip.
70
+ - `reindexSubgraph(def, opts)` — drop + rebuild schema tables from a start block. Breaking schema changes trigger this automatically on deploy.
71
+
72
+ ## Subscription emitter
73
+
74
+ Every row written through `ctx.insert()` / `ctx.upsert()` is atomically enqueued to `subscription_outbox` for every active subscription whose filter matches — inside the same transaction as the flush, so a processor crash rolls back both.
75
+
76
+ The emitter drains the outbox via `LISTEN subscriptions:new_outbox` and `FOR UPDATE SKIP LOCKED` batch claims. Live deliveries win a 90/10 split over replays. Each row dispatches through the format builder matching the subscription's `format` column (`standard-webhooks`, `inngest`, `trigger`, `cloudflare`, `cloudevents`, `raw`). Retries follow `30s → 2m → 10m → 1h → 6h → 24h → 72h`. Twenty consecutive failures trips the per-sub circuit breaker and pauses the subscription.
77
+
78
+ Delivery bodies and response previews land in `subscription_deliveries`. Rows whose retries exhaust mark `status = 'dead'` in the outbox and surface in the dashboard's dead-letter queue for one-click requeue.
79
+
80
+ ## Environment
81
+
82
+ | Variable | Default | Description |
83
+ | --- | --- | --- |
84
+ | `SECONDLAYER_EMIT_OUTBOX` | `true` | Set `false` to bypass outbox emission on every block (kill-switch). |
85
+ | `SECONDLAYER_ALLOW_PRIVATE_EGRESS` | `false` | Allow the emitter to deliver to private IP ranges (localhost, 10/8, 172.16/12, 192.168/16, link-local, v6 mapped). Leave off in production. |
86
+ | `SECONDLAYER_SECRETS_KEY` | — | 32-byte hex key for the AES-GCM envelope around subscription signing secrets. OSS mode auto-generates + persists to `.env.local`. |
87
+
88
+ ## Postgres + pool mode
89
+
90
+ The emitter holds a persistent `LISTEN` on `subscriptions:new_outbox` and `subscriptions:changed`, so it MUST connect through a session-mode pool. pgbouncer in transaction mode silently breaks it. Run the emitter against a session-mode port (`pool_mode = session`), or connect directly to Postgres as the default docker-compose setup does.
91
+
92
+ ## License
93
+
94
+ MIT
package/dist/src/index.js CHANGED
@@ -996,7 +996,7 @@ async function emitSubscriptionOutbox(tx, subgraphName, manifest, matcher, block
996
996
  subgraph_name: subgraphName,
997
997
  table_name: write.table,
998
998
  block_height: blockHeight,
999
- tx_id: write.pk.txId || null,
999
+ tx_id: write.pk.txId ?? null,
1000
1000
  row_pk: write.pk,
1001
1001
  event_type: eventType,
1002
1002
  payload: write.row,
@@ -1019,7 +1019,26 @@ function isPrimitive(v) {
1019
1019
  const t = typeof v;
1020
1020
  return t === "string" || t === "number" || t === "boolean";
1021
1021
  }
1022
- function coerceNumeric(v) {
1022
+ function coerceBigInt(v) {
1023
+ if (typeof v === "bigint")
1024
+ return v;
1025
+ if (typeof v === "number") {
1026
+ if (!Number.isFinite(v))
1027
+ return null;
1028
+ if (!Number.isInteger(v))
1029
+ return null;
1030
+ return BigInt(v);
1031
+ }
1032
+ if (typeof v === "string" && /^-?\d+$/.test(v)) {
1033
+ try {
1034
+ return BigInt(v);
1035
+ } catch {
1036
+ return null;
1037
+ }
1038
+ }
1039
+ return null;
1040
+ }
1041
+ function coerceFloat(v) {
1023
1042
  if (typeof v === "number" && Number.isFinite(v))
1024
1043
  return v;
1025
1044
  if (typeof v === "bigint")
@@ -1029,13 +1048,31 @@ function coerceNumeric(v) {
1029
1048
  }
1030
1049
  return null;
1031
1050
  }
1051
+ function compareNumeric(a, b) {
1052
+ const ba = coerceBigInt(a);
1053
+ const bb = coerceBigInt(b);
1054
+ if (ba !== null && bb !== null) {
1055
+ if (ba === bb)
1056
+ return 0;
1057
+ return ba > bb ? 1 : -1;
1058
+ }
1059
+ const fa = coerceFloat(a);
1060
+ const fb = coerceFloat(b);
1061
+ if (fa === null || fb === null)
1062
+ return null;
1063
+ if (fa === fb)
1064
+ return 0;
1065
+ return fa > fb ? 1 : -1;
1066
+ }
1032
1067
  function matchClause(rowValue, clause) {
1068
+ const rowIsPrimitive = isPrimitive(rowValue) || typeof rowValue === "bigint";
1033
1069
  if (isPrimitive(clause)) {
1034
- if (typeof clause === "number" || typeof rowValue === "number") {
1035
- const a = coerceNumeric(rowValue);
1036
- const b = coerceNumeric(clause);
1037
- if (a !== null && b !== null)
1038
- return a === b;
1070
+ if (!rowIsPrimitive)
1071
+ return false;
1072
+ if (typeof clause === "number" || typeof rowValue === "number" || typeof rowValue === "bigint") {
1073
+ const cmp = compareNumeric(rowValue, clause);
1074
+ if (cmp !== null)
1075
+ return cmp === 0;
1039
1076
  }
1040
1077
  return rowValue === clause || String(rowValue) === String(clause);
1041
1078
  }
@@ -1056,22 +1093,25 @@ function matchClause(rowValue, clause) {
1056
1093
  case "gte":
1057
1094
  case "lt":
1058
1095
  case "lte": {
1059
- const a = coerceNumeric(rowValue);
1060
- const b = coerceNumeric(c[op]);
1061
- if (a === null || b === null)
1096
+ if (!rowIsPrimitive)
1097
+ return false;
1098
+ const cmp = compareNumeric(rowValue, c[op]);
1099
+ if (cmp === null)
1062
1100
  return false;
1063
1101
  if (op === "gt")
1064
- return a > b;
1102
+ return cmp > 0;
1065
1103
  if (op === "gte")
1066
- return a >= b;
1104
+ return cmp >= 0;
1067
1105
  if (op === "lt")
1068
- return a < b;
1069
- return a <= b;
1106
+ return cmp < 0;
1107
+ return cmp <= 0;
1070
1108
  }
1071
1109
  case "in": {
1072
1110
  const list = c.in;
1073
1111
  if (!Array.isArray(list))
1074
1112
  return false;
1113
+ if (!rowIsPrimitive)
1114
+ return false;
1075
1115
  return list.some((item) => isPrimitive(item) && matchClause(rowValue, item));
1076
1116
  }
1077
1117
  default:
@@ -1254,7 +1294,12 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
1254
1294
  });
1255
1295
  }
1256
1296
  }
1257
- } catch {}
1297
+ } catch (err) {
1298
+ logger4.debug("Row count sample failed", {
1299
+ subgraph: subgraphName,
1300
+ error: err instanceof Error ? err.message : String(err)
1301
+ });
1302
+ }
1258
1303
  }
1259
1304
  return result;
1260
1305
  }
@@ -2044,5 +2089,5 @@ export {
2044
2089
  backfillSubgraph
2045
2090
  };
2046
2091
 
2047
- //# debugId=C453EF737BBEFDDD64756E2164756E21
2092
+ //# debugId=E6D35F38651A38BA64756E2164756E21
2048
2093
  //# sourceMappingURL=index.js.map