@secondlayer/subgraphs 3.20.0 → 3.22.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/dist/src/index.d.ts +188 -16
- package/dist/src/index.js +369 -41
- package/dist/src/index.js.map +12 -11
- package/dist/src/runtime/block-processor.d.ts +100 -13
- package/dist/src/runtime/block-processor.js +208 -22
- package/dist/src/runtime/block-processor.js.map +9 -8
- package/dist/src/runtime/catchup.d.ts +100 -13
- package/dist/src/runtime/catchup.js +208 -22
- package/dist/src/runtime/catchup.js.map +9 -8
- package/dist/src/runtime/context.d.ts +34 -8
- package/dist/src/runtime/context.js +25 -12
- package/dist/src/runtime/context.js.map +4 -4
- package/dist/src/runtime/processor.js +213 -22
- package/dist/src/runtime/processor.js.map +10 -9
- package/dist/src/runtime/reindex.d.ts +100 -13
- package/dist/src/runtime/reindex.js +208 -22
- package/dist/src/runtime/reindex.js.map +9 -8
- package/dist/src/runtime/reorg.d.ts +100 -13
- package/dist/src/runtime/reorg.js +213 -22
- package/dist/src/runtime/reorg.js.map +10 -9
- package/dist/src/runtime/replay.js +29 -6
- package/dist/src/runtime/replay.js.map +3 -3
- package/dist/src/runtime/runner.d.ts +125 -17
- package/dist/src/runtime/runner.js +100 -3
- package/dist/src/runtime/runner.js.map +5 -4
- package/dist/src/runtime/source-matcher.d.ts +98 -11
- package/dist/src/runtime/source-matcher.js +30 -6
- package/dist/src/runtime/source-matcher.js.map +3 -3
- package/dist/src/schema/index.d.ts +100 -13
- package/dist/src/schema/index.js +171 -20
- package/dist/src/schema/index.js.map +5 -5
- package/dist/src/service.js +213 -22
- package/dist/src/service.js.map +10 -9
- package/dist/src/testing/index.d.ts +620 -0
- package/dist/src/testing/index.js +1297 -0
- package/dist/src/testing/index.js.map +16 -0
- package/dist/src/triggers/index.d.ts +87 -9
- package/dist/src/types.d.ts +101 -14
- package/dist/src/validate.d.ts +136 -14
- package/dist/src/validate.js +158 -19
- package/dist/src/validate.js.map +3 -3
- package/package.json +7 -5
|
@@ -25,15 +25,24 @@ interface SubgraphRelation {
|
|
|
25
25
|
/** Target column(s) the fields point at (a uniqueKeys entry on the target). */
|
|
26
26
|
referencedColumns: string[];
|
|
27
27
|
}
|
|
28
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* Table definition within a subgraph schema.
|
|
30
|
+
*
|
|
31
|
+
* The array fields are `readonly` so a schema literal can be hoisted out of
|
|
32
|
+
* the `defineSubgraph()` call with `as const` (or {@link defineSchema}) and
|
|
33
|
+
* still typecheck — `as const` produces `readonly [readonly ["holder"]]`,
|
|
34
|
+
* which a mutable `string[][]` rejects. Without that, extracting a helper
|
|
35
|
+
* that takes `ctx` meant losing the entire typed surface, which is why the
|
|
36
|
+
* shipped starter reached for `ctx: any`.
|
|
37
|
+
*/
|
|
29
38
|
interface SubgraphTable {
|
|
30
39
|
columns: Record<string, SubgraphColumn>;
|
|
31
40
|
/** Composite indexes (each entry is an array of column names) */
|
|
32
|
-
indexes?: string[][];
|
|
41
|
+
indexes?: readonly (readonly string[])[];
|
|
33
42
|
/** Unique key constraints (each entry is an array of column names). Required for upsert. */
|
|
34
|
-
uniqueKeys?: string[][];
|
|
43
|
+
uniqueKeys?: readonly (readonly string[])[];
|
|
35
44
|
/** Foreign-key relations to other tables (for typed ORM joins). */
|
|
36
|
-
relations?: SubgraphRelation[];
|
|
45
|
+
relations?: readonly SubgraphRelation[];
|
|
37
46
|
}
|
|
38
47
|
/** Subgraph schema — maps table names to table definitions */
|
|
39
48
|
type SubgraphSchema = Record<string, SubgraphTable>;
|
|
@@ -68,6 +77,45 @@ interface StxLockFilter {
|
|
|
68
77
|
type TraitScope = {
|
|
69
78
|
trait?: string
|
|
70
79
|
};
|
|
80
|
+
/**
|
|
81
|
+
* Scope a source to a DYNAMIC address set discovered from another source's
|
|
82
|
+
* events, instead of a fixed contract list.
|
|
83
|
+
*
|
|
84
|
+
* The standard shape it unlocks: a router plus pools created after you
|
|
85
|
+
* deploy. `contractId` arrays cover a set you know at authoring time; a
|
|
86
|
+
* factory covers the set that grows. It is deliberately NOT tied to contract
|
|
87
|
+
* deployment — the address can come from any field of any event, so it also
|
|
88
|
+
* covers launchpad-minted tokens, DAO extension allowlists, and registry
|
|
89
|
+
* entries.
|
|
90
|
+
*
|
|
91
|
+
* ```ts
|
|
92
|
+
* sources: {
|
|
93
|
+
* registry: { type: "print_event", contractId: REGISTRY, topic: "pool-created" },
|
|
94
|
+
* swaps: {
|
|
95
|
+
* type: "print_event",
|
|
96
|
+
* topic: "swap",
|
|
97
|
+
* // every pool the registry has ever announced, including new ones
|
|
98
|
+
* factory: { from: "registry", field: "data.pool" },
|
|
99
|
+
* },
|
|
100
|
+
* }
|
|
101
|
+
* ```
|
|
102
|
+
*
|
|
103
|
+
* Two guarantees the runtime provides:
|
|
104
|
+
* - **Same-block ordering** — a contract discovered in block N receives its
|
|
105
|
+
* own block-N events. Discovery runs before matching, within the block.
|
|
106
|
+
* - **Reorg-scoped** — the discovered set is stamped with the block that
|
|
107
|
+
* revealed it and rolled back with everything else on a fork, so an address
|
|
108
|
+
* announced on an orphaned chain does not linger forever.
|
|
109
|
+
*/
|
|
110
|
+
interface FactoryScope {
|
|
111
|
+
factory?: {
|
|
112
|
+
/** Source name whose events reveal the addresses. */
|
|
113
|
+
from: string
|
|
114
|
+
/** Dotted path to the address on that source's payload
|
|
115
|
+
* (e.g. `"data.pool"`, `"contractId"`, `"data.token.id"`). */
|
|
116
|
+
field: string
|
|
117
|
+
};
|
|
118
|
+
}
|
|
71
119
|
/** FT event filters */
|
|
72
120
|
interface FtTransferFilter extends TraitScope {
|
|
73
121
|
type: "ft_transfer";
|
|
@@ -106,9 +154,19 @@ interface NftBurnFilter extends TraitScope {
|
|
|
106
154
|
sender?: string;
|
|
107
155
|
}
|
|
108
156
|
/** Contract event filters */
|
|
109
|
-
interface ContractCallFilter extends TraitScope {
|
|
157
|
+
interface ContractCallFilter extends TraitScope, FactoryScope {
|
|
110
158
|
type: "contract_call";
|
|
111
|
-
|
|
159
|
+
/**
|
|
160
|
+
* One contract id, or a SET of them (max 20) — the standard DeFi shape is
|
|
161
|
+
* a router plus N pools, which used to cost N near-identical sources and
|
|
162
|
+
* handlers, or the `"*"` catch-all that erases per-source typing. Payload
|
|
163
|
+
* types are identical per `type`, so one handler serves the set and
|
|
164
|
+
* `event.contractId` disambiguates.
|
|
165
|
+
*
|
|
166
|
+
* Supports `*` wildcards (e.g. `"SP1ABC….pool-*"`). Mutually exclusive
|
|
167
|
+
* with `trait`, which resolves its own set per block.
|
|
168
|
+
*/
|
|
169
|
+
contractId?: string | readonly string[];
|
|
112
170
|
functionName?: string;
|
|
113
171
|
caller?: string;
|
|
114
172
|
/**
|
|
@@ -124,18 +182,47 @@ interface ContractDeployFilter {
|
|
|
124
182
|
deployer?: string;
|
|
125
183
|
contractName?: string;
|
|
126
184
|
}
|
|
127
|
-
|
|
185
|
+
/**
|
|
186
|
+
* One declared field of a print payload.
|
|
187
|
+
*
|
|
188
|
+
* A bare {@link ColumnType} is a required scalar (`amount: "uint"`). The
|
|
189
|
+
* composite forms exist because real print payloads are not flat: BNS-V2
|
|
190
|
+
* emits `name` as a NESTED tuple, and a `prints` vocabulary that could only
|
|
191
|
+
* say `"jsonb"` is why a handler reading flat `data.name` type-checked,
|
|
192
|
+
* deployed, and then decoded to null on every event.
|
|
193
|
+
*
|
|
194
|
+
* - `{ type: F, optional: true }` — the KEY becomes optional on `event.data`
|
|
195
|
+
* (mirrors `always_present: false` in the inferred schema).
|
|
196
|
+
* - `{ tuple: { … } }` — a nested tuple, typed all the way down.
|
|
197
|
+
* - `{ list: F }` — a list of `F`.
|
|
198
|
+
*/
|
|
199
|
+
type PrintField = ColumnType | {
|
|
200
|
+
type: PrintField
|
|
201
|
+
optional: true
|
|
202
|
+
} | {
|
|
203
|
+
tuple: Record<string, PrintField>
|
|
204
|
+
} | {
|
|
205
|
+
list: PrintField
|
|
206
|
+
};
|
|
207
|
+
interface PrintEventFilter extends TraitScope, FactoryScope {
|
|
128
208
|
type: "print_event";
|
|
129
|
-
|
|
209
|
+
/** One contract id, or a set of them (max 20). Supports `*` wildcards.
|
|
210
|
+
* Mutually exclusive with `trait`. */
|
|
211
|
+
contractId?: string | readonly string[];
|
|
130
212
|
topic?: string;
|
|
131
213
|
/**
|
|
132
|
-
*
|
|
133
|
-
*
|
|
214
|
+
* Per-topic field schema. When declared, the handler's `event` is a
|
|
215
|
+
* discriminated union keyed by `topic` and `event.data` is typed per topic
|
|
134
216
|
* (e.g. `{ "completed-deposit": { amount: "uint", sender: "principal" } }`).
|
|
135
|
-
*
|
|
136
|
-
*
|
|
217
|
+
* Nested tuples, lists, and optional fields are expressible — see
|
|
218
|
+
* {@link PrintField}.
|
|
219
|
+
*
|
|
220
|
+
* Declaring `prints` also opts the source into RUNTIME validation: an
|
|
221
|
+
* event whose decoded payload does not match is skipped and logged rather
|
|
222
|
+
* than written as nulls (and the deploy-time field lint is promoted from
|
|
223
|
+
* a warning to an error).
|
|
137
224
|
*/
|
|
138
|
-
prints?: Record<string, Record<string,
|
|
225
|
+
prints?: Record<string, Record<string, PrintField>>;
|
|
139
226
|
}
|
|
140
227
|
/** All subgraph filter types — discriminated on `type` */
|
|
141
228
|
type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter;
|
|
@@ -216,6 +303,13 @@ interface SubgraphDefinition {
|
|
|
216
303
|
import { Database } from "@secondlayer/shared/db";
|
|
217
304
|
import { Kysely, Transaction } from "kysely";
|
|
218
305
|
type AnyDb = Kysely<Database> | Transaction<Database>;
|
|
306
|
+
interface WriteOp {
|
|
307
|
+
kind: "insert" | "update" | "delete" | "increment";
|
|
308
|
+
table: string;
|
|
309
|
+
data: Record<string, unknown>;
|
|
310
|
+
/** For update: SET clause. For increment: column → signed delta. */
|
|
311
|
+
set?: Record<string, unknown>;
|
|
312
|
+
}
|
|
219
313
|
interface FlushWrite {
|
|
220
314
|
op: "insert" | "update" | "delete";
|
|
221
315
|
table: string;
|
|
@@ -262,7 +356,10 @@ declare class SubgraphContext2 {
|
|
|
262
356
|
private readonly db;
|
|
263
357
|
private readonly pgSchemaName;
|
|
264
358
|
private readonly subgraphSchema;
|
|
265
|
-
|
|
359
|
+
/** Pending writes for this block. `protected` so the in-memory test
|
|
360
|
+
* context (`@secondlayer/subgraphs/testing`) can materialize them through
|
|
361
|
+
* the SAME overlay this class uses — never a second implementation. */
|
|
362
|
+
protected readonly ops: WriteOp[];
|
|
266
363
|
/**
|
|
267
364
|
* BYO data plane: handler writes land in a user-owned DB whose flush can't
|
|
268
365
|
* share the managed block transaction, so a crash replays the block. When
|
|
@@ -313,6 +410,13 @@ declare class SubgraphContext2 {
|
|
|
313
410
|
patchOrInsert(table: string, key: Record<string, unknown>, row: Record<string, ComputedValue>): Promise<void>;
|
|
314
411
|
/** Format a bigint amount with decimal places */
|
|
315
412
|
formatUnits(value: bigint, decimals: number): string;
|
|
413
|
+
/**
|
|
414
|
+
* Committed rows matching `where`, BEFORE the pending-ops overlay. The one
|
|
415
|
+
* seam a different backing store replaces (the in-memory test context);
|
|
416
|
+
* everything above it — validation, overlay, op queueing, flush semantics
|
|
417
|
+
* — stays here so the two can't diverge.
|
|
418
|
+
*/
|
|
419
|
+
protected readRows(table: string, where: Record<string, unknown>, limit?: number): Promise<Record<string, unknown>[]>;
|
|
316
420
|
findOne(table: string, where: Record<string, unknown>): Promise<Record<string, unknown> | null>;
|
|
317
421
|
findMany(table: string, where: Record<string, unknown>): Promise<Record<string, unknown>[]>;
|
|
318
422
|
/**
|
|
@@ -322,10 +426,10 @@ declare class SubgraphContext2 {
|
|
|
322
426
|
* apply by where-match. Overlaid rows synthesized from pending inserts
|
|
323
427
|
* lack DB-generated columns (_id, _created_at).
|
|
324
428
|
*/
|
|
325
|
-
|
|
326
|
-
|
|
429
|
+
protected overlayOne(table: string, where: Record<string, unknown>, dbRow: Record<string, unknown> | null): Record<string, unknown> | null;
|
|
430
|
+
protected overlayMany(table: string, where: Record<string, unknown>, dbRows: Record<string, unknown>[]): Record<string, unknown>[];
|
|
327
431
|
/** Apply one pending op to a candidate row state (null = row absent). */
|
|
328
|
-
|
|
432
|
+
protected applyOpToRow(op: WriteOp, row: Record<string, unknown> | null, where: Record<string, unknown>): Record<string, unknown> | null;
|
|
329
433
|
count(table: string, where?: Record<string, unknown>): Promise<number>;
|
|
330
434
|
sum(table: string, column: string, where?: Record<string, unknown>): Promise<bigint>;
|
|
331
435
|
min(table: string, column: string, where?: Record<string, unknown>): Promise<bigint | null>;
|
|
@@ -396,6 +500,10 @@ type EventRecord = {
|
|
|
396
500
|
interface RunResult {
|
|
397
501
|
processed: number;
|
|
398
502
|
errors: number;
|
|
503
|
+
/** Print events skipped because their decoded payload did not match the
|
|
504
|
+
* source's declared `prints` schema. Never an error: skipping keeps the
|
|
505
|
+
* block committable, which the checkpoint model requires. */
|
|
506
|
+
skipped?: number;
|
|
399
507
|
}
|
|
400
508
|
/**
|
|
401
509
|
* Build the named, ABI-decoded `event.input` for a contract_call source that
|
|
@@ -40,6 +40,87 @@ import {
|
|
|
40
40
|
deserializeCV as deserializeCV2,
|
|
41
41
|
toCamelCase
|
|
42
42
|
} from "@secondlayer/stacks/clarity";
|
|
43
|
+
|
|
44
|
+
// src/runtime/print-validate.ts
|
|
45
|
+
var COLUMN_TYPES = new Set([
|
|
46
|
+
"text",
|
|
47
|
+
"uint",
|
|
48
|
+
"int",
|
|
49
|
+
"principal",
|
|
50
|
+
"boolean",
|
|
51
|
+
"timestamp",
|
|
52
|
+
"jsonb"
|
|
53
|
+
]);
|
|
54
|
+
function isColumnType(field) {
|
|
55
|
+
return typeof field === "string" && COLUMN_TYPES.has(field);
|
|
56
|
+
}
|
|
57
|
+
function matchesField(field, value) {
|
|
58
|
+
if (isColumnType(field)) {
|
|
59
|
+
switch (field) {
|
|
60
|
+
case "uint":
|
|
61
|
+
case "int":
|
|
62
|
+
return typeof value === "bigint" || typeof value === "number";
|
|
63
|
+
case "boolean":
|
|
64
|
+
return typeof value === "boolean";
|
|
65
|
+
case "text":
|
|
66
|
+
case "principal":
|
|
67
|
+
case "timestamp":
|
|
68
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
|
|
69
|
+
case "jsonb":
|
|
70
|
+
return value !== undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (typeof field !== "object" || field === null)
|
|
74
|
+
return false;
|
|
75
|
+
if ("optional" in field) {
|
|
76
|
+
return value === undefined || value === null || matchesField(field.type, value);
|
|
77
|
+
}
|
|
78
|
+
if ("tuple" in field) {
|
|
79
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
return matchesTopic(field.tuple, value).ok;
|
|
83
|
+
}
|
|
84
|
+
if ("list" in field) {
|
|
85
|
+
return Array.isArray(value) && value.every((item) => matchesField(field.list, item));
|
|
86
|
+
}
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
function matchesTopic(declared, data) {
|
|
90
|
+
for (const [name, field] of Object.entries(declared)) {
|
|
91
|
+
const present = name in data;
|
|
92
|
+
const optional = typeof field === "object" && field !== null && "optional" in field;
|
|
93
|
+
if (!present) {
|
|
94
|
+
if (optional)
|
|
95
|
+
continue;
|
|
96
|
+
return { ok: false, reason: `missing declared field "${name}"` };
|
|
97
|
+
}
|
|
98
|
+
if (!matchesField(field, data[name])) {
|
|
99
|
+
return {
|
|
100
|
+
ok: false,
|
|
101
|
+
reason: `field "${name}" does not match its declared type (got ${describe(data[name])})`
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { ok: true };
|
|
106
|
+
}
|
|
107
|
+
function describe(value) {
|
|
108
|
+
if (value === null)
|
|
109
|
+
return "null";
|
|
110
|
+
if (Array.isArray(value))
|
|
111
|
+
return "array";
|
|
112
|
+
return typeof value;
|
|
113
|
+
}
|
|
114
|
+
function validatePrintPayload(prints, topic, data) {
|
|
115
|
+
if (!prints)
|
|
116
|
+
return { ok: true };
|
|
117
|
+
const declared = prints[topic];
|
|
118
|
+
if (!declared)
|
|
119
|
+
return { ok: true };
|
|
120
|
+
return matchesTopic(declared, data);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/runtime/runner.ts
|
|
43
124
|
var DEFAULT_ERROR_THRESHOLD = 50;
|
|
44
125
|
function camelCase(str) {
|
|
45
126
|
return str.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
@@ -284,6 +365,7 @@ function buildEventPayload(filter, tx, event) {
|
|
|
284
365
|
async function runHandlers(subgraph, matched, ctx, opts) {
|
|
285
366
|
let processed = 0;
|
|
286
367
|
let errors = 0;
|
|
368
|
+
let skipped = 0;
|
|
287
369
|
const threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;
|
|
288
370
|
const filterLookup = new Map;
|
|
289
371
|
if (!Array.isArray(subgraph.sources)) {
|
|
@@ -308,7 +390,7 @@ async function runHandlers(subgraph, matched, ctx, opts) {
|
|
|
308
390
|
errors,
|
|
309
391
|
threshold
|
|
310
392
|
});
|
|
311
|
-
return { processed, errors };
|
|
393
|
+
return { processed, errors, ...skipped > 0 ? { skipped } : {} };
|
|
312
394
|
}
|
|
313
395
|
const handler = subgraph.handlers[sourceName] ?? subgraph.handlers["*"] ?? null;
|
|
314
396
|
if (!handler) {
|
|
@@ -364,6 +446,21 @@ async function runHandlers(subgraph, matched, ctx, opts) {
|
|
|
364
446
|
if (event !== null && filter?.type === "print_event" && filter.topic && payload.topic !== filter.topic) {
|
|
365
447
|
continue;
|
|
366
448
|
}
|
|
449
|
+
if (event !== null && filter?.type === "print_event" && filter.prints) {
|
|
450
|
+
const printPayload = payload;
|
|
451
|
+
const verdict = validatePrintPayload(filter.prints, printPayload.topic ?? "", printPayload.data ?? {});
|
|
452
|
+
if (!verdict.ok) {
|
|
453
|
+
skipped++;
|
|
454
|
+
logger.warn("Print payload does not match declared prints schema", {
|
|
455
|
+
subgraph: subgraph.name,
|
|
456
|
+
sourceName,
|
|
457
|
+
topic: printPayload.topic,
|
|
458
|
+
txId: tx.tx_id,
|
|
459
|
+
reason: verdict.reason
|
|
460
|
+
});
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
367
464
|
await handler(payload, ctx);
|
|
368
465
|
processed++;
|
|
369
466
|
} catch (err) {
|
|
@@ -378,7 +475,7 @@ async function runHandlers(subgraph, matched, ctx, opts) {
|
|
|
378
475
|
});
|
|
379
476
|
}
|
|
380
477
|
}
|
|
381
|
-
return { processed, errors };
|
|
478
|
+
return { processed, errors, ...skipped > 0 ? { skipped } : {} };
|
|
382
479
|
}
|
|
383
480
|
export {
|
|
384
481
|
runHandlers,
|
|
@@ -386,5 +483,5 @@ export {
|
|
|
386
483
|
buildContractCallInput
|
|
387
484
|
};
|
|
388
485
|
|
|
389
|
-
//# debugId=
|
|
486
|
+
//# debugId=5FE61480B3DD60C064756E2164756E21
|
|
390
487
|
//# sourceMappingURL=runner.js.map
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/runtime/clarity.ts", "../src/runtime/runner.ts"],
|
|
3
|
+
"sources": ["../src/runtime/clarity.ts", "../src/runtime/runner.ts", "../src/runtime/print-validate.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import { cvToValue, deserializeCV } from \"@secondlayer/stacks/clarity\";\n\n/**\n * Decode a hex-encoded Clarity value to a JS object.\n * Returns original value on failure.\n */\nexport function decodeClarityValue(hex: string): unknown {\n\ttry {\n\t\tconst cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\tconst cv = deserializeCV(cleanHex);\n\t\treturn cvToValue(cv);\n\t} catch {\n\t\treturn hex;\n\t}\n}\n\n/**\n * Recursively decode all hex-encoded Clarity values in an object.\n * Any string starting with \"0x\" and longer than 10 chars is attempted.\n */\nexport function decodeEventData(data: unknown): unknown {\n\tif (typeof data === \"string\" && data.startsWith(\"0x\") && data.length > 10) {\n\t\treturn decodeClarityValue(data);\n\t}\n\n\tif (Array.isArray(data)) {\n\t\treturn data.map(decodeEventData);\n\t}\n\n\tif (typeof data === \"object\" && data !== null) {\n\t\tconst decoded: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(data)) {\n\t\t\tdecoded[key] = decodeEventData(value);\n\t\t}\n\t\treturn decoded;\n\t}\n\n\treturn data;\n}\n\n/**\n * Decode function args array (hex-encoded Clarity values).\n */\nexport function decodeFunctionArgs(args: string[]): unknown[] {\n\treturn args.map(decodeClarityValue);\n}\n",
|
|
6
|
-
"import { getErrorMessage } from \"@secondlayer/shared\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport {\n\tclarityValueToJS,\n\tdeserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport type {\n\tContractCallFilter,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n} from \"../types.ts\";\nimport { decodeClarityValue, decodeEventData } from \"./clarity.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport type { MatchedTx } from \"./source-matcher.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n\tprocessed: number;\n\terrors: number;\n}\n\n/** Convert kebab-case to camelCase: \"bitcoin-txid\" → \"bitcoinTxid\" */\nfunction camelCase(str: string): string {\n\treturn str.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());\n}\n\n/** Recursively camelize all object keys */\nfunction camelizeKeys(obj: unknown): unknown {\n\tif (obj === null || obj === undefined) return obj;\n\tif (typeof obj !== \"object\") return obj;\n\tif (Array.isArray(obj)) return obj.map(camelizeKeys);\n\tconst result: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n\t\tresult[camelCase(k)] = camelizeKeys(v);\n\t}\n\treturn result;\n}\n\n/**\n * Decode function_args (hex-encoded ClarityValues) to an array of JS values.\n * Returns decoded values via cvToValue.\n *\n * postgres.js returns JSONB columns as JSON strings rather than parsed objects —\n * parse the string first before checking Array.isArray.\n */\nfunction decodeFunctionArgs(args: unknown): unknown[] {\n\tlet parsed = args;\n\tif (typeof parsed === \"string\") {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.map((arg) => {\n\t\tif (typeof arg === \"string\") return decodeClarityValue(arg);\n\t\treturn arg;\n\t});\n}\n\n/**\n * Decode raw_result (hex-encoded Clarity return value) to JS value.\n */\nfunction decodeRawResult(raw: unknown): unknown {\n\tif (typeof raw === \"string\" && raw.length > 2) {\n\t\treturn decodeClarityValue(raw);\n\t}\n\treturn null;\n}\n\n/** Safely convert a value to BigInt. Handles string, number, bigint. Returns 0n on failure. */\nfunction safeBigInt(val: unknown): bigint {\n\tif (typeof val === \"bigint\") return val;\n\tif (typeof val === \"number\") return BigInt(val);\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn BigInt(val);\n\t\t} catch {\n\t\t\treturn 0n;\n\t\t}\n\t}\n\treturn 0n;\n}\n\n/**\n * Build the named, ABI-decoded `event.input` for a contract_call source that\n * declares an `abi`. Each function arg is decoded via `clarityValueToJS` so the\n * values match the types `ExtractFunctionArgs` promises (Uint8Array buffers,\n * camelCase tuple keys, wrapped responses). Returns undefined when no abi /\n * function match, leaving handlers with the positional `args` only.\n */\nexport function buildContractCallInput(\n\tfilter: ContractCallFilter,\n\ttx: MatchedTx[\"tx\"],\n): Record<string, unknown> | undefined {\n\tconst abi = filter.abi;\n\tconst fnName = tx.function_name;\n\tif (!abi || !fnName) return undefined;\n\tconst fn = abi.functions?.find((f) => f.name === fnName);\n\tif (!fn || !Array.isArray(fn.args)) return undefined;\n\n\tlet rawArgs: unknown = tx.function_args;\n\tif (typeof rawArgs === \"string\") {\n\t\ttry {\n\t\t\trawArgs = JSON.parse(rawArgs);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (!Array.isArray(rawArgs)) return undefined;\n\n\t// Call through a non-generic cast: clarityValueToJS<T> instantiates the deep\n\t// AbiToTS<T> conditional (TS2589) at runtime call sites. The static types\n\t// come from ContractCallPayload; here we only need its runtime reshaping.\n\tconst decodeArg = clarityValueToJS as unknown as (\n\t\ttype: unknown,\n\t\tcv: unknown,\n\t) => unknown;\n\tconst input: Record<string, unknown> = {};\n\tfn.args.forEach((arg, i) => {\n\t\tconst hex = rawArgs[i];\n\t\tif (typeof hex !== \"string\") return;\n\t\ttry {\n\t\t\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\t\tinput[toCamelCase(arg.name)] = decodeArg(arg.type, deserializeCV(clean));\n\t\t} catch {\n\t\t\t// Skip args that fail to decode rather than dropping the whole event.\n\t\t}\n\t});\n\treturn input;\n}\n\n/**\n * Build a typed event payload based on the source filter type.\n * Returns the payload the handler will receive.\n */\nexport function buildEventPayload(\n\tfilter: SubgraphFilter,\n\ttx: MatchedTx[\"tx\"],\n\tevent: MatchedTx[\"events\"][0] | null,\n): Record<string, unknown> {\n\tconst txMeta = {\n\t\ttxId: tx.tx_id,\n\t\tsender: tx.sender,\n\t\ttype: tx.type,\n\t\tstatus: tx.status,\n\t\tcontractId: tx.contract_id ?? null,\n\t\tfunctionName: tx.function_name ?? null,\n\t};\n\n\t// Decoded function args + result for contract_call payloads\n\tconst decodedArgs = decodeFunctionArgs(tx.function_args);\n\tconst decodedResult = decodeRawResult(tx.raw_result);\n\n\t// No event — tx-level match (contract_call or contract_deploy)\n\tif (!event) {\n\t\tswitch (filter.type) {\n\t\t\tcase \"contract_call\": {\n\t\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"contract_call\",\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\targs: decodedArgs,\n\t\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\t\tresult: decodedResult,\n\t\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"contract_deploy\":\n\t\t\t\treturn {\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tdeployer: tx.sender,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn { tx: txMeta };\n\t\t}\n\t}\n\n\t// Decode event data (Clarity values auto-unwrapped via cvToValue)\n\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\n\tswitch (filter.type) {\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── NFT events ──\n\t\t// tokenId decodes from the canonical hex (`raw_value`), not the node's\n\t\t// verbose serde-tagged `value` (`{UInt:223}`). The hex is source-\n\t\t// independent — present in both the DB tap and the Index API — so a\n\t\t// subgraph yields the same clean tokenId (e.g. 223n) on either source.\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tmemo: decoded.memo ?? \"\",\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\tlockedAddress: decoded.locked_address as string,\n\t\t\t\tlockedAmount: safeBigInt(decoded.locked_amount),\n\t\t\t\tunlockHeight: safeBigInt(decoded.unlock_height),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\t// Decode the print value from the canonical hex (`raw_value`) so it's\n\t\t\t// source-independent and clean — the node's verbose serde-tagged\n\t\t\t// `value` (e.g. `{Optional:{data:null}}`) is not reproducible from the\n\t\t\t// Index API and is no longer used (same rationale as nft tokenId).\n\t\t\t// decodeEventData skips hex ≤10 chars, so decode `raw_value` directly.\n\t\t\tconst rawHex = (event.data as Record<string, unknown> | null)?.raw_value;\n\t\t\tconst rawValue =\n\t\t\t\ttypeof rawHex === \"string\" && rawHex.startsWith(\"0x\")\n\t\t\t\t\t? decodeClarityValue(rawHex)\n\t\t\t\t\t: decoded.value;\n\t\t\t// Extract topic from decoded Clarity value (not raw event topic which is always \"print\")\n\t\t\tconst clarityObj =\n\t\t\t\trawValue && typeof rawValue === \"object\" && !Array.isArray(rawValue)\n\t\t\t\t\t? (rawValue as Record<string, unknown>)\n\t\t\t\t\t: null;\n\t\t\tconst topic = clarityObj?.topic\n\t\t\t\t? String(clarityObj.topic)\n\t\t\t\t: ((decoded.topic as string) ?? \"\");\n\t\t\t// Camelize remaining keys for developer convenience\n\t\t\tconst { topic: _, ...rest } = clarityObj ?? {};\n\t\t\tconst data =\n\t\t\t\tObject.keys(rest).length > 0\n\t\t\t\t\t? (camelizeKeys(rest) as Record<string, unknown>)\n\t\t\t\t\t: rawValue && typeof rawValue !== \"object\"\n\t\t\t\t\t\t? rawValue\n\t\t\t\t\t\t: {};\n\t\t\treturn {\n\t\t\t\tcontractId:\n\t\t\t\t\t(decoded.contract_identifier as string) ?? tx.contract_id ?? \"\",\n\t\t\t\ttopic,\n\t\t\t\tdata: data ?? {},\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract call (with events) ──\n\t\tcase \"contract_call\": {\n\t\t\t// Normalize the spread event Clarity `value` to the decoded canonical\n\t\t\t// (from `raw_value`), so it's identical whether the event came from the\n\t\t\t// DB tap or the Index API — the node's serde-tagged `value` is not\n\t\t\t// reproducible from Index (same rationale as nft tokenId / print).\n\t\t\tconst ccRawHex = (event.data as Record<string, unknown> | null)\n\t\t\t\t?.raw_value;\n\t\t\tconst normalized =\n\t\t\t\ttypeof ccRawHex === \"string\" && ccRawHex.startsWith(\"0x\")\n\t\t\t\t\t? { ...decoded, value: decodeClarityValue(ccRawHex) }\n\t\t\t\t\t: decoded;\n\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\treturn {\n\t\t\t\t...normalized,\n\t\t\t\ttype: \"contract_call\",\n\t\t\t\t_eventType: event.type,\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\tsender: tx.sender,\n\t\t\t\targs: decodedArgs,\n\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\tresult: decodedResult,\n\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\":\n\t\t\treturn {\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tdeployer: tx.sender,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\tdefault:\n\t\t\t// Fallback: spread decoded data with tx metadata\n\t\t\treturn {\n\t\t\t\t...decoded,\n\t\t\t\t_eventType: event.type,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t}\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceName from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n\tsubgraph: SubgraphDefinition,\n\tmatched: MatchedTx[],\n\tctx: SubgraphContext,\n\topts?: { errorThreshold?: number },\n): Promise<RunResult> {\n\tlet processed = 0;\n\tlet errors = 0;\n\tconst threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n\t// Build filter lookup from sources (supports both array and named object)\n\tconst filterLookup = new Map<string, SubgraphFilter>();\n\tif (!Array.isArray(subgraph.sources)) {\n\t\tfor (const [name, filter] of Object.entries(\n\t\t\tsubgraph.sources as Record<string, SubgraphFilter>,\n\t\t)) {\n\t\t\tfilterLookup.set(name, filter);\n\t\t}\n\t}\n\n\t// Flatten matches to per-event dispatch units and sort into CHAIN order\n\t// (tx_index, then event_index; tx-level matches first within their tx).\n\t// The matcher groups results by source, so without this a block's mints\n\t// all run before (or after) its transfers — a debit could apply before\n\t// the same block's funding credit, which on-chain ordering forbids. Chain\n\t// order makes per-statement invariants (e.g. uint CHECK >= 0) sound.\n\ttype DispatchUnit = {\n\t\ttx: MatchedTx[\"tx\"];\n\t\tsourceName: string;\n\t\tevent: MatchedTx[\"events\"][0] | null;\n\t};\n\tconst units: DispatchUnit[] = [];\n\tfor (const { tx, events, sourceName } of matched) {\n\t\tif (events.length === 0) {\n\t\t\tunits.push({ tx, sourceName, event: null });\n\t\t} else {\n\t\t\tfor (const event of events) units.push({ tx, sourceName, event });\n\t\t}\n\t}\n\tunits.sort(\n\t\t(a, b) =>\n\t\t\t(a.tx.tx_index ?? 0) - (b.tx.tx_index ?? 0) ||\n\t\t\t(a.event?.event_index ?? -1) - (b.event?.event_index ?? -1),\n\t);\n\n\tfor (const { tx, event, sourceName } of units) {\n\t\tif (errors >= threshold) {\n\t\t\tlogger.error(\n\t\t\t\t\"Subgraph error threshold reached, skipping remaining events\",\n\t\t\t\t{\n\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\terrors,\n\t\t\t\t\tthreshold,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { processed, errors };\n\t\t}\n\n\t\tconst handler =\n\t\t\tsubgraph.handlers[sourceName] ?? subgraph.handlers[\"*\"] ?? null;\n\t\tif (!handler) {\n\t\t\tlogger.warn(\"No handler found for source\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tctx.setTx({\n\t\t\ttxId: tx.tx_id,\n\t\t\tsender: tx.sender,\n\t\t\ttype: tx.type,\n\t\t\tstatus: tx.status,\n\t\t\tcontractId: tx.contract_id ?? null,\n\t\t\tfunctionName: tx.function_name ?? null,\n\t\t});\n\n\t\tconst filter = filterLookup.get(sourceName);\n\n\t\t// Checkpoint the ops queue: a handler that throws mid-way must\n\t\t// contribute nothing — a partial flush (e.g. a debit without its\n\t\t// credit) silently corrupts accumulator tables (fix-f040 B6).\n\t\tconst checkpoint = ctx.opsCheckpoint();\n\t\ttry {\n\t\t\tlet payload: Record<string, unknown>;\n\t\t\tif (event === null) {\n\t\t\t\t// Tx-level match (contract_call / contract_deploy)\n\t\t\t\tpayload = filter\n\t\t\t\t\t? buildEventPayload(filter, tx, null)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttx: {\n\t\t\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t} else if (filter) {\n\t\t\t\tpayload = buildEventPayload(filter, tx, event);\n\t\t\t} else {\n\t\t\t\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\t\t\t\tpayload = {\n\t\t\t\t\t...decoded,\n\t\t\t\t\t_eventId: event.id,\n\t\t\t\t\t_eventType: event.type,\n\t\t\t\t\t_eventIndex: event.event_index,\n\t\t\t\t\ttx: {\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Post-decode topic filter for print_event — source-matcher defers this\n\t\t\t// because data.value is raw hex at match time; apply it now after decode.\n\t\t\tif (\n\t\t\t\tevent !== null &&\n\t\t\t\tfilter?.type === \"print_event\" &&\n\t\t\t\tfilter.topic &&\n\t\t\t\tpayload.topic !== filter.topic\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tawait handler(payload, ctx);\n\t\t\tprocessed++;\n\t\t} catch (err) {\n\t\t\tctx.rollbackTo(checkpoint);\n\t\t\terrors++;\n\t\t\tlogger.error(\"Subgraph handler error\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t...(event !== null ? { eventId: event.id, eventType: event.type } : {}),\n\t\t\t\terror: getErrorMessage(err),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { processed, errors };\n}\n"
|
|
6
|
+
"import { getErrorMessage } from \"@secondlayer/shared\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport {\n\tclarityValueToJS,\n\tdeserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport type {\n\tContractCallFilter,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n} from \"../types.ts\";\nimport { decodeClarityValue, decodeEventData } from \"./clarity.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport { validatePrintPayload } from \"./print-validate.ts\";\nimport type { MatchedTx } from \"./source-matcher.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n\tprocessed: number;\n\terrors: number;\n\t/** Print events skipped because their decoded payload did not match the\n\t * source's declared `prints` schema. Never an error: skipping keeps the\n\t * block committable, which the checkpoint model requires. */\n\tskipped?: number;\n}\n\n/** Convert kebab-case to camelCase: \"bitcoin-txid\" → \"bitcoinTxid\" */\nfunction camelCase(str: string): string {\n\treturn str.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());\n}\n\n/** Recursively camelize all object keys */\nfunction camelizeKeys(obj: unknown): unknown {\n\tif (obj === null || obj === undefined) return obj;\n\tif (typeof obj !== \"object\") return obj;\n\tif (Array.isArray(obj)) return obj.map(camelizeKeys);\n\tconst result: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n\t\tresult[camelCase(k)] = camelizeKeys(v);\n\t}\n\treturn result;\n}\n\n/**\n * Decode function_args (hex-encoded ClarityValues) to an array of JS values.\n * Returns decoded values via cvToValue.\n *\n * postgres.js returns JSONB columns as JSON strings rather than parsed objects —\n * parse the string first before checking Array.isArray.\n */\nfunction decodeFunctionArgs(args: unknown): unknown[] {\n\tlet parsed = args;\n\tif (typeof parsed === \"string\") {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.map((arg) => {\n\t\tif (typeof arg === \"string\") return decodeClarityValue(arg);\n\t\treturn arg;\n\t});\n}\n\n/**\n * Decode raw_result (hex-encoded Clarity return value) to JS value.\n */\nfunction decodeRawResult(raw: unknown): unknown {\n\tif (typeof raw === \"string\" && raw.length > 2) {\n\t\treturn decodeClarityValue(raw);\n\t}\n\treturn null;\n}\n\n/** Safely convert a value to BigInt. Handles string, number, bigint. Returns 0n on failure. */\nfunction safeBigInt(val: unknown): bigint {\n\tif (typeof val === \"bigint\") return val;\n\tif (typeof val === \"number\") return BigInt(val);\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn BigInt(val);\n\t\t} catch {\n\t\t\treturn 0n;\n\t\t}\n\t}\n\treturn 0n;\n}\n\n/**\n * Build the named, ABI-decoded `event.input` for a contract_call source that\n * declares an `abi`. Each function arg is decoded via `clarityValueToJS` so the\n * values match the types `ExtractFunctionArgs` promises (Uint8Array buffers,\n * camelCase tuple keys, wrapped responses). Returns undefined when no abi /\n * function match, leaving handlers with the positional `args` only.\n */\nexport function buildContractCallInput(\n\tfilter: ContractCallFilter,\n\ttx: MatchedTx[\"tx\"],\n): Record<string, unknown> | undefined {\n\tconst abi = filter.abi;\n\tconst fnName = tx.function_name;\n\tif (!abi || !fnName) return undefined;\n\tconst fn = abi.functions?.find((f) => f.name === fnName);\n\tif (!fn || !Array.isArray(fn.args)) return undefined;\n\n\tlet rawArgs: unknown = tx.function_args;\n\tif (typeof rawArgs === \"string\") {\n\t\ttry {\n\t\t\trawArgs = JSON.parse(rawArgs);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (!Array.isArray(rawArgs)) return undefined;\n\n\t// Call through a non-generic cast: clarityValueToJS<T> instantiates the deep\n\t// AbiToTS<T> conditional (TS2589) at runtime call sites. The static types\n\t// come from ContractCallPayload; here we only need its runtime reshaping.\n\tconst decodeArg = clarityValueToJS as unknown as (\n\t\ttype: unknown,\n\t\tcv: unknown,\n\t) => unknown;\n\tconst input: Record<string, unknown> = {};\n\tfn.args.forEach((arg, i) => {\n\t\tconst hex = rawArgs[i];\n\t\tif (typeof hex !== \"string\") return;\n\t\ttry {\n\t\t\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\t\tinput[toCamelCase(arg.name)] = decodeArg(arg.type, deserializeCV(clean));\n\t\t} catch {\n\t\t\t// Skip args that fail to decode rather than dropping the whole event.\n\t\t}\n\t});\n\treturn input;\n}\n\n/**\n * Build a typed event payload based on the source filter type.\n * Returns the payload the handler will receive.\n */\nexport function buildEventPayload(\n\tfilter: SubgraphFilter,\n\ttx: MatchedTx[\"tx\"],\n\tevent: MatchedTx[\"events\"][0] | null,\n): Record<string, unknown> {\n\tconst txMeta = {\n\t\ttxId: tx.tx_id,\n\t\tsender: tx.sender,\n\t\ttype: tx.type,\n\t\tstatus: tx.status,\n\t\tcontractId: tx.contract_id ?? null,\n\t\tfunctionName: tx.function_name ?? null,\n\t};\n\n\t// Decoded function args + result for contract_call payloads\n\tconst decodedArgs = decodeFunctionArgs(tx.function_args);\n\tconst decodedResult = decodeRawResult(tx.raw_result);\n\n\t// No event — tx-level match (contract_call or contract_deploy)\n\tif (!event) {\n\t\tswitch (filter.type) {\n\t\t\tcase \"contract_call\": {\n\t\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"contract_call\",\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\targs: decodedArgs,\n\t\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\t\tresult: decodedResult,\n\t\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"contract_deploy\":\n\t\t\t\treturn {\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tdeployer: tx.sender,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn { tx: txMeta };\n\t\t}\n\t}\n\n\t// Decode event data (Clarity values auto-unwrapped via cvToValue)\n\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\n\tswitch (filter.type) {\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── NFT events ──\n\t\t// tokenId decodes from the canonical hex (`raw_value`), not the node's\n\t\t// verbose serde-tagged `value` (`{UInt:223}`). The hex is source-\n\t\t// independent — present in both the DB tap and the Index API — so a\n\t\t// subgraph yields the same clean tokenId (e.g. 223n) on either source.\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tmemo: decoded.memo ?? \"\",\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\tlockedAddress: decoded.locked_address as string,\n\t\t\t\tlockedAmount: safeBigInt(decoded.locked_amount),\n\t\t\t\tunlockHeight: safeBigInt(decoded.unlock_height),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\t// Decode the print value from the canonical hex (`raw_value`) so it's\n\t\t\t// source-independent and clean — the node's verbose serde-tagged\n\t\t\t// `value` (e.g. `{Optional:{data:null}}`) is not reproducible from the\n\t\t\t// Index API and is no longer used (same rationale as nft tokenId).\n\t\t\t// decodeEventData skips hex ≤10 chars, so decode `raw_value` directly.\n\t\t\tconst rawHex = (event.data as Record<string, unknown> | null)?.raw_value;\n\t\t\tconst rawValue =\n\t\t\t\ttypeof rawHex === \"string\" && rawHex.startsWith(\"0x\")\n\t\t\t\t\t? decodeClarityValue(rawHex)\n\t\t\t\t\t: decoded.value;\n\t\t\t// Extract topic from decoded Clarity value (not raw event topic which is always \"print\")\n\t\t\tconst clarityObj =\n\t\t\t\trawValue && typeof rawValue === \"object\" && !Array.isArray(rawValue)\n\t\t\t\t\t? (rawValue as Record<string, unknown>)\n\t\t\t\t\t: null;\n\t\t\tconst topic = clarityObj?.topic\n\t\t\t\t? String(clarityObj.topic)\n\t\t\t\t: ((decoded.topic as string) ?? \"\");\n\t\t\t// Camelize remaining keys for developer convenience\n\t\t\tconst { topic: _, ...rest } = clarityObj ?? {};\n\t\t\tconst data =\n\t\t\t\tObject.keys(rest).length > 0\n\t\t\t\t\t? (camelizeKeys(rest) as Record<string, unknown>)\n\t\t\t\t\t: rawValue && typeof rawValue !== \"object\"\n\t\t\t\t\t\t? rawValue\n\t\t\t\t\t\t: {};\n\t\t\treturn {\n\t\t\t\tcontractId:\n\t\t\t\t\t(decoded.contract_identifier as string) ?? tx.contract_id ?? \"\",\n\t\t\t\ttopic,\n\t\t\t\tdata: data ?? {},\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract call (with events) ──\n\t\tcase \"contract_call\": {\n\t\t\t// Normalize the spread event Clarity `value` to the decoded canonical\n\t\t\t// (from `raw_value`), so it's identical whether the event came from the\n\t\t\t// DB tap or the Index API — the node's serde-tagged `value` is not\n\t\t\t// reproducible from Index (same rationale as nft tokenId / print).\n\t\t\tconst ccRawHex = (event.data as Record<string, unknown> | null)\n\t\t\t\t?.raw_value;\n\t\t\tconst normalized =\n\t\t\t\ttypeof ccRawHex === \"string\" && ccRawHex.startsWith(\"0x\")\n\t\t\t\t\t? { ...decoded, value: decodeClarityValue(ccRawHex) }\n\t\t\t\t\t: decoded;\n\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\treturn {\n\t\t\t\t...normalized,\n\t\t\t\ttype: \"contract_call\",\n\t\t\t\t_eventType: event.type,\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\tsender: tx.sender,\n\t\t\t\targs: decodedArgs,\n\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\tresult: decodedResult,\n\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\":\n\t\t\treturn {\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tdeployer: tx.sender,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\tdefault:\n\t\t\t// Fallback: spread decoded data with tx metadata\n\t\t\treturn {\n\t\t\t\t...decoded,\n\t\t\t\t_eventType: event.type,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t}\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceName from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n\tsubgraph: SubgraphDefinition,\n\tmatched: MatchedTx[],\n\tctx: SubgraphContext,\n\topts?: { errorThreshold?: number },\n): Promise<RunResult> {\n\tlet processed = 0;\n\tlet errors = 0;\n\tlet skipped = 0;\n\tconst threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n\t// Build filter lookup from sources (supports both array and named object)\n\tconst filterLookup = new Map<string, SubgraphFilter>();\n\tif (!Array.isArray(subgraph.sources)) {\n\t\tfor (const [name, filter] of Object.entries(\n\t\t\tsubgraph.sources as Record<string, SubgraphFilter>,\n\t\t)) {\n\t\t\tfilterLookup.set(name, filter);\n\t\t}\n\t}\n\n\t// Flatten matches to per-event dispatch units and sort into CHAIN order\n\t// (tx_index, then event_index; tx-level matches first within their tx).\n\t// The matcher groups results by source, so without this a block's mints\n\t// all run before (or after) its transfers — a debit could apply before\n\t// the same block's funding credit, which on-chain ordering forbids. Chain\n\t// order makes per-statement invariants (e.g. uint CHECK >= 0) sound.\n\ttype DispatchUnit = {\n\t\ttx: MatchedTx[\"tx\"];\n\t\tsourceName: string;\n\t\tevent: MatchedTx[\"events\"][0] | null;\n\t};\n\tconst units: DispatchUnit[] = [];\n\tfor (const { tx, events, sourceName } of matched) {\n\t\tif (events.length === 0) {\n\t\t\tunits.push({ tx, sourceName, event: null });\n\t\t} else {\n\t\t\tfor (const event of events) units.push({ tx, sourceName, event });\n\t\t}\n\t}\n\tunits.sort(\n\t\t(a, b) =>\n\t\t\t(a.tx.tx_index ?? 0) - (b.tx.tx_index ?? 0) ||\n\t\t\t(a.event?.event_index ?? -1) - (b.event?.event_index ?? -1),\n\t);\n\n\tfor (const { tx, event, sourceName } of units) {\n\t\tif (errors >= threshold) {\n\t\t\tlogger.error(\n\t\t\t\t\"Subgraph error threshold reached, skipping remaining events\",\n\t\t\t\t{\n\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\terrors,\n\t\t\t\t\tthreshold,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n\t\t}\n\n\t\tconst handler =\n\t\t\tsubgraph.handlers[sourceName] ?? subgraph.handlers[\"*\"] ?? null;\n\t\tif (!handler) {\n\t\t\tlogger.warn(\"No handler found for source\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tctx.setTx({\n\t\t\ttxId: tx.tx_id,\n\t\t\tsender: tx.sender,\n\t\t\ttype: tx.type,\n\t\t\tstatus: tx.status,\n\t\t\tcontractId: tx.contract_id ?? null,\n\t\t\tfunctionName: tx.function_name ?? null,\n\t\t});\n\n\t\tconst filter = filterLookup.get(sourceName);\n\n\t\t// Checkpoint the ops queue: a handler that throws mid-way must\n\t\t// contribute nothing — a partial flush (e.g. a debit without its\n\t\t// credit) silently corrupts accumulator tables (fix-f040 B6).\n\t\tconst checkpoint = ctx.opsCheckpoint();\n\t\ttry {\n\t\t\tlet payload: Record<string, unknown>;\n\t\t\tif (event === null) {\n\t\t\t\t// Tx-level match (contract_call / contract_deploy)\n\t\t\t\tpayload = filter\n\t\t\t\t\t? buildEventPayload(filter, tx, null)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttx: {\n\t\t\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t} else if (filter) {\n\t\t\t\tpayload = buildEventPayload(filter, tx, event);\n\t\t\t} else {\n\t\t\t\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\t\t\t\tpayload = {\n\t\t\t\t\t...decoded,\n\t\t\t\t\t_eventId: event.id,\n\t\t\t\t\t_eventType: event.type,\n\t\t\t\t\t_eventIndex: event.event_index,\n\t\t\t\t\ttx: {\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Post-decode topic filter for print_event — source-matcher defers this\n\t\t\t// because data.value is raw hex at match time; apply it now after decode.\n\t\t\tif (\n\t\t\t\tevent !== null &&\n\t\t\t\tfilter?.type === \"print_event\" &&\n\t\t\t\tfilter.topic &&\n\t\t\t\tpayload.topic !== filter.topic\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Declared `prints` is the developer's stated payload shape, so a\n\t\t\t// mismatch is a real defect (a contract upgrade, or a declaration\n\t\t\t// that never matched — the bns-names class, where every event\n\t\t\t// decoded to null for an entire deploy). Skip + log rather than\n\t\t\t// write nulls; never throw, which would wedge the block.\n\t\t\tif (event !== null && filter?.type === \"print_event\" && filter.prints) {\n\t\t\t\tconst printPayload = payload as {\n\t\t\t\t\ttopic?: string;\n\t\t\t\t\tdata?: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst verdict = validatePrintPayload(\n\t\t\t\t\tfilter.prints,\n\t\t\t\t\tprintPayload.topic ?? \"\",\n\t\t\t\t\tprintPayload.data ?? {},\n\t\t\t\t);\n\t\t\t\tif (!verdict.ok) {\n\t\t\t\t\tskipped++;\n\t\t\t\t\tlogger.warn(\"Print payload does not match declared prints schema\", {\n\t\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\ttopic: printPayload.topic,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: verdict.reason,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait handler(payload, ctx);\n\t\t\tprocessed++;\n\t\t} catch (err) {\n\t\t\tctx.rollbackTo(checkpoint);\n\t\t\terrors++;\n\t\t\tlogger.error(\"Subgraph handler error\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t...(event !== null ? { eventId: event.id, eventType: event.type } : {}),\n\t\t\t\terror: getErrorMessage(err),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n}\n",
|
|
7
|
+
"import type { ColumnType, PrintField } from \"../types.ts\";\n\n/**\n * Runtime validation of a decoded print payload against a source's declared\n * `prints` schema.\n *\n * Declaring `prints` is the opt-in that makes strictness safe: the developer\n * has stated the shape, so a mismatch is a real defect (a contract upgrade,\n * or a hand-written declaration that never matched — the bns-names class of\n * bug, where a handler read flat `data.name` while BNS-V2 emitted a nested\n * tuple, and every event silently decoded to null for a whole deploy).\n *\n * Failure mode is SKIP + LOG, never throw: throwing would fail the block, and\n * a poisoned block that can never advance is incompatible with the\n * checkpoint model. One bad event is dropped and counted; the rest of the\n * block commits.\n */\n\nconst COLUMN_TYPES = new Set<string>([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\nfunction isColumnType(field: PrintField): field is ColumnType {\n\treturn typeof field === \"string\" && COLUMN_TYPES.has(field);\n}\n\n/** Does a decoded value match one declared field? */\nfunction matchesField(field: PrintField, value: unknown): boolean {\n\tif (isColumnType(field)) {\n\t\tswitch (field) {\n\t\t\tcase \"uint\":\n\t\t\tcase \"int\":\n\t\t\t\treturn typeof value === \"bigint\" || typeof value === \"number\";\n\t\t\tcase \"boolean\":\n\t\t\t\treturn typeof value === \"boolean\";\n\t\t\tcase \"text\":\n\t\t\tcase \"principal\":\n\t\t\tcase \"timestamp\":\n\t\t\t\t// Buffers decode to strings; principals too. Accept any scalar the\n\t\t\t\t// decoder can render, but reject objects/arrays.\n\t\t\t\treturn (\n\t\t\t\t\ttypeof value === \"string\" ||\n\t\t\t\t\ttypeof value === \"number\" ||\n\t\t\t\t\ttypeof value === \"bigint\"\n\t\t\t\t);\n\t\t\tcase \"jsonb\":\n\t\t\t\t// Deliberately permissive: `jsonb` is the \"shape unknown\" escape.\n\t\t\t\treturn value !== undefined;\n\t\t}\n\t}\n\tif (typeof field !== \"object\" || field === null) return false;\n\tif (\"optional\" in field) {\n\t\treturn (\n\t\t\tvalue === undefined || value === null || matchesField(field.type, value)\n\t\t);\n\t}\n\tif (\"tuple\" in field) {\n\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn matchesTopic(field.tuple, value as Record<string, unknown>).ok;\n\t}\n\tif (\"list\" in field) {\n\t\treturn (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.every((item) => matchesField(field.list, item))\n\t\t);\n\t}\n\treturn false;\n}\n\nexport type PrintValidationResult =\n\t| { ok: true }\n\t| { ok: false; reason: string };\n\n/** Validate a decoded payload object against one topic's declared fields. */\nexport function matchesTopic(\n\tdeclared: Record<string, PrintField>,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tfor (const [name, field] of Object.entries(declared)) {\n\t\tconst present = name in data;\n\t\tconst optional =\n\t\t\ttypeof field === \"object\" && field !== null && \"optional\" in field;\n\t\tif (!present) {\n\t\t\tif (optional) continue;\n\t\t\treturn { ok: false, reason: `missing declared field \"${name}\"` };\n\t\t}\n\t\tif (!matchesField(field, data[name])) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: `field \"${name}\" does not match its declared type (got ${describe(data[name])})`,\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction describe(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"array\";\n\treturn typeof value;\n}\n\n/**\n * Validate one decoded print event against a source's `prints` declaration.\n * Returns `{ ok: true }` when no declaration covers this topic (undeclared\n * topics are not the developer's stated contract, so they pass through).\n */\nexport function validatePrintPayload(\n\tprints: Record<string, Record<string, PrintField>> | undefined,\n\ttopic: string,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tif (!prints) return { ok: true };\n\tconst declared = prints[topic];\n\tif (!declared) return { ok: true };\n\treturn matchesTopic(declared, data);\n}\n"
|
|
7
8
|
],
|
|
8
|
-
"mappings": ";;;;AAAA;AAMO,SAAS,kBAAkB,CAAC,KAAsB;AAAA,EACxD,IAAI;AAAA,IACH,MAAM,WAAW,IAAI,WAAW,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI;AAAA,IACvD,MAAM,KAAK,cAAc,QAAQ;AAAA,IACjC,OAAO,UAAU,EAAE;AAAA,IAClB,MAAM;AAAA,IACP,OAAO;AAAA;AAAA;AAQF,SAAS,eAAe,CAAC,MAAwB;AAAA,EACvD,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,IAAI,KAAK,KAAK,SAAS,IAAI;AAAA,IAC1E,OAAO,mBAAmB,IAAI;AAAA,EAC/B;AAAA,EAEA,IAAI,MAAM,QAAQ,IAAI,GAAG;AAAA,IACxB,OAAO,KAAK,IAAI,eAAe;AAAA,EAChC;AAAA,EAEA,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM;AAAA,IAC9C,MAAM,UAAmC,CAAC;AAAA,IAC1C,YAAY,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;AAAA,MAChD,QAAQ,OAAO,gBAAgB,KAAK;AAAA,IACrC;AAAA,IACA,OAAO;AAAA,EACR;AAAA,EAEA,OAAO;AAAA;AAMD,SAAS,kBAAkB,CAAC,MAA2B;AAAA,EAC7D,OAAO,KAAK,IAAI,kBAAkB;AAAA;;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A,OAAO,MAAM,0BAA0B;AAAA,QACtC,UAAU,SAAS;AAAA,QACnB;AAAA,QACA,MAAM,GAAG;AAAA,WACL,UAAU,OAAO,EAAE,SAAS,MAAM,IAAI,WAAW,MAAM,KAAK,IAAI,CAAC;AAAA,QACrE,OAAO,gBAAgB,GAAG;AAAA,MAC3B,CAAC;AAAA;AAAA,EAEH;AAAA,EAEA,OAAO,EAAE,WAAW,WAAY,UAAU,IAAI,EAAE,QAAQ,IAAI,CAAC,EAAG;AAAA;",
|
|
10
|
+
"debugId": "5FE61480B3DD60C064756E2164756E21",
|
|
10
11
|
"names": []
|
|
11
12
|
}
|
|
@@ -32,6 +32,45 @@ interface StxLockFilter {
|
|
|
32
32
|
type TraitScope = {
|
|
33
33
|
trait?: string
|
|
34
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Scope a source to a DYNAMIC address set discovered from another source's
|
|
37
|
+
* events, instead of a fixed contract list.
|
|
38
|
+
*
|
|
39
|
+
* The standard shape it unlocks: a router plus pools created after you
|
|
40
|
+
* deploy. `contractId` arrays cover a set you know at authoring time; a
|
|
41
|
+
* factory covers the set that grows. It is deliberately NOT tied to contract
|
|
42
|
+
* deployment — the address can come from any field of any event, so it also
|
|
43
|
+
* covers launchpad-minted tokens, DAO extension allowlists, and registry
|
|
44
|
+
* entries.
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* sources: {
|
|
48
|
+
* registry: { type: "print_event", contractId: REGISTRY, topic: "pool-created" },
|
|
49
|
+
* swaps: {
|
|
50
|
+
* type: "print_event",
|
|
51
|
+
* topic: "swap",
|
|
52
|
+
* // every pool the registry has ever announced, including new ones
|
|
53
|
+
* factory: { from: "registry", field: "data.pool" },
|
|
54
|
+
* },
|
|
55
|
+
* }
|
|
56
|
+
* ```
|
|
57
|
+
*
|
|
58
|
+
* Two guarantees the runtime provides:
|
|
59
|
+
* - **Same-block ordering** — a contract discovered in block N receives its
|
|
60
|
+
* own block-N events. Discovery runs before matching, within the block.
|
|
61
|
+
* - **Reorg-scoped** — the discovered set is stamped with the block that
|
|
62
|
+
* revealed it and rolled back with everything else on a fork, so an address
|
|
63
|
+
* announced on an orphaned chain does not linger forever.
|
|
64
|
+
*/
|
|
65
|
+
interface FactoryScope {
|
|
66
|
+
factory?: {
|
|
67
|
+
/** Source name whose events reveal the addresses. */
|
|
68
|
+
from: string
|
|
69
|
+
/** Dotted path to the address on that source's payload
|
|
70
|
+
* (e.g. `"data.pool"`, `"contractId"`, `"data.token.id"`). */
|
|
71
|
+
field: string
|
|
72
|
+
};
|
|
73
|
+
}
|
|
35
74
|
/** FT event filters */
|
|
36
75
|
interface FtTransferFilter extends TraitScope {
|
|
37
76
|
type: "ft_transfer";
|
|
@@ -70,9 +109,19 @@ interface NftBurnFilter extends TraitScope {
|
|
|
70
109
|
sender?: string;
|
|
71
110
|
}
|
|
72
111
|
/** Contract event filters */
|
|
73
|
-
interface ContractCallFilter extends TraitScope {
|
|
112
|
+
interface ContractCallFilter extends TraitScope, FactoryScope {
|
|
74
113
|
type: "contract_call";
|
|
75
|
-
|
|
114
|
+
/**
|
|
115
|
+
* One contract id, or a SET of them (max 20) — the standard DeFi shape is
|
|
116
|
+
* a router plus N pools, which used to cost N near-identical sources and
|
|
117
|
+
* handlers, or the `"*"` catch-all that erases per-source typing. Payload
|
|
118
|
+
* types are identical per `type`, so one handler serves the set and
|
|
119
|
+
* `event.contractId` disambiguates.
|
|
120
|
+
*
|
|
121
|
+
* Supports `*` wildcards (e.g. `"SP1ABC….pool-*"`). Mutually exclusive
|
|
122
|
+
* with `trait`, which resolves its own set per block.
|
|
123
|
+
*/
|
|
124
|
+
contractId?: string | readonly string[];
|
|
76
125
|
functionName?: string;
|
|
77
126
|
caller?: string;
|
|
78
127
|
/**
|
|
@@ -88,18 +137,47 @@ interface ContractDeployFilter {
|
|
|
88
137
|
deployer?: string;
|
|
89
138
|
contractName?: string;
|
|
90
139
|
}
|
|
91
|
-
|
|
140
|
+
/**
|
|
141
|
+
* One declared field of a print payload.
|
|
142
|
+
*
|
|
143
|
+
* A bare {@link ColumnType} is a required scalar (`amount: "uint"`). The
|
|
144
|
+
* composite forms exist because real print payloads are not flat: BNS-V2
|
|
145
|
+
* emits `name` as a NESTED tuple, and a `prints` vocabulary that could only
|
|
146
|
+
* say `"jsonb"` is why a handler reading flat `data.name` type-checked,
|
|
147
|
+
* deployed, and then decoded to null on every event.
|
|
148
|
+
*
|
|
149
|
+
* - `{ type: F, optional: true }` — the KEY becomes optional on `event.data`
|
|
150
|
+
* (mirrors `always_present: false` in the inferred schema).
|
|
151
|
+
* - `{ tuple: { … } }` — a nested tuple, typed all the way down.
|
|
152
|
+
* - `{ list: F }` — a list of `F`.
|
|
153
|
+
*/
|
|
154
|
+
type PrintField = ColumnType | {
|
|
155
|
+
type: PrintField
|
|
156
|
+
optional: true
|
|
157
|
+
} | {
|
|
158
|
+
tuple: Record<string, PrintField>
|
|
159
|
+
} | {
|
|
160
|
+
list: PrintField
|
|
161
|
+
};
|
|
162
|
+
interface PrintEventFilter extends TraitScope, FactoryScope {
|
|
92
163
|
type: "print_event";
|
|
93
|
-
|
|
164
|
+
/** One contract id, or a set of them (max 20). Supports `*` wildcards.
|
|
165
|
+
* Mutually exclusive with `trait`. */
|
|
166
|
+
contractId?: string | readonly string[];
|
|
94
167
|
topic?: string;
|
|
95
168
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
169
|
+
* Per-topic field schema. When declared, the handler's `event` is a
|
|
170
|
+
* discriminated union keyed by `topic` and `event.data` is typed per topic
|
|
98
171
|
* (e.g. `{ "completed-deposit": { amount: "uint", sender: "principal" } }`).
|
|
99
|
-
*
|
|
100
|
-
*
|
|
172
|
+
* Nested tuples, lists, and optional fields are expressible — see
|
|
173
|
+
* {@link PrintField}.
|
|
174
|
+
*
|
|
175
|
+
* Declaring `prints` also opts the source into RUNTIME validation: an
|
|
176
|
+
* event whose decoded payload does not match is skipped and logged rather
|
|
177
|
+
* than written as nulls (and the deploy-time field lint is promoted from
|
|
178
|
+
* a warning to an error).
|
|
101
179
|
*/
|
|
102
|
-
prints?: Record<string, Record<string,
|
|
180
|
+
prints?: Record<string, Record<string, PrintField>>;
|
|
103
181
|
}
|
|
104
182
|
/** All subgraph filter types — discriminated on `type` */
|
|
105
183
|
type SubgraphFilter = StxTransferFilter | StxMintFilter | StxBurnFilter | StxLockFilter | FtTransferFilter | FtMintFilter | FtBurnFilter | NftTransferFilter | NftMintFilter | NftBurnFilter | ContractCallFilter | ContractDeployFilter | PrintEventFilter;
|
|
@@ -130,8 +208,17 @@ type EventRecord = {
|
|
|
130
208
|
};
|
|
131
209
|
type TraitContracts = Map<string, ReadonlySet<string>>;
|
|
132
210
|
/**
|
|
211
|
+
* True when a filter's optional `trait` admits this contract: no trait → always
|
|
212
|
+
* allowed; trait set → the contract must be in the resolved conforming set.
|
|
213
|
+
*/
|
|
214
|
+
/** Addresses discovered per source name (factory sets), resolved by the
|
|
215
|
+
* caller as-of the block being processed. */
|
|
216
|
+
type FactoryContracts = ReadonlyMap<string, ReadonlySet<string>>;
|
|
217
|
+
/** Read a dotted path off a decoded payload (`"data.pool"`). */
|
|
218
|
+
declare function readPath(payload: unknown, path: string): unknown;
|
|
219
|
+
/**
|
|
133
220
|
* Match named filters against a block's transactions and events.
|
|
134
221
|
* Returns matches with sourceName = the object key from sources.
|
|
135
222
|
*/
|
|
136
|
-
declare function matchSources(sources: Record<string, SubgraphFilter>, transactions: TxRecord[], events: EventRecord[], traitContracts?: TraitContracts): MatchedTx[];
|
|
137
|
-
export { matchSources, TraitContracts, MatchedTx };
|
|
223
|
+
declare function matchSources(sources: Record<string, SubgraphFilter>, transactions: TxRecord[], events: EventRecord[], traitContracts?: TraitContracts, factoryContracts?: FactoryContracts): MatchedTx[];
|
|
224
|
+
export { readPath, matchSources, TxRecord, TraitContracts, MatchedTx, FactoryContracts, EventRecord };
|