@bsv/expo-wallet-toolbox 0.17.0 → 0.18.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,844 @@
1
+ /**
2
+ * DirectPayManager owns the open wallet's direct (peer-to-peer) payment client. Ported from
3
+ * BSV Desktop's `src/lib/services/DirectPayManager.ts`; what differs on a phone is listed last.
4
+ *
5
+ * `DirectPayProvider` starts it once a wallet is built and stops it when the wallet goes. While
6
+ * a wallet is open there is always a client, so this wallet can dial others. Dialing and
7
+ * receiving by identity key need a signaler, chosen in the device settings: a relay server (the
8
+ * default) or the message box. Receiving is on when the user left it on and the app is in the
9
+ * foreground; payments are taken into the wallet at once (`receive.ts`). Through a relay,
10
+ * receiving follows the relay connection, which reconnects by itself, and every connection may
11
+ * use the short-lived TURN servers the relay hands out.
12
+ *
13
+ * While receiving through the relay, a relay that cannot be reached (it refuses or drops the
14
+ * connection, or this wallet is not online on it within {@link RELAY_START_MS}) hands receiving
15
+ * to the message box, when this wallet has one (`relayUnreachable` in the snapshot). The relay
16
+ * is retried in the background and receiving moves back to it once it accepts this wallet. The
17
+ * retry starts {@link RELAY_RETRY_FIRST_MS} after a fallback, doubling with each fallback in a
18
+ * row up to {@link RELAY_RETRY_MAX_MS}, so a relay that accepts and then drops this wallet does
19
+ * not cycle quickly; once the relay has stayed online for {@link RELAY_STABLE_MS} the wait
20
+ * starts over (as it does on every start). A user who chose the message box stays on it.
21
+ *
22
+ * While a wallet is open, its kept payments (acknowledged, not yet in the wallet) are retried:
23
+ * when it opens, then on a backing-off timer, whenever the network comes back, and when the
24
+ * app returns to the foreground. One pass at a time; a pass stops between payments once
25
+ * {@link RETRY_PASS_MS} have passed, and a wallet call that takes longer than
26
+ * {@link RETRY_CALL_MS} ends it.
27
+ *
28
+ * On a phone, unlike the desktop:
29
+ * - Receiving runs only in the foreground. `setForeground(false)` (the app went to the
30
+ * background) starts the client over without receiving, so this wallet stops answering at
31
+ * once rather than when the OS suspends its sockets; `setForeground(true)` starts it over
32
+ * receiving. Starting over closes the client, so a payment being sent at that moment stops
33
+ * (before it is made, or it is left for the message box; see `rails/direct.ts`). The
34
+ * provider counts only `background` as leaving: `inactive` is a Face ID prompt or the
35
+ * control centre, which a payment in progress must survive.
36
+ * - Toasts go through the host's `onToast`, in the user's language; there are no window
37
+ * events (a payment's `internalizeAction` refreshes balances by itself).
38
+ * - The desktop's wallet-busy guards (its HTTP bridge, network switches) have no equivalent:
39
+ * the provider stops the manager before the wallet it runs on is torn down, and a retry pass
40
+ * holds no lock between payments.
41
+ * - Network changes come from `subscribeOnline` (NetInfo) rather than the window's `online`.
42
+ *
43
+ * React integration: `subscribe` / `getSnapshot` (see DirectPayProvider).
44
+ */
45
+ import i18n from '../i18n/translations'
46
+ import type { KVStorage } from '../localpay/pending'
47
+ import { classifyCreditError, type CreditFailureKind } from '../pay/creditErrors'
48
+ import { iceServersFrom } from './settings'
49
+ import {
50
+ receiveDirectPayment,
51
+ retryKeptDirectPayments,
52
+ RetryStopped,
53
+ type DirectPayStore,
54
+ type DirectReceipt,
55
+ type KeptDirectPaymentInfo
56
+ } from './receive'
57
+ import type { DirectPaySettings, DirectPayStatus } from './types'
58
+ import type {
59
+ DirectPayClientLike,
60
+ IncomingDirectPayment,
61
+ MessageBoxLike,
62
+ RelaySignalerLike,
63
+ RelayState,
64
+ SignalerLike,
65
+ WebRTPayErrorLike,
66
+ WebRTPayModule,
67
+ WebRTPayWallet
68
+ } from './webrtpay'
69
+
70
+ export interface DirectPaySnapshot {
71
+ /** For sending; null while no wallet is open. */
72
+ client: DirectPayClientLike | null
73
+ status: DirectPayStatus
74
+ /** How this wallet reaches others by identity key; null when it cannot. */
75
+ via: 'messagebox' | 'relay' | null
76
+ /** The settings choose the relay, but it cannot be reached, so `via` is the message box until it can. */
77
+ relayUnreachable: boolean
78
+ /** Why `status` is `error`, in English, for the log (the Receive card words it from `status`). */
79
+ error: string
80
+ /** Why direct payments by identity key are not set up, when that is not a failure (no message box). */
81
+ notice: string
82
+ /** Direct payments received since the wallet opened. */
83
+ received: number
84
+ /** The app is in the background, so this wallet is not receiving whatever the settings say. */
85
+ background: boolean
86
+ }
87
+
88
+ export interface DirectPayStartOptions {
89
+ wallet: WebRTPayWallet
90
+ originator: string
91
+ /** This wallet's identity key. */
92
+ identity: string
93
+ /** `main` or `test`: dials and answers are bound to it. */
94
+ chain: string
95
+ /** Carries signals when the settings choose the message box; null without a message box. */
96
+ peerPayClient: MessageBoxLike | null
97
+ /** The message box host to poll for signals (skips an overlay lookup per poll). */
98
+ messageBoxUrl?: string
99
+ settings: DirectPaySettings
100
+ /** The host's `RTCPeerConnection` (react-native-webrtc's), from `ToolboxConfig.directPay`. */
101
+ RTCPeerConnection?: unknown
102
+ }
103
+
104
+ /** The host's toast, as WalletContextProvider and VaultProvider take it. */
105
+ export type DirectPayToast = (message: string, opts?: { type?: 'info' | 'success' | 'error' }) => void
106
+
107
+ export interface DirectPayManagerDeps {
108
+ webrtpay: WebRTPayModule
109
+ /** The device store for the seen store and kept payments (`deviceKVStorage`). */
110
+ storage: KVStorage
111
+ /**
112
+ * How a failure to take a payment is classified. Built per payment and per retry pass, as
113
+ * `makeCreditClassifier` builds it for the inbox; `classifyCreditError` without context when
114
+ * omitted.
115
+ */
116
+ classifier?: () => Promise<(e: unknown) => CreditFailureKind>
117
+ onToast?: DirectPayToast
118
+ /** A payment arrived (once per payment): in the wallet (`accepted`) or kept on this device. */
119
+ onReceived?: (p: { amount: number; sender: string; status: DirectReceipt['status'] }) => void
120
+ /** NetInfo's online signal (`core/net/online.ts`); kept payments are retried when it comes back. */
121
+ subscribeOnline?: (cb: (online: boolean) => void) => () => void
122
+ getOnline?: () => Promise<boolean>
123
+ /** Whether the app starts in the foreground. Default true. */
124
+ foreground?: boolean
125
+ }
126
+
127
+ const OFF: DirectPaySnapshot = {
128
+ client: null,
129
+ status: 'off',
130
+ via: null,
131
+ relayUnreachable: false,
132
+ error: '',
133
+ notice: '',
134
+ received: 0,
135
+ background: false
136
+ }
137
+
138
+ /** How long receiving through the relay may take to come online before it falls back to the message box. */
139
+ export const RELAY_START_MS = 5000
140
+ /** How long a dial may take to open the link once the recipient has answered (package default 6 s). */
141
+ export const DIAL_MS = 10_000
142
+ /** The wait before the relay is retried after a fallback; doubles per fallback in a row. */
143
+ export const RELAY_RETRY_FIRST_MS = 5000
144
+ export const RELAY_RETRY_MAX_MS = 5 * 60_000
145
+ /** How long the relay must stay online before the retry wait starts over. */
146
+ export const RELAY_STABLE_MS = 60_000
147
+
148
+ /** Kept payments are retried when a wallet opens, then after 60 s, doubling to every 15 minutes. */
149
+ export const RETRY_FIRST_MS = 60_000
150
+ export const RETRY_MAX_MS = 15 * 60_000
151
+ /** A retry pass starts no payment after this long. */
152
+ export const RETRY_PASS_MS = 15_000
153
+ /** A retry's wallet call that takes longer ends the pass. */
154
+ export const RETRY_CALL_MS = 15_000
155
+
156
+ /** Failed polls of the message box in a row before the status says it cannot be reached. */
157
+ const POLL_FAILURES_SHOWN = 2
158
+
159
+ const NO_RELAY = 'No relay server is set; enter one in Settings, or use the message box for direct payments.'
160
+ const NO_MESSAGE_BOX =
161
+ 'Direct payments reach other wallets through the message box. Connect a message box in Settings, or use a relay server.'
162
+
163
+ type Started = {
164
+ options: DirectPayStartOptions
165
+ /** The client's signaler when it is a relay, or the relay being retried while on the message box. */
166
+ relay: RelaySignalerLike | null
167
+ /** Runs on teardown. */
168
+ unsubscribe: () => void
169
+ }
170
+
171
+ /** Which way a launch signals: as the settings say, or (`fallback`) through the message box while the relay is retried. */
172
+ type Carrier = 'settings' | 'fallback'
173
+
174
+ type RetrySchedule = {
175
+ options: DirectPayStartOptions
176
+ /** The wait before the next timed pass; doubles after each, up to {@link RETRY_MAX_MS}. */
177
+ delay: number
178
+ timer?: ReturnType<typeof setTimeout>
179
+ /** When `timer` fires (ms since the epoch). */
180
+ due?: number
181
+ /** The next pass also offers payments that need attention (the wallet opened, or the network came back). */
182
+ withAttention: boolean
183
+ running: boolean
184
+ /** Asked for while a pass was running: run another as soon as it ends. */
185
+ again: boolean
186
+ unsubscribeOnline: () => void
187
+ }
188
+
189
+ export class DirectPayManager {
190
+ private _snapshot: DirectPaySnapshot = OFF
191
+ private readonly _listeners = new Set<(s: DirectPaySnapshot) => void>()
192
+ private _started: Started | null = null
193
+ /** Settles when the current start has finished setting up receiving. */
194
+ private _starting: Promise<void> = Promise.resolve()
195
+ /** Bumped by every start and stop; a start that is no longer current changes nothing. */
196
+ private _generation = 0
197
+ private _retry: RetrySchedule | null = null
198
+ /** Fallbacks to the message box in a row: sets the wait before the relay is retried. */
199
+ private _fallbacks = 0
200
+ /** Resets {@link _fallbacks} once the relay has stayed online; cleared by every teardown. */
201
+ private _stableTimer: ReturnType<typeof setTimeout> | undefined
202
+ private _foreground: boolean
203
+ /** The last relay connection failed and has not come online since (see {@link signalingDown}). */
204
+ private _relayDown = false
205
+
206
+ private readonly _deps: DirectPayManagerDeps
207
+
208
+ constructor(deps: DirectPayManagerDeps) {
209
+ this._deps = { ...deps }
210
+ this._foreground = deps.foreground ?? true
211
+ }
212
+
213
+ /** Replaces the toast, the arrival callback or the classifier (a React host passes its latest). */
214
+ setCallbacks(callbacks: Pick<DirectPayManagerDeps, 'onToast' | 'onReceived' | 'classifier'>): void {
215
+ Object.assign(this._deps, callbacks)
216
+ }
217
+
218
+ getSnapshot = (): DirectPaySnapshot => this._snapshot
219
+
220
+ /** Calls `fn` with every new snapshot; returns the unsubscribe. */
221
+ subscribe = (fn: (s: DirectPaySnapshot) => void): (() => void) => {
222
+ this._listeners.add(fn)
223
+ return () => {
224
+ this._listeners.delete(fn)
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Starts direct payments for a wallet. Called again with the same inputs it does nothing,
230
+ * unless receiving failed (the relay is unreachable): then it starts over at once. With
231
+ * different inputs it replaces the client. Never rejects: problems show as `status: 'error'`.
232
+ */
233
+ start(o: DirectPayStartOptions): Promise<void> {
234
+ const previous = this._started?.options
235
+ if (previous && sameInputs(previous, o) && !receiveFailed(this._snapshot)) return this._starting
236
+ const sameWallet = previous !== undefined && isSameWallet(previous, o)
237
+ const received = sameWallet ? this._snapshot.received : 0
238
+ const closing = this._teardown()
239
+ this._fallbacks = 0
240
+ this._starting = this._launch(o, received, closing, 'settings')
241
+ if (!sameWallet) this._startRetries(o)
242
+ return this._starting
243
+ }
244
+
245
+ /** Uses new settings for the open wallet (no-op when nothing changed or none is open). */
246
+ async applySettings(s: DirectPaySettings): Promise<void> {
247
+ if (!this._started) return
248
+ await this.start({ ...this._started.options, settings: s })
249
+ }
250
+
251
+ /**
252
+ * The app moved to (`true`) or from (`false`) the foreground. Receiving follows: the client
253
+ * starts over with receiving on or off (see the header). Kept-payment retries pause in the
254
+ * background and run once on return.
255
+ */
256
+ setForeground(foreground: boolean): void {
257
+ if (foreground === this._foreground) return
258
+ this._foreground = foreground
259
+ const started = this._started
260
+ if (started) {
261
+ const received = this._snapshot.received
262
+ const closing = this._teardown()
263
+ this._fallbacks = 0
264
+ this._starting = this._launch(started.options, received, closing, 'settings')
265
+ }
266
+ const s = this._retry
267
+ if (!s) return
268
+ if (foreground) {
269
+ this._retryNow(s, false)
270
+ } else {
271
+ clearTimeout(s.timer)
272
+ s.timer = undefined
273
+ s.due = undefined
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Whether this wallet's own way of reaching others is down: the device is offline, or the
279
+ * relay's last connection failed and has not come back. A dial nobody answered then says
280
+ * nothing about the recipient (`rails/direct.ts` reports it as `unavailable`).
281
+ */
282
+ signalingDown = async (): Promise<boolean> => {
283
+ if (this._relayDown && this._snapshot.via === 'relay') return true
284
+ try {
285
+ return this._deps.getOnline ? !(await this._deps.getOnline()) : false
286
+ } catch {
287
+ return false
288
+ }
289
+ }
290
+
291
+ /** Closes the client and signaler. The snapshot clears at once; never rejects. */
292
+ async stop(): Promise<void> {
293
+ this._stopRetries()
294
+ const closing = this._teardown()
295
+ if (this._snapshot !== OFF) this._set(OFF)
296
+ await closing
297
+ }
298
+
299
+ // ------------------------------------------------------------------
300
+ // Private helpers
301
+ // ------------------------------------------------------------------
302
+
303
+ /** Sets up a client synchronously (so the snapshot has it at once), then receiving. */
304
+ private async _launch(
305
+ o: DirectPayStartOptions,
306
+ received: number,
307
+ closing: Promise<void>,
308
+ carrier: Carrier
309
+ ): Promise<void> {
310
+ const { webrtpay } = this._deps
311
+ const generation = this._generation
312
+ let client: DirectPayClientLike | null = null
313
+ let relay: RelaySignalerLike | null = null
314
+ let signaler: SignalerLike | undefined
315
+ let via: DirectPaySnapshot['via'] = null
316
+ let error = ''
317
+ let notice = ''
318
+ const fallback = carrier === 'fallback'
319
+ try {
320
+ if (o.settings.signaling === 'relay' && !fallback) {
321
+ if (!o.settings.relayUrl) {
322
+ error = NO_RELAY
323
+ } else {
324
+ const url = o.settings.relayUrl
325
+ relay = new webrtpay.RelaySignaler({
326
+ url,
327
+ wallet: o.wallet,
328
+ originator: o.originator,
329
+ onStateChange: (state, e) => this._relayChanged(generation, o, url, state, e)
330
+ })
331
+ signaler = relay
332
+ via = 'relay'
333
+ }
334
+ } else if (!o.peerPayClient) {
335
+ notice = NO_MESSAGE_BOX
336
+ } else {
337
+ let failures = 0
338
+ const polled = (pollError?: unknown) => {
339
+ failures = pollError === undefined ? 0 : failures + 1
340
+ this._messageBoxPolled(generation, this._receives(o), failures, pollError)
341
+ }
342
+ signaler = new webrtpay.MessageBoxSignaler(watchingPolls(o.peerPayClient, polled), {
343
+ host: o.messageBoxUrl || undefined,
344
+ messageBox: signalBox(o.chain)
345
+ })
346
+ via = 'messagebox'
347
+ }
348
+ client = new webrtpay.DirectPayClient({
349
+ wallet: o.wallet,
350
+ originator: o.originator,
351
+ chain: o.chain,
352
+ signaler,
353
+ rtc: {
354
+ iceServers: iceServersFrom(o.settings),
355
+ ...(o.RTCPeerConnection !== undefined && { RTCPeerConnection: o.RTCPeerConnection })
356
+ },
357
+ // Once the recipient has answered, give the link 10 s (the package default is 6 s): a
358
+ // slow STUN or TURN answer on a phone network otherwise ends a payment the recipient is
359
+ // online for.
360
+ timeouts: { dialMs: DIAL_MS },
361
+ // The relay's TURN servers, asked for before each ICE gather. One provider for the
362
+ // client's life: it reuses live credentials.
363
+ ...(relay &&
364
+ !fallback && {
365
+ iceServersProvider: relay.turnProvider(),
366
+ onIceServersProviderError: (e: unknown) =>
367
+ console.warn("[DirectPayManager] Connecting without the relay's TURN servers:", messageOf(e))
368
+ })
369
+ })
370
+ } catch (e) {
371
+ void relay?.close().catch(() => {})
372
+ relay = null
373
+ via = null
374
+ notice = ''
375
+ error = `Direct payments could not be set up: ${messageOf(e)}`
376
+ }
377
+
378
+ const receive = !error && !notice && this._receives(o)
379
+ this._started = { options: o, relay, unsubscribe: () => {} }
380
+ this._set({
381
+ client,
382
+ status: error ? 'error' : receive ? 'starting' : 'off',
383
+ via,
384
+ relayUnreachable: fallback,
385
+ error,
386
+ notice,
387
+ received,
388
+ background: !this._foreground
389
+ })
390
+ if (!receive || !client) return
391
+ if (relay && !fallback && o.peerPayClient) {
392
+ // Not online through the relay in time: receive through the message box meanwhile.
393
+ const timer = setTimeout(() => {
394
+ if (generation === this._generation && this._snapshot.status !== 'online') {
395
+ this._fallBack(generation, o, 'it did not accept this wallet in time')
396
+ }
397
+ }, RELAY_START_MS)
398
+ this._onTeardown(() => clearTimeout(timer))
399
+ }
400
+ if (fallback) this._retryRelayLater(generation, o)
401
+
402
+ // The previous client stops listening first, so two never answer the same offer.
403
+ await closing
404
+ if (generation !== this._generation) return
405
+ try {
406
+ await client.startReceiving({
407
+ onPayment: (p, ctx) => this._onPayment(o, p, ctx.note),
408
+ onError: e => console.warn('[DirectPayManager] Inbound direct payment session failed:', messageOf(e))
409
+ })
410
+ // The status follows the relay's connection (_relayChanged) or the message box's polls
411
+ // (_messageBoxPolled), so it says online only once receiving works.
412
+ } catch (e) {
413
+ if (generation === this._generation) {
414
+ this._update({ status: 'error', error: `Direct payments cannot be received: ${messageOf(e)}` })
415
+ }
416
+ }
417
+ }
418
+
419
+ /** Receiving is on: the user's switch, and the app in the foreground. */
420
+ private _receives(o: DirectPayStartOptions): boolean {
421
+ return o.settings.receiveEnabled && this._foreground
422
+ }
423
+
424
+ /** Receiving through the relay failed: receive through the message box, retrying the relay. */
425
+ private _fallBack(generation: number, o: DirectPayStartOptions, why: string): void {
426
+ if (generation !== this._generation) return
427
+ this._fallbacks++
428
+ console.warn(`[DirectPayManager] Receiving through the message box: the relay cannot be reached (${why}).`)
429
+ const received = this._snapshot.received
430
+ const closing = this._teardown()
431
+ this._starting = this._launch(o, received, closing, 'fallback')
432
+ }
433
+
434
+ /**
435
+ * After the wait for this many fallbacks in a row, retries the relay while receiving through
436
+ * the message box: listening keeps it trying, with the relay signaler's own backoff, until it
437
+ * accepts this wallet. Teardown cancels the wait or closes the retry.
438
+ */
439
+ private _retryRelayLater(generation: number, o: DirectPayStartOptions): void {
440
+ const wait = Math.min(RELAY_RETRY_FIRST_MS * 2 ** Math.max(0, this._fallbacks - 1), RELAY_RETRY_MAX_MS)
441
+ const timer = setTimeout(() => {
442
+ const started = this._started
443
+ if (generation !== this._generation || !started) return
444
+ const retry = new this._deps.webrtpay.RelaySignaler({
445
+ url: o.settings.relayUrl,
446
+ wallet: o.wallet,
447
+ originator: o.originator,
448
+ onStateChange: (state, e) => this._relayRetried(generation, o, state, e)
449
+ })
450
+ started.relay = retry
451
+ retry
452
+ .listen(() => {
453
+ // Signals that reach the retry before receiving moves back to the relay: payers dial again.
454
+ })
455
+ .catch(() => {
456
+ /* closed */
457
+ })
458
+ }, wait)
459
+ this._onTeardown(() => clearTimeout(timer))
460
+ }
461
+
462
+ /** Runs `fn` when the current client is torn down. */
463
+ private _onTeardown(fn: () => void): void {
464
+ const started = this._started
465
+ if (!started) return
466
+ const unsubscribe = started.unsubscribe
467
+ started.unsubscribe = () => {
468
+ fn()
469
+ unsubscribe()
470
+ }
471
+ }
472
+
473
+ /** The relay being retried accepted this wallet: receiving moves back to it. */
474
+ private _relayRetried(generation: number, o: DirectPayStartOptions, state: RelayState, e?: WebRTPayErrorLike): void {
475
+ if (generation !== this._generation) return
476
+ if (state === 'offline' && e)
477
+ console.warn('[DirectPayManager] The relay still cannot be reached:', e.code, e.message)
478
+ if (state !== 'online') return
479
+ const received = this._snapshot.received
480
+ const closing = this._teardown()
481
+ this._starting = this._launch(o, received, closing, 'settings')
482
+ }
483
+
484
+ /**
485
+ * While receiving through a relay, the status follows its connection: `starting` while it
486
+ * connects, `online` once the relay accepted this wallet, and `error` while it is offline
487
+ * (the signaler keeps trying). With a message box, a relay gone offline hands receiving to it.
488
+ * While not receiving, the relay connects only for payments, and the status stays `off`.
489
+ */
490
+ private _relayChanged(
491
+ generation: number,
492
+ o: DirectPayStartOptions,
493
+ url: string,
494
+ state: RelayState,
495
+ e?: WebRTPayErrorLike
496
+ ): void {
497
+ if (generation !== this._generation) return
498
+ if (state === 'online') this._relayDown = false
499
+ else if (state === 'offline' && e) this._relayDown = true
500
+ if (!this._receives(o)) return
501
+ // Online long enough: the next fallback retries the relay after the shortest wait again.
502
+ if (state === 'online' && this._stableTimer === undefined) {
503
+ this._stableTimer = setTimeout(() => {
504
+ this._stableTimer = undefined
505
+ if (generation === this._generation) this._fallbacks = 0
506
+ }, RELAY_STABLE_MS)
507
+ } else if (state !== 'online') {
508
+ clearTimeout(this._stableTimer)
509
+ this._stableTimer = undefined
510
+ }
511
+ if (state === 'online') this._update({ status: 'online', error: '' })
512
+ else if (state === 'offline' && e && o.peerPayClient) this._fallBack(generation, o, `${e.code}: ${e.message}`)
513
+ else if (state === 'offline' && e) {
514
+ this._update({ status: 'error', error: `Direct payments cannot be received: ${relayProblem(e, url)}` })
515
+ }
516
+ // Connecting again: keep showing why the last try failed until one succeeds.
517
+ else if (this._snapshot.status !== 'error') this._update({ status: 'starting', error: '' })
518
+ }
519
+
520
+ /**
521
+ * While receiving through the message box, the status follows its polls: `online` once a poll
522
+ * worked, and `error` after {@link POLL_FAILURES_SHOWN} failures in a row (the signaler keeps
523
+ * polling, and the status recovers by itself).
524
+ */
525
+ private _messageBoxPolled(generation: number, receiving: boolean, failures: number, error: unknown): void {
526
+ if (generation !== this._generation || !receiving) return
527
+ if (failures === 0) this._update({ status: 'online', error: '' })
528
+ else if (failures >= POLL_FAILURES_SHOWN) {
529
+ this._update({
530
+ status: 'error',
531
+ error: `Direct payments cannot be received: the message box cannot be reached (${messageOf(error)}). Trying again…`
532
+ })
533
+ }
534
+ }
535
+
536
+ /** Takes a payment into the wallet; a throw becomes a `rejected` ack for the payer. */
537
+ private async _onPayment(
538
+ o: DirectPayStartOptions,
539
+ p: IncomingDirectPayment,
540
+ note: string | undefined
541
+ ): Promise<'accepted' | 'received'> {
542
+ const classify = await this._classifier()
543
+ const receipt = await receiveDirectPayment({
544
+ webrtpay: this._deps.webrtpay,
545
+ wallet: o.wallet,
546
+ originator: o.originator,
547
+ store: this._store(o),
548
+ payment: p,
549
+ note,
550
+ classify
551
+ })
552
+ // The payment is taken: nothing below may turn the ack into a rejection.
553
+ try {
554
+ if (receipt.status === 'received' && !receipt.repeat) this._retrySoon(o)
555
+ // Delivered again after a lost ack, or credited from the inbox first: announced already.
556
+ if (!receipt.repeat) {
557
+ const current = this._started?.options
558
+ if (current && isSameWallet(current, o)) this._set({ ...this._snapshot, received: this._snapshot.received + 1 })
559
+ this._deps.onToast?.(i18n.t('payment_arrived'), { type: 'success' })
560
+ this._deps.onReceived?.({ amount: p.token.amount, sender: p.sender, status: receipt.status })
561
+ }
562
+ } catch (e) {
563
+ console.warn('[DirectPayManager] Could not announce a received direct payment:', messageOf(e))
564
+ }
565
+ return receipt.status
566
+ }
567
+
568
+ private _store(o: DirectPayStartOptions): DirectPayStore {
569
+ return { storage: this._deps.storage, identity: o.identity, chain: o.chain }
570
+ }
571
+
572
+ private async _classifier(): Promise<(e: unknown) => CreditFailureKind> {
573
+ try {
574
+ if (this._deps.classifier) return await this._deps.classifier()
575
+ } catch {
576
+ // Without its context, the plain classifier is still right for most failures.
577
+ }
578
+ return e => classifyCreditError(e)
579
+ }
580
+
581
+ /** Retries the kept payments of a wallet that just opened, now and while it stays open. */
582
+ private _startRetries(o: DirectPayStartOptions): void {
583
+ this._stopRetries()
584
+ const s: RetrySchedule = {
585
+ options: o,
586
+ delay: RETRY_FIRST_MS,
587
+ withAttention: true,
588
+ running: false,
589
+ again: false,
590
+ unsubscribeOnline: () => {}
591
+ }
592
+ this._retry = s
593
+ try {
594
+ s.unsubscribeOnline =
595
+ this._deps.subscribeOnline?.(online => {
596
+ if (!online) return
597
+ s.delay = RETRY_FIRST_MS
598
+ this._retryNow(s, true)
599
+ }) ?? (() => {})
600
+ } catch (e) {
601
+ console.warn('[DirectPayManager] Could not follow the network state:', messageOf(e))
602
+ }
603
+ this._retryNow(s, true)
604
+ }
605
+
606
+ /** The wallet closed: no more passes (one already running ends at its next payment). */
607
+ private _stopRetries(): void {
608
+ const s = this._retry
609
+ if (!s) return
610
+ this._retry = null
611
+ clearTimeout(s.timer)
612
+ try {
613
+ s.unsubscribeOnline()
614
+ } catch {
615
+ // Nothing to undo.
616
+ }
617
+ }
618
+
619
+ /** A payment was just kept: the next pass comes after the first wait at the latest. */
620
+ private _retrySoon(o: DirectPayStartOptions): void {
621
+ const s = this._retry
622
+ if (!s || !isSameWallet(s.options, o)) return
623
+ s.delay = RETRY_FIRST_MS
624
+ if (s.running || !this._foreground) return // the pass, or the return to the foreground, schedules the next
625
+ if (s.due !== undefined && s.due <= Date.now() + RETRY_FIRST_MS) return
626
+ this._retryIn(s, RETRY_FIRST_MS)
627
+ }
628
+
629
+ /** Runs the next pass `ms` from now, replacing any pass already waiting. */
630
+ private _retryIn(s: RetrySchedule, ms: number): void {
631
+ clearTimeout(s.timer)
632
+ s.due = Date.now() + ms
633
+ s.timer = setTimeout(() => this._retryNow(s, false), ms)
634
+ }
635
+
636
+ /** Runs a pass now: never two at once (then once the running one ends), and not in the background. */
637
+ private _retryNow(s: RetrySchedule, withAttention: boolean): void {
638
+ if (this._retry !== s) return
639
+ clearTimeout(s.timer)
640
+ s.timer = undefined
641
+ s.due = undefined
642
+ s.withAttention ||= withAttention
643
+ if (s.running) {
644
+ s.again = true
645
+ return
646
+ }
647
+ // In the background: the return to the foreground runs the pass.
648
+ if (!this._foreground) return
649
+ const withAttentionNow = s.withAttention
650
+ s.withAttention = false
651
+ s.running = true
652
+ void this._runRetry(s, withAttentionNow).then(() => {
653
+ s.running = false
654
+ if (this._retry !== s) return
655
+ if (s.again) {
656
+ s.again = false
657
+ this._retryNow(s, false)
658
+ return
659
+ }
660
+ if (!this._foreground) return
661
+ this._retryIn(s, s.delay)
662
+ s.delay = Math.min(s.delay * 2, RETRY_MAX_MS)
663
+ })
664
+ }
665
+
666
+ /** One pass over the wallet's kept payments (see the header). Never rejects. */
667
+ private async _runRetry(s: RetrySchedule, includeNeedsAttention: boolean): Promise<void> {
668
+ const o = s.options
669
+ const deadline = Date.now() + RETRY_PASS_MS
670
+ const run = async <T>(call: () => Promise<T>): Promise<T> => {
671
+ if (this._retry !== s) throw new RetryStopped('The wallet closed')
672
+ if (Date.now() >= deadline) throw new RetryStopped('The pass took its time')
673
+ return await withDeadline(call(), RETRY_CALL_MS)
674
+ }
675
+ try {
676
+ await retryKeptDirectPayments({
677
+ webrtpay: this._deps.webrtpay,
678
+ wallet: o.wallet,
679
+ originator: o.originator,
680
+ store: this._store(o),
681
+ classify: await this._classifier(),
682
+ includeNeedsAttention,
683
+ onNeedsAttention: kept => this._reportNeedsAttention(kept),
684
+ run
685
+ })
686
+ } catch (e) {
687
+ console.warn('[DirectPayManager] Retrying kept direct payments failed:', messageOf(e))
688
+ }
689
+ }
690
+
691
+ /** The payer will not send a kept payment again; it stays kept, and the user is told. */
692
+ private _reportNeedsAttention(p: KeptDirectPaymentInfo): void {
693
+ this._deps.onToast?.(
694
+ i18n.t('direct_pay_kept_needs_attention', {
695
+ amount: p.amount.toLocaleString(),
696
+ name: `${p.sender.slice(0, 8)}…`
697
+ }),
698
+ { type: 'error' }
699
+ )
700
+ }
701
+
702
+ /** Detaches the current client and signaler; returns their closing (never rejects). */
703
+ private _teardown(): Promise<void> {
704
+ this._generation++
705
+ clearTimeout(this._stableTimer)
706
+ this._stableTimer = undefined
707
+ this._relayDown = false
708
+ const started = this._started
709
+ const client = this._snapshot.client
710
+ this._started = null
711
+ this._starting = Promise.resolve()
712
+ if (!started) return Promise.resolve()
713
+ started.unsubscribe()
714
+ // Close the relay too, so a listen still connecting cannot hold the client's close.
715
+ return Promise.allSettled([client?.close(), started.relay?.close()]).then(results => {
716
+ for (const r of results) {
717
+ if (r.status === 'rejected') console.warn('[DirectPayManager] Close failed:', messageOf(r.reason))
718
+ }
719
+ })
720
+ }
721
+
722
+ private _set(snapshot: DirectPaySnapshot) {
723
+ this._snapshot = snapshot
724
+ for (const fn of [...this._listeners]) {
725
+ try {
726
+ fn(snapshot)
727
+ } catch (e) {
728
+ console.warn('[DirectPayManager] A listener failed:', messageOf(e))
729
+ }
730
+ }
731
+ }
732
+
733
+ /** Changes the status and its message; emits only when they change. */
734
+ private _update(change: Pick<DirectPaySnapshot, 'status' | 'error'>) {
735
+ if (change.status !== this._snapshot.status || change.error !== this._snapshot.error) {
736
+ this._set({ ...this._snapshot, ...change })
737
+ }
738
+ }
739
+ }
740
+
741
+ /**
742
+ * The message box that carries this network's signals. An identity key is the same on every
743
+ * network, so one identity open on two networks would otherwise take the other network's dials.
744
+ * Mainnet keeps the package's default box, where other wallets (BSV Desktop) dial.
745
+ */
746
+ export const signalBox = (chain: string) => (chain === 'main' ? 'webrtpay_signals' : `webrtpay_signals_${chain}`)
747
+
748
+ /**
749
+ * The message box client as the signaler sees it: the same calls, with each listing (a poll)
750
+ * reported to `polled`, with its error when it failed. The live websocket calls and the host
751
+ * lookup are passed on, bound to the client, when it has them: without them the signaler only
752
+ * polls, which is too slow for a dial's presence window.
753
+ */
754
+ function watchingPolls(client: MessageBoxLike, polled: (error?: unknown) => void): MessageBoxLike {
755
+ // The status is only shown: reporting it must never fail a poll (its messages would be lost).
756
+ const report = (error?: unknown) => {
757
+ try {
758
+ polled(error)
759
+ } catch (e) {
760
+ console.warn('[DirectPayManager] Could not show the message box status:', messageOf(e))
761
+ }
762
+ }
763
+ return {
764
+ sendMessage: (a, host) => client.sendMessage(a, host),
765
+ listMessages: async a => {
766
+ let messages: Awaited<ReturnType<MessageBoxLike['listMessages']>>
767
+ try {
768
+ messages = await client.listMessages(a)
769
+ } catch (e) {
770
+ report(e ?? new Error('The message box could not be listed'))
771
+ throw e
772
+ }
773
+ report()
774
+ return messages
775
+ },
776
+ acknowledgeMessage: a => client.acknowledgeMessage(a),
777
+ ...(typeof client.sendLiveMessage === 'function' && {
778
+ sendLiveMessage: (a: Parameters<NonNullable<MessageBoxLike['sendLiveMessage']>>[0], host?: string) =>
779
+ client.sendLiveMessage!(a, host)
780
+ }),
781
+ ...(typeof client.listenForLiveMessages === 'function' && {
782
+ listenForLiveMessages: (a: Parameters<NonNullable<MessageBoxLike['listenForLiveMessages']>>[0]) =>
783
+ client.listenForLiveMessages!(a)
784
+ }),
785
+ ...(typeof client.joinRoom === 'function' && {
786
+ joinRoom: (box: string, host?: string) => client.joinRoom!(box, host)
787
+ }),
788
+ ...(typeof client.leaveRoom === 'function' && { leaveRoom: (box: string) => client.leaveRoom!(box) }),
789
+ ...(typeof client.resolveHostForRecipient === 'function' && {
790
+ resolveHostForRecipient: (recipient: string) => client.resolveHostForRecipient!(recipient)
791
+ })
792
+ }
793
+ }
794
+
795
+ /** `p`, or a {@link RetryStopped} after `ms` (the call goes on, unobserved). */
796
+ function withDeadline<T>(p: Promise<T>, ms: number): Promise<T> {
797
+ let timer: ReturnType<typeof setTimeout> | undefined
798
+ const late = new Promise<never>((_, reject) => {
799
+ timer = setTimeout(() => reject(new RetryStopped('The wallet took too long')), ms)
800
+ })
801
+ return Promise.race([p, late]).finally(() => clearTimeout(timer))
802
+ }
803
+
804
+ function isSameWallet(a: DirectPayStartOptions, b: DirectPayStartOptions): boolean {
805
+ return a.wallet === b.wallet && a.identity === b.identity && a.chain === b.chain
806
+ }
807
+
808
+ /** Receiving was set up and failed (the relay is offline); a setup problem leaves `via` null instead. */
809
+ function receiveFailed(s: DirectPaySnapshot): boolean {
810
+ return s.status === 'error' && s.via !== null
811
+ }
812
+
813
+ function sameInputs(a: DirectPayStartOptions, b: DirectPayStartOptions): boolean {
814
+ return (
815
+ isSameWallet(a, b) &&
816
+ a.originator === b.originator &&
817
+ a.peerPayClient === b.peerPayClient &&
818
+ (a.messageBoxUrl || '') === (b.messageBoxUrl || '') &&
819
+ a.RTCPeerConnection === b.RTCPeerConnection &&
820
+ JSON.stringify(a.settings) === JSON.stringify(b.settings)
821
+ )
822
+ }
823
+
824
+ /** Why the relay connection is down, for the log. */
825
+ function relayProblem(e: WebRTPayErrorLike, url: string): string {
826
+ switch (e.code) {
827
+ case 'auth_failed': {
828
+ // The signaler gives a cause only when this wallet could not sign the relay's challenge.
829
+ const { cause } = e as WebRTPayErrorLike & { cause?: unknown }
830
+ if (cause !== undefined) {
831
+ return `this wallet could not sign in to the relay server (${messageOf(cause).replace(/\.$/, '')}). Trying again…`
832
+ }
833
+ return `the relay server did not accept this wallet at ${url}; the address must be exactly one the relay serves. Trying again…`
834
+ }
835
+ case 'rate_limited':
836
+ return 'the relay server is limiting connections from this network. Trying again…'
837
+ case 'peer_unreachable':
838
+ return 'the relay server cannot be reached. Trying again…'
839
+ default:
840
+ return `${e.message}. Trying again…`
841
+ }
842
+ }
843
+
844
+ const messageOf = (e: unknown) => (e instanceof Error ? e.message : String(e))