@toon-protocol/relay 1.3.1 → 1.3.2

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.
@@ -0,0 +1,2033 @@
1
+ // src/types.ts
2
+ var DEFAULT_RELAY_CONFIG = {
3
+ port: 7e3,
4
+ host: "0.0.0.0",
5
+ maxConnections: 100,
6
+ maxSubscriptionsPerConnection: 20,
7
+ maxFiltersPerSubscription: 10,
8
+ databasePath: ":memory:"
9
+ };
10
+
11
+ // src/filters/matchFilter.ts
12
+ function matchFilter(event, filter) {
13
+ if (Object.keys(filter).length === 0) {
14
+ return true;
15
+ }
16
+ if (filter.ids !== void 0 && filter.ids.length > 0) {
17
+ const matches = filter.ids.some((id) => event.id.startsWith(id));
18
+ if (!matches) return false;
19
+ }
20
+ if (filter.authors !== void 0 && filter.authors.length > 0) {
21
+ const matches = filter.authors.some(
22
+ (author) => event.pubkey.startsWith(author)
23
+ );
24
+ if (!matches) return false;
25
+ }
26
+ if (filter.kinds !== void 0 && filter.kinds.length > 0) {
27
+ if (!filter.kinds.includes(event.kind)) return false;
28
+ }
29
+ if (filter.since !== void 0) {
30
+ if (event.created_at < filter.since) return false;
31
+ }
32
+ if (filter.until !== void 0) {
33
+ if (event.created_at > filter.until) return false;
34
+ }
35
+ for (const key of Object.keys(filter)) {
36
+ if (key.startsWith("#") && key.length === 2) {
37
+ const tagName = key.slice(1);
38
+ const filterValues = filter[key];
39
+ if (filterValues !== void 0 && filterValues.length > 0) {
40
+ const eventTagValues = event.tags.filter((tag) => tag[0] === tagName).map((tag) => tag[1]);
41
+ const hasMatch = filterValues.some((v) => eventTagValues.includes(v));
42
+ if (!hasMatch) return false;
43
+ }
44
+ }
45
+ }
46
+ return true;
47
+ }
48
+
49
+ // src/storage/InMemoryEventStore.ts
50
+ var InMemoryEventStore = class {
51
+ events = /* @__PURE__ */ new Map();
52
+ store(event) {
53
+ this.events.set(event.id, event);
54
+ }
55
+ get(id) {
56
+ return this.events.get(id);
57
+ }
58
+ query(filters) {
59
+ const allEvents = Array.from(this.events.values());
60
+ if (filters.length === 0) {
61
+ return allEvents.sort((a, b) => b.created_at - a.created_at);
62
+ }
63
+ const matchingEvents = [];
64
+ for (const event of allEvents) {
65
+ for (const filter of filters) {
66
+ if (matchFilter(event, filter)) {
67
+ matchingEvents.push(event);
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ matchingEvents.sort((a, b) => b.created_at - a.created_at);
73
+ const limitFilter = filters.find((f) => f.limit !== void 0);
74
+ if (limitFilter?.limit !== void 0) {
75
+ return matchingEvents.slice(0, limitFilter.limit);
76
+ }
77
+ return matchingEvents;
78
+ }
79
+ /**
80
+ * Close the storage backend (no-op for in-memory store).
81
+ */
82
+ close() {
83
+ }
84
+ };
85
+
86
+ // src/storage/SqliteEventStore.ts
87
+ import Database from "better-sqlite3";
88
+ var SCHEMA_SQL = `
89
+ CREATE TABLE IF NOT EXISTS events (
90
+ id TEXT PRIMARY KEY,
91
+ pubkey TEXT NOT NULL,
92
+ kind INTEGER NOT NULL,
93
+ content TEXT NOT NULL,
94
+ tags TEXT NOT NULL,
95
+ created_at INTEGER NOT NULL,
96
+ sig TEXT NOT NULL,
97
+ received_at INTEGER NOT NULL
98
+ )
99
+ `;
100
+ var INDEX_SQL = [
101
+ "CREATE INDEX IF NOT EXISTS idx_events_pubkey ON events(pubkey)",
102
+ "CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind)",
103
+ "CREATE INDEX IF NOT EXISTS idx_events_created_at ON events(created_at)",
104
+ "CREATE INDEX IF NOT EXISTS idx_events_pubkey_kind ON events(pubkey, kind)"
105
+ ];
106
+ function initializeSchema(db) {
107
+ db.exec(SCHEMA_SQL);
108
+ for (const indexSql of INDEX_SQL) {
109
+ db.exec(indexSql);
110
+ }
111
+ }
112
+ var RelayError = class extends Error {
113
+ constructor(message, code) {
114
+ super(message);
115
+ this.code = code;
116
+ this.name = "RelayError";
117
+ }
118
+ code;
119
+ };
120
+ function isReplaceableKind(kind) {
121
+ return kind >= 1e4 && kind <= 19999 && !(kind >= 10032 && kind <= 10099);
122
+ }
123
+ function isParameterizedReplaceableKind(kind) {
124
+ return kind >= 3e4 && kind <= 39999 || kind >= 10032 && kind <= 10099;
125
+ }
126
+ function getDTagValue(tags) {
127
+ const dTag = tags.find((tag) => tag[0] === "d");
128
+ return dTag?.[1] ?? "";
129
+ }
130
+ var SqliteEventStore = class {
131
+ db;
132
+ insertStmt;
133
+ getStmt;
134
+ deleteByPubkeyKindStmt;
135
+ deleteByPubkeyKindDTagStmt;
136
+ getByPubkeyKindStmt;
137
+ getByPubkeyKindDTagStmt;
138
+ /**
139
+ * Create a new SqliteEventStore.
140
+ * @param dbPath - Path to the database file. Use ':memory:' for in-memory database.
141
+ */
142
+ constructor(dbPath = ":memory:") {
143
+ try {
144
+ this.db = new Database(dbPath);
145
+ initializeSchema(this.db);
146
+ this.insertStmt = this.db.prepare(`
147
+ INSERT OR REPLACE INTO events (id, pubkey, kind, content, tags, created_at, sig, received_at)
148
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
149
+ `);
150
+ this.getStmt = this.db.prepare("SELECT * FROM events WHERE id = ?");
151
+ this.deleteByPubkeyKindStmt = this.db.prepare(
152
+ "DELETE FROM events WHERE pubkey = ? AND kind = ?"
153
+ );
154
+ this.deleteByPubkeyKindDTagStmt = this.db.prepare(
155
+ "DELETE FROM events WHERE pubkey = ? AND kind = ? AND json_extract(tags, '$') LIKE ?"
156
+ );
157
+ this.getByPubkeyKindStmt = this.db.prepare(
158
+ "SELECT id, created_at FROM events WHERE pubkey = ? AND kind = ?"
159
+ );
160
+ this.getByPubkeyKindDTagStmt = this.db.prepare(
161
+ "SELECT id, created_at FROM events WHERE pubkey = ? AND kind = ? AND tags LIKE ?"
162
+ );
163
+ } catch (error) {
164
+ throw new RelayError(
165
+ `Failed to initialize database: ${error instanceof Error ? error.message : String(error)}`,
166
+ "STORAGE_ERROR"
167
+ );
168
+ }
169
+ }
170
+ /**
171
+ * Store an event in the database.
172
+ * Handles replaceable and parameterized replaceable events according to NIP-01.
173
+ */
174
+ store(event) {
175
+ try {
176
+ const tagsJson = JSON.stringify(event.tags);
177
+ const receivedAt = Math.floor(Date.now() / 1e3);
178
+ if (isReplaceableKind(event.kind)) {
179
+ this.storeReplaceableEvent(event, tagsJson, receivedAt);
180
+ } else if (isParameterizedReplaceableKind(event.kind)) {
181
+ this.storeParameterizedReplaceableEvent(event, tagsJson, receivedAt);
182
+ } else {
183
+ const insertOrIgnore = this.db.prepare(`
184
+ INSERT OR IGNORE INTO events (id, pubkey, kind, content, tags, created_at, sig, received_at)
185
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
186
+ `);
187
+ insertOrIgnore.run(
188
+ event.id,
189
+ event.pubkey,
190
+ event.kind,
191
+ event.content,
192
+ tagsJson,
193
+ event.created_at,
194
+ event.sig,
195
+ receivedAt
196
+ );
197
+ }
198
+ } catch (error) {
199
+ if (error instanceof RelayError) {
200
+ throw error;
201
+ }
202
+ throw new RelayError(
203
+ `Failed to store event: ${error instanceof Error ? error.message : String(error)}`,
204
+ "STORAGE_ERROR"
205
+ );
206
+ }
207
+ }
208
+ /**
209
+ * Store a replaceable event (kinds 10000-19999).
210
+ * Only keeps the latest event per pubkey+kind.
211
+ */
212
+ storeReplaceableEvent(event, tagsJson, receivedAt) {
213
+ const existing = this.getByPubkeyKindStmt.get(event.pubkey, event.kind);
214
+ if (existing) {
215
+ if (event.created_at > existing.created_at || event.created_at === existing.created_at && event.id < existing.id) {
216
+ const transaction = this.db.transaction(() => {
217
+ this.deleteByPubkeyKindStmt.run(event.pubkey, event.kind);
218
+ this.insertStmt.run(
219
+ event.id,
220
+ event.pubkey,
221
+ event.kind,
222
+ event.content,
223
+ tagsJson,
224
+ event.created_at,
225
+ event.sig,
226
+ receivedAt
227
+ );
228
+ });
229
+ transaction();
230
+ }
231
+ } else {
232
+ this.insertStmt.run(
233
+ event.id,
234
+ event.pubkey,
235
+ event.kind,
236
+ event.content,
237
+ tagsJson,
238
+ event.created_at,
239
+ event.sig,
240
+ receivedAt
241
+ );
242
+ }
243
+ }
244
+ /**
245
+ * Store a parameterized replaceable event (kinds 30000-39999).
246
+ * Only keeps the latest event per pubkey+kind+d-tag.
247
+ */
248
+ storeParameterizedReplaceableEvent(event, tagsJson, receivedAt) {
249
+ const dTagValue = getDTagValue(event.tags);
250
+ let existing;
251
+ if (dTagValue === "") {
252
+ const candidates = this.db.prepare(
253
+ "SELECT id, created_at, tags FROM events WHERE pubkey = ? AND kind = ?"
254
+ ).all(event.pubkey, event.kind);
255
+ for (const candidate of candidates) {
256
+ const candidateTags = JSON.parse(candidate.tags);
257
+ const candidateDTagValue = getDTagValue(candidateTags);
258
+ if (candidateDTagValue === "") {
259
+ existing = { id: candidate.id, created_at: candidate.created_at };
260
+ break;
261
+ }
262
+ }
263
+ } else {
264
+ const dTagPattern = `%["d","${dTagValue}"%`;
265
+ existing = this.getByPubkeyKindDTagStmt.get(
266
+ event.pubkey,
267
+ event.kind,
268
+ dTagPattern
269
+ );
270
+ }
271
+ if (existing) {
272
+ if (event.created_at > existing.created_at || event.created_at === existing.created_at && event.id < existing.id) {
273
+ const transaction = this.db.transaction(() => {
274
+ this.db.prepare("DELETE FROM events WHERE id = ?").run(existing.id);
275
+ this.insertStmt.run(
276
+ event.id,
277
+ event.pubkey,
278
+ event.kind,
279
+ event.content,
280
+ tagsJson,
281
+ event.created_at,
282
+ event.sig,
283
+ receivedAt
284
+ );
285
+ });
286
+ transaction();
287
+ }
288
+ } else {
289
+ this.insertStmt.run(
290
+ event.id,
291
+ event.pubkey,
292
+ event.kind,
293
+ event.content,
294
+ tagsJson,
295
+ event.created_at,
296
+ event.sig,
297
+ receivedAt
298
+ );
299
+ }
300
+ }
301
+ /**
302
+ * Retrieve an event by its ID.
303
+ */
304
+ get(id) {
305
+ try {
306
+ const row = this.getStmt.get(id);
307
+ if (!row) {
308
+ return void 0;
309
+ }
310
+ return {
311
+ id: row.id,
312
+ pubkey: row.pubkey,
313
+ kind: row.kind,
314
+ content: row.content,
315
+ tags: JSON.parse(row.tags),
316
+ created_at: row.created_at,
317
+ sig: row.sig
318
+ };
319
+ } catch (error) {
320
+ throw new RelayError(
321
+ `Failed to get event: ${error instanceof Error ? error.message : String(error)}`,
322
+ "STORAGE_ERROR"
323
+ );
324
+ }
325
+ }
326
+ /**
327
+ * Query events matching any of the provided filters.
328
+ */
329
+ query(filters) {
330
+ try {
331
+ const { sql, params } = this.buildQuerySql(filters);
332
+ const stmt = this.db.prepare(sql);
333
+ const rows = stmt.all(...params);
334
+ return rows.map((row) => ({
335
+ id: row.id,
336
+ pubkey: row.pubkey,
337
+ kind: row.kind,
338
+ content: row.content,
339
+ tags: JSON.parse(row.tags),
340
+ created_at: row.created_at,
341
+ sig: row.sig
342
+ }));
343
+ } catch (error) {
344
+ throw new RelayError(
345
+ `Failed to query events: ${error instanceof Error ? error.message : String(error)}`,
346
+ "STORAGE_ERROR"
347
+ );
348
+ }
349
+ }
350
+ /**
351
+ * Build SQL query from filters.
352
+ */
353
+ buildQuerySql(filters) {
354
+ if (filters.length === 0) {
355
+ return {
356
+ sql: "SELECT * FROM events ORDER BY created_at DESC",
357
+ params: []
358
+ };
359
+ }
360
+ const conditions = [];
361
+ const params = [];
362
+ for (const filter of filters) {
363
+ const filterConditions = [];
364
+ if (filter.ids?.length) {
365
+ const idConditions = filter.ids.map(() => "id LIKE ?");
366
+ filterConditions.push(`(${idConditions.join(" OR ")})`);
367
+ params.push(...filter.ids.map((id) => `${id}%`));
368
+ }
369
+ if (filter.authors?.length) {
370
+ const authorConditions = filter.authors.map(() => "pubkey LIKE ?");
371
+ filterConditions.push(`(${authorConditions.join(" OR ")})`);
372
+ params.push(...filter.authors.map((a) => `${a}%`));
373
+ }
374
+ if (filter.kinds?.length) {
375
+ filterConditions.push(
376
+ `kind IN (${filter.kinds.map(() => "?").join(", ")})`
377
+ );
378
+ params.push(...filter.kinds);
379
+ }
380
+ if (filter.since !== void 0) {
381
+ filterConditions.push("created_at >= ?");
382
+ params.push(filter.since);
383
+ }
384
+ if (filter.until !== void 0) {
385
+ filterConditions.push("created_at <= ?");
386
+ params.push(filter.until);
387
+ }
388
+ for (const [key, values] of Object.entries(filter)) {
389
+ if (key.startsWith("#") && Array.isArray(values) && values.length > 0) {
390
+ const tagName = key.slice(1);
391
+ const tagConditions = values.map(() => `tags LIKE ?`);
392
+ filterConditions.push(`(${tagConditions.join(" OR ")})`);
393
+ params.push(...values.map((v) => `%["${tagName}","${v}"%`));
394
+ }
395
+ }
396
+ if (filterConditions.length > 0) {
397
+ conditions.push(`(${filterConditions.join(" AND ")})`);
398
+ }
399
+ }
400
+ let sql = "SELECT * FROM events";
401
+ if (conditions.length > 0) {
402
+ sql += ` WHERE ${conditions.join(" OR ")}`;
403
+ }
404
+ sql += " ORDER BY created_at DESC";
405
+ const limitFilter = filters.find((f) => f.limit !== void 0);
406
+ if (limitFilter?.limit !== void 0) {
407
+ sql += " LIMIT ?";
408
+ params.push(limitFilter.limit);
409
+ }
410
+ return { sql, params };
411
+ }
412
+ /**
413
+ * Close the database connection.
414
+ */
415
+ close() {
416
+ this.db.close();
417
+ }
418
+ };
419
+
420
+ // src/toon/index.ts
421
+ import {
422
+ encodeEventToToon,
423
+ encodeEventToToonString,
424
+ ToonEncodeError
425
+ } from "@toon-protocol/core";
426
+ import { decodeEventFromToon, ToonDecodeError } from "@toon-protocol/core";
427
+
428
+ // src/websocket/ConnectionHandler.ts
429
+ var ConnectionHandler = class {
430
+ constructor(ws, eventStore, config = {}) {
431
+ this.ws = ws;
432
+ this.eventStore = eventStore;
433
+ this.config = { ...DEFAULT_RELAY_CONFIG, ...config };
434
+ }
435
+ ws;
436
+ eventStore;
437
+ subscriptions = /* @__PURE__ */ new Map();
438
+ config;
439
+ /**
440
+ * Handle an incoming message from the WebSocket.
441
+ */
442
+ handleMessage(data) {
443
+ console.log(`[ConnectionHandler] Received message:`, data.slice(0, 150));
444
+ let message;
445
+ try {
446
+ const parsed = JSON.parse(data);
447
+ if (!Array.isArray(parsed)) {
448
+ this.sendNotice("error: invalid message format, expected JSON array");
449
+ return;
450
+ }
451
+ message = parsed;
452
+ } catch {
453
+ this.sendNotice("error: invalid JSON");
454
+ return;
455
+ }
456
+ const messageType = message[0];
457
+ console.log(`[ConnectionHandler] Message type: ${messageType}`);
458
+ if (messageType === "REQ") {
459
+ const subscriptionId = message[1];
460
+ const filters = message.slice(2);
461
+ this.handleReq(subscriptionId, filters);
462
+ } else if (messageType === "EVENT") {
463
+ const event = message[1];
464
+ this.handleEvent(event);
465
+ } else if (messageType === "CLOSE") {
466
+ const subscriptionId = message[1];
467
+ this.handleClose(subscriptionId);
468
+ } else {
469
+ this.sendNotice(`error: unknown message type: ${messageType}`);
470
+ }
471
+ }
472
+ /**
473
+ * Handle a REQ message to create/update a subscription.
474
+ */
475
+ handleReq(subscriptionId, filters) {
476
+ if (typeof subscriptionId !== "string" || subscriptionId.length === 0) {
477
+ this.sendNotice("error: invalid subscription id");
478
+ return;
479
+ }
480
+ if (!this.subscriptions.has(subscriptionId)) {
481
+ if (this.subscriptions.size >= this.config.maxSubscriptionsPerConnection) {
482
+ this.sendNotice("error: too many subscriptions");
483
+ return;
484
+ }
485
+ }
486
+ if (filters.length > this.config.maxFiltersPerSubscription) {
487
+ this.sendNotice("error: too many filters");
488
+ return;
489
+ }
490
+ this.subscriptions.set(subscriptionId, {
491
+ id: subscriptionId,
492
+ filters
493
+ });
494
+ console.log(
495
+ `[ConnectionHandler] REQ: ${subscriptionId}, filters:`,
496
+ JSON.stringify(filters).slice(0, 100)
497
+ );
498
+ const events = this.eventStore.query(filters);
499
+ console.log(
500
+ `[ConnectionHandler] Query returned ${events.length} events for ${subscriptionId}`
501
+ );
502
+ for (const event of events) {
503
+ console.log(
504
+ `[ConnectionHandler] Sending event ${event.id.slice(0, 16)}... to ${subscriptionId}`
505
+ );
506
+ this.sendEvent(subscriptionId, event);
507
+ }
508
+ console.log(`[ConnectionHandler] Sending EOSE for ${subscriptionId}`);
509
+ this.sendEose(subscriptionId);
510
+ }
511
+ /**
512
+ * Handle an EVENT message from a WebSocket client.
513
+ *
514
+ * Rejects all external writes — the relay is ILP-gated (pay to write).
515
+ * Events are only stored through the ILP packet handler which calls
516
+ * eventStore.store() directly and then broadcastEvent() to notify subscribers.
517
+ */
518
+ handleEvent(event) {
519
+ this.sendOk(event.id, false, "restricted: writes require ILP payment");
520
+ }
521
+ /**
522
+ * Handle a CLOSE message to terminate a subscription.
523
+ */
524
+ handleClose(subscriptionId) {
525
+ this.subscriptions.delete(subscriptionId);
526
+ }
527
+ /**
528
+ * Push a new event to all matching subscriptions on this connection.
529
+ * Used when events are stored outside the WebSocket flow (e.g., via ILP).
530
+ */
531
+ notifyNewEvent(event) {
532
+ for (const sub of this.subscriptions.values()) {
533
+ const matches = sub.filters.some((f) => matchFilter(event, f));
534
+ if (matches) {
535
+ this.sendEvent(sub.id, event);
536
+ }
537
+ }
538
+ }
539
+ /**
540
+ * Clean up all subscriptions for this connection.
541
+ */
542
+ cleanup() {
543
+ this.subscriptions.clear();
544
+ }
545
+ /**
546
+ * Get the number of active subscriptions.
547
+ */
548
+ getSubscriptionCount() {
549
+ return this.subscriptions.size;
550
+ }
551
+ sendEvent(subscriptionId, event) {
552
+ this.send(["EVENT", subscriptionId, encodeEventToToonString(event)]);
553
+ }
554
+ sendEose(subscriptionId) {
555
+ this.send(["EOSE", subscriptionId]);
556
+ }
557
+ sendOk(eventId, success, message) {
558
+ this.send(["OK", eventId, success, message]);
559
+ }
560
+ sendNotice(message) {
561
+ this.send(["NOTICE", message]);
562
+ }
563
+ send(message) {
564
+ if (this.ws.readyState === 1) {
565
+ this.ws.send(JSON.stringify(message));
566
+ }
567
+ }
568
+ };
569
+
570
+ // src/websocket/NostrRelayServer.ts
571
+ import { WebSocketServer } from "ws";
572
+ var NostrRelayServer = class {
573
+ constructor(config = {}, eventStore) {
574
+ this.eventStore = eventStore;
575
+ this.config = { ...DEFAULT_RELAY_CONFIG, ...config };
576
+ }
577
+ eventStore;
578
+ wss = null;
579
+ handlers = /* @__PURE__ */ new Map();
580
+ config;
581
+ /**
582
+ * Start the WebSocket server.
583
+ */
584
+ async start() {
585
+ return new Promise((resolve, reject) => {
586
+ try {
587
+ this.wss = new WebSocketServer({
588
+ port: this.config.port,
589
+ host: this.config.host
590
+ });
591
+ this.wss.on("connection", (ws) => {
592
+ this.handleConnection(ws);
593
+ });
594
+ this.wss.on("error", (error) => {
595
+ console.error("[NostrRelayServer] Server error:", error.message);
596
+ });
597
+ this.wss.on("listening", () => {
598
+ const address = this.wss?.address();
599
+ if (address && typeof address === "object") {
600
+ console.log(`[NostrRelayServer] Listening on port ${address.port}`);
601
+ }
602
+ resolve();
603
+ });
604
+ } catch (error) {
605
+ reject(error);
606
+ }
607
+ });
608
+ }
609
+ /**
610
+ * Stop the WebSocket server and close all connections.
611
+ */
612
+ async stop() {
613
+ return new Promise((resolve) => {
614
+ if (!this.wss) {
615
+ resolve();
616
+ return;
617
+ }
618
+ for (const [ws, handler] of this.handlers) {
619
+ handler.cleanup();
620
+ ws.close();
621
+ }
622
+ this.handlers.clear();
623
+ this.wss.close(() => {
624
+ this.wss = null;
625
+ resolve();
626
+ });
627
+ });
628
+ }
629
+ /**
630
+ * Get the port the server is listening on.
631
+ * Returns 0 if the server is not started.
632
+ */
633
+ getPort() {
634
+ if (!this.wss) return 0;
635
+ const address = this.wss.address();
636
+ if (address && typeof address === "object") {
637
+ return address.port;
638
+ }
639
+ return 0;
640
+ }
641
+ /**
642
+ * Get the number of connected clients.
643
+ */
644
+ getClientCount() {
645
+ return this.handlers.size;
646
+ }
647
+ /**
648
+ * Broadcast an event to all connected clients with matching subscriptions.
649
+ * Call this after storing an event outside the WebSocket flow (e.g., via ILP)
650
+ * so that discovery subscribers are notified.
651
+ */
652
+ broadcastEvent(event) {
653
+ for (const handler of this.handlers.values()) {
654
+ handler.notifyNewEvent(event);
655
+ }
656
+ }
657
+ handleConnection(ws) {
658
+ if (this.handlers.size >= this.config.maxConnections) {
659
+ ws.close(1013, "max connections reached");
660
+ return;
661
+ }
662
+ console.log("[NostrRelayServer] Client connected");
663
+ const handler = new ConnectionHandler(ws, this.eventStore, this.config);
664
+ this.handlers.set(ws, handler);
665
+ ws.on("message", (data) => {
666
+ const message = typeof data === "string" ? data : data.toString();
667
+ handler.handleMessage(message);
668
+ });
669
+ ws.on("close", () => {
670
+ console.log("[NostrRelayServer] Client disconnected");
671
+ handler.cleanup();
672
+ this.handlers.delete(ws);
673
+ });
674
+ ws.on("error", (error) => {
675
+ console.error("[NostrRelayServer] Client error:", error.message);
676
+ handler.cleanup();
677
+ this.handlers.delete(ws);
678
+ });
679
+ }
680
+ };
681
+
682
+ // src/subscriber/RelaySubscriber.ts
683
+ import { SimplePool } from "nostr-tools/pool";
684
+ import { verifyEvent } from "nostr-tools/pure";
685
+ var RelaySubscriber = class {
686
+ config;
687
+ eventStore;
688
+ pool;
689
+ started = false;
690
+ /**
691
+ * @param config - Subscriber configuration
692
+ * @param eventStore - Storage backend to write events into
693
+ * @param pool - Optional SimplePool instance (creates new one if not provided)
694
+ */
695
+ constructor(config, eventStore, pool) {
696
+ this.config = config;
697
+ this.eventStore = eventStore;
698
+ this.pool = pool ?? new SimplePool();
699
+ }
700
+ /**
701
+ * Start subscribing to the configured upstream relays.
702
+ *
703
+ * @returns Handle with unsubscribe() to stop the subscription
704
+ * @throws Error if already started
705
+ */
706
+ start() {
707
+ if (this.started) {
708
+ throw new Error("RelaySubscriber already started");
709
+ }
710
+ this.started = true;
711
+ const shouldVerify = this.config.verifySignatures !== false;
712
+ let isUnsubscribed = false;
713
+ const subCloser = this.pool.subscribeMany(
714
+ this.config.relayUrls,
715
+ this.config.filter,
716
+ {
717
+ onevent: (event) => {
718
+ if (isUnsubscribed) return;
719
+ if (shouldVerify && !verifyEvent(event)) {
720
+ return;
721
+ }
722
+ try {
723
+ this.eventStore.store(event);
724
+ } catch (error) {
725
+ console.warn(
726
+ "[RelaySubscriber] Failed to store event:",
727
+ error instanceof Error ? error.message : "Unknown error"
728
+ );
729
+ }
730
+ }
731
+ }
732
+ );
733
+ return {
734
+ unsubscribe: () => {
735
+ if (!isUnsubscribed) {
736
+ isUnsubscribed = true;
737
+ subCloser.close();
738
+ this.started = false;
739
+ }
740
+ }
741
+ };
742
+ }
743
+ };
744
+
745
+ // src/launcher/handlers/event-storage-handler.ts
746
+ function createEventStorageHandler(config) {
747
+ const { eventStore } = config;
748
+ return async (ctx) => {
749
+ const event = ctx.decode();
750
+ eventStore.store(event);
751
+ return ctx.accept({ eventId: event.id, storedAt: Date.now() });
752
+ };
753
+ }
754
+
755
+ // src/launcher/handlers/x402-pricing.ts
756
+ function calculateX402Price(config, toonLength) {
757
+ const clampedBuffer = Math.max(0, Math.min(200, config.routingBufferPercent));
758
+ const basePrice = config.basePricePerByte * BigInt(toonLength);
759
+ const buffer = basePrice * BigInt(clampedBuffer) / 100n;
760
+ return basePrice + buffer;
761
+ }
762
+
763
+ // src/launcher/handlers/x402-types.ts
764
+ var EIP_3009_TYPES = {
765
+ TransferWithAuthorization: [
766
+ { name: "from", type: "address" },
767
+ { name: "to", type: "address" },
768
+ { name: "value", type: "uint256" },
769
+ { name: "validAfter", type: "uint256" },
770
+ { name: "validBefore", type: "uint256" },
771
+ { name: "nonce", type: "bytes32" }
772
+ ]
773
+ };
774
+ var USDC_EIP712_DOMAIN = {
775
+ name: "USD Coin",
776
+ version: "2"
777
+ };
778
+ var USDC_ABI = [
779
+ {
780
+ name: "balanceOf",
781
+ type: "function",
782
+ stateMutability: "view",
783
+ inputs: [{ name: "account", type: "address" }],
784
+ outputs: [{ name: "", type: "uint256" }]
785
+ },
786
+ {
787
+ name: "authorizationState",
788
+ type: "function",
789
+ stateMutability: "view",
790
+ inputs: [
791
+ { name: "authorizer", type: "address" },
792
+ { name: "nonce", type: "bytes32" }
793
+ ],
794
+ outputs: [{ name: "", type: "bool" }]
795
+ },
796
+ {
797
+ name: "transferWithAuthorization",
798
+ type: "function",
799
+ stateMutability: "nonpayable",
800
+ inputs: [
801
+ { name: "from", type: "address" },
802
+ { name: "to", type: "address" },
803
+ { name: "value", type: "uint256" },
804
+ { name: "validAfter", type: "uint256" },
805
+ { name: "validBefore", type: "uint256" },
806
+ { name: "nonce", type: "bytes32" },
807
+ { name: "v", type: "uint8" },
808
+ { name: "r", type: "bytes32" },
809
+ { name: "s", type: "bytes32" }
810
+ ],
811
+ outputs: []
812
+ }
813
+ ];
814
+
815
+ // src/launcher/handlers/x402-preflight.ts
816
+ import { verifyTypedData } from "viem";
817
+ import { shallowParseToon } from "@toon-protocol/core/toon";
818
+ async function runPreflight(authorization, toonData, destination, config) {
819
+ const checksPerformed = [];
820
+ checksPerformed.push("eip3009-signature");
821
+ try {
822
+ const domain = {
823
+ ...USDC_EIP712_DOMAIN,
824
+ chainId: config.chainConfig.chainId,
825
+ verifyingContract: config.chainConfig.usdcAddress
826
+ };
827
+ const valid = await verifyTypedData({
828
+ address: authorization.from,
829
+ domain,
830
+ types: EIP_3009_TYPES,
831
+ primaryType: "TransferWithAuthorization",
832
+ message: {
833
+ from: authorization.from,
834
+ to: authorization.to,
835
+ value: authorization.value,
836
+ validAfter: BigInt(authorization.validAfter),
837
+ validBefore: BigInt(authorization.validBefore),
838
+ nonce: authorization.nonce
839
+ },
840
+ signature: encodeSignature(authorization)
841
+ });
842
+ if (!valid) {
843
+ return {
844
+ passed: false,
845
+ failedCheck: "eip3009-signature",
846
+ checksPerformed
847
+ };
848
+ }
849
+ } catch {
850
+ return { passed: false, failedCheck: "eip3009-signature", checksPerformed };
851
+ }
852
+ checksPerformed.push("usdc-balance");
853
+ if (config.publicClient) {
854
+ try {
855
+ const balance = await config.publicClient.readContract({
856
+ address: config.chainConfig.usdcAddress,
857
+ abi: USDC_ABI,
858
+ functionName: "balanceOf",
859
+ args: [authorization.from]
860
+ });
861
+ if (balance < authorization.value) {
862
+ return { passed: false, failedCheck: "usdc-balance", checksPerformed };
863
+ }
864
+ } catch {
865
+ return { passed: false, failedCheck: "usdc-balance", checksPerformed };
866
+ }
867
+ }
868
+ checksPerformed.push("nonce-freshness");
869
+ if (config.publicClient) {
870
+ try {
871
+ const used = await config.publicClient.readContract({
872
+ address: config.chainConfig.usdcAddress,
873
+ abi: USDC_ABI,
874
+ functionName: "authorizationState",
875
+ args: [
876
+ authorization.from,
877
+ authorization.nonce
878
+ ]
879
+ });
880
+ if (used) {
881
+ return {
882
+ passed: false,
883
+ failedCheck: "nonce-freshness",
884
+ checksPerformed
885
+ };
886
+ }
887
+ } catch {
888
+ return { passed: false, failedCheck: "nonce-freshness", checksPerformed };
889
+ }
890
+ }
891
+ checksPerformed.push("toon-shallow-parse");
892
+ let toonMeta;
893
+ try {
894
+ const toonBytes = Buffer.from(toonData, "base64");
895
+ toonMeta = shallowParseToon(toonBytes);
896
+ } catch {
897
+ return {
898
+ passed: false,
899
+ failedCheck: "toon-shallow-parse",
900
+ checksPerformed
901
+ };
902
+ }
903
+ checksPerformed.push("schnorr-signature");
904
+ if (!config.devMode && config.schnorrVerify) {
905
+ try {
906
+ const valid = await config.schnorrVerify(toonMeta);
907
+ if (!valid) {
908
+ return {
909
+ passed: false,
910
+ failedCheck: "schnorr-signature",
911
+ checksPerformed
912
+ };
913
+ }
914
+ } catch {
915
+ return {
916
+ passed: false,
917
+ failedCheck: "schnorr-signature",
918
+ checksPerformed
919
+ };
920
+ }
921
+ }
922
+ checksPerformed.push("destination-reachability");
923
+ if (config.eventStore) {
924
+ try {
925
+ const events = config.eventStore.query([{ kinds: [10032] }]);
926
+ if (events.length === 0) {
927
+ return {
928
+ passed: false,
929
+ failedCheck: "destination-reachability",
930
+ checksPerformed
931
+ };
932
+ }
933
+ } catch {
934
+ return {
935
+ passed: false,
936
+ failedCheck: "destination-reachability",
937
+ checksPerformed
938
+ };
939
+ }
940
+ }
941
+ return { passed: true, checksPerformed };
942
+ }
943
+ function encodeSignature(auth) {
944
+ const r = auth.r.startsWith("0x") ? auth.r.slice(2) : auth.r;
945
+ const s = auth.s.startsWith("0x") ? auth.s.slice(2) : auth.s;
946
+ const v = auth.v.toString(16).padStart(2, "0");
947
+ return `0x${r}${s}${v}`;
948
+ }
949
+
950
+ // src/launcher/handlers/x402-settlement.ts
951
+ async function settleEip3009(authorization, config) {
952
+ try {
953
+ const hash = await config.walletClient.writeContract({
954
+ address: config.chainConfig.usdcAddress,
955
+ abi: USDC_ABI,
956
+ functionName: "transferWithAuthorization",
957
+ args: [
958
+ authorization.from,
959
+ authorization.to,
960
+ authorization.value,
961
+ BigInt(authorization.validAfter),
962
+ BigInt(authorization.validBefore),
963
+ authorization.nonce,
964
+ authorization.v,
965
+ authorization.r,
966
+ authorization.s
967
+ ],
968
+ chain: null,
969
+ // Use the wallet client's configured chain
970
+ account: config.walletClient.account ?? null
971
+ });
972
+ if (config.publicClient) {
973
+ const receipt = await config.publicClient.waitForTransactionReceipt({
974
+ hash
975
+ });
976
+ if (receipt.status === "reverted") {
977
+ return {
978
+ success: false,
979
+ error: "Transaction reverted on-chain"
980
+ };
981
+ }
982
+ }
983
+ return {
984
+ success: true,
985
+ txHash: hash
986
+ };
987
+ } catch (error) {
988
+ const message = error instanceof Error ? error.message : "Unknown settlement error";
989
+ return {
990
+ success: false,
991
+ error: message
992
+ };
993
+ }
994
+ }
995
+
996
+ // src/launcher/handlers/x402-publish-handler.ts
997
+ import { buildIlpPrepare, encodeEventToToon as encodeEventToToon2 } from "@toon-protocol/core";
998
+ function createX402Handler(config) {
999
+ const encoder = config.toonEncoder ?? encodeEventToToon2;
1000
+ if (config.x402Enabled && (!config.facilitatorAddress || !/^0x[0-9a-fA-F]{40}$/.test(config.facilitatorAddress))) {
1001
+ throw new Error(
1002
+ "x402 enabled but facilitatorAddress is not a valid EVM address"
1003
+ );
1004
+ }
1005
+ return {
1006
+ async handlePublish(c) {
1007
+ if (!config.x402Enabled) {
1008
+ return c.json({ error: "x402 not enabled" }, 404);
1009
+ }
1010
+ let body;
1011
+ try {
1012
+ body = await c.req.json();
1013
+ } catch {
1014
+ return c.json({ error: "Invalid request body" }, 400);
1015
+ }
1016
+ if (!body.event || !body.destination) {
1017
+ return c.json(
1018
+ { error: "Missing required fields: event, destination" },
1019
+ 400
1020
+ );
1021
+ }
1022
+ if (typeof body.destination !== "string" || !body.destination.startsWith("g.")) {
1023
+ return c.json(
1024
+ { error: "Invalid destination: must be a global ILP address (g.*)" },
1025
+ 400
1026
+ );
1027
+ }
1028
+ let toonBytes;
1029
+ try {
1030
+ toonBytes = encoder(body.event);
1031
+ } catch {
1032
+ return c.json({ error: "Failed to TOON-encode event" }, 400);
1033
+ }
1034
+ const toonBase64 = Buffer.from(toonBytes).toString("base64");
1035
+ const paymentHeader = c.req.header("X-PAYMENT");
1036
+ if (!paymentHeader) {
1037
+ const price = calculateX402Price(
1038
+ {
1039
+ basePricePerByte: config.basePricePerByte,
1040
+ routingBufferPercent: config.routingBufferPercent
1041
+ },
1042
+ toonBytes.length
1043
+ );
1044
+ const pricing = {
1045
+ amount: String(price),
1046
+ facilitatorAddress: config.facilitatorAddress,
1047
+ paymentNetwork: "eip-3009",
1048
+ chainId: config.chainConfig.chainId,
1049
+ usdcAddress: config.chainConfig.usdcAddress
1050
+ };
1051
+ return c.json(pricing, 402);
1052
+ }
1053
+ let authorization;
1054
+ try {
1055
+ const parsed = JSON.parse(paymentHeader);
1056
+ authorization = parseAuthorization(parsed);
1057
+ } catch {
1058
+ return c.json({ error: "Invalid X-PAYMENT header" }, 400);
1059
+ }
1060
+ const preflightConfig = {
1061
+ chainConfig: config.chainConfig,
1062
+ basePricePerByte: config.basePricePerByte,
1063
+ ownPubkey: config.ownPubkey,
1064
+ devMode: config.devMode,
1065
+ publicClient: config.publicClient,
1066
+ eventStore: config.eventStore
1067
+ };
1068
+ try {
1069
+ const preflightFn = config.runPreflightFn ?? runPreflight;
1070
+ const preflightResult = await preflightFn(
1071
+ authorization,
1072
+ toonBase64,
1073
+ body.destination,
1074
+ preflightConfig
1075
+ );
1076
+ if (!preflightResult.passed) {
1077
+ return c.json(
1078
+ {
1079
+ error: `Pre-flight check failed: ${preflightResult.failedCheck}`,
1080
+ failedCheck: preflightResult.failedCheck
1081
+ },
1082
+ 400
1083
+ );
1084
+ }
1085
+ } catch {
1086
+ console.error("[x402] Pre-flight error");
1087
+ return c.json({ error: "Internal server error" }, 500);
1088
+ }
1089
+ let settlementResult;
1090
+ try {
1091
+ const settleFn = config.settle ?? settleEip3009;
1092
+ if (!config.settle && !config.walletClient) {
1093
+ console.error("[x402] Settlement error: walletClient not configured");
1094
+ return c.json({ error: "Internal server error" }, 500);
1095
+ }
1096
+ const settlementConfig = {
1097
+ chainConfig: config.chainConfig,
1098
+ walletClient: config.walletClient,
1099
+ publicClient: config.publicClient
1100
+ };
1101
+ settlementResult = await settleFn(authorization, settlementConfig);
1102
+ } catch {
1103
+ console.error("[x402] Settlement error");
1104
+ return c.json({ error: "Internal server error" }, 500);
1105
+ }
1106
+ if (!settlementResult.success) {
1107
+ console.error(
1108
+ "[x402] Settlement failed:",
1109
+ settlementResult.error ?? "unknown"
1110
+ );
1111
+ return c.json({ error: "Settlement failed" }, 400);
1112
+ }
1113
+ const amount = config.basePricePerByte * BigInt(toonBytes.length);
1114
+ const prepareParams = {
1115
+ destination: body.destination,
1116
+ amount,
1117
+ data: toonBytes
1118
+ };
1119
+ const prepare = buildIlpPrepare(prepareParams);
1120
+ let deliveryStatus = "rejected";
1121
+ if (config.ilpClient) {
1122
+ try {
1123
+ const ilpResult = await config.ilpClient.sendIlpPacket(prepare);
1124
+ deliveryStatus = ilpResult.accepted ? "fulfilled" : "rejected";
1125
+ } catch {
1126
+ deliveryStatus = "rejected";
1127
+ }
1128
+ }
1129
+ const response = {
1130
+ eventId: body.event.id,
1131
+ settlementTxHash: settlementResult.txHash ?? "",
1132
+ deliveryStatus,
1133
+ refundInitiated: false
1134
+ };
1135
+ return c.json(response, 200);
1136
+ }
1137
+ };
1138
+ }
1139
+ function isValidHex(value, expectedLength) {
1140
+ if (value.length !== expectedLength) return false;
1141
+ if (!value.startsWith("0x")) return false;
1142
+ return /^0x[0-9a-fA-F]+$/.test(value);
1143
+ }
1144
+ function parseAuthorization(parsed) {
1145
+ if (typeof parsed !== "object" || parsed === null) {
1146
+ throw new Error("Authorization must be an object");
1147
+ }
1148
+ const obj = parsed;
1149
+ const from = obj["from"];
1150
+ const to = obj["to"];
1151
+ const value = obj["value"];
1152
+ const validAfter = obj["validAfter"];
1153
+ const validBefore = obj["validBefore"];
1154
+ const nonce = obj["nonce"];
1155
+ const v = obj["v"];
1156
+ const r = obj["r"];
1157
+ const s = obj["s"];
1158
+ if (typeof from !== "string" || !isValidHex(from, 42)) {
1159
+ throw new Error("Invalid from address");
1160
+ }
1161
+ if (typeof to !== "string" || !isValidHex(to, 42)) {
1162
+ throw new Error("Invalid to address");
1163
+ }
1164
+ if (typeof nonce !== "string" || !isValidHex(nonce, 66)) {
1165
+ throw new Error("Invalid nonce");
1166
+ }
1167
+ if (typeof r !== "string" || !isValidHex(r, 66)) {
1168
+ throw new Error("Invalid r");
1169
+ }
1170
+ if (typeof s !== "string" || !isValidHex(s, 66)) {
1171
+ throw new Error("Invalid s");
1172
+ }
1173
+ if (typeof v !== "number" || v !== 27 && v !== 28) {
1174
+ throw new Error("Invalid v");
1175
+ }
1176
+ const parsedValidAfter = Number(validAfter);
1177
+ const parsedValidBefore = Number(validBefore);
1178
+ if (Number.isNaN(parsedValidAfter) || parsedValidAfter < 0) {
1179
+ throw new Error("Invalid validAfter");
1180
+ }
1181
+ if (Number.isNaN(parsedValidBefore) || parsedValidBefore < 0) {
1182
+ throw new Error("Invalid validBefore");
1183
+ }
1184
+ const valueStr = String(value);
1185
+ let valueBigInt;
1186
+ try {
1187
+ valueBigInt = BigInt(valueStr);
1188
+ } catch {
1189
+ throw new Error("Invalid value");
1190
+ }
1191
+ if (valueBigInt < 0n) {
1192
+ throw new Error("Invalid value: must be non-negative");
1193
+ }
1194
+ return {
1195
+ from,
1196
+ to,
1197
+ value: valueBigInt,
1198
+ validAfter: parsedValidAfter,
1199
+ validBefore: parsedValidBefore,
1200
+ nonce,
1201
+ v,
1202
+ r,
1203
+ s
1204
+ };
1205
+ }
1206
+
1207
+ // src/launcher/health.ts
1208
+ import { VERSION } from "@toon-protocol/core";
1209
+ function createHealthResponse(config) {
1210
+ const response = {
1211
+ status: "healthy",
1212
+ phase: config.phase,
1213
+ pubkey: config.pubkey,
1214
+ ilpAddress: config.ilpAddress,
1215
+ peerCount: config.peerCount,
1216
+ discoveredPeerCount: config.discoveredPeerCount,
1217
+ channelCount: config.channelCount,
1218
+ pricing: {
1219
+ basePricePerByte: Number(config.basePricePerByte),
1220
+ currency: "USDC"
1221
+ },
1222
+ capabilities: config.x402Enabled ? ["relay", "x402"] : ["relay"],
1223
+ chain: config.chain,
1224
+ version: VERSION,
1225
+ sdk: true,
1226
+ timestamp: Date.now()
1227
+ };
1228
+ if (config.x402Enabled) {
1229
+ response.x402 = {
1230
+ enabled: true,
1231
+ endpoint: "/publish"
1232
+ };
1233
+ }
1234
+ if (config.tee) {
1235
+ response.tee = config.tee;
1236
+ }
1237
+ return response;
1238
+ }
1239
+
1240
+ // src/launcher/town.ts
1241
+ import { mkdirSync } from "fs";
1242
+ import { join } from "path";
1243
+ import { serve } from "@hono/node-server";
1244
+ import { Hono } from "hono";
1245
+ import {
1246
+ HandlerRegistry,
1247
+ createVerificationPipeline,
1248
+ createPricingValidator,
1249
+ createHandlerContext,
1250
+ fromMnemonic,
1251
+ fromSecretKey
1252
+ } from "@toon-protocol/sdk";
1253
+ import {
1254
+ BootstrapService,
1255
+ createDiscoveryTracker,
1256
+ ILP_PEER_INFO_KIND,
1257
+ createDirectIlpClient,
1258
+ createDirectConnectorAdmin,
1259
+ createDirectChannelClient,
1260
+ SocialPeerDiscovery,
1261
+ buildIlpPeerInfoEvent,
1262
+ resolveChainConfig,
1263
+ SeedRelayDiscovery,
1264
+ publishSeedRelayEntry,
1265
+ buildServiceDiscoveryEvent,
1266
+ VERSION as VERSION2
1267
+ } from "@toon-protocol/core";
1268
+ import {
1269
+ shallowParseToon as shallowParseToon2,
1270
+ decodeEventFromToon as decodeEventFromToon2,
1271
+ encodeEventToToon as encodeEventToToon3
1272
+ } from "@toon-protocol/core/toon";
1273
+ import {
1274
+ ConnectorNode,
1275
+ createLogger as createConnectorLogger
1276
+ } from "@toon-protocol/connector";
1277
+ import {
1278
+ createPublicClient,
1279
+ createWalletClient,
1280
+ defineChain,
1281
+ http
1282
+ } from "viem";
1283
+ import { privateKeyToAccount } from "viem/accounts";
1284
+ var MAX_PAYLOAD_BASE64_LENGTH = 1048576;
1285
+ function createSubscription(relayUrl, filter, eventStore, activeSubscriptions) {
1286
+ if (!relayUrl.startsWith("ws://") && !relayUrl.startsWith("wss://")) {
1287
+ throw new Error(
1288
+ "Invalid relay URL -- must use WebSocket scheme (ws or wss)"
1289
+ );
1290
+ }
1291
+ const subscriber = new RelaySubscriber(
1292
+ { relayUrls: [relayUrl], filter },
1293
+ eventStore
1294
+ );
1295
+ const handle = subscriber.start();
1296
+ let active = true;
1297
+ let _lastSeenTimestamp = 0;
1298
+ void _lastSeenTimestamp;
1299
+ const subscription = {
1300
+ close() {
1301
+ if (!active) return;
1302
+ active = false;
1303
+ handle.unsubscribe();
1304
+ activeSubscriptions.delete(subscription);
1305
+ },
1306
+ relayUrl,
1307
+ isActive() {
1308
+ return active;
1309
+ }
1310
+ };
1311
+ activeSubscriptions.add(subscription);
1312
+ return subscription;
1313
+ }
1314
+ async function startRelay(config) {
1315
+ const hasMnemonic = config.mnemonic !== void 0;
1316
+ const hasSecretKey = config.secretKey !== void 0;
1317
+ if (hasMnemonic && hasSecretKey) {
1318
+ throw new Error(
1319
+ "RelayConfig: provide either mnemonic or secretKey, not both"
1320
+ );
1321
+ }
1322
+ if (!hasMnemonic && !hasSecretKey) {
1323
+ throw new Error("RelayConfig: one of mnemonic or secretKey is required");
1324
+ }
1325
+ const hasConnector = config.connector !== void 0;
1326
+ const hasConnectorUrl = config.connectorUrl !== void 0;
1327
+ if (hasConnector && hasConnectorUrl) {
1328
+ throw new Error(
1329
+ "RelayConfig: provide either connector or connectorUrl, not both"
1330
+ );
1331
+ }
1332
+ if (hasConnectorUrl && config.ilpAddress === void 0) {
1333
+ throw new Error(
1334
+ "RelayConfig: ilpAddress is required when connectorUrl is set (must fall under the parent connector prefix, e.g. g.townhouse.<self>)"
1335
+ );
1336
+ }
1337
+ const identity = hasMnemonic ? fromMnemonic(config.mnemonic) : fromSecretKey(config.secretKey);
1338
+ const relayPort = config.relayPort ?? 7100;
1339
+ const blsPort = config.blsPort ?? 3100;
1340
+ const pubkeyShort = identity.pubkey.slice(0, 16);
1341
+ const ilpAddress = config.ilpAddress ?? `g.toon.${pubkeyShort}`;
1342
+ const btpEndpoint = config.btpEndpoint ?? "";
1343
+ const nodeId = config.nodeId ?? `toon-${pubkeyShort}`;
1344
+ const parentPeerId = config.parentPeerId ?? "apex";
1345
+ const parentAuthToken = config.parentAuthToken ?? "";
1346
+ const connectorUrl = config.connectorUrl;
1347
+ const basePricePerByte = config.feePerEvent !== void 0 ? BigInt(config.feePerEvent) : config.basePricePerByte ?? 10n;
1348
+ const routingBufferPercent = config.routingBufferPercent ?? 10;
1349
+ const x402Enabled = config.x402Enabled ?? false;
1350
+ const knownPeers = [...config.knownPeers ?? []];
1351
+ const dataDir = config.dataDir ?? "./data";
1352
+ const devMode = config.devMode ?? false;
1353
+ const ardriveEnabled = config.ardriveEnabled ?? false;
1354
+ const relayUrls = config.relayUrls ?? [`ws://localhost:${relayPort}`];
1355
+ const assetCode = config.assetCode ?? "USD";
1356
+ const assetScale = config.assetScale ?? 6;
1357
+ const discovery = config.discovery ?? "genesis";
1358
+ const announcementTtlSeconds = (() => {
1359
+ const fromEnv = process.env["TOON_ANNOUNCEMENT_TTL_SECONDS"];
1360
+ const raw = fromEnv !== void 0 && fromEnv !== "" ? Number(fromEnv) : config.announcementTtlSeconds;
1361
+ if (raw === void 0) return 3600;
1362
+ if (!Number.isFinite(raw) || raw < 0) return 3600;
1363
+ return Math.floor(raw);
1364
+ })();
1365
+ const seedRelays = config.seedRelays ?? [];
1366
+ const publishSeedEntryFlag = config.publishSeedEntry ?? false;
1367
+ const externalRelayUrl = config.externalRelayUrl ?? (config.ator?.enabled && config.ator.anonAddress ? config.ator.anonAddress : void 0);
1368
+ const requestedChain = process.env["TOON_CHAIN"] || config.chain;
1369
+ const relayOnly = requestedChain === "none";
1370
+ if (relayOnly) {
1371
+ console.log("[Town] connector.relay_only", {
1372
+ reason: "no settlement chain configured (chain=none)"
1373
+ });
1374
+ }
1375
+ const chainConfig = relayOnly ? {
1376
+ name: "none",
1377
+ chainId: 0,
1378
+ rpcUrl: "",
1379
+ usdcAddress: "",
1380
+ tokenNetworkAddress: "",
1381
+ registryAddress: ""
1382
+ } : resolveChainConfig(config.chain);
1383
+ const chainKey = `evm:base:${chainConfig.chainId}`;
1384
+ const resolvedConfig = {
1385
+ relayPort,
1386
+ blsPort,
1387
+ ilpAddress,
1388
+ btpEndpoint,
1389
+ nodeId,
1390
+ ...connectorUrl && { connectorUrl, parentPeerId },
1391
+ basePricePerByte,
1392
+ routingBufferPercent,
1393
+ x402Enabled,
1394
+ knownPeers,
1395
+ dataDir,
1396
+ devMode,
1397
+ ardriveEnabled,
1398
+ relayUrls,
1399
+ assetCode,
1400
+ assetScale,
1401
+ discovery,
1402
+ seedRelays,
1403
+ publishSeedEntry: publishSeedEntryFlag,
1404
+ ...externalRelayUrl && { externalRelayUrl },
1405
+ chain: chainConfig.name
1406
+ };
1407
+ let autoCreatedConnector = null;
1408
+ if (!hasConnector) {
1409
+ const btpServerPort = config.btpServerPort ?? 3e3;
1410
+ const connectorLogger = createConnectorLogger(
1411
+ nodeId,
1412
+ process.env["TOON_CONNECTOR_LOG_LEVEL"] ?? "warn"
1413
+ );
1414
+ const routes = [{ prefix: ilpAddress, nextHop: nodeId, priority: 100 }];
1415
+ const peers = [];
1416
+ if (hasConnectorUrl) {
1417
+ peers.push({
1418
+ id: parentPeerId,
1419
+ url: connectorUrl,
1420
+ authToken: parentAuthToken,
1421
+ // Tag the upstream as our PARENT so the embedded connector's
1422
+ // relation-aware logic applies (toon-protocol/connector#78): a child
1423
+ // skips the inbound per-packet-claim requirement for PREPAREs forwarded
1424
+ // by its parent (the parent settles in aggregate and attaches no
1425
+ // per-packet claim to a child). Without this the peer defaults to
1426
+ // 'peer' and the child F06-rejects every parent-forwarded paid packet.
1427
+ // NOTE: `parentPeerId` MUST equal the parent connector's nodeId (its BTP
1428
+ // auth identity), since the connector keys peerRelations by the
1429
+ // auth-declared peerId of the inbound session — not a local alias.
1430
+ relation: "parent",
1431
+ // When the operator publishes their EVM treasury address to the
1432
+ // parent, the apex can open a settlement channel toward this child
1433
+ // without needing to discover the address via kind:10032. The
1434
+ // connector schema treats this field as optional metadata.
1435
+ ...config.parentEvmAddress && { evmAddress: config.parentEvmAddress }
1436
+ });
1437
+ routes.push({ prefix: "g", nextHop: parentPeerId, priority: 0 });
1438
+ }
1439
+ const hasSettlementAddresses = !!chainConfig.rpcUrl && !!chainConfig.registryAddress && !!chainConfig.tokenNetworkAddress && !!chainConfig.usdcAddress;
1440
+ let chainProvidersEntry = null;
1441
+ if (hasSettlementAddresses) {
1442
+ const keyHex = config.settlementPrivateKey ?? `0x${Buffer.from(identity.secretKey).toString("hex")}`;
1443
+ if (!/^0x[0-9a-fA-F]{64}$/.test(keyHex)) {
1444
+ throw new Error(
1445
+ `RelayConfig.settlementPrivateKey must be a 0x-prefixed 32-byte hex string (got length ${keyHex.length}); cannot wire chainProviders for ${chainConfig.name}`
1446
+ );
1447
+ }
1448
+ chainProvidersEntry = {
1449
+ chainType: "evm",
1450
+ chainId: `evm:${chainConfig.chainId}`,
1451
+ rpcUrl: chainConfig.rpcUrl,
1452
+ registryAddress: chainConfig.registryAddress,
1453
+ tokenAddress: chainConfig.usdcAddress,
1454
+ keyId: keyHex
1455
+ };
1456
+ } else {
1457
+ console.warn("[Town] connector.chain_providers_skipped", {
1458
+ chain: chainConfig.name,
1459
+ reason: "missing settlement addresses"
1460
+ });
1461
+ }
1462
+ const connectorConfig = {
1463
+ nodeId,
1464
+ btpServerPort,
1465
+ environment: "development",
1466
+ deploymentMode: "embedded",
1467
+ peers,
1468
+ routes,
1469
+ localDelivery: { enabled: false },
1470
+ // Children don't expose an admin API — the apex parent is the
1471
+ // operator-facing surface. Disabling avoids a hard runtime dep on
1472
+ // express in the town docker bundle.
1473
+ adminApi: { enabled: false },
1474
+ // Belt-and-braces: zero connector forwarding fee. Combined with the
1475
+ // packet-handler's automatic skip for local-delivery hops this keeps the
1476
+ // child fee surface flat regardless of peering topology.
1477
+ settlement: {
1478
+ connectorFeePercentage: 0
1479
+ },
1480
+ ...chainProvidersEntry && { chainProviders: [chainProvidersEntry] }
1481
+ };
1482
+ if (config.ator?.enabled && config.ator.anonAddress) {
1483
+ connectorConfig.transport = {
1484
+ type: "socks5",
1485
+ socksProxy: config.ator.socksProxy ?? "socks5h://127.0.0.1:9050",
1486
+ externalUrl: config.ator.anonAddress,
1487
+ managed: false
1488
+ };
1489
+ }
1490
+ autoCreatedConnector = new ConnectorNode(connectorConfig, connectorLogger);
1491
+ }
1492
+ const effectiveConnector = config.connector ?? autoCreatedConnector;
1493
+ mkdirSync(dataDir, { recursive: true });
1494
+ const dbPath = join(dataDir, "events.db");
1495
+ const eventStore = new SqliteEventStore(dbPath);
1496
+ const effectiveChainRpcUrls = config.chainRpcUrls ?? (relayOnly ? void 0 : { [chainKey]: chainConfig.rpcUrl });
1497
+ const effectivePreferredTokens = config.preferredTokens ?? (relayOnly ? void 0 : { [chainKey]: chainConfig.usdcAddress });
1498
+ const effectiveTokenNetworks = config.tokenNetworks ?? (chainConfig.tokenNetworkAddress ? { [chainKey]: chainConfig.tokenNetworkAddress } : void 0);
1499
+ let channelClient;
1500
+ let settlementInfo;
1501
+ const hasSettlement = effectiveChainRpcUrls || effectiveTokenNetworks || effectivePreferredTokens || config.settlementAddresses;
1502
+ if (hasSettlement) {
1503
+ const supportedChains = Array.from(
1504
+ /* @__PURE__ */ new Set([
1505
+ ...Object.keys(effectiveChainRpcUrls ?? {}),
1506
+ ...Object.keys(effectiveTokenNetworks ?? {}),
1507
+ ...Object.keys(effectivePreferredTokens ?? {}),
1508
+ ...Object.keys(config.settlementAddresses ?? {})
1509
+ ])
1510
+ );
1511
+ const settlementAddresses = {};
1512
+ for (const chain of supportedChains) {
1513
+ settlementAddresses[chain] = config.settlementAddresses?.[chain] ?? identity.evmAddress;
1514
+ }
1515
+ settlementInfo = {
1516
+ supportedChains,
1517
+ settlementAddresses,
1518
+ preferredTokens: effectivePreferredTokens,
1519
+ tokenNetworks: effectiveTokenNetworks
1520
+ };
1521
+ if (effectiveConnector.openChannel && effectiveConnector.getChannelState) {
1522
+ channelClient = createDirectChannelClient(
1523
+ effectiveConnector
1524
+ );
1525
+ }
1526
+ }
1527
+ const adminClient = createDirectConnectorAdmin(effectiveConnector);
1528
+ const verifier = createVerificationPipeline({ devMode });
1529
+ const pricer = createPricingValidator({
1530
+ basePricePerByte,
1531
+ ownPubkey: identity.pubkey
1532
+ });
1533
+ const registry = new HandlerRegistry();
1534
+ registry.onDefault(createEventStorageHandler({ eventStore }));
1535
+ const toonDecoder = (toon) => {
1536
+ const bytes = Buffer.from(toon, "base64");
1537
+ return decodeEventFromToon2(bytes);
1538
+ };
1539
+ const handlePacket = async (request) => {
1540
+ if (request.data.length > MAX_PAYLOAD_BASE64_LENGTH) {
1541
+ return { accept: false, code: "F08", message: "Payload too large" };
1542
+ }
1543
+ const toonBytes = Buffer.from(request.data, "base64");
1544
+ let meta;
1545
+ try {
1546
+ meta = shallowParseToon2(toonBytes);
1547
+ } catch {
1548
+ return { accept: false, code: "F06", message: "Invalid TOON payload" };
1549
+ }
1550
+ const verifyResult = await verifier.verify(meta, request.data);
1551
+ if (!verifyResult.verified) {
1552
+ if (verifyResult.rejection) {
1553
+ return verifyResult.rejection;
1554
+ }
1555
+ return { accept: false, code: "F06", message: "Verification failed" };
1556
+ }
1557
+ let amount;
1558
+ try {
1559
+ amount = BigInt(request.amount);
1560
+ } catch {
1561
+ return {
1562
+ accept: false,
1563
+ code: "T00",
1564
+ message: "Invalid payment amount"
1565
+ };
1566
+ }
1567
+ const priceResult = pricer.validate(meta, amount);
1568
+ if (!priceResult.accepted) {
1569
+ if (priceResult.rejection) {
1570
+ return priceResult.rejection;
1571
+ }
1572
+ return {
1573
+ accept: false,
1574
+ code: "F04",
1575
+ message: "Pricing validation failed"
1576
+ };
1577
+ }
1578
+ const ctx = createHandlerContext({
1579
+ toon: request.data,
1580
+ meta,
1581
+ amount,
1582
+ destination: request.destination,
1583
+ toonDecoder
1584
+ });
1585
+ try {
1586
+ const result = await registry.dispatch(ctx);
1587
+ if (result.accept) {
1588
+ try {
1589
+ const event = decodeEventFromToon2(toonBytes);
1590
+ wsRelayRef.current?.broadcastEvent(event);
1591
+ } catch {
1592
+ }
1593
+ }
1594
+ return result;
1595
+ } catch (err) {
1596
+ const errMsg = err instanceof Error ? err.message : "Unknown error";
1597
+ console.error("[Town] Handler dispatch failed:", errMsg);
1598
+ return { accept: false, code: "T00", message: "Internal error" };
1599
+ }
1600
+ };
1601
+ const bootstrapService = new BootstrapService(
1602
+ {
1603
+ knownPeers,
1604
+ ardriveEnabled,
1605
+ defaultRelayUrl: `ws://localhost:${relayPort}`,
1606
+ ...settlementInfo && { settlementInfo },
1607
+ ownIlpAddress: ilpAddress,
1608
+ toonEncoder: encodeEventToToon3,
1609
+ toonDecoder: decodeEventFromToon2,
1610
+ basePricePerByte
1611
+ },
1612
+ identity.secretKey,
1613
+ {
1614
+ ilpAddress,
1615
+ btpEndpoint,
1616
+ assetCode,
1617
+ assetScale
1618
+ }
1619
+ );
1620
+ let peerCount = 0;
1621
+ let channelCount = 0;
1622
+ const discoveryTrackerRef = {};
1623
+ const wsRelayRef = {};
1624
+ const app = new Hono();
1625
+ app.get("/health", (c) => {
1626
+ const bootstrapPhase = bootstrapService.getPhase();
1627
+ const dt = discoveryTrackerRef.current;
1628
+ return c.json(
1629
+ createHealthResponse({
1630
+ phase: bootstrapPhase,
1631
+ pubkey: identity.pubkey,
1632
+ ilpAddress,
1633
+ peerCount: (dt ? dt.getPeerCount() : 0) + peerCount,
1634
+ discoveredPeerCount: dt ? dt.getDiscoveredCount() : 0,
1635
+ channelCount,
1636
+ basePricePerByte,
1637
+ x402Enabled,
1638
+ chain: chainConfig.name
1639
+ })
1640
+ );
1641
+ });
1642
+ app.post("/handle-packet", async (c) => {
1643
+ try {
1644
+ const body = await c.req.json();
1645
+ if (body.amount === void 0 || body.amount === null || body.destination === void 0 || body.destination === null || body.data === void 0 || body.data === null) {
1646
+ return c.json(
1647
+ { accept: false, code: "F00", message: "Missing required fields" },
1648
+ 400
1649
+ );
1650
+ }
1651
+ const result = await handlePacket(body);
1652
+ if (result.accept) {
1653
+ try {
1654
+ const toonBytes = Buffer.from(body.data, "base64");
1655
+ const decoded = decodeEventFromToon2(toonBytes);
1656
+ if (decoded && decoded.kind === ILP_PEER_INFO_KIND) {
1657
+ discoveryTrackerRef.current?.processEvent(decoded);
1658
+ }
1659
+ } catch {
1660
+ }
1661
+ }
1662
+ return c.json(result, result.accept ? 200 : 400);
1663
+ } catch (error) {
1664
+ console.error("[Town] handle-packet error:", error);
1665
+ return c.json(
1666
+ { accept: false, code: "T00", message: "Internal server error" },
1667
+ 500
1668
+ );
1669
+ }
1670
+ });
1671
+ const ilpClient = createDirectIlpClient(effectiveConnector, {
1672
+ toonDecoder: (bytes) => decodeEventFromToon2(bytes)
1673
+ });
1674
+ let x402WalletClient;
1675
+ let x402PublicClient;
1676
+ if (x402Enabled) {
1677
+ let keyBuffer;
1678
+ try {
1679
+ keyBuffer = Buffer.from(identity.secretKey);
1680
+ const privateKeyHex = `0x${keyBuffer.toString("hex")}`;
1681
+ const account = privateKeyToAccount(privateKeyHex);
1682
+ const viemChain = defineChain({
1683
+ id: chainConfig.chainId,
1684
+ name: chainConfig.name,
1685
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
1686
+ rpcUrls: { default: { http: [] } }
1687
+ });
1688
+ x402PublicClient = createPublicClient({
1689
+ chain: viemChain,
1690
+ transport: http(chainConfig.rpcUrl)
1691
+ });
1692
+ x402WalletClient = createWalletClient({
1693
+ account,
1694
+ chain: viemChain,
1695
+ transport: http(chainConfig.rpcUrl)
1696
+ });
1697
+ } catch (error) {
1698
+ throw new Error(
1699
+ `x402 initialization failed: could not derive EVM account from identity key: ${error instanceof Error ? error.message : String(error)}`
1700
+ );
1701
+ } finally {
1702
+ if (keyBuffer) {
1703
+ keyBuffer.fill(0);
1704
+ }
1705
+ }
1706
+ }
1707
+ const x402Handler = createX402Handler({
1708
+ x402Enabled,
1709
+ chainConfig,
1710
+ basePricePerByte,
1711
+ routingBufferPercent,
1712
+ facilitatorAddress: config.facilitatorAddress ?? identity.evmAddress,
1713
+ ownPubkey: identity.pubkey,
1714
+ devMode,
1715
+ eventStore,
1716
+ ilpClient,
1717
+ walletClient: x402WalletClient,
1718
+ publicClient: x402PublicClient
1719
+ });
1720
+ app.get("/publish", (c) => x402Handler.handlePublish(c));
1721
+ app.post("/publish", (c) => x402Handler.handlePublish(c));
1722
+ const blsServer = serve({
1723
+ fetch: app.fetch,
1724
+ port: blsPort
1725
+ });
1726
+ const relayHost = config.ator?.enabled ? "127.0.0.1" : void 0;
1727
+ const wsRelay = new NostrRelayServer(
1728
+ { port: relayPort, host: relayHost },
1729
+ eventStore
1730
+ );
1731
+ wsRelayRef.current = wsRelay;
1732
+ await wsRelay.start();
1733
+ await new Promise((resolve) => setTimeout(resolve, 500));
1734
+ let running = true;
1735
+ bootstrapService.setConnectorAdmin(adminClient);
1736
+ if (channelClient) {
1737
+ bootstrapService.setChannelClient(channelClient);
1738
+ }
1739
+ bootstrapService.setIlpClient(ilpClient);
1740
+ bootstrapService.on((event) => {
1741
+ switch (event.type) {
1742
+ case "bootstrap:peer-registered":
1743
+ peerCount++;
1744
+ break;
1745
+ case "bootstrap:channel-opened":
1746
+ channelCount++;
1747
+ break;
1748
+ case "bootstrap:ready":
1749
+ break;
1750
+ }
1751
+ });
1752
+ if (effectiveConnector.setPacketHandler) {
1753
+ effectiveConnector.setPacketHandler(async (request) => {
1754
+ const result = await handlePacket(request);
1755
+ if (result.accept && discoveryTrackerRef.current) {
1756
+ try {
1757
+ const toonBytes = Buffer.from(
1758
+ request.data,
1759
+ "base64"
1760
+ );
1761
+ const decoded = decodeEventFromToon2(toonBytes);
1762
+ if (decoded && decoded.kind === ILP_PEER_INFO_KIND) {
1763
+ discoveryTrackerRef.current.processEvent(decoded);
1764
+ }
1765
+ } catch {
1766
+ }
1767
+ }
1768
+ return result;
1769
+ });
1770
+ }
1771
+ if (autoCreatedConnector) {
1772
+ await autoCreatedConnector.start();
1773
+ }
1774
+ const discoveryTracker = createDiscoveryTracker({
1775
+ secretKey: identity.secretKey,
1776
+ settlementInfo
1777
+ });
1778
+ discoveryTracker.setConnectorAdmin(adminClient);
1779
+ if (channelClient) {
1780
+ discoveryTracker.setChannelClient(channelClient);
1781
+ }
1782
+ discoveryTrackerRef.current = discoveryTracker;
1783
+ let seedRelayDiscovery;
1784
+ if (discovery === "seed-list" && seedRelays.length > 0) {
1785
+ seedRelayDiscovery = new SeedRelayDiscovery({
1786
+ publicRelays: seedRelays
1787
+ });
1788
+ try {
1789
+ const seedResult = await seedRelayDiscovery.discover();
1790
+ const seedPeers = seedResult.discoveredPeers.filter((info) => info.pubkey).map((info) => ({
1791
+ pubkey: info.pubkey,
1792
+ relayUrl: seedResult.connectedUrls[0] ?? `ws://localhost:${relayPort}`,
1793
+ btpEndpoint: info.btpEndpoint
1794
+ }));
1795
+ const existingPubkeys = new Set(knownPeers.map((p) => p.pubkey));
1796
+ for (const seedPeer of seedPeers) {
1797
+ if (!existingPubkeys.has(seedPeer.pubkey)) {
1798
+ knownPeers.push(seedPeer);
1799
+ }
1800
+ }
1801
+ console.log(
1802
+ `[Town] Seed relay discovery: found ${seedPeers.length} peers from ${seedResult.connectedUrls.length} seed relay(s)`
1803
+ );
1804
+ } catch (seedError) {
1805
+ const msg = seedError instanceof Error ? seedError.message : "Unknown error";
1806
+ console.warn(`[Town] Seed relay discovery failed: ${msg}`);
1807
+ }
1808
+ }
1809
+ let announcementHeartbeat;
1810
+ try {
1811
+ const results = await bootstrapService.bootstrap();
1812
+ const ownIlpInfo = {
1813
+ ilpAddress,
1814
+ btpEndpoint,
1815
+ assetCode,
1816
+ assetScale,
1817
+ // Advertise the publish price (per byte, in ILP base units) so clients can
1818
+ // compute the amount to attach before sending — derived from feePerEvent /
1819
+ // basePricePerByte. Previously omitted, leaving peers to assume free.
1820
+ feePerByte: String(basePricePerByte),
1821
+ // Public Nostr relay URL for FREE reads, so clients discover where to
1822
+ // subscribe (separate from btpEndpoint, which is the pay-to-write path).
1823
+ // Set when the operator exposes the relay publicly (HS .anyone or direct).
1824
+ ...externalRelayUrl && { relayUrl: externalRelayUrl },
1825
+ ...settlementInfo?.supportedChains && {
1826
+ supportedChains: settlementInfo.supportedChains
1827
+ },
1828
+ ...settlementInfo?.settlementAddresses && {
1829
+ settlementAddresses: settlementInfo.settlementAddresses
1830
+ },
1831
+ ...settlementInfo?.preferredTokens && {
1832
+ preferredTokens: settlementInfo.preferredTokens
1833
+ },
1834
+ ...settlementInfo?.tokenNetworks && {
1835
+ tokenNetworks: settlementInfo.tokenNetworks
1836
+ }
1837
+ };
1838
+ const publishOwnAnnouncement = () => {
1839
+ try {
1840
+ const ilpInfoEvent = buildIlpPeerInfoEvent(
1841
+ ownIlpInfo,
1842
+ identity.secretKey,
1843
+ announcementTtlSeconds > 0 ? { ttlSeconds: announcementTtlSeconds } : {}
1844
+ );
1845
+ eventStore.store(ilpInfoEvent);
1846
+ const firstPeer = knownPeers[0];
1847
+ const genesisResult = results[0];
1848
+ if (firstPeer && genesisResult) {
1849
+ const genesisIlpAddress = genesisResult.peerInfo.ilpAddress;
1850
+ const toonBytes = encodeEventToToon3(ilpInfoEvent);
1851
+ const base64Toon = Buffer.from(toonBytes).toString("base64");
1852
+ const ilpAmount = String(BigInt(toonBytes.length) * basePricePerByte);
1853
+ ilpClient.sendIlpPacket({
1854
+ destination: genesisIlpAddress,
1855
+ amount: ilpAmount,
1856
+ data: base64Toon
1857
+ }).catch((err) => {
1858
+ const msg = err instanceof Error ? err.message : "Unknown";
1859
+ console.warn("[Town] Failed to publish via ILP:", msg);
1860
+ });
1861
+ }
1862
+ } catch (error) {
1863
+ console.warn("[Town] Failed to publish ILP info:", error);
1864
+ }
1865
+ };
1866
+ publishOwnAnnouncement();
1867
+ if (announcementTtlSeconds > 0) {
1868
+ const heartbeatMs = Math.max(
1869
+ 1,
1870
+ Math.floor(announcementTtlSeconds * 1e3 / 2)
1871
+ );
1872
+ announcementHeartbeat = setInterval(publishOwnAnnouncement, heartbeatMs);
1873
+ announcementHeartbeat.unref?.();
1874
+ }
1875
+ try {
1876
+ const serviceDiscoveryContent = {
1877
+ serviceType: "relay",
1878
+ ilpAddress,
1879
+ pricing: {
1880
+ basePricePerByte: Number(basePricePerByte),
1881
+ currency: "USDC"
1882
+ },
1883
+ supportedKinds: [1, 10032, 10035, 10036],
1884
+ capabilities: x402Enabled ? ["relay", "x402"] : ["relay"],
1885
+ chain: chainConfig.name,
1886
+ version: VERSION2
1887
+ };
1888
+ if (x402Enabled) {
1889
+ serviceDiscoveryContent.x402 = {
1890
+ enabled: true,
1891
+ endpoint: "/publish"
1892
+ };
1893
+ }
1894
+ if (config.skill) {
1895
+ serviceDiscoveryContent.skill = config.skill;
1896
+ }
1897
+ const serviceDiscoveryEvent = buildServiceDiscoveryEvent(
1898
+ serviceDiscoveryContent,
1899
+ identity.secretKey
1900
+ );
1901
+ eventStore.store(serviceDiscoveryEvent);
1902
+ const firstPeer = knownPeers[0];
1903
+ const genesisResult = results[0];
1904
+ if (firstPeer && genesisResult) {
1905
+ const genesisIlpAddress = genesisResult.peerInfo.ilpAddress;
1906
+ const sdToonBytes = encodeEventToToon3(serviceDiscoveryEvent);
1907
+ const sdBase64Toon = Buffer.from(sdToonBytes).toString("base64");
1908
+ const sdIlpAmount = String(
1909
+ BigInt(sdToonBytes.length) * basePricePerByte
1910
+ );
1911
+ ilpClient.sendIlpPacket({
1912
+ destination: genesisIlpAddress,
1913
+ amount: sdIlpAmount,
1914
+ data: sdBase64Toon
1915
+ }).catch((err) => {
1916
+ const msg = err instanceof Error ? err.message : "Unknown";
1917
+ console.warn(
1918
+ "[Town] Failed to publish service discovery via ILP:",
1919
+ msg
1920
+ );
1921
+ });
1922
+ }
1923
+ } catch (error) {
1924
+ console.warn("[Town] Failed to publish service discovery:", error);
1925
+ }
1926
+ const bootstrapPeerPubkeys = results.map((r) => r.knownPeer.pubkey);
1927
+ discoveryTracker.addExcludedPubkeys(bootstrapPeerPubkeys);
1928
+ } catch (error) {
1929
+ console.error("[Town] Bootstrap failed:", error);
1930
+ }
1931
+ if (publishSeedEntryFlag && !externalRelayUrl) {
1932
+ console.warn(
1933
+ "[Town] publishSeedEntry is true but externalRelayUrl is not set -- skipping seed relay entry publication"
1934
+ );
1935
+ }
1936
+ if (publishSeedEntryFlag && externalRelayUrl && seedRelays.length > 0) {
1937
+ publishSeedRelayEntry({
1938
+ secretKey: identity.secretKey,
1939
+ relayUrl: externalRelayUrl,
1940
+ publicRelays: seedRelays
1941
+ }).then(({ publishedTo, eventId }) => {
1942
+ console.log(
1943
+ `[Town] Published seed relay entry to ${publishedTo} relay(s), eventId: ${eventId}`
1944
+ );
1945
+ }).catch((err) => {
1946
+ const msg = err instanceof Error ? err.message : "Unknown error";
1947
+ console.warn(`[Town] Failed to publish seed relay entry: ${msg}`);
1948
+ });
1949
+ }
1950
+ const socialDiscovery = new SocialPeerDiscovery(
1951
+ { relayUrls },
1952
+ identity.secretKey
1953
+ );
1954
+ const socialSubscription = socialDiscovery.start();
1955
+ const activeSubscriptions = /* @__PURE__ */ new Set();
1956
+ const instance = {
1957
+ isRunning() {
1958
+ return running;
1959
+ },
1960
+ subscribe(subscribeRelayUrl, filter) {
1961
+ if (!running) {
1962
+ throw new Error("Cannot subscribe: town is not running");
1963
+ }
1964
+ return createSubscription(
1965
+ subscribeRelayUrl,
1966
+ filter,
1967
+ eventStore,
1968
+ activeSubscriptions
1969
+ );
1970
+ },
1971
+ async stop() {
1972
+ if (!running) return;
1973
+ running = false;
1974
+ if (announcementHeartbeat) {
1975
+ clearInterval(announcementHeartbeat);
1976
+ announcementHeartbeat = void 0;
1977
+ }
1978
+ for (const sub of activeSubscriptions) {
1979
+ sub.close();
1980
+ }
1981
+ activeSubscriptions.clear();
1982
+ if (socialSubscription) {
1983
+ socialSubscription.unsubscribe();
1984
+ }
1985
+ if (seedRelayDiscovery) {
1986
+ await seedRelayDiscovery.close();
1987
+ }
1988
+ await wsRelay.stop();
1989
+ blsServer.close();
1990
+ if (autoCreatedConnector) {
1991
+ await autoCreatedConnector.stop();
1992
+ }
1993
+ eventStore.close?.();
1994
+ },
1995
+ pubkey: identity.pubkey,
1996
+ evmAddress: identity.evmAddress,
1997
+ config: resolvedConfig,
1998
+ bootstrapResult: {
1999
+ peerCount,
2000
+ channelCount
2001
+ },
2002
+ discoveryMode: discovery
2003
+ };
2004
+ return instance;
2005
+ }
2006
+ var startTown = startRelay;
2007
+
2008
+ export {
2009
+ DEFAULT_RELAY_CONFIG,
2010
+ matchFilter,
2011
+ InMemoryEventStore,
2012
+ RelayError,
2013
+ SqliteEventStore,
2014
+ encodeEventToToon,
2015
+ ToonEncodeError,
2016
+ decodeEventFromToon,
2017
+ ToonDecodeError,
2018
+ ConnectionHandler,
2019
+ NostrRelayServer,
2020
+ RelaySubscriber,
2021
+ createEventStorageHandler,
2022
+ calculateX402Price,
2023
+ EIP_3009_TYPES,
2024
+ USDC_EIP712_DOMAIN,
2025
+ USDC_ABI,
2026
+ runPreflight,
2027
+ settleEip3009,
2028
+ createX402Handler,
2029
+ createHealthResponse,
2030
+ startRelay,
2031
+ startTown
2032
+ };
2033
+ //# sourceMappingURL=chunk-4RYYKZXO.js.map