@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,613 @@
1
+ /**
2
+ * clawser-peer-payments.js -- Payment mechanisms for resource sharing.
3
+ *
4
+ * Provides a PaymentProvider abstraction with two implementations:
5
+ * 1. CreditLedger — internal credit system (no real money)
6
+ * 2. WebLNProvider — Lightning Network payments (optional, requires browser extension)
7
+ *
8
+ * CreditLedger manages multi-peer balances and transaction history with
9
+ * resource-based cost calculation. WebLNProvider wraps the WebLN browser API
10
+ * for optional real-money Lightning payments.
11
+ *
12
+ * No browser-only imports at module level. All dependencies injected.
13
+ *
14
+ * Run tests:
15
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-payments.test.mjs
16
+ */
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Constants
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /**
23
+ * Default payment configuration for resource sharing.
24
+ * All costs are in internal credits (not real money).
25
+ */
26
+ export const PAYMENT_DEFAULTS = Object.freeze({
27
+ initialCredits: 100,
28
+ creditCostPerToken: 0.001, // 0.001 credits per LLM token
29
+ creditCostPerMbStorage: 0.1, // 0.1 credits per MB stored
30
+ creditCostPerMinuteCompute: 1, // 1 credit per minute compute
31
+ creditEarnPerMbServed: 0.05, // earn for serving files
32
+ creditEarnPerTokenServed: 0.0005, // earn for serving LLM responses
33
+ })
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // ID generation
37
+ // ---------------------------------------------------------------------------
38
+
39
+ let _txSeq = 0
40
+
41
+ function generateTxId() {
42
+ return `tx_${Date.now().toString(36)}_${(++_txSeq).toString(36)}`
43
+ }
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // CreditLedger
47
+ // ---------------------------------------------------------------------------
48
+
49
+ /**
50
+ * Multi-peer credit ledger for resource sharing.
51
+ *
52
+ * Tracks per-pod balances with automatic initialization at a configurable
53
+ * credit amount. Maintains a transaction log with optional capping.
54
+ */
55
+ export class CreditLedger {
56
+ /** @type {Map<string, number>} podId -> balance */
57
+ #balances = new Map()
58
+
59
+ /** @type {Array<object>} Transaction[] */
60
+ #transactions = []
61
+
62
+ /** @type {number} */
63
+ #initialCredits
64
+
65
+ /** @type {number} */
66
+ #maxTransactions
67
+
68
+ /** @type {Function} */
69
+ #onLog
70
+
71
+ /** @type {Map<string, Function[]>} */
72
+ #listeners = new Map()
73
+
74
+ /**
75
+ * @param {object} [opts]
76
+ * @param {number} [opts.initialCredits] - Starting credits for new peers
77
+ * @param {number} [opts.maxTransactions] - Cap on stored transaction history
78
+ * @param {Function} [opts.onLog] - Logging callback
79
+ */
80
+ constructor(opts = {}) {
81
+ this.#initialCredits = opts.initialCredits ?? PAYMENT_DEFAULTS.initialCredits
82
+ this.#maxTransactions = opts.maxTransactions ?? 10000
83
+ this.#onLog = opts.onLog ?? (() => {})
84
+ }
85
+
86
+ // ── Balance ──────────────────────────────────────────────────────
87
+
88
+ /**
89
+ * Get balance for a peer. Returns initialCredits for unknown peers
90
+ * (auto-initializes on first access).
91
+ *
92
+ * @param {string} podId
93
+ * @returns {number}
94
+ */
95
+ getBalance(podId) {
96
+ if (!this.#balances.has(podId)) {
97
+ this.#balances.set(podId, this.#initialCredits)
98
+ }
99
+ return this.#balances.get(podId)
100
+ }
101
+
102
+ // ── Charge ───────────────────────────────────────────────────────
103
+
104
+ /**
105
+ * Charge credits (spending). Deducts from the peer's balance.
106
+ *
107
+ * @param {string} podId
108
+ * @param {number} amount - Must be positive
109
+ * @param {string} [memo]
110
+ * @returns {{ success: boolean, txId: string|null, balance: number }}
111
+ */
112
+ charge(podId, amount, memo) {
113
+ if (typeof amount !== 'number' || amount <= 0) {
114
+ throw new RangeError(`Charge amount must be positive, got ${amount}`)
115
+ }
116
+
117
+ const balance = this.getBalance(podId)
118
+
119
+ if (balance < amount) {
120
+ this.#onLog(`Insufficient balance for ${podId}: need ${amount}, have ${balance}`)
121
+ this.#emit('insufficient', { podId, amount, balance })
122
+ return { success: false, txId: null, balance }
123
+ }
124
+
125
+ const newBalance = balance - amount
126
+ this.#balances.set(podId, newBalance)
127
+
128
+ const tx = this.#recordTransaction({
129
+ type: 'charge',
130
+ podId,
131
+ amount,
132
+ memo: memo || null,
133
+ balance: newBalance,
134
+ })
135
+
136
+ this.#onLog(`Charged ${amount} from ${podId}: balance ${newBalance}`)
137
+ this.#emit('charge', tx)
138
+
139
+ return { success: true, txId: tx.txId, balance: newBalance }
140
+ }
141
+
142
+ // ── Credit ───────────────────────────────────────────────────────
143
+
144
+ /**
145
+ * Credit (earning). Adds to the peer's balance.
146
+ *
147
+ * @param {string} podId
148
+ * @param {number} amount - Must be positive
149
+ * @param {string} [memo]
150
+ * @returns {{ success: boolean, txId: string, balance: number }}
151
+ */
152
+ credit(podId, amount, memo) {
153
+ if (typeof amount !== 'number' || amount <= 0) {
154
+ throw new RangeError(`Credit amount must be positive, got ${amount}`)
155
+ }
156
+
157
+ const balance = this.getBalance(podId)
158
+ const newBalance = balance + amount
159
+ this.#balances.set(podId, newBalance)
160
+
161
+ const tx = this.#recordTransaction({
162
+ type: 'credit',
163
+ podId,
164
+ amount,
165
+ memo: memo || null,
166
+ balance: newBalance,
167
+ })
168
+
169
+ this.#onLog(`Credited ${amount} to ${podId}: balance ${newBalance}`)
170
+ this.#emit('credit', tx)
171
+
172
+ return { success: true, txId: tx.txId, balance: newBalance }
173
+ }
174
+
175
+ // ── Transfer ─────────────────────────────────────────────────────
176
+
177
+ /**
178
+ * Transfer credits between two peers. Debits the sender and credits
179
+ * the receiver atomically (both succeed or neither does).
180
+ *
181
+ * @param {string} fromPodId
182
+ * @param {string} toPodId
183
+ * @param {number} amount - Must be positive
184
+ * @param {string} [memo]
185
+ * @returns {{ success: boolean, txId: string|null }}
186
+ */
187
+ transfer(fromPodId, toPodId, amount, memo) {
188
+ if (typeof amount !== 'number' || amount <= 0) {
189
+ throw new RangeError(`Transfer amount must be positive, got ${amount}`)
190
+ }
191
+
192
+ const fromBalance = this.getBalance(fromPodId)
193
+
194
+ if (fromBalance < amount) {
195
+ this.#onLog(`Transfer failed: ${fromPodId} has ${fromBalance}, needs ${amount}`)
196
+ this.#emit('insufficient', { podId: fromPodId, amount, balance: fromBalance })
197
+ return { success: false, txId: null }
198
+ }
199
+
200
+ // Debit sender
201
+ const newFromBalance = fromBalance - amount
202
+ this.#balances.set(fromPodId, newFromBalance)
203
+
204
+ // Credit receiver
205
+ const toBalance = this.getBalance(toPodId)
206
+ const newToBalance = toBalance + amount
207
+ this.#balances.set(toPodId, newToBalance)
208
+
209
+ const transferMemo = memo || `transfer ${fromPodId} -> ${toPodId}`
210
+
211
+ const tx = this.#recordTransaction({
212
+ type: 'transfer',
213
+ podId: fromPodId,
214
+ toPodId,
215
+ amount,
216
+ memo: transferMemo,
217
+ balance: newFromBalance,
218
+ })
219
+
220
+ this.#onLog(`Transfer ${amount} from ${fromPodId} to ${toPodId}`)
221
+ this.#emit('transfer', tx)
222
+
223
+ return { success: true, txId: tx.txId }
224
+ }
225
+
226
+ // ── Transaction history ──────────────────────────────────────────
227
+
228
+ /**
229
+ * Get transaction history, optionally filtered by pod ID.
230
+ *
231
+ * @param {string} [podId] - If provided, only transactions involving this pod
232
+ * @param {number} [limit] - Max results to return
233
+ * @returns {object[]} Transaction[]
234
+ */
235
+ getTransactions(podId, limit) {
236
+ let result = this.#transactions
237
+
238
+ if (podId) {
239
+ result = result.filter(
240
+ (tx) => tx.podId === podId || tx.toPodId === podId
241
+ )
242
+ }
243
+
244
+ if (typeof limit === 'number' && limit > 0) {
245
+ result = result.slice(-limit)
246
+ }
247
+
248
+ return [...result]
249
+ }
250
+
251
+ /**
252
+ * Look up a single transaction by ID.
253
+ *
254
+ * @param {string} txId
255
+ * @returns {object|null}
256
+ */
257
+ getTransactionById(txId) {
258
+ return this.#transactions.find((tx) => tx.txId === txId) ?? null
259
+ }
260
+
261
+ // ── Resource cost calculation ────────────────────────────────────
262
+
263
+ /**
264
+ * Calculate the credit cost for a given resource type and quantity.
265
+ *
266
+ * @param {'tokens'|'storage_mb'|'compute_minutes'} resourceType
267
+ * @param {number} quantity
268
+ * @returns {number}
269
+ */
270
+ calculateCost(resourceType, quantity) {
271
+ if (typeof quantity !== 'number' || quantity < 0) {
272
+ throw new RangeError(`Quantity must be non-negative, got ${quantity}`)
273
+ }
274
+
275
+ switch (resourceType) {
276
+ case 'tokens':
277
+ return quantity * PAYMENT_DEFAULTS.creditCostPerToken
278
+ case 'storage_mb':
279
+ return quantity * PAYMENT_DEFAULTS.creditCostPerMbStorage
280
+ case 'compute_minutes':
281
+ return quantity * PAYMENT_DEFAULTS.creditCostPerMinuteCompute
282
+ default:
283
+ throw new Error(`Unknown resource type: ${resourceType}`)
284
+ }
285
+ }
286
+
287
+ // ── Summary ──────────────────────────────────────────────────────
288
+
289
+ /**
290
+ * Get a summary of a peer's financial activity.
291
+ *
292
+ * @param {string} podId
293
+ * @returns {{ balance: number, totalEarned: number, totalSpent: number, transactionCount: number }}
294
+ */
295
+ getSummary(podId) {
296
+ const balance = this.getBalance(podId)
297
+ let totalEarned = 0
298
+ let totalSpent = 0
299
+ let transactionCount = 0
300
+
301
+ for (const tx of this.#transactions) {
302
+ if (tx.podId === podId) {
303
+ transactionCount++
304
+ if (tx.type === 'credit') {
305
+ totalEarned += tx.amount
306
+ } else if (tx.type === 'charge') {
307
+ totalSpent += tx.amount
308
+ } else if (tx.type === 'transfer') {
309
+ totalSpent += tx.amount
310
+ }
311
+ }
312
+ if (tx.toPodId === podId) {
313
+ transactionCount++
314
+ if (tx.type === 'transfer') {
315
+ totalEarned += tx.amount
316
+ }
317
+ }
318
+ }
319
+
320
+ return { balance, totalEarned, totalSpent, transactionCount }
321
+ }
322
+
323
+ // ── Serialization ────────────────────────────────────────────────
324
+
325
+ /**
326
+ * Serialize to a JSON-safe object.
327
+ * @returns {object}
328
+ */
329
+ toJSON() {
330
+ return {
331
+ initialCredits: this.#initialCredits,
332
+ maxTransactions: this.#maxTransactions,
333
+ balances: Object.fromEntries(this.#balances),
334
+ transactions: this.#transactions.map((tx) => ({ ...tx })),
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Restore a CreditLedger from serialized data.
340
+ * @param {object} data
341
+ * @returns {CreditLedger}
342
+ */
343
+ static fromJSON(data) {
344
+ const ledger = new CreditLedger({
345
+ initialCredits: data.initialCredits,
346
+ maxTransactions: data.maxTransactions,
347
+ })
348
+ for (const [podId, balance] of Object.entries(data.balances)) {
349
+ ledger.#balances.set(podId, balance)
350
+ }
351
+ ledger.#transactions = data.transactions.map((tx) => ({ ...tx }))
352
+ return ledger
353
+ }
354
+
355
+ // ── Events ───────────────────────────────────────────────────────
356
+
357
+ /**
358
+ * Subscribe to an event.
359
+ * @param {string} event - 'charge' | 'credit' | 'transfer' | 'insufficient'
360
+ * @param {Function} cb
361
+ */
362
+ on(event, cb) {
363
+ if (!this.#listeners.has(event)) {
364
+ this.#listeners.set(event, [])
365
+ }
366
+ this.#listeners.get(event).push(cb)
367
+ }
368
+
369
+ /**
370
+ * Unsubscribe from an event.
371
+ * @param {string} event
372
+ * @param {Function} cb
373
+ */
374
+ off(event, cb) {
375
+ const cbs = this.#listeners.get(event)
376
+ if (!cbs) return
377
+ const idx = cbs.indexOf(cb)
378
+ if (idx !== -1) cbs.splice(idx, 1)
379
+ }
380
+
381
+ // ── Private helpers ──────────────────────────────────────────────
382
+
383
+ /**
384
+ * Emit an event to all listeners.
385
+ * @param {string} event
386
+ * @param {...any} args
387
+ */
388
+ #emit(event, ...args) {
389
+ const cbs = this.#listeners.get(event)
390
+ if (!cbs) return
391
+ for (const cb of [...cbs]) {
392
+ try { cb(...args) } catch { /* listener errors do not propagate */ }
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Record a transaction and enforce the maxTransactions cap.
398
+ * @param {object} fields
399
+ * @returns {object} The recorded transaction
400
+ */
401
+ #recordTransaction(fields) {
402
+ const tx = {
403
+ txId: generateTxId(),
404
+ timestamp: Date.now(),
405
+ ...fields,
406
+ }
407
+
408
+ this.#transactions.push(tx)
409
+
410
+ // Enforce cap: drop oldest transactions when over limit
411
+ if (this.#transactions.length > this.#maxTransactions) {
412
+ this.#transactions = this.#transactions.slice(-this.#maxTransactions)
413
+ }
414
+
415
+ return tx
416
+ }
417
+ }
418
+
419
+ // ---------------------------------------------------------------------------
420
+ // WebLNProvider
421
+ // ---------------------------------------------------------------------------
422
+
423
+ /**
424
+ * Wrapper around the WebLN browser API for optional Lightning Network payments.
425
+ *
426
+ * WebLN is a browser extension API (e.g., Alby) that enables Lightning
427
+ * Network payments directly from the browser. This class provides a safe
428
+ * abstraction that degrades gracefully when WebLN is not available.
429
+ *
430
+ * @see https://www.webln.guide/
431
+ */
432
+ export class WebLNProvider {
433
+ /** @type {boolean} */
434
+ #available
435
+
436
+ /** @type {boolean} */
437
+ #connected = false
438
+
439
+ /** @type {Function} */
440
+ #onLog
441
+
442
+ /** @type {object|null} — reference to the webln global, injectable for testing */
443
+ #weblnRef
444
+
445
+ /**
446
+ * @param {object} [opts]
447
+ * @param {Function} [opts.onLog] - Logging callback
448
+ * @param {object} [opts.webln] - Injected webln reference (for testing)
449
+ */
450
+ constructor(opts = {}) {
451
+ this.#onLog = opts.onLog ?? (() => {})
452
+ this.#weblnRef = opts.webln ?? (typeof globalThis !== 'undefined' ? globalThis.webln : undefined) ?? null
453
+ this.#available = this.#weblnRef != null
454
+ }
455
+
456
+ // ── Status ───────────────────────────────────────────────────────
457
+
458
+ /**
459
+ * Whether the WebLN API is available in the current environment.
460
+ * @returns {boolean}
461
+ */
462
+ get available() {
463
+ return this.#available
464
+ }
465
+
466
+ /**
467
+ * Whether we have an active connection to the user's Lightning wallet.
468
+ * @returns {boolean}
469
+ */
470
+ get connected() {
471
+ return this.#connected
472
+ }
473
+
474
+ // ── Connect ──────────────────────────────────────────────────────
475
+
476
+ /**
477
+ * Connect to the user's Lightning wallet via WebLN.
478
+ * Calls window.webln.enable().
479
+ *
480
+ * @returns {Promise<boolean>} true if connected successfully
481
+ */
482
+ async connect() {
483
+ if (!this.#available) {
484
+ this.#onLog('WebLN not available')
485
+ return false
486
+ }
487
+
488
+ try {
489
+ await this.#weblnRef.enable()
490
+ this.#connected = true
491
+ this.#onLog('WebLN connected')
492
+ return true
493
+ } catch (err) {
494
+ this.#onLog(`WebLN connect failed: ${err.message}`)
495
+ this.#connected = false
496
+ return false
497
+ }
498
+ }
499
+
500
+ // ── Balance ──────────────────────────────────────────────────────
501
+
502
+ /**
503
+ * Get the wallet balance in sats.
504
+ * Requires an active connection.
505
+ *
506
+ * @returns {Promise<number|null>} Balance in sats, or null on failure
507
+ */
508
+ async getBalance() {
509
+ if (!this.#connected) {
510
+ this.#onLog('WebLN not connected')
511
+ return null
512
+ }
513
+
514
+ try {
515
+ const result = await this.#weblnRef.getBalance()
516
+ return typeof result === 'number' ? result : (result?.balance ?? null)
517
+ } catch (err) {
518
+ this.#onLog(`WebLN getBalance failed: ${err.message}`)
519
+ return null
520
+ }
521
+ }
522
+
523
+ // ── Invoices ─────────────────────────────────────────────────────
524
+
525
+ /**
526
+ * Create a Lightning invoice for receiving payment.
527
+ *
528
+ * @param {number} amount - Amount in sats
529
+ * @param {string} [memo] - Invoice description
530
+ * @returns {Promise<{ paymentRequest: string, rHash: string }|null>}
531
+ */
532
+ async createInvoice(amount, memo) {
533
+ if (!this.#connected) {
534
+ this.#onLog('WebLN not connected')
535
+ return null
536
+ }
537
+
538
+ try {
539
+ const invoice = await this.#weblnRef.makeInvoice({
540
+ amount,
541
+ defaultMemo: memo || '',
542
+ })
543
+ return {
544
+ paymentRequest: invoice.paymentRequest,
545
+ rHash: invoice.rHash || invoice.paymentHash || '',
546
+ }
547
+ } catch (err) {
548
+ this.#onLog(`WebLN makeInvoice failed: ${err.message}`)
549
+ return null
550
+ }
551
+ }
552
+
553
+ // ── Pay ──────────────────────────────────────────────────────────
554
+
555
+ /**
556
+ * Pay a Lightning invoice.
557
+ *
558
+ * @param {string} paymentRequest - BOLT11 invoice string
559
+ * @returns {Promise<{ preimage: string, success: boolean }|null>}
560
+ */
561
+ async payInvoice(paymentRequest) {
562
+ if (!this.#connected) {
563
+ this.#onLog('WebLN not connected')
564
+ return null
565
+ }
566
+
567
+ try {
568
+ const result = await this.#weblnRef.sendPayment(paymentRequest)
569
+ return {
570
+ preimage: result.preimage || '',
571
+ success: true,
572
+ }
573
+ } catch (err) {
574
+ this.#onLog(`WebLN sendPayment failed: ${err.message}`)
575
+ return null
576
+ }
577
+ }
578
+
579
+ // ── Info ──────────────────────────────────────────────────────────
580
+
581
+ /**
582
+ * Get wallet/node info.
583
+ *
584
+ * @returns {Promise<object|null>}
585
+ */
586
+ async getInfo() {
587
+ if (!this.#connected) {
588
+ this.#onLog('WebLN not connected')
589
+ return null
590
+ }
591
+
592
+ try {
593
+ return await this.#weblnRef.getInfo()
594
+ } catch (err) {
595
+ this.#onLog(`WebLN getInfo failed: ${err.message}`)
596
+ return null
597
+ }
598
+ }
599
+
600
+ // ── Serialization ────────────────────────────────────────────────
601
+
602
+ /**
603
+ * Serialize to a JSON-safe object.
604
+ * @returns {object}
605
+ */
606
+ toJSON() {
607
+ return {
608
+ available: this.#available,
609
+ connected: this.#connected,
610
+ type: 'webln',
611
+ }
612
+ }
613
+ }