@sig-net/midnight 0.0.1

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.
Files changed (90) hide show
  1. package/README.md +20 -0
  2. package/dist/constants.d.ts +62 -0
  3. package/dist/constants.d.ts.map +1 -0
  4. package/dist/constants.js +83 -0
  5. package/dist/constants.js.map +1 -0
  6. package/dist/epsilon-derivation.d.ts +32 -0
  7. package/dist/epsilon-derivation.d.ts.map +1 -0
  8. package/dist/epsilon-derivation.js +54 -0
  9. package/dist/epsilon-derivation.js.map +1 -0
  10. package/dist/index.d.ts +26 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +30 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/managed/compiler/contract-info.json +165 -0
  15. package/dist/managed/compiler/contract-manifest.json +32 -0
  16. package/dist/managed/contract/index.d.ts +65 -0
  17. package/dist/managed/contract/index.js +611 -0
  18. package/dist/managed/contract/index.js.map +8 -0
  19. package/dist/schnorr.d.ts +100 -0
  20. package/dist/schnorr.d.ts.map +1 -0
  21. package/dist/schnorr.js +144 -0
  22. package/dist/schnorr.js.map +1 -0
  23. package/dist/signature-requests-state-reader.d.ts +74 -0
  24. package/dist/signature-requests-state-reader.d.ts.map +1 -0
  25. package/dist/signature-requests-state-reader.js +167 -0
  26. package/dist/signature-requests-state-reader.js.map +1 -0
  27. package/dist/signature-response-verification.d.ts +27 -0
  28. package/dist/signature-response-verification.d.ts.map +1 -0
  29. package/dist/signature-response-verification.js +45 -0
  30. package/dist/signature-response-verification.js.map +1 -0
  31. package/dist/signature-state-reading.d.ts +36 -0
  32. package/dist/signature-state-reading.d.ts.map +1 -0
  33. package/dist/signature-state-reading.js +62 -0
  34. package/dist/signature-state-reading.js.map +1 -0
  35. package/dist/signet-contract-state-reader.d.ts +146 -0
  36. package/dist/signet-contract-state-reader.d.ts.map +1 -0
  37. package/dist/signet-contract-state-reader.js +226 -0
  38. package/dist/signet-contract-state-reader.js.map +1 -0
  39. package/dist/signet-event-observer.d.ts +102 -0
  40. package/dist/signet-event-observer.d.ts.map +1 -0
  41. package/dist/signet-event-observer.js +127 -0
  42. package/dist/signet-event-observer.js.map +1 -0
  43. package/dist/signet-events.d.ts +175 -0
  44. package/dist/signet-events.d.ts.map +1 -0
  45. package/dist/signet-events.js +210 -0
  46. package/dist/signet-events.js.map +1 -0
  47. package/dist/signet-request-feed.d.ts +78 -0
  48. package/dist/signet-request-feed.d.ts.map +1 -0
  49. package/dist/signet-request-feed.js +116 -0
  50. package/dist/signet-request-feed.js.map +1 -0
  51. package/dist/signet-request-resolver.d.ts +58 -0
  52. package/dist/signet-request-resolver.d.ts.map +1 -0
  53. package/dist/signet-request-resolver.js +76 -0
  54. package/dist/signet-request-resolver.js.map +1 -0
  55. package/dist/signet-request-response-reader.d.ts +160 -0
  56. package/dist/signet-request-response-reader.d.ts.map +1 -0
  57. package/dist/signet-request-response-reader.js +198 -0
  58. package/dist/signet-request-response-reader.js.map +1 -0
  59. package/dist/signet-requests.d.ts +363 -0
  60. package/dist/signet-requests.d.ts.map +1 -0
  61. package/dist/signet-requests.js +497 -0
  62. package/dist/signet-requests.js.map +1 -0
  63. package/dist/signet-response-feed.d.ts +161 -0
  64. package/dist/signet-response-feed.d.ts.map +1 -0
  65. package/dist/signet-response-feed.js +234 -0
  66. package/dist/signet-response-feed.js.map +1 -0
  67. package/package.json +47 -0
  68. package/src/Schnorr.compact +63 -0
  69. package/src/Signet.compact +529 -0
  70. package/src/circuits.compact +36 -0
  71. package/src/constants.ts +97 -0
  72. package/src/epsilon-derivation.ts +62 -0
  73. package/src/index.ts +31 -0
  74. package/src/managed/compiler/contract-info.json +165 -0
  75. package/src/managed/compiler/contract-manifest.json +32 -0
  76. package/src/managed/contract/index.d.ts +65 -0
  77. package/src/managed/contract/index.js +611 -0
  78. package/src/managed/contract/index.js.map +8 -0
  79. package/src/schnorr.ts +210 -0
  80. package/src/signature-requests-state-reader.ts +223 -0
  81. package/src/signature-response-verification.ts +64 -0
  82. package/src/signature-state-reading.ts +87 -0
  83. package/src/signet-contract-state-reader.ts +391 -0
  84. package/src/signet-event-observer.ts +186 -0
  85. package/src/signet-events.ts +337 -0
  86. package/src/signet-request-feed.ts +158 -0
  87. package/src/signet-request-resolver.ts +116 -0
  88. package/src/signet-request-response-reader.ts +324 -0
  89. package/src/signet-requests.ts +737 -0
  90. package/src/signet-response-feed.ts +325 -0
@@ -0,0 +1,391 @@
1
+ // MPC-/client-style raw state reader for the central SIGNET contract: decode
2
+ // its ledger fields out of a contract's raw state WITHOUT the compiled
3
+ // contract, the mirror image of signature-requests-state-reader.ts. A poller
4
+ // has only the contract address, queries raw state from the indexer
5
+ // (queryContractState(address).data), and decodes by the signet contract
6
+ // layout convention (see "Signet Contract Ledger Layout" in Signet.compact):
7
+ // signature response counter index (field 0), signature response log
8
+ // (field 1), respond-bidirectional index (field 2), sealed MPC key hash
9
+ // (field 3). The generic state-tree walk (RawContractState, signetFieldNode)
10
+ // and the shared base descriptors live in signature-state-reading.ts.
11
+
12
+ import {
13
+ CompactTypeBytes,
14
+ CompactTypeField,
15
+ CompactTypeJubjubPoint,
16
+ CompactTypeUnsignedInteger,
17
+ type CompactType,
18
+ type JubjubPoint,
19
+ } from "@midnight-ntwrk/compact-runtime";
20
+
21
+ import {
22
+ requestIdHex,
23
+ type RequestId,
24
+ type RequestIdHex,
25
+ } from "./signet-requests.ts";
26
+
27
+ import {
28
+ requestIdType,
29
+ signetFieldNode,
30
+ u64,
31
+ type RawContractState,
32
+ } from "./signature-state-reading.ts";
33
+
34
+ /** Signet contract layout: the signature response counter index is ledger field 0. */
35
+ export const SIGNATURE_RESPONSE_COUNTER_INDEX_FIELD = 0;
36
+
37
+ /** Signet contract layout: the signature response log is ledger field 1. */
38
+ export const SIGNATURE_RESPONSE_INDEX_FIELD = 1;
39
+
40
+ /** Signet contract layout: the respond-bidirectional index is ledger field 2. */
41
+ export const RESPOND_BIDIRECTIONAL_INDEX_FIELD = 2;
42
+
43
+ /** Signet contract layout: the sealed MPC attestation key hash is ledger field 3. */
44
+ export const MPC_PUB_KEY_HASH_FIELD = 3;
45
+
46
+ // ---- Type descriptors (must mirror Signet.compact field-for-field) ----
47
+ // As in the requests reader, fromValue consumes the aligned value
48
+ // sequentially, so field order and width here must match the Compact structs
49
+ // exactly — a mismatch is silent data corruption, not an error.
50
+
51
+ /** Descriptor for a signature scalar / MPC key hash (`Bytes<32>`). */
52
+ const bytes32 = new CompactTypeBytes(32);
53
+
54
+ /** Descriptor for the attestation's serialized output (`Bytes<128>`). */
55
+ const bytes128 = new CompactTypeBytes(128);
56
+
57
+ /** Descriptor for a Compact `Uint<8>` (1-byte unsigned integer). */
58
+ const u8 = new CompactTypeUnsignedInteger(255n, 1);
59
+
60
+ /**
61
+ * The MPC's secp256k1 signature over the requested EVM transaction (Compact
62
+ * `SignatureResponse` — the canonical MPC `Signature { big_r, s,
63
+ * recovery_id }` with `big_r` decomposed into affine coordinates, big-endian
64
+ * scalar bytes). The request id it answers lives in the response index key,
65
+ * not here.
66
+ */
67
+ export interface SignatureResponse {
68
+ /** Signature R.x, 32 big-endian bytes. */
69
+ bigRx: Uint8Array;
70
+ /** Signature R.y, 32 big-endian bytes. */
71
+ bigRy: Uint8Array;
72
+ /** Signature s, 32 big-endian bytes. */
73
+ s: Uint8Array;
74
+ /** Parity of R.y for public-key recovery (0 or 1). */
75
+ recoveryId: bigint;
76
+ }
77
+
78
+ /**
79
+ * Hand-composed descriptor for {@link SignatureResponse}. Field
80
+ * order (bigRx, bigRy, s, recoveryId) must match the Compact struct.
81
+ */
82
+ export const signatureResponseType: CompactType<SignatureResponse> = {
83
+ /** @returns Compound alignment of the struct's fields in declaration order. */
84
+ alignment() {
85
+ return bytes32
86
+ .alignment()
87
+ .concat(bytes32.alignment())
88
+ .concat(bytes32.alignment())
89
+ .concat(u8.alignment());
90
+ },
91
+ /**
92
+ * Decode one signature response from an aligned value, consuming it field
93
+ * by field.
94
+ *
95
+ * @param value - Mutable aligned value cursor; pass a copy.
96
+ * @returns The decoded record.
97
+ */
98
+ fromValue(value) {
99
+ return {
100
+ bigRx: bytes32.fromValue(value),
101
+ bigRy: bytes32.fromValue(value),
102
+ s: bytes32.fromValue(value),
103
+ recoveryId: u8.fromValue(value),
104
+ };
105
+ },
106
+ /**
107
+ * Encode a signature response into its aligned on-ledger representation.
108
+ *
109
+ * @param record - The record to encode.
110
+ * @returns The aligned value, fields concatenated in declaration order.
111
+ */
112
+ toValue(record) {
113
+ return bytes32
114
+ .toValue(record.bigRx)
115
+ .concat(bytes32.toValue(record.bigRy))
116
+ .concat(bytes32.toValue(record.s))
117
+ .concat(u8.toValue(record.recoveryId));
118
+ },
119
+ };
120
+
121
+ /**
122
+ * The MPC's respond-bidirectional attestation of a request's remote EVM
123
+ * execution (Compact `RespondBidirectional`): the serialized execution
124
+ * output plus the Schnorr signature over
125
+ * `(requestId, hash(serializedOutput, outputLen))`. Stored records were
126
+ * verified IN-CIRCUIT by the signet contract at post time, so readers can
127
+ * trust them without re-verifying.
128
+ */
129
+ export interface RespondBidirectional {
130
+ /** ABI-encoded return data (canonical serialized_output), zero-padded to 128 bytes. */
131
+ serializedOutput: Uint8Array;
132
+ /** Meaningful byte count of {@link serializedOutput}. */
133
+ outputLen: bigint;
134
+ /** The MPC attestation key (hash-checked against the sealed key at post). */
135
+ pk: JubjubPoint;
136
+ /** Schnorr nonce commitment R. */
137
+ announcement: JubjubPoint;
138
+ /** Schnorr response scalar s. */
139
+ response: bigint;
140
+ }
141
+
142
+ /**
143
+ * Composite key of one posted signature response (Compact
144
+ * `SignetResponseKey`): the request id it answers plus this post's 0-based
145
+ * count. Field order — count first, then request id — mirrors the Compact
146
+ * struct.
147
+ */
148
+ export interface SignetResponseKey {
149
+ /** 0-based position of this post among the responses for {@link requestId}. */
150
+ count: bigint;
151
+ /** 32-byte id of the request this response answers. */
152
+ requestId: RequestId;
153
+ }
154
+
155
+ /**
156
+ * Hand-composed descriptor for {@link SignetResponseKey} — the map key of
157
+ * the signature response log. Field order (count, then requestId) must match
158
+ * the Compact struct.
159
+ */
160
+ export const signetResponseKeyType: CompactType<SignetResponseKey> = {
161
+ /** @returns Compound alignment of the struct's fields in declaration order. */
162
+ alignment() {
163
+ return u64.alignment().concat(requestIdType.alignment());
164
+ },
165
+ /**
166
+ * Decode one key from an aligned value, consuming it field by field.
167
+ *
168
+ * @param value - Mutable aligned value cursor; pass a copy.
169
+ * @returns The decoded composite key.
170
+ */
171
+ fromValue(value) {
172
+ return {
173
+ count: u64.fromValue(value),
174
+ requestId: requestIdType.fromValue(value),
175
+ };
176
+ },
177
+ /**
178
+ * Encode a key into its aligned on-ledger representation.
179
+ *
180
+ * @param key - The composite key to encode.
181
+ * @returns The aligned value, fields concatenated in declaration order.
182
+ */
183
+ toValue(key) {
184
+ return u64.toValue(key.count).concat(requestIdType.toValue(key.requestId));
185
+ },
186
+ };
187
+
188
+ /**
189
+ * Hand-composed descriptor for {@link RespondBidirectional}. Field
190
+ * order (serializedOutput, outputLen, pk, announcement, response) must match
191
+ * the Compact struct.
192
+ */
193
+ export const respondBidirectionalType: CompactType<RespondBidirectional> = {
194
+ /** @returns Compound alignment of the struct's fields in declaration order. */
195
+ alignment() {
196
+ return bytes128
197
+ .alignment()
198
+ .concat(u8.alignment())
199
+ .concat(CompactTypeJubjubPoint.alignment())
200
+ .concat(CompactTypeJubjubPoint.alignment())
201
+ .concat(CompactTypeField.alignment());
202
+ },
203
+ /**
204
+ * Decode one attestation record from an aligned value, consuming it field
205
+ * by field.
206
+ *
207
+ * @param value - Mutable aligned value cursor; pass a copy.
208
+ * @returns The decoded record.
209
+ */
210
+ fromValue(value) {
211
+ return {
212
+ serializedOutput: bytes128.fromValue(value),
213
+ outputLen: u8.fromValue(value),
214
+ pk: CompactTypeJubjubPoint.fromValue(value),
215
+ announcement: CompactTypeJubjubPoint.fromValue(value),
216
+ response: CompactTypeField.fromValue(value),
217
+ };
218
+ },
219
+ /**
220
+ * Encode an attestation record into its aligned on-ledger representation.
221
+ *
222
+ * @param record - The record to encode.
223
+ * @returns The aligned value, fields concatenated in declaration order.
224
+ */
225
+ toValue(record) {
226
+ return bytes128
227
+ .toValue(record.serializedOutput)
228
+ .concat(u8.toValue(record.outputLen))
229
+ .concat(CompactTypeJubjubPoint.toValue(record.pk))
230
+ .concat(CompactTypeJubjubPoint.toValue(record.announcement))
231
+ .concat(CompactTypeField.toValue(record.response));
232
+ },
233
+ };
234
+
235
+ /**
236
+ * Plain-JS signature response counter index parsed out of the ledger: hex
237
+ * request id (see {@link requestIdHex}) to the number of responses posted for
238
+ * that request. Entries in the response log exist for counts `0 .. value - 1`.
239
+ */
240
+ export type SignatureResponseCounterIndex = Map<RequestIdHex, bigint>;
241
+
242
+ /**
243
+ * Plain-JS signature response log parsed out of the ledger, keyed by
244
+ * {@link signetResponseIndexKey} (`"<hexRequestId>:<count>"`) so the
245
+ * composite Compact key survives as a usable JS `Map` key.
246
+ */
247
+ export type SignatureResponseIndex = Map<string, SignatureResponse>;
248
+
249
+ /**
250
+ * Plain-JS respond-bidirectional index parsed out of the ledger: hex
251
+ * request id to the contract-verified attestation. One slot per request.
252
+ */
253
+ export type RespondBidirectionalIndex = Map<
254
+ RequestIdHex,
255
+ RespondBidirectional
256
+ >;
257
+
258
+ /**
259
+ * Build the {@link SignatureResponseIndex} key for a `(requestId, count)`
260
+ * pair — the composite Compact key flattened to a string so it works as a JS
261
+ * `Map` key.
262
+ *
263
+ * @param id - The request id the response answers, in canonical hex form.
264
+ * @param count - 0-based post count within that request.
265
+ * @returns `"<hexRequestId>:<count>"`.
266
+ */
267
+ export function signetResponseIndexKey(
268
+ id: RequestIdHex,
269
+ count: bigint,
270
+ ): string {
271
+ return `${id}:${count}`;
272
+ }
273
+
274
+ /**
275
+ * The decoded ledger fields of the signet contract: the signature response
276
+ * counter (field 0) and log (field 1), the respond-bidirectional index
277
+ * (field 2), and the sealed MPC attestation key hash (field 3). Together
278
+ * they give a client everything the MPC ever delivers for a request.
279
+ */
280
+ export interface SignetContractLedger {
281
+ /**
282
+ * The signature response counter index (ledger field
283
+ * {@link SIGNATURE_RESPONSE_COUNTER_INDEX_FIELD}), keyed by hex request id.
284
+ */
285
+ signatureResponseCounterIndex: SignatureResponseCounterIndex;
286
+ /**
287
+ * The signature response log (ledger field
288
+ * {@link SIGNATURE_RESPONSE_INDEX_FIELD}), keyed by
289
+ * {@link signetResponseIndexKey}.
290
+ */
291
+ signatureResponseIndex: SignatureResponseIndex;
292
+ /**
293
+ * The respond-bidirectional index (ledger field
294
+ * {@link RESPOND_BIDIRECTIONAL_INDEX_FIELD}), keyed by hex request id.
295
+ */
296
+ respondBidirectionalIndex: RespondBidirectionalIndex;
297
+ /**
298
+ * The sealed MPC attestation key hash (ledger field
299
+ * {@link MPC_PUB_KEY_HASH_FIELD}) posts are verified against.
300
+ */
301
+ mpcPubKeyHash: Uint8Array;
302
+ }
303
+
304
+ /**
305
+ * MPC-/client-style read: parse the signet contract's ledger fields out of
306
+ * raw contract state by field position alone — no compiled contract, no
307
+ * generated `ledger()`, only the signet contract layout convention and the
308
+ * canonical descriptors above.
309
+ *
310
+ * @param raw - Raw contract state, e.g. `queryContractState(address).data`
311
+ * from the indexer or `ctx.currentQueryContext.state` from the simulator.
312
+ * @returns The decoded {@link SignetContractLedger}.
313
+ * @throws Error if a field is missing or has the wrong state-value shape.
314
+ */
315
+ export function readSignetContractLedgerFromState(
316
+ raw: RawContractState,
317
+ ): SignetContractLedger {
318
+ const counterMap = signetFieldNode(
319
+ raw,
320
+ SIGNATURE_RESPONSE_COUNTER_INDEX_FIELD,
321
+ ).asMap();
322
+ if (counterMap === undefined) {
323
+ throw new Error(
324
+ `Ledger field ${SIGNATURE_RESPONSE_COUNTER_INDEX_FIELD} is not a Map`,
325
+ );
326
+ }
327
+ const signatureResponseCounterIndex: SignatureResponseCounterIndex =
328
+ new Map();
329
+ for (const key of counterMap.keys()) {
330
+ // fromValue consumes its input, so hand each descriptor a copy.
331
+ const requestId = requestIdType.fromValue([...key.value]);
332
+ // A Counter is stored as a plain u64 cell.
333
+ const cell = counterMap.get(key)?.asCell();
334
+ if (cell === undefined) continue;
335
+ signatureResponseCounterIndex.set(
336
+ requestIdHex(requestId),
337
+ u64.fromValue([...cell.value]),
338
+ );
339
+ }
340
+
341
+ const responseMap = signetFieldNode(
342
+ raw,
343
+ SIGNATURE_RESPONSE_INDEX_FIELD,
344
+ ).asMap();
345
+ if (responseMap === undefined) {
346
+ throw new Error(`Ledger field ${SIGNATURE_RESPONSE_INDEX_FIELD} is not a Map`);
347
+ }
348
+ const signatureResponseIndex: SignatureResponseIndex = new Map();
349
+ for (const key of responseMap.keys()) {
350
+ const responseKey = signetResponseKeyType.fromValue([...key.value]);
351
+ const cell = responseMap.get(key)?.asCell();
352
+ if (cell === undefined) continue;
353
+ signatureResponseIndex.set(
354
+ signetResponseIndexKey(requestIdHex(responseKey.requestId), responseKey.count),
355
+ signatureResponseType.fromValue([...cell.value]),
356
+ );
357
+ }
358
+
359
+ const respondBidirectionalMap = signetFieldNode(
360
+ raw,
361
+ RESPOND_BIDIRECTIONAL_INDEX_FIELD,
362
+ ).asMap();
363
+ if (respondBidirectionalMap === undefined) {
364
+ throw new Error(
365
+ `Ledger field ${RESPOND_BIDIRECTIONAL_INDEX_FIELD} is not a Map`,
366
+ );
367
+ }
368
+ const respondBidirectionalIndex: RespondBidirectionalIndex = new Map();
369
+ for (const key of respondBidirectionalMap.keys()) {
370
+ const requestId = requestIdType.fromValue([...key.value]);
371
+ const cell = respondBidirectionalMap.get(key)?.asCell();
372
+ if (cell === undefined) continue;
373
+ respondBidirectionalIndex.set(
374
+ requestIdHex(requestId),
375
+ respondBidirectionalType.fromValue([...cell.value]),
376
+ );
377
+ }
378
+
379
+ const hashCell = signetFieldNode(raw, MPC_PUB_KEY_HASH_FIELD).asCell();
380
+ if (hashCell === undefined) {
381
+ throw new Error(`Ledger field ${MPC_PUB_KEY_HASH_FIELD} is not a Cell`);
382
+ }
383
+ const mpcPubKeyHash = bytes32.fromValue([...hashCell.value]);
384
+
385
+ return {
386
+ signatureResponseCounterIndex,
387
+ signatureResponseIndex,
388
+ respondBidirectionalIndex,
389
+ mpcPubKeyHash,
390
+ };
391
+ }
@@ -0,0 +1,186 @@
1
+ // Watch the CENTRAL signet contract's `Misc` events and surface ONE kind of
2
+ // signet notification (selected by the codec) as typed events in id order —
3
+ // the event-observation replacement for polling ledgers blind. Instantiated
4
+ // with `signBidirectionalEventCodec` it discovers signature requests for the
5
+ // MPC (see signet-request-feed.ts); with `signatureRespondedEventCodec` it
6
+ // discovers posted signature responses for the requesting client (see
7
+ // signet-response-feed.ts). The observer only DISCOVERS; authenticating /
8
+ // verifying what an event points at is its consumer's job. The event is a
9
+ // ping, never the source of truth — see
10
+ // knowledge-base/caller-attribution.md.
11
+
12
+ import type {
13
+ ContractEvent,
14
+ ContractEventQueryFilter,
15
+ PublicDataProvider,
16
+ } from "@midnight-ntwrk/midnight-js-types";
17
+
18
+ import {
19
+ eventNameTag,
20
+ hexToBytes,
21
+ type SignetMiscEventCodec,
22
+ } from "./signet-events.ts";
23
+
24
+ /** Default gap between polls of the indexer's event stream. */
25
+ export const DEFAULT_EVENT_POLL_INTERVAL_MS = 3000;
26
+
27
+ /**
28
+ * The least of midnight-js's `PublicDataProvider` the event path needs: read a
29
+ * contract's events, and (optionally) stream them live. Declared structurally
30
+ * so tests can satisfy it with a plain stub; any full `PublicDataProvider`
31
+ * (e.g. `indexerPublicDataProvider`) is assignable to it.
32
+ */
33
+ export interface SignetEventSource {
34
+ /**
35
+ * Point-in-time read of a contract's events matching `filter`.
36
+ *
37
+ * @param filter - The event filter; `contractAddress` is required, an empty
38
+ * `types` array is rejected (omit for all).
39
+ * @returns The matching events, in ascending indexer-id order.
40
+ */
41
+ queryContractEvents(filter: ContractEventQueryFilter): Promise<ContractEvent[]>;
42
+ /**
43
+ * Optional live stream, for a future push path. Typed off
44
+ * `PublicDataProvider` so a full provider stays assignable; the observer's
45
+ * default path polls {@link queryContractEvents}.
46
+ */
47
+ contractEventsObservable?: PublicDataProvider["contractEventsObservable"];
48
+ }
49
+
50
+ /** Everything a {@link SignetEventObserver} needs. */
51
+ export interface SignetEventObserverConfig<T> {
52
+ /** Address of the central signet contract whose events to watch. */
53
+ readonly signetContractAddress: string;
54
+ /** Source of contract events, e.g. midnight-js's `indexerPublicDataProvider`. */
55
+ readonly source: SignetEventSource;
56
+ /**
57
+ * Which signet event kind to surface: the `Misc.name` tag to filter on and
58
+ * the payload decoder, e.g. `signBidirectionalEventCodec` or
59
+ * `signatureRespondedEventCodec` (signet-events.ts).
60
+ */
61
+ readonly codec: SignetMiscEventCodec<T>;
62
+ /**
63
+ * Durable resume floor: only events with `id >= fromEventId` are considered
64
+ * (the in-memory cursor of a prior run, persisted across restarts so nothing
65
+ * is missed or replayed). Defaults to 0 — the start of the event stream.
66
+ */
67
+ readonly fromEventId?: number;
68
+ /** Poll cadence for {@link SignetEventObserver.watch}; default {@link DEFAULT_EVENT_POLL_INTERVAL_MS}. */
69
+ readonly pollIntervalMs?: number;
70
+ }
71
+
72
+ /**
73
+ * Resolve after `ms`, or immediately once `signal` aborts. Used to space out
74
+ * polls without wedging a shutdown.
75
+ */
76
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
77
+ return new Promise((resolve) => {
78
+ if (signal?.aborted) return resolve();
79
+ const timer = setTimeout(() => {
80
+ signal?.removeEventListener("abort", onAbort);
81
+ resolve();
82
+ }, ms);
83
+ const onAbort = () => {
84
+ clearTimeout(timer);
85
+ resolve();
86
+ };
87
+ signal?.addEventListener("abort", onAbort, { once: true });
88
+ });
89
+ }
90
+
91
+ /**
92
+ * Watches one signet contract's `Misc` events and surfaces the notifications
93
+ * of ONE kind among them (the codec's name tag), decoded and in ascending
94
+ * indexer-id order. A single decode failure is logged and skipped — one
95
+ * malformed event never stalls the stream.
96
+ */
97
+ export class SignetEventObserver<T> {
98
+ private readonly signetContractAddress: string;
99
+ private readonly source: SignetEventSource;
100
+ private readonly codec: SignetMiscEventCodec<T>;
101
+ private readonly fromEventId: number;
102
+ private readonly pollIntervalMs: number;
103
+
104
+ /**
105
+ * @param config - The signet contract, event source, codec, and resume floor.
106
+ */
107
+ constructor(config: SignetEventObserverConfig<T>) {
108
+ this.signetContractAddress = config.signetContractAddress;
109
+ this.source = config.source;
110
+ this.codec = config.codec;
111
+ this.fromEventId = config.fromEventId ?? 0;
112
+ this.pollIntervalMs = config.pollIntervalMs ?? DEFAULT_EVENT_POLL_INTERVAL_MS;
113
+ }
114
+
115
+ /** The `Misc` filter for the watched signet contract. */
116
+ private filter(): ContractEventQueryFilter {
117
+ return { contractAddress: this.signetContractAddress, types: ["Misc"] };
118
+ }
119
+
120
+ /**
121
+ * Every currently-visible notification of the codec's kind at or after the
122
+ * resume floor, each paired with its indexer cursor id, ascending by id.
123
+ * Non-`Misc` events, other name tags, and decode failures are dropped
124
+ * (failures logged).
125
+ */
126
+ private async scan(): Promise<Array<{ id: number; event: T }>> {
127
+ const events = await this.source.queryContractEvents(this.filter());
128
+ const out: Array<{ id: number; event: T }> = [];
129
+ for (const event of events) {
130
+ if (event.eventType !== "Misc") continue;
131
+ if (event.id < this.fromEventId) continue;
132
+ if (eventNameTag(event.name) !== this.codec.tag) continue;
133
+ let decoded: T;
134
+ try {
135
+ decoded = this.codec.decode(hexToBytes(event.payload));
136
+ } catch (error) {
137
+ console.warn(
138
+ `SignetEventObserver: dropping undecodable ${this.codec.tag} ` +
139
+ `event id=${event.id}: ${String(error)}`,
140
+ );
141
+ continue;
142
+ }
143
+ out.push({ id: event.id, event: decoded });
144
+ }
145
+ out.sort((a, b) => a.id - b.id);
146
+ return out;
147
+ }
148
+
149
+ /**
150
+ * One-shot: every notification of the codec's kind currently visible at or
151
+ * after the resume floor, in id order. The polling feeds
152
+ * ({@link SignetRequestFeed}, `SignetResponseFeed`) re-scan through this
153
+ * each cycle (so a not-yet-indexed write is retried); it does NOT advance a
154
+ * cursor — the feeds dedupe by content instead.
155
+ *
156
+ * @returns The decoded notifications, ascending by indexer id.
157
+ */
158
+ async currentEvents(): Promise<T[]> {
159
+ return (await this.scan()).map((entry) => entry.event);
160
+ }
161
+
162
+ /**
163
+ * Live stream: poll the event source forever, yielding each notification
164
+ * exactly once in id order — nothing at or below the last yielded id is
165
+ * re-emitted (the cursor advances as `id + 1`, matching the indexer's
166
+ * resume convention). Runs until `opts.signal` aborts.
167
+ *
168
+ * @param opts.signal - Abort to stop the stream (between polls or on the next yield).
169
+ * @yields Each decoded notification once, ascending by indexer id.
170
+ */
171
+ async *watch(opts?: { signal?: AbortSignal }): AsyncIterableIterator<T> {
172
+ let cursor = this.fromEventId;
173
+ while (!opts?.signal?.aborted) {
174
+ const batch = await this.scan();
175
+ for (const { id, event } of batch) {
176
+ if (id < cursor) continue;
177
+ yield event;
178
+ cursor = id + 1;
179
+ }
180
+ if (opts?.signal?.aborted) break;
181
+ await sleep(this.pollIntervalMs, opts?.signal);
182
+ }
183
+ }
184
+ }
185
+
186
+ export { sleep as sleepUnlessAborted };