@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,573 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-escrow.js — Hold credits in escrow until consensus confirms delivery.
4
+ *
5
+ * Enables trustless compute marketplace, dispute resolution, and
6
+ * guaranteed payment for services.
7
+ *
8
+ * Run tests:
9
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-escrow.test.mjs
10
+ */
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Polyfill
14
+ // ---------------------------------------------------------------------------
15
+
16
+ if (!globalThis.crypto) globalThis.crypto = {}
17
+ if (!crypto.randomUUID) crypto.randomUUID = () => 'esc-' + Math.random().toString(36).slice(2)
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Constants
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Condition types that can gate escrow release.
25
+ * @type {Readonly<Record<string, string>>}
26
+ */
27
+ export const ESCROW_CONDITIONS = Object.freeze({
28
+ RESULT_HASH_MATCH: 'result_hash_match',
29
+ ATTESTATION_QUORUM: 'attestation_quorum',
30
+ MANUAL_APPROVAL: 'manual_approval',
31
+ TIMEOUT_AUTO_RELEASE: 'timeout_release',
32
+ TIMEOUT_AUTO_REFUND: 'timeout_refund',
33
+ })
34
+
35
+ /**
36
+ * All possible escrow statuses in lifecycle order.
37
+ * @type {ReadonlyArray<string>}
38
+ */
39
+ export const ESCROW_STATUSES = Object.freeze([
40
+ 'pending', 'funded', 'released', 'refunded', 'disputed', 'expired',
41
+ ])
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // ID generation
45
+ // ---------------------------------------------------------------------------
46
+
47
+ let _escrowSeq = 0
48
+
49
+ function generateEscrowId() {
50
+ return `esc_${Date.now().toString(36)}_${(++_escrowSeq).toString(36)}`
51
+ }
52
+
53
+ function generateDisputeId() {
54
+ return `dsp_${Date.now().toString(36)}_${(++_escrowSeq).toString(36)}`
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // EscrowContract
59
+ // ---------------------------------------------------------------------------
60
+
61
+ /**
62
+ * Represents a single escrow contract between a payer and a payee.
63
+ *
64
+ * Contracts hold funds in escrow and release them when all conditions
65
+ * are met, or refund them on timeout/dispute.
66
+ */
67
+ export class EscrowContract {
68
+ /** @type {string} */
69
+ id
70
+
71
+ /** @type {string} */
72
+ payer
73
+
74
+ /** @type {string} */
75
+ payee
76
+
77
+ /** @type {number} */
78
+ amount
79
+
80
+ /** @type {Array<{ type: string, params?: object }>} */
81
+ conditions
82
+
83
+ /** @type {number|null} */
84
+ timeoutMs
85
+
86
+ /** @type {string} */
87
+ status
88
+
89
+ /** @type {number} */
90
+ createdAt
91
+
92
+ /** @type {string|null} */
93
+ description
94
+
95
+ /**
96
+ * @param {object} opts
97
+ * @param {string} [opts.id]
98
+ * @param {string} opts.payer
99
+ * @param {string} opts.payee
100
+ * @param {number} opts.amount
101
+ * @param {Array<{ type: string, params?: object }>} [opts.conditions]
102
+ * @param {number|null} [opts.timeoutMs]
103
+ * @param {string} [opts.status]
104
+ * @param {number} [opts.createdAt]
105
+ * @param {string|null} [opts.description]
106
+ */
107
+ constructor(opts) {
108
+ this.id = opts.id || crypto.randomUUID()
109
+ this.payer = opts.payer
110
+ this.payee = opts.payee
111
+ this.amount = opts.amount
112
+ this.conditions = opts.conditions || []
113
+ this.timeoutMs = opts.timeoutMs ?? null
114
+ this.status = opts.status || 'pending'
115
+ this.createdAt = opts.createdAt ?? Date.now()
116
+ this.description = opts.description ?? null
117
+ }
118
+
119
+ // ── Condition checking ─────────────────────────────────────────
120
+
121
+ /**
122
+ * Check whether all conditions are satisfied by the provided proof.
123
+ *
124
+ * @param {object} proof
125
+ * @param {string} [proof.resultHash]
126
+ * @param {number} [proof.attestationCount]
127
+ * @param {boolean} [proof.manualApproval]
128
+ * @returns {{ met: boolean, unmet: string[] }}
129
+ */
130
+ checkConditions(proof = {}) {
131
+ const unmet = []
132
+
133
+ for (const cond of this.conditions) {
134
+ switch (cond.type) {
135
+ case ESCROW_CONDITIONS.RESULT_HASH_MATCH: {
136
+ const expected = cond.params?.expectedHash
137
+ if (proof.resultHash !== expected) {
138
+ unmet.push(cond.type)
139
+ }
140
+ break
141
+ }
142
+
143
+ case ESCROW_CONDITIONS.ATTESTATION_QUORUM: {
144
+ const required = cond.params?.requiredCount ?? 1
145
+ if ((proof.attestationCount ?? 0) < required) {
146
+ unmet.push(cond.type)
147
+ }
148
+ break
149
+ }
150
+
151
+ case ESCROW_CONDITIONS.MANUAL_APPROVAL: {
152
+ if (!proof.manualApproval) {
153
+ unmet.push(cond.type)
154
+ }
155
+ break
156
+ }
157
+
158
+ case ESCROW_CONDITIONS.TIMEOUT_AUTO_RELEASE:
159
+ case ESCROW_CONDITIONS.TIMEOUT_AUTO_REFUND:
160
+ // Timeout conditions are handled by EscrowManager.checkExpired()
161
+ break
162
+
163
+ default:
164
+ unmet.push(cond.type)
165
+ }
166
+ }
167
+
168
+ return { met: unmet.length === 0, unmet }
169
+ }
170
+
171
+ // ── Timeout ────────────────────────────────────────────────────
172
+
173
+ /**
174
+ * Check whether this contract has expired based on its timeout.
175
+ *
176
+ * @param {number} [now] - Current timestamp (default: Date.now())
177
+ * @returns {boolean}
178
+ */
179
+ isExpired(now) {
180
+ if (this.timeoutMs == null) return false
181
+ const elapsed = (now ?? Date.now()) - this.createdAt
182
+ return elapsed >= this.timeoutMs
183
+ }
184
+
185
+ // ── Serialization ──────────────────────────────────────────────
186
+
187
+ /**
188
+ * Serialize to a JSON-safe plain object.
189
+ * @returns {object}
190
+ */
191
+ toJSON() {
192
+ return {
193
+ id: this.id,
194
+ payer: this.payer,
195
+ payee: this.payee,
196
+ amount: this.amount,
197
+ conditions: this.conditions.map(c => ({ ...c })),
198
+ timeoutMs: this.timeoutMs,
199
+ status: this.status,
200
+ createdAt: this.createdAt,
201
+ description: this.description,
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Restore an EscrowContract from serialized data.
207
+ *
208
+ * @param {object} json
209
+ * @returns {EscrowContract}
210
+ */
211
+ static fromJSON(json) {
212
+ return new EscrowContract({
213
+ id: json.id,
214
+ payer: json.payer,
215
+ payee: json.payee,
216
+ amount: json.amount,
217
+ conditions: (json.conditions || []).map(c => ({ ...c })),
218
+ timeoutMs: json.timeoutMs,
219
+ status: json.status,
220
+ createdAt: json.createdAt,
221
+ description: json.description,
222
+ })
223
+ }
224
+ }
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // EscrowManager
228
+ // ---------------------------------------------------------------------------
229
+
230
+ /**
231
+ * Manages escrow contracts — creation, funding, release, refund, dispute.
232
+ *
233
+ * Works with a credit ledger (e.g. CreditLedger from clawser-peer-payments.js)
234
+ * to hold funds in escrow until conditions are met.
235
+ */
236
+ export class EscrowManager {
237
+ /** @type {Map<string, EscrowContract>} */
238
+ #contracts = new Map()
239
+
240
+ /** @type {object} creditLedger */
241
+ #creditLedger
242
+
243
+ /** @type {Function} */
244
+ #onLog
245
+
246
+ /** @type {Map<string, Function[]>} */
247
+ #listeners = new Map()
248
+
249
+ /**
250
+ * @param {object} opts
251
+ * @param {object} opts.creditLedger - Must have charge(), credit(), getBalance()
252
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
253
+ */
254
+ constructor(opts) {
255
+ if (!opts?.creditLedger) {
256
+ throw new Error('EscrowManager requires a creditLedger')
257
+ }
258
+ this.#creditLedger = opts.creditLedger
259
+ this.#onLog = opts.onLog ?? (() => {})
260
+ }
261
+
262
+ // ── Create ─────────────────────────────────────────────────────
263
+
264
+ /**
265
+ * Create and fund an escrow contract. Debits the payer immediately.
266
+ *
267
+ * @param {object} opts
268
+ * @param {string} opts.payerPodId
269
+ * @param {string} opts.payeePodId
270
+ * @param {number} opts.amount
271
+ * @param {string} [opts.description]
272
+ * @param {Array<{ type: string, params?: object }>} [opts.conditions]
273
+ * @param {number} [opts.timeoutMs]
274
+ * @returns {EscrowContract}
275
+ * @throws {Error} If payer has insufficient balance
276
+ */
277
+ create(opts) {
278
+ const { payerPodId, payeePodId, amount, description, conditions, timeoutMs } = opts
279
+
280
+ // Debit payer — throws on insufficient balance
281
+ this.#creditLedger.charge(payerPodId, amount, `escrow: ${description || 'contract'}`)
282
+
283
+ const contract = new EscrowContract({
284
+ payer: payerPodId,
285
+ payee: payeePodId,
286
+ amount,
287
+ description: description ?? null,
288
+ conditions: conditions || [],
289
+ timeoutMs: timeoutMs ?? null,
290
+ status: 'funded',
291
+ })
292
+
293
+ this.#contracts.set(contract.id, contract)
294
+ this.#onLog('info', `Escrow created: ${contract.id} (${amount} from ${payerPodId})`)
295
+ this.#emit('created', contract)
296
+
297
+ return contract
298
+ }
299
+
300
+ // ── Release ────────────────────────────────────────────────────
301
+
302
+ /**
303
+ * Release escrow funds to the payee.
304
+ *
305
+ * @param {string} contractId
306
+ * @param {object} [proof] - Proof object for condition checking
307
+ * @returns {{ success: boolean, txId?: string }}
308
+ * @throws {Error} If contract not found, not funded, expired, or conditions not met
309
+ */
310
+ release(contractId, proof) {
311
+ const contract = this.#getValidContract(contractId, 'release')
312
+
313
+ if (contract.status !== 'funded') {
314
+ throw new Error(`Cannot release contract ${contractId}: not funded (status: ${contract.status})`)
315
+ }
316
+
317
+ if (contract.isExpired()) {
318
+ throw new Error(`Cannot release contract ${contractId}: expired`)
319
+ }
320
+
321
+ // Check conditions
322
+ if (contract.conditions.length > 0) {
323
+ const result = contract.checkConditions(proof || {})
324
+ if (!result.met) {
325
+ throw new Error(`Cannot release contract ${contractId}: conditions not met (${result.unmet.join(', ')})`)
326
+ }
327
+ }
328
+
329
+ // Credit payee
330
+ this.#creditLedger.credit(contract.payee, contract.amount, `escrow release: ${contractId}`)
331
+ contract.status = 'released'
332
+
333
+ this.#onLog('info', `Escrow released: ${contractId} (${contract.amount} to ${contract.payee})`)
334
+ this.#emit('released', contract)
335
+
336
+ return { success: true, txId: contractId }
337
+ }
338
+
339
+ // ── Refund ─────────────────────────────────────────────────────
340
+
341
+ /**
342
+ * Refund escrow funds back to the payer.
343
+ *
344
+ * @param {string} contractId
345
+ * @param {string} [reason]
346
+ * @returns {{ success: boolean, txId?: string }}
347
+ * @throws {Error} If contract not found or not funded
348
+ */
349
+ refund(contractId, reason) {
350
+ const contract = this.#getValidContract(contractId, 'refund')
351
+
352
+ if (contract.status !== 'funded') {
353
+ throw new Error(`Cannot refund contract ${contractId}: not funded (status: ${contract.status})`)
354
+ }
355
+
356
+ // Credit payer
357
+ this.#creditLedger.credit(contract.payer, contract.amount, `escrow refund: ${reason || contractId}`)
358
+ contract.status = 'refunded'
359
+
360
+ this.#onLog('info', `Escrow refunded: ${contractId} (${contract.amount} to ${contract.payer})`)
361
+ this.#emit('refunded', contract)
362
+
363
+ return { success: true, txId: contractId }
364
+ }
365
+
366
+ // ── Dispute ────────────────────────────────────────────────────
367
+
368
+ /**
369
+ * Mark a contract as disputed. Funds remain locked until resolution.
370
+ *
371
+ * @param {string} contractId
372
+ * @param {object} [evidence]
373
+ * @returns {{ disputeId: string }}
374
+ * @throws {Error} If contract not found
375
+ */
376
+ dispute(contractId, evidence) {
377
+ const contract = this.#getValidContract(contractId, 'dispute')
378
+ contract.status = 'disputed'
379
+
380
+ const disputeId = generateDisputeId()
381
+
382
+ this.#onLog('warn', `Escrow disputed: ${contractId} (dispute: ${disputeId})`)
383
+ this.#emit('disputed', { contract, disputeId, evidence })
384
+
385
+ return { disputeId }
386
+ }
387
+
388
+ // ── Expiry sweep ───────────────────────────────────────────────
389
+
390
+ /**
391
+ * Check all contracts for expiration. Refunds any that are expired
392
+ * and still funded.
393
+ *
394
+ * @param {number} [now] - Current timestamp (default: Date.now())
395
+ * @returns {number} Count of expired contracts
396
+ */
397
+ checkExpired(now) {
398
+ let count = 0
399
+ const ts = now ?? Date.now()
400
+
401
+ for (const contract of this.#contracts.values()) {
402
+ if (contract.status === 'funded' && contract.isExpired(ts)) {
403
+ // Auto-refund expired contracts
404
+ this.#creditLedger.credit(
405
+ contract.payer,
406
+ contract.amount,
407
+ `escrow expired: ${contract.id}`,
408
+ )
409
+ contract.status = 'expired'
410
+ count++
411
+
412
+ this.#onLog('info', `Escrow expired: ${contract.id}`)
413
+ this.#emit('expired', contract)
414
+ }
415
+ }
416
+
417
+ return count
418
+ }
419
+
420
+ // ── Queries ────────────────────────────────────────────────────
421
+
422
+ /**
423
+ * Get a contract by ID.
424
+ *
425
+ * @param {string} id
426
+ * @returns {EscrowContract|null}
427
+ */
428
+ getContract(id) {
429
+ return this.#contracts.get(id) ?? null
430
+ }
431
+
432
+ /**
433
+ * List contracts, optionally filtered.
434
+ *
435
+ * @param {object} [filter]
436
+ * @param {string} [filter.status]
437
+ * @param {string} [filter.payerPodId]
438
+ * @param {string} [filter.payeePodId]
439
+ * @returns {EscrowContract[]}
440
+ */
441
+ listContracts(filter) {
442
+ let results = [...this.#contracts.values()]
443
+
444
+ if (filter?.status) {
445
+ results = results.filter(c => c.status === filter.status)
446
+ }
447
+ if (filter?.payerPodId) {
448
+ results = results.filter(c => c.payer === filter.payerPodId)
449
+ }
450
+ if (filter?.payeePodId) {
451
+ results = results.filter(c => c.payee === filter.payeePodId)
452
+ }
453
+
454
+ return results
455
+ }
456
+
457
+ /**
458
+ * Get aggregate statistics across all contracts.
459
+ *
460
+ * @returns {{ active: number, completed: number, disputed: number, totalEscrowed: number }}
461
+ */
462
+ getStats() {
463
+ let active = 0
464
+ let completed = 0
465
+ let disputed = 0
466
+ let totalEscrowed = 0
467
+
468
+ for (const contract of this.#contracts.values()) {
469
+ switch (contract.status) {
470
+ case 'funded':
471
+ active++
472
+ totalEscrowed += contract.amount
473
+ break
474
+ case 'released':
475
+ completed++
476
+ break
477
+ case 'disputed':
478
+ disputed++
479
+ break
480
+ }
481
+ }
482
+
483
+ return { active, completed, disputed, totalEscrowed }
484
+ }
485
+
486
+ // ── Events ─────────────────────────────────────────────────────
487
+
488
+ /**
489
+ * Subscribe to an event.
490
+ *
491
+ * @param {string} event - 'created' | 'released' | 'refunded' | 'disputed' | 'expired'
492
+ * @param {Function} cb
493
+ */
494
+ on(event, cb) {
495
+ if (!this.#listeners.has(event)) {
496
+ this.#listeners.set(event, [])
497
+ }
498
+ this.#listeners.get(event).push(cb)
499
+ }
500
+
501
+ /**
502
+ * Unsubscribe from an event.
503
+ *
504
+ * @param {string} event
505
+ * @param {Function} cb
506
+ */
507
+ off(event, cb) {
508
+ const cbs = this.#listeners.get(event)
509
+ if (!cbs) return
510
+ const idx = cbs.indexOf(cb)
511
+ if (idx !== -1) cbs.splice(idx, 1)
512
+ }
513
+
514
+ // ── Serialization ──────────────────────────────────────────────
515
+
516
+ /**
517
+ * Serialize all contracts to a JSON-safe object.
518
+ * @returns {object}
519
+ */
520
+ toJSON() {
521
+ return {
522
+ contracts: [...this.#contracts.values()].map(c => c.toJSON()),
523
+ }
524
+ }
525
+
526
+ /**
527
+ * Restore an EscrowManager from serialized data.
528
+ *
529
+ * @param {object} json
530
+ * @param {object} deps - { creditLedger, onLog? }
531
+ * @returns {EscrowManager}
532
+ */
533
+ static fromJSON(json, deps) {
534
+ const mgr = new EscrowManager(deps)
535
+ for (const cData of json.contracts) {
536
+ const contract = EscrowContract.fromJSON(cData)
537
+ mgr.#contracts.set(contract.id, contract)
538
+ }
539
+ return mgr
540
+ }
541
+
542
+ // ── Private helpers ────────────────────────────────────────────
543
+
544
+ /**
545
+ * Emit an event to all registered listeners.
546
+ * Uses a snapshot to avoid mutation during iteration.
547
+ *
548
+ * @param {string} event
549
+ * @param {...any} args
550
+ */
551
+ #emit(event, ...args) {
552
+ const cbs = this.#listeners.get(event)
553
+ if (!cbs) return
554
+ for (const cb of [...cbs]) {
555
+ try { cb(...args) } catch { /* listener errors do not propagate */ }
556
+ }
557
+ }
558
+
559
+ /**
560
+ * Get a contract by ID, throwing if not found.
561
+ *
562
+ * @param {string} contractId
563
+ * @param {string} action - For error messages
564
+ * @returns {EscrowContract}
565
+ */
566
+ #getValidContract(contractId, action) {
567
+ const contract = this.#contracts.get(contractId)
568
+ if (!contract) {
569
+ throw new Error(`Cannot ${action}: contract ${contractId} not found`)
570
+ }
571
+ return contract
572
+ }
573
+ }