@bsv/expo-wallet-toolbox 0.19.0 → 0.21.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.
Files changed (141) hide show
  1. package/CHANGELOG.md +154 -30
  2. package/README.md +79 -79
  3. package/core/backup/RemoteSyncReader.ts +26 -24
  4. package/core/backup/appData.ts +9 -8
  5. package/core/backup/codec.ts +21 -18
  6. package/core/backup/constants.ts +5 -5
  7. package/core/backup/contactsBackup.ts +8 -8
  8. package/core/backup/cursor.ts +12 -7
  9. package/core/backup/derive.ts +3 -3
  10. package/core/backup/deviceId.ts +2 -2
  11. package/core/backup/erase.ts +2 -2
  12. package/core/backup/preference.ts +2 -2
  13. package/core/backup/push.ts +10 -12
  14. package/core/backup/restore.ts +22 -14
  15. package/core/backup/restoreOnImport.ts +3 -2
  16. package/core/config.tsx +17 -13
  17. package/core/constants.ts +34 -11
  18. package/core/contacts/contactsStore.ts +4 -3
  19. package/core/context/WalletConnectionContext.tsx +294 -212
  20. package/core/context/WalletContext.tsx +132 -97
  21. package/core/context/defaultWalletSettings.ts +4 -2
  22. package/core/demo/demoLedger.ts +1 -5
  23. package/core/directpay/DirectPayManager.ts +148 -29
  24. package/core/directpay/DirectPayProvider.tsx +26 -26
  25. package/core/directpay/payFlow.ts +10 -1
  26. package/core/directpay/receive.ts +2 -1
  27. package/core/directpay/settings.ts +56 -9
  28. package/core/directpay/types.ts +11 -2
  29. package/core/directpay/webrtpay.ts +4 -0
  30. package/core/headers/checkpoints.ts +10 -1
  31. package/core/headers/headerStore.ts +13 -2
  32. package/core/hooks/useConfirmationSound.ts +3 -3
  33. package/core/hooks/useHaptics.ts +23 -6
  34. package/core/i18n/translations.tsx +382 -209
  35. package/core/index.ts +2 -0
  36. package/core/localpay/codec.ts +12 -6
  37. package/core/localpay/deviceCaps.ts +4 -14
  38. package/core/localpay/pending.ts +2 -1
  39. package/core/localpay/qr.ts +1 -1
  40. package/core/localpay/settlementAck.ts +1 -4
  41. package/core/localpay/transport/ble.ts +2 -2
  42. package/core/localpay/transport/socket.ts +1 -1
  43. package/core/mandala/abortGuard.ts +1 -1
  44. package/core/mandala/drain.ts +3 -0
  45. package/core/mandala/permissionModule.ts +3 -2
  46. package/core/mandala/resendTransfer.ts +4 -1
  47. package/core/mandala/runtime.ts +4 -4
  48. package/core/monitor/TaskBackupPush.ts +10 -13
  49. package/core/net/chainMatch.ts +8 -5
  50. package/core/networks.ts +145 -0
  51. package/core/parsePeerPayURI.ts +4 -1
  52. package/core/pay/beefRepair.ts +6 -3
  53. package/core/pay/creditErrors.ts +37 -1
  54. package/core/pay/rails/address.ts +10 -6
  55. package/core/pay/rails/direct.ts +6 -2
  56. package/core/pay/rails/handle.ts +84 -11
  57. package/core/pay/rails/index.ts +18 -2
  58. package/core/pay/receiveHistory.ts +8 -8
  59. package/core/peerpay/handleResendRequests.ts +11 -18
  60. package/core/peerpay/inboxAttempts.ts +1 -4
  61. package/core/peerpay/rebuildToken.ts +12 -9
  62. package/core/profiles/profileStore.ts +2 -1
  63. package/core/profiles/removalProblems.ts +3 -1
  64. package/core/services/arcTokenStorage.ts +2 -1
  65. package/core/services/arcadeBroadcastProvider.ts +7 -17
  66. package/core/services/secrets/envelope.ts +1 -6
  67. package/core/services/secrets/hkdf.ts +1 -6
  68. package/core/services/secrets/index.ts +3 -22
  69. package/core/services/usdFxRates.ts +1 -4
  70. package/core/services/vault/VaultKeyService.ts +2 -1
  71. package/core/services/vault/chainRecovery.ts +48 -21
  72. package/core/services/vault/metaAuthority.ts +4 -1
  73. package/core/services/vault/r1comb.ts +113 -51
  74. package/core/services/vault/session.ts +5 -1
  75. package/core/services/vault/transfers.ts +699 -576
  76. package/core/services/vault/vaultStore.ts +12 -10
  77. package/core/services/walletArgLimits.ts +1 -2
  78. package/core/services/walletConnectionValidation.ts +44 -28
  79. package/core/services/walletServiceConfig.ts +9 -40
  80. package/core/storage/StorageExpoSQLite.ts +7 -21
  81. package/core/storage/methods/listActionsSql.ts +81 -67
  82. package/core/storage/methods/listOutputsSql.ts +21 -16
  83. package/core/storage/methods/reviewStatusSql.ts +1 -4
  84. package/core/stores/ConnectionStore.ts +1 -1
  85. package/core/theme/ThemeContext.tsx +12 -16
  86. package/core/theme/motion.ts +3 -3
  87. package/core/theme/tokens.ts +6 -6
  88. package/core/toolboxConfig.ts +23 -0
  89. package/core/walletDbRegistry.ts +7 -5
  90. package/core/walletRepair/runWalletCheck.ts +1 -4
  91. package/package.json +2 -2
  92. package/ui/components/pay/AddressReceive.tsx +3 -3
  93. package/ui/components/pay/HandleReceive.tsx +21 -15
  94. package/ui/components/pay/MessageBoxConfig.tsx +46 -20
  95. package/ui/components/pay/NearbyFlow.tsx +575 -507
  96. package/ui/components/pay/OfflineNotice.tsx +1 -3
  97. package/ui/components/pay/PayCellRow.tsx +1 -4
  98. package/ui/components/pay/PayForm.tsx +1 -3
  99. package/ui/components/pay/RequestHub.tsx +14 -6
  100. package/ui/components/pay/UniversalSend.tsx +79 -27
  101. package/ui/components/pay/tokenSendCopy.ts +1 -2
  102. package/ui/components/pay/useRecipientInput.ts +2 -2
  103. package/ui/components/security/WalletLockNotice.tsx +1 -3
  104. package/ui/components/ui/AlertCard.tsx +44 -45
  105. package/ui/components/ui/BlurChrome.tsx +4 -15
  106. package/ui/components/ui/Celebration.tsx +3 -3
  107. package/ui/components/ui/ChoiceSheet.ts +1 -3
  108. package/ui/components/ui/ErrorBoundary.tsx +2 -6
  109. package/ui/components/ui/GroupedList.tsx +13 -31
  110. package/ui/components/ui/IconButton.tsx +6 -9
  111. package/ui/components/ui/ListRow.tsx +19 -25
  112. package/ui/components/ui/PresenceRow.tsx +4 -4
  113. package/ui/components/ui/PressableScale.tsx +24 -20
  114. package/ui/components/ui/Toast.tsx +23 -16
  115. package/ui/components/vault/KeyChooser.tsx +9 -6
  116. package/ui/components/vault/VaultBackdrop.tsx +1 -8
  117. package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
  118. package/ui/components/wallet/ActivityRow.tsx +3 -2
  119. package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
  120. package/ui/components/wallet/Balance.tsx +4 -1
  121. package/ui/components/wallet/ContactActivityList.tsx +7 -7
  122. package/ui/components/wallet/IconPickerSheet.tsx +1 -5
  123. package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
  124. package/ui/components/wallet/tokenEviction.ts +4 -1
  125. package/ui/hooks/useMandala.ts +1 -7
  126. package/ui/hooks/useOfflineNoticeActions.ts +21 -27
  127. package/ui/hooks/useSpendableBalance.ts +2 -2
  128. package/ui/hooks/useVaultCoverage.ts +7 -1
  129. package/ui/index.ts +9 -1
  130. package/ui/resolveIdentity.ts +20 -8
  131. package/ui/screens/ConnectionsScreen.tsx +44 -18
  132. package/ui/screens/LogsScreen.tsx +24 -22
  133. package/ui/screens/PairScreen.tsx +85 -54
  134. package/ui/screens/PayScreen.tsx +5 -1
  135. package/ui/screens/ProfileScreen.tsx +0 -3
  136. package/ui/screens/TrustScreen.tsx +125 -80
  137. package/ui/screens/VaultScreen.tsx +19 -7
  138. package/ui/screens/VaultTransferScreen.tsx +5 -1
  139. package/ui/screens/WalletCheckScreen.tsx +14 -17
  140. package/ui/screens/WalletConfigScreen.tsx +414 -376
  141. package/ui/screens/WalletHomeScreen.tsx +47 -42
@@ -5,8 +5,14 @@
5
5
  * `DirectPayProvider` starts it once a wallet is built and stops it when the wallet goes. While
6
6
  * a wallet is open there is always a client, so this wallet can dial others. Dialing and
7
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,
8
+ * default) or the message box. Receiving is on when the user left it on, the app is in the
9
+ * foreground and the Receive screen is showing ({@link DirectPayManager.openReceiveScreen}; the
10
+ * user's decision, 2026-10-21): the rest of the time this wallet answers no dial, so nobody can
11
+ * learn its address or that it is open, and payers use the message box. Opening and closing the
12
+ * screen starts and stops receiving on the same client, so a payment being sent is not cut off.
13
+ * Payments are taken into the wallet at once (`receive.ts`). Live sessions carry payments only
14
+ * (no payment request handler is given), and an authenticated peer may send at most
15
+ * MAX_LIVE_MESSAGE_BYTES (a 1 MB transaction). Through a relay,
10
16
  * receiving follows the relay connection, which reconnects by itself, and every connection may
11
17
  * use the short-lived TURN servers the relay hands out.
12
18
  *
@@ -45,7 +51,7 @@
45
51
  import i18n from '../i18n/translations'
46
52
  import type { KVStorage } from '../localpay/pending'
47
53
  import { classifyCreditError, type CreditFailureKind } from '../pay/creditErrors'
48
- import { iceServersFrom } from './settings'
54
+ import { iceServersFrom, MAX_LIVE_MESSAGE_BYTES, onlyOwnStun } from './settings'
49
55
  import {
50
56
  receiveDirectPayment,
51
57
  retryKeptDirectPayments,
@@ -202,6 +208,14 @@ export class DirectPayManager {
202
208
  private _foreground: boolean
203
209
  /** The last relay connection failed and has not come online since (see {@link signalingDown}). */
204
210
  private _relayDown = false
211
+ /** Receive screens showing now (see {@link openReceiveScreen}). */
212
+ private _receiveScreens = 0
213
+ /** The current client answers dials: set by {@link _beginReceiving}, cleared by {@link _endReceiving} and teardown. */
214
+ private _receiving = false
215
+ /** Bumped whenever receiving starts or ends; a start that is no longer current changes nothing. */
216
+ private _receiveRun = 0
217
+ /** Undone when receiving ends: the relay start timer, the relay retry. */
218
+ private _receiveCleanups: Array<() => void> = []
205
219
 
206
220
  private readonly _deps: DirectPayManagerDeps
207
221
 
@@ -288,6 +302,24 @@ export class DirectPayManager {
288
302
  }
289
303
  }
290
304
 
305
+ /**
306
+ * The Receive screen is showing: while at least one is, receiving is on (when the settings
307
+ * turn it on and the app is in the foreground). Returns the function to call when it stops
308
+ * showing; calling it again does nothing. Works with no wallet open: receiving then starts
309
+ * with the wallet.
310
+ */
311
+ openReceiveScreen = (): (() => void) => {
312
+ this._receiveScreens++
313
+ if (this._receiveScreens === 1) this._receiveScreenChanged()
314
+ let open = true
315
+ return () => {
316
+ if (!open) return
317
+ open = false
318
+ this._receiveScreens--
319
+ if (this._receiveScreens === 0) this._receiveScreenChanged()
320
+ }
321
+ }
322
+
291
323
  /** Closes the client and signaler. The snapshot clears at once; never rejects. */
292
324
  async stop(): Promise<void> {
293
325
  this._stopRetries()
@@ -337,7 +369,7 @@ export class DirectPayManager {
337
369
  let failures = 0
338
370
  const polled = (pollError?: unknown) => {
339
371
  failures = pollError === undefined ? 0 : failures + 1
340
- this._messageBoxPolled(generation, this._receives(o), failures, pollError)
372
+ this._messageBoxPolled(generation, failures, pollError)
341
373
  }
342
374
  signaler = new webrtpay.MessageBoxSignaler(watchingPolls(o.peerPayClient, polled), {
343
375
  host: o.messageBoxUrl || undefined,
@@ -354,6 +386,10 @@ export class DirectPayManager {
354
386
  iceServers: iceServersFrom(o.settings),
355
387
  ...(o.RTCPeerConnection !== undefined && { RTCPeerConnection: o.RTCPeerConnection })
356
388
  },
389
+ // Live sessions carry a payment and its ack: an authenticated peer may send this wallet
390
+ // no more than a payment with a 1 MB transaction (larger ones go by message box).
391
+ maxMessageBytes: MAX_LIVE_MESSAGE_BYTES,
392
+ limits: { maxMessageBytes: MAX_LIVE_MESSAGE_BYTES },
357
393
  // Once the recipient has answered, give the link 10 s (the package default is 6 s): a
358
394
  // slow STUN or TURN answer on a phone network otherwise ends a payment the recipient is
359
395
  // online for.
@@ -362,7 +398,7 @@ export class DirectPayManager {
362
398
  // client's life: it reuses live credentials.
363
399
  ...(relay &&
364
400
  !fallback && {
365
- iceServersProvider: relay.turnProvider(),
401
+ iceServersProvider: ownStunOnly(relay.turnProvider()),
366
402
  onIceServersProviderError: (e: unknown) =>
367
403
  console.warn("[DirectPayManager] Connecting without the relay's TURN servers:", messageOf(e))
368
404
  })
@@ -388,37 +424,115 @@ export class DirectPayManager {
388
424
  background: !this._foreground
389
425
  })
390
426
  if (!receive || !client) return
427
+ await this._beginReceiving(generation, o, client, relay, fallback, closing)
428
+ }
429
+
430
+ /** Receiving is on: the user's switch, the app in the foreground, and a Receive screen showing. */
431
+ private _receives(o: DirectPayStartOptions): boolean {
432
+ return o.settings.receiveEnabled && this._foreground && this._receiveScreens > 0
433
+ }
434
+
435
+ /**
436
+ * A Receive screen opened or the last one closed: starts or stops receiving on the current
437
+ * client, without replacing it (a payment being sent keeps its connection).
438
+ */
439
+ private _receiveScreenChanged(): void {
440
+ const started = this._started
441
+ const client = this._snapshot.client
442
+ if (!started || !client) return
443
+ const want = this._receives(started.options)
444
+ if (want === this._receiving) return
445
+ if (!want) {
446
+ this._endReceiving()
447
+ return
448
+ }
449
+ // A setup problem (no relay address, no message box) leaves nothing to receive through.
450
+ if (this._snapshot.via === null || this._snapshot.notice) return
451
+ const fallback = this._snapshot.relayUnreachable
452
+ this._update({ status: 'starting', error: '' })
453
+ // On the message box after a fallback, `started.relay` is only the relay being retried.
454
+ void this._beginReceiving(
455
+ this._generation,
456
+ started.options,
457
+ client,
458
+ fallback ? null : started.relay,
459
+ fallback,
460
+ Promise.resolve()
461
+ )
462
+ }
463
+
464
+ /**
465
+ * Starts receiving on `client`: with the relay, the fallback to the message box when it is not
466
+ * online in time; on that fallback, the relay retry; then the client listens.
467
+ */
468
+ private async _beginReceiving(
469
+ generation: number,
470
+ o: DirectPayStartOptions,
471
+ client: DirectPayClientLike,
472
+ relay: RelaySignalerLike | null,
473
+ fallback: boolean,
474
+ closing: Promise<void>
475
+ ): Promise<void> {
476
+ this._receiving = true
477
+ const run = ++this._receiveRun
391
478
  if (relay && !fallback && o.peerPayClient) {
392
479
  // Not online through the relay in time: receive through the message box meanwhile.
393
480
  const timer = setTimeout(() => {
394
- if (generation === this._generation && this._snapshot.status !== 'online') {
481
+ if (generation === this._generation && run === this._receiveRun && this._snapshot.status !== 'online') {
395
482
  this._fallBack(generation, o, 'it did not accept this wallet in time')
396
483
  }
397
484
  }, RELAY_START_MS)
398
- this._onTeardown(() => clearTimeout(timer))
485
+ this._receiveCleanups.push(() => clearTimeout(timer))
399
486
  }
400
487
  if (fallback) this._retryRelayLater(generation, o)
401
488
 
402
489
  // The previous client stops listening first, so two never answer the same offer.
403
490
  await closing
404
- if (generation !== this._generation) return
491
+ if (generation !== this._generation || run !== this._receiveRun) return
405
492
  try {
493
+ // onPayment only: payment requests sent over a live session are dropped unanswered.
406
494
  await client.startReceiving({
407
495
  onPayment: (p, ctx) => this._onPayment(o, p, ctx.note),
408
496
  onError: e => console.warn('[DirectPayManager] Inbound direct payment session failed:', messageOf(e))
409
497
  })
410
498
  // The status follows the relay's connection (_relayChanged) or the message box's polls
411
- // (_messageBoxPolled), so it says online only once receiving works.
499
+ // (_messageBoxPolled), so it says online only once receiving works. A stop asked for
500
+ // meanwhile has already called stopReceiving, which runs after this start.
412
501
  } catch (e) {
413
- if (generation === this._generation) {
502
+ if (generation === this._generation && run === this._receiveRun) {
414
503
  this._update({ status: 'error', error: `Direct payments cannot be received: ${messageOf(e)}` })
415
504
  }
416
505
  }
417
506
  }
418
507
 
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
508
+ /**
509
+ * The last Receive screen closed: the client stops answering dials (sessions already open run
510
+ * to their end), the relay retry stops, and the status is `off`. The client stays, for sending.
511
+ */
512
+ private _endReceiving(): void {
513
+ if (!this._receiving) return
514
+ this._receiving = false
515
+ this._receiveRun++
516
+ this._runReceiveCleanups()
517
+ clearTimeout(this._stableTimer)
518
+ this._stableTimer = undefined
519
+ const client = this._snapshot.client
520
+ if (client) {
521
+ void client.stopReceiving().catch(e => console.warn('[DirectPayManager] Could not stop receiving:', messageOf(e)))
522
+ }
523
+ this._update({ status: 'off', error: '' })
524
+ }
525
+
526
+ private _runReceiveCleanups(): void {
527
+ const cleanups = this._receiveCleanups
528
+ this._receiveCleanups = []
529
+ for (const fn of cleanups) {
530
+ try {
531
+ fn()
532
+ } catch (e) {
533
+ console.warn('[DirectPayManager] Cleanup failed:', messageOf(e))
534
+ }
535
+ }
422
536
  }
423
537
 
424
538
  /** Receiving through the relay failed: receive through the message box, retrying the relay. */
@@ -438,10 +552,11 @@ export class DirectPayManager {
438
552
  */
439
553
  private _retryRelayLater(generation: number, o: DirectPayStartOptions): void {
440
554
  const wait = Math.min(RELAY_RETRY_FIRST_MS * 2 ** Math.max(0, this._fallbacks - 1), RELAY_RETRY_MAX_MS)
555
+ let retry: RelaySignalerLike | null = null
441
556
  const timer = setTimeout(() => {
442
557
  const started = this._started
443
558
  if (generation !== this._generation || !started) return
444
- const retry = new this._deps.webrtpay.RelaySignaler({
559
+ retry = new this._deps.webrtpay.RelaySignaler({
445
560
  url: o.settings.relayUrl,
446
561
  wallet: o.wallet,
447
562
  originator: o.originator,
@@ -456,18 +571,14 @@ export class DirectPayManager {
456
571
  /* closed */
457
572
  })
458
573
  }, 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
- }
574
+ // Receiving ended: the retry's relay connection (which makes this wallet look online) closes.
575
+ this._receiveCleanups.push(() => {
576
+ clearTimeout(timer)
577
+ const started = this._started
578
+ if (!retry) return
579
+ if (started?.relay === retry) started.relay = null
580
+ void retry.close().catch(() => {})
581
+ })
471
582
  }
472
583
 
473
584
  /** The relay being retried accepted this wallet: receiving moves back to it. */
@@ -497,7 +608,7 @@ export class DirectPayManager {
497
608
  if (generation !== this._generation) return
498
609
  if (state === 'online') this._relayDown = false
499
610
  else if (state === 'offline' && e) this._relayDown = true
500
- if (!this._receives(o)) return
611
+ if (!this._receiving) return
501
612
  // Online long enough: the next fallback retries the relay after the shortest wait again.
502
613
  if (state === 'online' && this._stableTimer === undefined) {
503
614
  this._stableTimer = setTimeout(() => {
@@ -522,8 +633,8 @@ export class DirectPayManager {
522
633
  * worked, and `error` after {@link POLL_FAILURES_SHOWN} failures in a row (the signaler keeps
523
634
  * polling, and the status recovers by itself).
524
635
  */
525
- private _messageBoxPolled(generation: number, receiving: boolean, failures: number, error: unknown): void {
526
- if (generation !== this._generation || !receiving) return
636
+ private _messageBoxPolled(generation: number, failures: number, error: unknown): void {
637
+ if (generation !== this._generation || !this._receiving) return
527
638
  if (failures === 0) this._update({ status: 'online', error: '' })
528
639
  else if (failures >= POLL_FAILURES_SHOWN) {
529
640
  this._update({
@@ -702,6 +813,9 @@ export class DirectPayManager {
702
813
  /** Detaches the current client and signaler; returns their closing (never rejects). */
703
814
  private _teardown(): Promise<void> {
704
815
  this._generation++
816
+ this._receiving = false
817
+ this._receiveRun++
818
+ this._runReceiveCleanups()
705
819
  clearTimeout(this._stableTimer)
706
820
  this._stableTimer = undefined
707
821
  this._relayDown = false
@@ -745,6 +859,11 @@ export class DirectPayManager {
745
859
  */
746
860
  export const signalBox = (chain: string) => (chain === 'main' ? 'webrtpay_signals' : `webrtpay_signals_${chain}`)
747
861
 
862
+ /** The relay's TURN servers without the STUN servers its answer names (see onlyOwnStun). */
863
+ function ownStunOnly<T extends { urls: string | string[] }>(provider: () => Promise<T[]>): () => Promise<T[]> {
864
+ return async () => onlyOwnStun(await provider())
865
+ }
866
+
748
867
  /**
749
868
  * The message box client as the signaler sees it: the same calls, with each listing (a poll)
750
869
  * reported to `polled`, with its error when it failed. The live websocket calls and the host
@@ -26,20 +26,13 @@ import React, {
26
26
  useSyncExternalStore
27
27
  } from 'react'
28
28
  import { AppState } from 'react-native'
29
- import AsyncStorage from '@react-native-async-storage/async-storage'
30
29
  import { useWallet, useWalletManagers, useWalletStatus } from '../context/WalletContext'
31
30
  import { getDirectPayConfig } from '../toolboxConfig'
32
31
  import { getOnline, subscribeOnline } from '../net/online'
33
32
  import { makeCreditClassifier } from '../pay/creditErrors'
34
- import {
35
- DEFAULT_MESSAGE_BOX_URL,
36
- LEGACY_MESSAGE_BOX_URL,
37
- MESSAGE_BOX_URL_KEY,
38
- NO_MESSAGE_BOX,
39
- makePeerPayClient
40
- } from '../pay/rails/handle'
33
+ import type { AppChain } from '../networks'
34
+ import { makePeerPayClient, readMessageBoxUrl } from '../pay/rails/handle'
41
35
  import { sendViaDirect, type DirectSendResult } from '../pay/rails/direct'
42
- import { profileScopedKey } from '../profiles/profileStore'
43
36
  import { deviceKVStorage } from './deviceStore'
44
37
  import { DirectPayManager, type DirectPaySnapshot, type DirectPayToast } from './DirectPayManager'
45
38
  import { NotSentError } from './payFlow'
@@ -78,6 +71,11 @@ export interface DirectPayContextValue {
78
71
  * `NotSentError` when it stopped before the payment was made.
79
72
  */
80
73
  sendDirect: (args: DirectPaySendArgs) => Promise<DirectSendResult>
74
+ /**
75
+ * The Receive screen is showing: live payments are answered only while it is (see
76
+ * `DirectPayManager.openReceiveScreen`). Returns the function to call when it stops showing.
77
+ */
78
+ openReceiveScreen: () => () => void
81
79
  }
82
80
 
83
81
  const OFF_SNAPSHOT: DirectPaySnapshot = {
@@ -95,6 +93,8 @@ const unavailable = async (): Promise<never> => {
95
93
  throw new NotSentError('Direct payments are not available', 'not configured')
96
94
  }
97
95
 
96
+ const noReceiveScreen = () => () => {}
97
+
98
98
  const DirectPayContext = createContext<DirectPayContextValue>({
99
99
  available: false,
100
100
  snapshot: OFF_SNAPSHOT,
@@ -103,25 +103,23 @@ const DirectPayContext = createContext<DirectPayContextValue>({
103
103
  saveSettings: unavailable,
104
104
  reload: async () => {},
105
105
  canSendDirect: false,
106
- sendDirect: unavailable
106
+ sendDirect: unavailable,
107
+ openReceiveScreen: () => () => {}
107
108
  })
108
109
 
109
110
  export const useDirectPay = (): DirectPayContextValue => useContext(DirectPayContext)
110
111
 
111
- /** The message box this profile uses, or undefined when the user turned it off (as WalletContext reads it). */
112
- async function readMessageBoxHost(): Promise<string | undefined> {
113
- const saved = await AsyncStorage.getItem(profileScopedKey(MESSAGE_BOX_URL_KEY))
114
- if (saved === NO_MESSAGE_BOX) return undefined
115
- return !saved || saved === LEGACY_MESSAGE_BOX_URL ? DEFAULT_MESSAGE_BOX_URL : saved
116
- }
117
-
118
- /** The device settings (user's, else the host's, else built-in) and this profile's message box. */
112
+ /**
113
+ * The device settings (user's, else the host's, else built-in) and this
114
+ * profile's message box on `network` (undefined when the user turned it off).
115
+ */
119
116
  async function readInputs(
120
- hostDefaults: DirectPayHostDefaults
117
+ hostDefaults: DirectPayHostDefaults,
118
+ network: AppChain
121
119
  ): Promise<{ settings: DirectPaySettings; messageBoxUrl: string | undefined }> {
122
120
  const [settings, messageBoxUrl] = await Promise.all([
123
121
  loadDirectPaySettings(deviceKVStorage, hostDefaults),
124
- readMessageBoxHost().catch(() => undefined)
122
+ readMessageBoxUrl(network).catch(() => undefined)
125
123
  ])
126
124
  return { settings, messageBoxUrl }
127
125
  }
@@ -178,7 +176,7 @@ export const DirectPayProvider: React.FC<{ children: React.ReactNode; onToast?:
178
176
  useEffect(() => {
179
177
  if (!manager) return
180
178
  let current = true
181
- void readInputs(hostDefaults).then(inputs => {
179
+ void readInputs(hostDefaults, selectedNetwork).then(inputs => {
182
180
  if (!current) return
183
181
  setSettings(inputs.settings)
184
182
  setMessageBoxUrl(inputs.messageBoxUrl)
@@ -186,14 +184,14 @@ export const DirectPayProvider: React.FC<{ children: React.ReactNode; onToast?:
186
184
  return () => {
187
185
  current = false
188
186
  }
189
- }, [manager, hostDefaults])
187
+ }, [manager, hostDefaults, selectedNetwork])
190
188
 
191
189
  const reload = useCallback(async () => {
192
190
  if (!manager) return
193
- const inputs = await readInputs(hostDefaults)
191
+ const inputs = await readInputs(hostDefaults, selectedNetwork)
194
192
  setSettings(inputs.settings)
195
193
  setMessageBoxUrl(inputs.messageBoxUrl)
196
- }, [manager, hostDefaults])
194
+ }, [manager, hostDefaults, selectedNetwork])
197
195
 
198
196
  const wallet = managers.permissionsManager as unknown as WebRTPayWallet | undefined
199
197
  // The identity key of the wallet it was read from, so a rebuilt wallet never runs on the last one's.
@@ -219,10 +217,11 @@ export const DirectPayProvider: React.FC<{ children: React.ReactNode; onToast?:
219
217
  ? (makePeerPayClient({
220
218
  wallet: wallet as never,
221
219
  messageBoxUrl,
220
+ network: selectedNetwork,
222
221
  originator: adminOriginator
223
222
  }) as MessageBoxLike | null)
224
223
  : null,
225
- [wallet, messageBoxUrl, adminOriginator]
224
+ [wallet, messageBoxUrl, selectedNetwork, adminOriginator]
226
225
  )
227
226
 
228
227
  // Start with the wallet, follow its inputs, stop when it goes.
@@ -312,7 +311,8 @@ export const DirectPayProvider: React.FC<{ children: React.ReactNode; onToast?:
312
311
  saveSettings,
313
312
  reload,
314
313
  canSendDirect,
315
- sendDirect
314
+ sendDirect,
315
+ openReceiveScreen: manager ? manager.openReceiveScreen : noReceiveScreen
316
316
  }),
317
317
  [manager, snapshot, settings, saveSettings, reload, canSendDirect, sendDirect]
318
318
  )
@@ -87,6 +87,10 @@ export async function payIdentity(o: {
87
87
  case 'unknown':
88
88
  if (o.messageBox) return { kind: 'ask_fallback', reason: 'link_failed' }
89
89
  return failed('no', 'direct_pay_failed_link', { name: o.name })
90
+ case 'too_large':
91
+ // Released before anything was spent: the message box carries any size.
92
+ if (o.messageBox) return { kind: 'ask_fallback', reason: 'too_large' }
93
+ return stopped(error, o.name)
90
94
  case 'unavailable':
91
95
  return failed('no', 'direct_pay_failed_network')
92
96
  case 'wrong_network':
@@ -111,7 +115,12 @@ export async function payIdentity(o: {
111
115
  /** The fallback prompt for `reason`, naming the recipient. */
112
116
  export function fallbackPrompt(reason: FallbackReason, name: string): Required<DirectPayMessage> {
113
117
  return {
114
- key: reason === 'offline' ? 'direct_pay_fallback_offline' : 'direct_pay_fallback_link_failed',
118
+ key:
119
+ reason === 'offline'
120
+ ? 'direct_pay_fallback_offline'
121
+ : reason === 'too_large'
122
+ ? 'direct_pay_fallback_too_large'
123
+ : 'direct_pay_fallback_link_failed',
115
124
  params: { name }
116
125
  }
117
126
  }
@@ -12,7 +12,8 @@
12
12
  * dropped before the ack, so it sent the same token there) is credited, and announced, once.
13
13
  *
14
14
  * Kept. A failure `classifyCreditError` calls environmental (offline, headers behind, a locked
15
- * database) keeps the payment on this device and answers `received`: by then the payer may
15
+ * database, or no broadcaster could take the payment when internalizeAction posted it) keeps
16
+ * the payment on this device and answers `received`: by then the payer may
16
17
  * broadcast it, so it is better kept than refused. Anything else is refused (`rejected`), which
17
18
  * is safe at that point because the payer still has the payment and sends it through the
18
19
  * message box instead. A kept payment was acknowledged, so its payer will not send it again,
@@ -6,9 +6,11 @@
6
6
  * not the wallet's key/value table, which is per wallet and cleared with it).
7
7
  *
8
8
  * Receiving is on by default, and wallets find each other through the public WebRTPay relay by
9
- * default, with the message box as the other choice. There is no migration: this key is the
10
- * first, and a stored value that is missing or no longer valid falls back to the default
11
- * field by field.
9
+ * default, with the message box as the other choice. A stored value that is missing or no
10
+ * longer valid falls back to the default field by field; a stored STUN list that is exactly
11
+ * the previous default ({@link PREVIOUS_DEFAULT_STUN_URLS}) is read as the current default.
12
+ * Receiving answers live payments only while the Receive screen is showing (see
13
+ * DirectPayManager.openReceiveScreen).
12
14
  *
13
15
  * Addresses are checked with regexes, not `URL`: `URL.hostname` is unreliable on Hermes. A relay
14
16
  * must be `wss://` (desktop also allows `ws://` for localhost; a phone has no local relay, so
@@ -33,11 +35,54 @@ export const DEFAULT_DIRECT_PAY_SETTINGS: Readonly<Omit<DirectPaySettings, 'stun
33
35
  receiveEnabled: true,
34
36
  signaling: 'relay',
35
37
  relayUrl: DEFAULT_RELAY_URL,
36
- stunUrls: Object.freeze([
37
- 'stun:stun-us-1.bsvb.tech:3478',
38
- 'stun:stun.l.google.com:19302',
39
- 'stun:stun.cloudflare.com:3478'
40
- ])
38
+ // BSVA's own STUN server only (2026-10-21): every STUN server learns this device's address
39
+ // and when it connects.
40
+ stunUrls: Object.freeze(['stun:stun-us-1.bsvb.tech:3478'])
41
+ }
42
+
43
+ /**
44
+ * The STUN list that was the default until 2026-10-21. A stored list that is exactly this
45
+ * (saved before, never edited) is read as the current default; any other list is the user's.
46
+ */
47
+ export const PREVIOUS_DEFAULT_STUN_URLS: readonly string[] = Object.freeze([
48
+ 'stun:stun-us-1.bsvb.tech:3478',
49
+ 'stun:stun.l.google.com:19302',
50
+ 'stun:stun.cloudflare.com:3478'
51
+ ])
52
+
53
+ /**
54
+ * Largest transaction (Atomic BEEF) sent or taken live: 1 MB (2026-10-21). A larger payment
55
+ * is refused before anything is spent and the message box is offered; a payee refuses larger
56
+ * live messages and closes the session.
57
+ */
58
+ export const MAX_LIVE_TRANSACTION_BYTES = 1_000_000
59
+ /**
60
+ * The largest message an authenticated live session may send this wallet: a `payment` with a
61
+ * {@link MAX_LIVE_TRANSACTION_BYTES} transaction in base64 (a third larger), plus 4096 bytes for
62
+ * the rest of the message, as @bsv/webrtpay counts it (MAX_DIRECT_TRANSACTION_BYTES).
63
+ */
64
+ export const MAX_LIVE_MESSAGE_BYTES = 4 * Math.ceil(MAX_LIVE_TRANSACTION_BYTES / 3) + 4096
65
+
66
+ /**
67
+ * `servers` (the relay's TURN answer) without its STUN entries: the relay passes on the TURN
68
+ * provider's STUN urls (Cloudflare's), and only the settings' STUN list is asked.
69
+ */
70
+ export function onlyOwnStun<T extends { urls: string | string[] }>(servers: T[]): T[] {
71
+ const out: T[] = []
72
+ for (const server of servers) {
73
+ const urls = (typeof server.urls === 'string' ? [server.urls] : [...server.urls]).filter(u => !/^stuns?:/i.test(u))
74
+ if (urls.length > 0) out.push({ ...server, urls })
75
+ }
76
+ return out
77
+ }
78
+
79
+ /** True for a stored STUN list that is exactly {@link PREVIOUS_DEFAULT_STUN_URLS}. */
80
+ function previousDefaultStun(value: unknown): boolean {
81
+ return (
82
+ Array.isArray(value) &&
83
+ value.length === PREVIOUS_DEFAULT_STUN_URLS.length &&
84
+ value.every((u, i) => u === PREVIOUS_DEFAULT_STUN_URLS[i])
85
+ )
41
86
  }
42
87
 
43
88
  // A host is a name or IPv4 address that starts and ends with a letter or digit, or a bracketed
@@ -208,7 +253,9 @@ export async function loadDirectPaySettings(
208
253
  receiveEnabled: field(checkReceiveEnabled, stored.receiveEnabled, defaults.receiveEnabled),
209
254
  signaling: field(checkSignaling, stored.signaling, defaults.signaling),
210
255
  relayUrl: field(checkRelayUrl, stored.relayUrl, defaults.relayUrl),
211
- stunUrls: field(checkStunUrls, stored.stunUrls, [...defaults.stunUrls])
256
+ stunUrls: field(checkStunUrls, previousDefaultStun(stored.stunUrls) ? [...defaults.stunUrls] : stored.stunUrls, [
257
+ ...defaults.stunUrls
258
+ ])
212
259
  },
213
260
  field(checkTurn, stored.turn, undefined)
214
261
  )
@@ -52,7 +52,16 @@ export interface DirectPaySettings {
52
52
  * - `aborted`: the dial was cancelled.
53
53
  * - `unknown`: anything else (a refusal with some other reason, a closed link, a bad handshake).
54
54
  */
55
- export type DialFailure = 'offline' | 'rejected' | 'unavailable' | 'timeout' | 'wrong_network' | 'aborted' | 'unknown'
55
+ export type DialFailure =
56
+ | 'offline'
57
+ | 'rejected'
58
+ | 'unavailable'
59
+ | 'timeout'
60
+ | 'wrong_network'
61
+ | 'aborted'
62
+ | 'unknown'
63
+ /** Not a dial failure: the recipient was reached, but the payment is over the 1 MB live limit (released). */
64
+ | 'too_large'
56
65
 
57
66
  /** Some wording for the user, as an i18n key and its parameters (core modules never return English). */
58
67
  export interface DirectPayMessage {
@@ -61,7 +70,7 @@ export interface DirectPayMessage {
61
70
  }
62
71
 
63
72
  /** Why a live attempt is offering the message box: the recipient is not there, or the link failed. */
64
- export type FallbackReason = 'offline' | 'link_failed'
73
+ export type FallbackReason = 'offline' | 'link_failed' | 'too_large'
65
74
 
66
75
  /** Paying stopped, and nothing more is offered. */
67
76
  export interface PayFailure extends DirectPayMessage {
@@ -147,6 +147,10 @@ export interface DirectPayClientOptions {
147
147
  onIceServersProviderError?: (e: unknown) => void
148
148
  chain?: string
149
149
  timeouts?: { connectMs?: number; ackMs?: number; presenceMs?: number; dialMs?: number }
150
+ /** Largest message a peer may send once authenticated, while this client dials. */
151
+ maxMessageBytes?: number
152
+ /** What a payee allows from peers that dial it (the package's `InboundLimits`, in part). */
153
+ limits?: { maxMessageBytes?: number }
150
154
  }
151
155
 
152
156
  export interface RelaySignalerOptions {
@@ -15,7 +15,12 @@
15
15
  * · test — height 1,697,402, about 52,560 blocks behind its 1,749,962 tip.
16
16
  * · ttn — height 0. The whole teratest chain was 27,502 blocks (~2.2 MB), so
17
17
  * windowing it buys nothing and starting from genesis costs nothing.
18
+ * · regtest (scaletest) — height 0, the canonical regtest genesis. The chain is
19
+ * short-lived and reset often, and the genesis is the one header every
20
+ * reset keeps.
18
21
  */
22
+ import type { WalletChain } from '../networks'
23
+
19
24
  export interface HeaderCheckpoint {
20
25
  /** Height of the last a-priori-trusted header. The window starts above it. */
21
26
  height: number
@@ -23,7 +28,7 @@ export interface HeaderCheckpoint {
23
28
  hash: string
24
29
  }
25
30
 
26
- export const HEADER_CHECKPOINTS: Record<'main' | 'test' | 'ttn', HeaderCheckpoint> = {
31
+ export const HEADER_CHECKPOINTS: Record<WalletChain, HeaderCheckpoint | undefined> = {
27
32
  main: {
28
33
  height: 907324,
29
34
  hash: '00000000000000000ccc802efeef429acb6b670a6b2bac373ece30f7d2df3e26'
@@ -35,5 +40,9 @@ export const HEADER_CHECKPOINTS: Record<'main' | 'test' | 'ttn', HeaderCheckpoin
35
40
  ttn: {
36
41
  height: 0,
37
42
  hash: '000000000499eabba0a88f5b3747231c74b9191c1a4a04b2c2ea817976b7776d'
43
+ },
44
+ regtest: {
45
+ height: 0,
46
+ hash: '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206'
38
47
  }
39
48
  }
@@ -24,7 +24,18 @@ import { utils as chaintracksUtils } from '@bsv/wallet-toolbox-mobile'
24
24
  import type { HeaderCheckpoint } from './checkpoints'
25
25
  import type { HeaderFs } from './fs'
26
26
 
27
- const { blockHash, deserializeBaseBlockHeader, validateHeaderProofOfWork } = chaintracksUtils
27
+ const { blockHash, deserializeBaseBlockHeader } = chaintracksUtils
28
+ /**
29
+ * The toolbox's proof-of-work check, given this store's chain. From
30
+ * @bsv/wallet-toolbox 2.15.0 (bsv-blockchain/ts-stack#819) the chain selects
31
+ * the proof-of-work limit — regtest's is far higher than mainnet's — and an
32
+ * omitted chain keeps mainnet's. Older releases take one argument and ignore
33
+ * the second, which changes nothing for the chains they support.
34
+ */
35
+ const validateHeaderProofOfWork = chaintracksUtils.validateHeaderProofOfWork as (
36
+ header: Parameters<typeof chaintracksUtils.validateHeaderProofOfWork>[0],
37
+ chain?: string
38
+ ) => true
28
39
 
29
40
  const HEADER_BYTES = 80
30
41
  const ROOT_BYTES = 32
@@ -218,7 +229,7 @@ export class HeaderStore {
218
229
  // header, and accepting it would let anyone mint merkle roots. Takes the
219
230
  // display-order hex hash blockHash returns, validates the compact target
220
231
  // encoding, and honours the toolbox's consensus proof-of-work exceptions.
221
- validateHeaderProofOfWork({ ...parsed, height: firstHeight + i, hash })
232
+ validateHeaderProofOfWork({ ...parsed, height: firstHeight + i, hash }, this.chain)
222
233
  newRoots.set(new Uint8Array(Utils.toArray(parsed.merkleRoot, 'hex')), i * ROOT_BYTES)
223
234
  prev = hash
224
235
  }