@johnhenry/browsermesh-apps 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,909 @@
1
+ /**
2
+ * clawser-mesh-payments.js -- Payment channels for BrowserMesh.
3
+ *
4
+ * Double-entry credit ledger, bidirectional micropayment channels,
5
+ * escrow management, and a payment router that ties them together.
6
+ *
7
+ * No browser-only imports at module level.
8
+ *
9
+ * Run tests:
10
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-payments.test.mjs
11
+ */
12
+
13
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
14
+ import { silentCatch } from './silent-catch.mjs'
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Wire constants — imported from canonical registry
18
+ // ---------------------------------------------------------------------------
19
+
20
+ export const PAYMENT_OPEN = MESH_TYPE.PAYMENT_OPEN;
21
+ export const PAYMENT_UPDATE = MESH_TYPE.PAYMENT_UPDATE;
22
+ export const PAYMENT_CLOSE = MESH_TYPE.PAYMENT_CLOSE;
23
+ export const ESCROW_CREATE = MESH_TYPE.ESCROW_CREATE;
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Channel states
27
+ // ---------------------------------------------------------------------------
28
+
29
+ export const CHANNEL_STATES = Object.freeze([
30
+ 'idle', 'opening', 'open', 'closing', 'closed',
31
+ ]);
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // ID generation
35
+ // ---------------------------------------------------------------------------
36
+
37
+ let _entrySeq = 0;
38
+
39
+ function generateEntryId() {
40
+ return `le_${Date.now().toString(36)}_${(++_entrySeq).toString(36)}`;
41
+ }
42
+
43
+ let _channelSeq = 0;
44
+
45
+ function generateChannelId(localPodId, remotePodId) {
46
+ const pair = [localPodId, remotePodId].sort().join(':');
47
+ return `ch_${pair}_${Date.now().toString(36)}_${(++_channelSeq).toString(36)}`;
48
+ }
49
+
50
+ let _escrowSeq = 0;
51
+
52
+ function generateEscrowId() {
53
+ return `esc_${Date.now().toString(36)}_${(++_escrowSeq).toString(36)}`;
54
+ }
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // LedgerEntry typedef
58
+ // ---------------------------------------------------------------------------
59
+
60
+ /**
61
+ * @typedef {object} LedgerEntry
62
+ * @property {string} id
63
+ * @property {'credit'|'debit'} type
64
+ * @property {number} amount
65
+ * @property {string} counterparty - Pod ID of the other party
66
+ * @property {string} [memo]
67
+ * @property {number} timestamp
68
+ * @property {number} balance - Running balance after this entry
69
+ */
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // CreditLedger
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /**
76
+ * Double-entry accounting ledger for a single pod.
77
+ *
78
+ * Every mutation produces an immutable LedgerEntry recording amount,
79
+ * counterparty, running balance, and optional memo.
80
+ */
81
+ export class CreditLedger {
82
+ /** @type {string} */
83
+ #ownerId;
84
+
85
+ /** @type {number} */
86
+ #balance = 0;
87
+
88
+ /** @type {LedgerEntry[]} */
89
+ #entries = [];
90
+
91
+ /**
92
+ * @param {string} ownerId - Pod ID that owns this ledger
93
+ */
94
+ constructor(ownerId) {
95
+ if (!ownerId || typeof ownerId !== 'string') {
96
+ throw new Error('ownerId must be a non-empty string');
97
+ }
98
+ this.#ownerId = ownerId;
99
+ }
100
+
101
+ /** Pod ID that owns this ledger. */
102
+ get ownerId() {
103
+ return this.#ownerId;
104
+ }
105
+
106
+ /** Current balance. */
107
+ get balance() {
108
+ return this.#balance;
109
+ }
110
+
111
+ /** Total number of ledger entries. */
112
+ get entryCount() {
113
+ return this.#entries.length;
114
+ }
115
+
116
+ /**
117
+ * Record an incoming credit.
118
+ *
119
+ * @param {number} amount - Positive amount to credit
120
+ * @param {string} fromPodId - Source pod ID
121
+ * @param {string} [memo]
122
+ * @returns {LedgerEntry}
123
+ */
124
+ credit(amount, fromPodId, memo) {
125
+ if (typeof amount !== 'number' || amount <= 0) {
126
+ throw new RangeError(`Credit amount must be positive, got ${amount}`);
127
+ }
128
+ this.#balance += amount;
129
+ const entry = Object.freeze({
130
+ id: generateEntryId(),
131
+ type: 'credit',
132
+ amount,
133
+ counterparty: fromPodId,
134
+ memo: memo || null,
135
+ timestamp: Date.now(),
136
+ balance: this.#balance,
137
+ });
138
+ this.#entries.push(entry);
139
+ return entry;
140
+ }
141
+
142
+ /**
143
+ * Record an outgoing debit.
144
+ *
145
+ * @param {number} amount - Positive amount to debit
146
+ * @param {string} toPodId - Destination pod ID
147
+ * @param {string} [memo]
148
+ * @returns {LedgerEntry}
149
+ * @throws {Error} If insufficient balance
150
+ */
151
+ debit(amount, toPodId, memo) {
152
+ if (typeof amount !== 'number' || amount <= 0) {
153
+ throw new RangeError(`Debit amount must be positive, got ${amount}`);
154
+ }
155
+ if (this.#balance < amount) {
156
+ throw new Error(
157
+ `Insufficient balance: need ${amount}, have ${this.#balance}`
158
+ );
159
+ }
160
+ this.#balance -= amount;
161
+ const entry = Object.freeze({
162
+ id: generateEntryId(),
163
+ type: 'debit',
164
+ amount,
165
+ counterparty: toPodId,
166
+ memo: memo || null,
167
+ timestamp: Date.now(),
168
+ balance: this.#balance,
169
+ });
170
+ this.#entries.push(entry);
171
+ return entry;
172
+ }
173
+
174
+ /**
175
+ * Transfer amount from this ledger to a peer ledger.
176
+ * Creates a debit here and a credit on the peer.
177
+ *
178
+ * @param {CreditLedger} peerLedger - The receiving ledger
179
+ * @param {number} amount
180
+ * @param {string} [memo]
181
+ * @returns {{ debit: LedgerEntry, credit: LedgerEntry }}
182
+ */
183
+ transfer(peerLedger, amount, memo) {
184
+ const debitEntry = this.debit(amount, peerLedger.ownerId, memo);
185
+ const creditEntry = peerLedger.credit(amount, this.#ownerId, memo);
186
+ return { debit: debitEntry, credit: creditEntry };
187
+ }
188
+
189
+ /**
190
+ * Query ledger entries with optional filtering.
191
+ *
192
+ * @param {object} [opts]
193
+ * @param {number} [opts.since] - Only entries at or after this timestamp
194
+ * @param {number} [opts.limit] - Max entries to return
195
+ * @returns {LedgerEntry[]}
196
+ */
197
+ getEntries(opts = {}) {
198
+ let result = this.#entries;
199
+ if (opts.since != null) {
200
+ result = result.filter((e) => e.timestamp >= opts.since);
201
+ }
202
+ if (opts.limit != null && opts.limit > 0) {
203
+ result = result.slice(0, opts.limit);
204
+ }
205
+ return [...result];
206
+ }
207
+
208
+ /**
209
+ * Serialize to JSON-safe object.
210
+ * @returns {object}
211
+ */
212
+ toJSON() {
213
+ return {
214
+ ownerId: this.#ownerId,
215
+ balance: this.#balance,
216
+ entries: this.#entries.map((e) => ({ ...e })),
217
+ };
218
+ }
219
+
220
+ /**
221
+ * Restore a CreditLedger from serialized data.
222
+ * @param {object} data
223
+ * @returns {CreditLedger}
224
+ */
225
+ static fromJSON(data) {
226
+ const ledger = new CreditLedger(data.ownerId);
227
+ ledger.#balance = data.balance;
228
+ ledger.#entries = data.entries.map((e) => Object.freeze({ ...e }));
229
+ return ledger;
230
+ }
231
+ }
232
+
233
+ // ---------------------------------------------------------------------------
234
+ // PaymentUpdate typedef
235
+ // ---------------------------------------------------------------------------
236
+
237
+ /**
238
+ * @typedef {object} PaymentUpdate
239
+ * @property {string} channelId
240
+ * @property {number} sequence
241
+ * @property {number} amount
242
+ * @property {number} localBalance
243
+ * @property {number} remoteBalance
244
+ * @property {number} timestamp
245
+ * @property {string|null} signature
246
+ */
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // ChannelSettlement typedef
250
+ // ---------------------------------------------------------------------------
251
+
252
+ /**
253
+ * @typedef {object} ChannelSettlement
254
+ * @property {string} channelId
255
+ * @property {number} finalLocalBalance
256
+ * @property {number} finalRemoteBalance
257
+ * @property {number} entryCount
258
+ * @property {number} closedAt
259
+ */
260
+
261
+ // ---------------------------------------------------------------------------
262
+ // PaymentChannel
263
+ // ---------------------------------------------------------------------------
264
+
265
+ /** Default channel capacity (credits). */
266
+ const DEFAULT_CAPACITY = 1000;
267
+
268
+ /** Default TTL: 1 hour. */
269
+ const DEFAULT_TTL_MS = 3600000;
270
+
271
+ /**
272
+ * Bidirectional micropayment channel between two pods.
273
+ *
274
+ * Tracks local and remote balances, enforces capacity, and
275
+ * produces PaymentUpdate records for each payment.
276
+ */
277
+ export class PaymentChannel {
278
+ /** @type {string} */
279
+ #localPodId;
280
+
281
+ /** @type {string} */
282
+ #remotePodId;
283
+
284
+ /** @type {string} */
285
+ #channelId;
286
+
287
+ /** @type {number} */
288
+ #capacity;
289
+
290
+ /** @type {number} */
291
+ #ttlMs;
292
+
293
+ /** @type {number} */
294
+ #createdAt;
295
+
296
+ /** @type {string} */
297
+ #state = 'idle';
298
+
299
+ /** @type {number} */
300
+ #localBalance = 0;
301
+
302
+ /** @type {number} */
303
+ #remoteBalance = 0;
304
+
305
+ /** @type {number} */
306
+ #sequence = 0;
307
+
308
+ /**
309
+ * @param {string} localPodId
310
+ * @param {string} remotePodId
311
+ * @param {object} [opts]
312
+ * @param {number} [opts.capacity]
313
+ * @param {number} [opts.ttlMs]
314
+ */
315
+ constructor(localPodId, remotePodId, opts = {}) {
316
+ if (!localPodId || !remotePodId) {
317
+ throw new Error('localPodId and remotePodId are required');
318
+ }
319
+ this.#localPodId = localPodId;
320
+ this.#remotePodId = remotePodId;
321
+ this.#channelId = generateChannelId(localPodId, remotePodId);
322
+ this.#capacity = opts.capacity || DEFAULT_CAPACITY;
323
+ this.#ttlMs = opts.ttlMs || DEFAULT_TTL_MS;
324
+ this.#createdAt = Date.now();
325
+ }
326
+
327
+ /** Channel identifier. */
328
+ get channelId() {
329
+ return this.#channelId;
330
+ }
331
+
332
+ /** Current state. */
333
+ get state() {
334
+ return this.#state;
335
+ }
336
+
337
+ /** Local pod balance. */
338
+ get localBalance() {
339
+ return this.#localBalance;
340
+ }
341
+
342
+ /** Remote pod balance. */
343
+ get remoteBalance() {
344
+ return this.#remoteBalance;
345
+ }
346
+
347
+ /** Channel capacity. */
348
+ get capacity() {
349
+ return this.#capacity;
350
+ }
351
+
352
+ /** Current sequence number. */
353
+ get sequence() {
354
+ return this.#sequence;
355
+ }
356
+
357
+ /**
358
+ * Open the channel with an initial deposit.
359
+ *
360
+ * @param {number} initialDeposit - Amount to deposit into local balance
361
+ */
362
+ open(initialDeposit) {
363
+ if (this.#state !== 'idle') {
364
+ throw new Error(`Cannot open channel in state: ${this.#state}`);
365
+ }
366
+ if (typeof initialDeposit !== 'number' || initialDeposit <= 0) {
367
+ throw new RangeError('Initial deposit must be positive');
368
+ }
369
+ if (initialDeposit > this.#capacity) {
370
+ throw new RangeError(
371
+ `Deposit ${initialDeposit} exceeds capacity ${this.#capacity}`
372
+ );
373
+ }
374
+ this.#state = 'opening';
375
+ this.#localBalance = initialDeposit;
376
+ this.#state = 'open';
377
+ }
378
+
379
+ /**
380
+ * Send a payment to the remote pod.
381
+ *
382
+ * @param {number} amount
383
+ * @returns {PaymentUpdate}
384
+ */
385
+ pay(amount) {
386
+ if (this.#state !== 'open') {
387
+ throw new Error(`Cannot pay in state: ${this.#state}`);
388
+ }
389
+ if (typeof amount !== 'number' || amount <= 0) {
390
+ throw new RangeError('Payment amount must be positive');
391
+ }
392
+ if (amount > this.#localBalance) {
393
+ throw new Error(
394
+ `Insufficient channel balance: need ${amount}, have ${this.#localBalance}`
395
+ );
396
+ }
397
+ this.#localBalance -= amount;
398
+ this.#remoteBalance += amount;
399
+ this.#sequence += 1;
400
+ return Object.freeze({
401
+ channelId: this.#channelId,
402
+ sequence: this.#sequence,
403
+ amount,
404
+ localBalance: this.#localBalance,
405
+ remoteBalance: this.#remoteBalance,
406
+ timestamp: Date.now(),
407
+ signature: null,
408
+ });
409
+ }
410
+
411
+ /**
412
+ * Receive a payment update from the remote pod.
413
+ *
414
+ * @param {PaymentUpdate} update
415
+ */
416
+ receive(update) {
417
+ if (this.#state !== 'open') {
418
+ throw new Error(`Cannot receive in state: ${this.#state}`);
419
+ }
420
+ if (update.channelId !== this.#channelId) {
421
+ throw new Error('Channel ID mismatch');
422
+ }
423
+ if (update.sequence <= this.#sequence) {
424
+ throw new Error(
425
+ `Stale sequence: got ${update.sequence}, expected > ${this.#sequence}`
426
+ );
427
+ }
428
+ // From our perspective: remote sent to us, so our local goes up
429
+ this.#localBalance += update.amount;
430
+ this.#remoteBalance -= update.amount;
431
+ this.#sequence = update.sequence;
432
+ }
433
+
434
+ /**
435
+ * Close the channel and produce a settlement.
436
+ *
437
+ * @returns {ChannelSettlement}
438
+ */
439
+ close() {
440
+ if (this.#state !== 'open') {
441
+ throw new Error(`Cannot close channel in state: ${this.#state}`);
442
+ }
443
+ this.#state = 'closing';
444
+ const settlement = Object.freeze({
445
+ channelId: this.#channelId,
446
+ finalLocalBalance: this.#localBalance,
447
+ finalRemoteBalance: this.#remoteBalance,
448
+ entryCount: this.#sequence,
449
+ closedAt: Date.now(),
450
+ });
451
+ this.#state = 'closed';
452
+ return settlement;
453
+ }
454
+
455
+ /**
456
+ * Check whether this channel has expired.
457
+ *
458
+ * @returns {boolean}
459
+ */
460
+ isExpired() {
461
+ return Date.now() - this.#createdAt > this.#ttlMs;
462
+ }
463
+
464
+ /**
465
+ * Serialize to JSON-safe object.
466
+ * @returns {object}
467
+ */
468
+ toJSON() {
469
+ return {
470
+ localPodId: this.#localPodId,
471
+ remotePodId: this.#remotePodId,
472
+ channelId: this.#channelId,
473
+ capacity: this.#capacity,
474
+ ttlMs: this.#ttlMs,
475
+ createdAt: this.#createdAt,
476
+ state: this.#state,
477
+ localBalance: this.#localBalance,
478
+ remoteBalance: this.#remoteBalance,
479
+ sequence: this.#sequence,
480
+ };
481
+ }
482
+
483
+ /**
484
+ * Restore a PaymentChannel from serialized data.
485
+ * @param {object} data
486
+ * @returns {PaymentChannel}
487
+ */
488
+ static fromJSON(data) {
489
+ const ch = new PaymentChannel(data.localPodId, data.remotePodId, {
490
+ capacity: data.capacity,
491
+ ttlMs: data.ttlMs,
492
+ });
493
+ ch.#channelId = data.channelId;
494
+ ch.#createdAt = data.createdAt;
495
+ ch.#state = data.state;
496
+ ch.#localBalance = data.localBalance;
497
+ ch.#remoteBalance = data.remoteBalance;
498
+ ch.#sequence = data.sequence;
499
+ return ch;
500
+ }
501
+ }
502
+
503
+ // ---------------------------------------------------------------------------
504
+ // Escrow typedef
505
+ // ---------------------------------------------------------------------------
506
+
507
+ /**
508
+ * @typedef {object} Escrow
509
+ * @property {string} escrowId
510
+ * @property {string} payerPodId
511
+ * @property {string} payeePodId
512
+ * @property {number} amount
513
+ * @property {'held'|'released'|'refunded'|'expired'} status
514
+ * @property {object} conditions
515
+ * @property {number} createdAt
516
+ * @property {number|null} resolvedAt
517
+ */
518
+
519
+ // ---------------------------------------------------------------------------
520
+ // EscrowManager
521
+ // ---------------------------------------------------------------------------
522
+
523
+ /**
524
+ * Manages escrow holds between pods. Funds are locked until
525
+ * explicitly released, refunded, or expired.
526
+ */
527
+ export class EscrowManager {
528
+ /** @type {Map<string, object>} escrowId -> Escrow */
529
+ #escrows = new Map();
530
+
531
+ constructor() {}
532
+
533
+ /** Number of active escrows. */
534
+ get size() {
535
+ return this.#escrows.size;
536
+ }
537
+
538
+ /**
539
+ * Create a new escrow hold.
540
+ *
541
+ * @param {string} payerPodId
542
+ * @param {string} payeePodId
543
+ * @param {number} amount
544
+ * @param {object} [conditions]
545
+ * @param {number} [conditions.timeout] - Auto-expire after this many ms
546
+ * @param {string} [conditions.description]
547
+ * @returns {object} Escrow record
548
+ */
549
+ create(payerPodId, payeePodId, amount, conditions = {}) {
550
+ if (typeof amount !== 'number' || amount <= 0) {
551
+ throw new RangeError('Escrow amount must be positive');
552
+ }
553
+ const escrow = {
554
+ escrowId: generateEscrowId(),
555
+ payerPodId,
556
+ payeePodId,
557
+ amount,
558
+ status: 'held',
559
+ conditions: {
560
+ timeout: conditions.timeout || null,
561
+ description: conditions.description || null,
562
+ },
563
+ createdAt: Date.now(),
564
+ resolvedAt: null,
565
+ };
566
+ this.#escrows.set(escrow.escrowId, escrow);
567
+ return { ...escrow };
568
+ }
569
+
570
+ /**
571
+ * Look up an escrow by ID.
572
+ *
573
+ * @param {string} escrowId
574
+ * @returns {object|null}
575
+ */
576
+ get(escrowId) {
577
+ const e = this.#escrows.get(escrowId);
578
+ return e ? { ...e } : null;
579
+ }
580
+
581
+ /**
582
+ * Release escrow to payee (pay out).
583
+ *
584
+ * @param {string} escrowId
585
+ * @returns {boolean} true if released, false if not found or already resolved
586
+ */
587
+ release(escrowId) {
588
+ const e = this.#escrows.get(escrowId);
589
+ if (!e || e.status !== 'held') return false;
590
+ e.status = 'released';
591
+ e.resolvedAt = Date.now();
592
+ return true;
593
+ }
594
+
595
+ /**
596
+ * Refund escrow to payer.
597
+ *
598
+ * @param {string} escrowId
599
+ * @returns {boolean} true if refunded, false if not found or already resolved
600
+ */
601
+ refund(escrowId) {
602
+ const e = this.#escrows.get(escrowId);
603
+ if (!e || e.status !== 'held') return false;
604
+ e.status = 'refunded';
605
+ e.resolvedAt = Date.now();
606
+ return true;
607
+ }
608
+
609
+ /**
610
+ * Expire escrow (auto-refund on timeout).
611
+ *
612
+ * @param {string} escrowId
613
+ * @returns {boolean} true if expired, false if not found or already resolved
614
+ */
615
+ expire(escrowId) {
616
+ const e = this.#escrows.get(escrowId);
617
+ if (!e || e.status !== 'held') return false;
618
+ e.status = 'expired';
619
+ e.resolvedAt = Date.now();
620
+ return true;
621
+ }
622
+
623
+ /**
624
+ * List all escrows involving a pod (as payer or payee).
625
+ *
626
+ * @param {string} podId
627
+ * @returns {object[]}
628
+ */
629
+ listByParty(podId) {
630
+ const result = [];
631
+ for (const e of this.#escrows.values()) {
632
+ if (e.payerPodId === podId || e.payeePodId === podId) {
633
+ result.push({ ...e });
634
+ }
635
+ }
636
+ return result;
637
+ }
638
+
639
+ /**
640
+ * Prune all escrows that have timed out. Sets status to 'expired'.
641
+ *
642
+ * @param {number} [now=Date.now()]
643
+ * @returns {number} Number of escrows expired
644
+ */
645
+ pruneExpired(now = Date.now()) {
646
+ return this.pruneExpiredDetailed(now).length;
647
+ }
648
+
649
+ /**
650
+ * Same as `pruneExpired`, but returns the expired escrow records
651
+ * (copies) instead of just a count — used by callers that need to
652
+ * notify the counterparty which escrows just timed out.
653
+ *
654
+ * @param {number} [now=Date.now()]
655
+ * @returns {object[]} Copies of the escrows that were just expired
656
+ */
657
+ pruneExpiredDetailed(now = Date.now()) {
658
+ const expired = [];
659
+ for (const e of this.#escrows.values()) {
660
+ if (e.status !== 'held') continue;
661
+ if (e.conditions.timeout == null) continue;
662
+ if (now - e.createdAt >= e.conditions.timeout) {
663
+ e.status = 'expired';
664
+ e.resolvedAt = now;
665
+ expired.push({ ...e });
666
+ }
667
+ }
668
+ return expired;
669
+ }
670
+ }
671
+
672
+ // ---------------------------------------------------------------------------
673
+ // PaymentRouter
674
+ // ---------------------------------------------------------------------------
675
+
676
+ /**
677
+ * High-level payment manager for a single pod.
678
+ * Ties together a credit ledger, payment channels, and escrow.
679
+ */
680
+ export class PaymentRouter {
681
+ /** @type {string} */
682
+ #localPodId;
683
+
684
+ /** @type {CreditLedger} */
685
+ #ledger;
686
+
687
+ /** @type {Map<string, PaymentChannel>} remotePodId -> channel */
688
+ #channels = new Map();
689
+
690
+ /** @type {EscrowManager} */
691
+ #escrow;
692
+
693
+ /** @type {function|null} */
694
+ #broadcastFn = null;
695
+
696
+ /** @type {ReturnType<typeof setInterval>|null} */
697
+ #escrowSweeperTimer = null;
698
+
699
+ /**
700
+ * @param {string} localPodId
701
+ */
702
+ constructor(localPodId) {
703
+ if (!localPodId || typeof localPodId !== 'string') {
704
+ throw new Error('localPodId must be a non-empty string');
705
+ }
706
+ this.#localPodId = localPodId;
707
+ this.#ledger = new CreditLedger(localPodId);
708
+ this.#escrow = new EscrowManager();
709
+ }
710
+
711
+ /**
712
+ * Get the local credit ledger.
713
+ * @returns {CreditLedger}
714
+ */
715
+ getLedger() {
716
+ return this.#ledger;
717
+ }
718
+
719
+ /**
720
+ * Open a payment channel to a remote pod.
721
+ *
722
+ * @param {string} remotePodId
723
+ * @param {number} [capacity]
724
+ * @returns {PaymentChannel}
725
+ */
726
+ openChannel(remotePodId, capacity) {
727
+ if (this.#channels.has(remotePodId)) {
728
+ throw new Error(`Channel to ${remotePodId} already exists`);
729
+ }
730
+ const opts = capacity != null ? { capacity } : {};
731
+ const ch = new PaymentChannel(this.#localPodId, remotePodId, opts);
732
+ this.#channels.set(remotePodId, ch);
733
+ return ch;
734
+ }
735
+
736
+ /**
737
+ * Look up a channel by remote pod ID.
738
+ *
739
+ * @param {string} remotePodId
740
+ * @returns {PaymentChannel|null}
741
+ */
742
+ getChannel(remotePodId) {
743
+ return this.#channels.get(remotePodId) || null;
744
+ }
745
+
746
+ /**
747
+ * Close a channel and return the settlement.
748
+ *
749
+ * @param {string} remotePodId
750
+ * @returns {ChannelSettlement|null}
751
+ */
752
+ closeChannel(remotePodId) {
753
+ const ch = this.#channels.get(remotePodId);
754
+ if (!ch) return null;
755
+ const settlement = ch.close();
756
+ this.#channels.delete(remotePodId);
757
+ return settlement;
758
+ }
759
+
760
+ /**
761
+ * List all open channels.
762
+ *
763
+ * @returns {PaymentChannel[]}
764
+ */
765
+ listChannels() {
766
+ return [...this.#channels.values()];
767
+ }
768
+
769
+ /**
770
+ * Get the escrow manager.
771
+ *
772
+ * @returns {EscrowManager}
773
+ */
774
+ getEscrow() {
775
+ return this.#escrow;
776
+ }
777
+
778
+ /**
779
+ * Start periodic escrow-timeout enforcement. Without this,
780
+ * `EscrowManager.pruneExpired()` exists but nothing ever calls it, so
781
+ * timed-out escrows sit in `held` status forever.
782
+ *
783
+ * There is no dedicated wire message for escrow expiry in the mesh
784
+ * wire format (`browsermesh-primitives`) today — adding one is an
785
+ * upstream package change, tracked separately. Until then, expiry is
786
+ * enforced locally per-pod and surfaced via `onExpired`; each party
787
+ * to an escrow independently expires it once its own clock passes
788
+ * the timeout, so both sides converge without needing a message.
789
+ *
790
+ * @param {number} [intervalMs=30000]
791
+ * @param {(expired: object[]) => void} [onExpired] - Called with the escrows that just expired (may be empty)
792
+ */
793
+ startEscrowSweeper(intervalMs = 30000, onExpired = null) {
794
+ this.stopEscrowSweeper();
795
+ this.#escrowSweeperTimer = setInterval(() => {
796
+ const expired = this.#escrow.pruneExpiredDetailed();
797
+ if (expired.length > 0 && onExpired) {
798
+ try { onExpired(expired); } catch (e) { silentCatch('clawser-mesh-payments', 'onExpired', e) }
799
+ }
800
+ }, intervalMs);
801
+ }
802
+
803
+ /** Stop escrow-timeout enforcement. Call on pod teardown. */
804
+ stopEscrowSweeper() {
805
+ if (this.#escrowSweeperTimer) {
806
+ clearInterval(this.#escrowSweeperTimer);
807
+ this.#escrowSweeperTimer = null;
808
+ }
809
+ }
810
+
811
+ /**
812
+ * Wire the PaymentRouter to a mesh transport layer.
813
+ *
814
+ * Outbound: channel open/update/close and escrow messages sent via
815
+ * `broadcastFn(type, payload)`.
816
+ *
817
+ * Inbound: messages received via `subscribeFn(type, handler)`.
818
+ *
819
+ * @param {function} broadcastFn - `(wireType: number, payload: object) => void`
820
+ * @param {function} subscribeFn - `(wireType: number, handler: (payload, fromPodId) => void) => void`
821
+ */
822
+ wireTransport(broadcastFn, subscribeFn) {
823
+ if (typeof broadcastFn !== 'function' || typeof subscribeFn !== 'function') {
824
+ throw new Error('broadcastFn and subscribeFn must be functions');
825
+ }
826
+
827
+ this.#broadcastFn = broadcastFn;
828
+
829
+ // Inbound: channel open request
830
+ subscribeFn(PAYMENT_OPEN, (payload, fromPodId) => {
831
+ try {
832
+ const { remotePodId, capacity } = payload;
833
+ if (remotePodId === this.#localPodId) {
834
+ // Remote peer wants to open a channel with us
835
+ this.openChannel(fromPodId, capacity);
836
+ }
837
+ } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-duplicate-or-invalid-opens', e) }
838
+ });
839
+
840
+ // Inbound: channel payment update
841
+ subscribeFn(PAYMENT_UPDATE, (payload, fromPodId) => {
842
+ try {
843
+ const ch = this.#channels.get(fromPodId);
844
+ if (ch) {
845
+ ch.receive(payload);
846
+ }
847
+ } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-invalid-updates', e) }
848
+ });
849
+
850
+ // Inbound: channel close
851
+ subscribeFn(PAYMENT_CLOSE, (payload, fromPodId) => {
852
+ try { this.closeChannel(fromPodId); } catch (e) { silentCatch('clawser-mesh-payments', 'this.closeChannel', e) }
853
+ });
854
+
855
+ // Inbound: escrow creation
856
+ subscribeFn(ESCROW_CREATE, (payload, fromPodId) => {
857
+ try {
858
+ const { payeePodId, amount, conditions } = payload;
859
+ this.#escrow.create(fromPodId, payeePodId, amount, conditions);
860
+ } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-invalid-escrow', e) }
861
+ });
862
+ }
863
+
864
+ /**
865
+ * Broadcast a channel open over the transport.
866
+ *
867
+ * @param {string} remotePodId
868
+ * @param {number} [capacity]
869
+ */
870
+ broadcastOpen(remotePodId, capacity) {
871
+ if (this.#broadcastFn) {
872
+ this.#broadcastFn(PAYMENT_OPEN, { remotePodId, capacity });
873
+ }
874
+ }
875
+
876
+ /**
877
+ * Broadcast a payment update over the transport.
878
+ *
879
+ * @param {PaymentUpdate} update
880
+ */
881
+ broadcastUpdate(update) {
882
+ if (this.#broadcastFn) {
883
+ this.#broadcastFn(PAYMENT_UPDATE, update);
884
+ }
885
+ }
886
+
887
+ /**
888
+ * Broadcast a channel close over the transport.
889
+ *
890
+ * @param {string} remotePodId
891
+ * @param {ChannelSettlement} settlement
892
+ */
893
+ broadcastClose(remotePodId, settlement) {
894
+ if (this.#broadcastFn) {
895
+ this.#broadcastFn(PAYMENT_CLOSE, { remotePodId, ...settlement });
896
+ }
897
+ }
898
+
899
+ /**
900
+ * Broadcast an escrow creation over the transport.
901
+ *
902
+ * @param {object} escrow
903
+ */
904
+ broadcastEscrow(escrow) {
905
+ if (this.#broadcastFn) {
906
+ this.#broadcastFn(ESCROW_CREATE, escrow);
907
+ }
908
+ }
909
+ }