@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The icons offered as an avatar, grouped the way the picker shows them.
3
+ *
4
+ * Only families this app already ships (see `@expo/vector-icons`): Ionicons
5
+ * for people, nature and objects, MaterialCommunityIcons for the animals,
6
+ * which Ionicons has almost none of. Nothing here adds a dependency.
7
+ *
8
+ * Chosen for being something a person would actually WEAR — creatures and
9
+ * characters, not UI furniture. Every name below was checked against the
10
+ * shipped glyph maps; a name that is not in them renders as a blank square,
11
+ * which is why this list is explicit rather than generated from a prefix.
12
+ */
13
+ import type { AvatarIconFamily } from '@bsv/expo-wallet-toolbox'
14
+
15
+ export interface AvatarIconOption {
16
+ family: AvatarIconFamily
17
+ name: string
18
+ }
19
+
20
+ export interface AvatarIconGroup {
21
+ /** i18n key for the section heading, with an English fallback. */
22
+ labelKey: string
23
+ labelFallback: string
24
+ icons: AvatarIconOption[]
25
+ }
26
+
27
+ const mc = (name: string): AvatarIconOption => ({ family: 'material-community', name })
28
+ const io = (name: string): AvatarIconOption => ({ family: 'ionicons', name })
29
+
30
+ export const AVATAR_ICON_GROUPS: AvatarIconGroup[] = [
31
+ {
32
+ labelKey: 'avatar_group_animals',
33
+ labelFallback: 'Animals',
34
+ icons: [
35
+ mc('cat'),
36
+ mc('dog'),
37
+ mc('rabbit'),
38
+ mc('owl'),
39
+ mc('panda'),
40
+ mc('koala'),
41
+ mc('penguin'),
42
+ mc('bird'),
43
+ mc('duck'),
44
+ mc('horse'),
45
+ mc('elephant'),
46
+ mc('kangaroo'),
47
+ mc('cow'),
48
+ mc('pig'),
49
+ mc('sheep'),
50
+ mc('turtle'),
51
+ mc('tortoise'),
52
+ mc('snake'),
53
+ mc('dolphin'),
54
+ mc('shark'),
55
+ mc('fish'),
56
+ mc('jellyfish'),
57
+ mc('butterfly'),
58
+ mc('bee'),
59
+ mc('ladybug'),
60
+ mc('snail'),
61
+ mc('spider'),
62
+ mc('bat'),
63
+ mc('unicorn')
64
+ ]
65
+ },
66
+ {
67
+ labelKey: 'avatar_group_characters',
68
+ labelFallback: 'Characters',
69
+ icons: [
70
+ mc('emoticon-happy-outline'),
71
+ mc('emoticon-cool-outline'),
72
+ mc('robot'),
73
+ mc('alien'),
74
+ mc('ghost'),
75
+ mc('account'),
76
+ mc('human'),
77
+ mc('sunglasses'),
78
+ io('happy-outline'),
79
+ io('person-outline'),
80
+ io('people-outline'),
81
+ io('skull-outline')
82
+ ]
83
+ },
84
+ {
85
+ labelKey: 'avatar_group_nature',
86
+ labelFallback: 'Nature',
87
+ icons: [
88
+ io('leaf-outline'),
89
+ io('flower-outline'),
90
+ io('paw-outline'),
91
+ io('planet-outline'),
92
+ io('moon-outline'),
93
+ io('sunny-outline'),
94
+ io('snow-outline'),
95
+ io('flame-outline'),
96
+ io('star-outline'),
97
+ io('heart-outline'),
98
+ io('diamond-outline'),
99
+ io('flash-outline')
100
+ ]
101
+ },
102
+ {
103
+ labelKey: 'avatar_group_things',
104
+ labelFallback: 'Things',
105
+ icons: [
106
+ io('rocket-outline'),
107
+ io('game-controller-outline'),
108
+ io('musical-note-outline'),
109
+ io('headset-outline'),
110
+ io('camera-outline'),
111
+ io('bicycle-outline'),
112
+ io('football-outline'),
113
+ io('basketball-outline'),
114
+ io('pizza-outline'),
115
+ io('ice-cream-outline'),
116
+ io('cafe-outline'),
117
+ io('balloon-outline'),
118
+ io('gift-outline'),
119
+ io('glasses-outline')
120
+ ]
121
+ }
122
+ ]
@@ -19,6 +19,23 @@ function loadExpoSharing(): typeof import('expo-sharing') {
19
19
 
20
20
  const PAGE = 200
21
21
 
22
+ /**
23
+ * A remote PeerPay/nearby-payment sender's note reaches this file's
24
+ * `description` column verbatim (trimmed, length-capped — see
25
+ * core/pay/rails/handle.ts and core/localpay/pending.ts), and this export is
26
+ * shared as text/csv straight to whatever the OS share sheet opens it in.
27
+ * Any cell whose text begins with `=`, `+`, `-`, `@`, a tab or a carriage
28
+ * return is a live formula/command to spreadsheet software that still
29
+ * evaluates leading-character formulas on open (OWASP CSV Injection). Prefix
30
+ * such a value with a single leading apostrophe first — spreadsheet
31
+ * applications that honor that convention render it as literal text, and the
32
+ * original content is still fully visible rather than dropped — before the
33
+ * existing delimiter/quote escaping below runs.
34
+ */
35
+ function neutralizeFormula(s: string): string {
36
+ return /^[=+\-@\t\r]/.test(s) ? `'${s}` : s
37
+ }
38
+
22
39
  function csvEscape(v: unknown): string {
23
40
  if (v == null) return ''
24
41
  const s = String(v)
@@ -26,6 +43,21 @@ function csvEscape(v: unknown): string {
26
43
  return s
27
44
  }
28
45
 
46
+ /**
47
+ * Same as csvEscape, but for the columns that can carry attacker-controlled
48
+ * free text (description, tags, labels, outputDescriptions) — these alone
49
+ * are run through neutralizeFormula first. Columns that are always
50
+ * app-derived (txid, satoshis, status, blockHeight) use plain csvEscape:
51
+ * `satoshis` in particular is a signed number whose string form starts with
52
+ * '-' for every outgoing transaction, which would otherwise trip
53
+ * neutralizeFormula's leading-character check and corrupt a plain numeric
54
+ * cell (e.g. `-50000`) into text (`'-50000`) for no security benefit.
55
+ */
56
+ function csvEscapeUntrusted(v: unknown): string {
57
+ if (v == null) return ''
58
+ return csvEscape(neutralizeFormula(String(v)))
59
+ }
60
+
29
61
  /**
30
62
  * Exports all wallet transactions as a CSV file via the OS share dialog.
31
63
  * Columns: txid, satoshis (signed), description, status, blockHeight,
@@ -91,12 +123,12 @@ export async function exportTransactionsAsCsv(
91
123
  return [
92
124
  csvEscape(a.txid),
93
125
  csvEscape(sats),
94
- csvEscape(a.description),
126
+ csvEscapeUntrusted(a.description),
95
127
  csvEscape(a.status),
96
128
  csvEscape(height),
97
- csvEscape(tags),
98
- csvEscape(labels),
99
- csvEscape(outDescs)
129
+ csvEscapeUntrusted(tags),
130
+ csvEscapeUntrusted(labels),
131
+ csvEscapeUntrusted(outDescs)
100
132
  ].join(',')
101
133
  })
102
134
 
@@ -0,0 +1,10 @@
1
+ import { useMemo } from 'react'
2
+ import { useWallet } from '@bsv/expo-wallet-toolbox'
3
+ import { createContactsStore, type ContactsDb, type ContactsStore } from '../../core/contacts/contactsStore'
4
+
5
+ /** The contacts store for the open wallet, or null before its database is ready. */
6
+ export function useContactsStore(): ContactsStore | null {
7
+ const { storage } = useWallet()
8
+ const db = storage?.sqliteDb
9
+ return useMemo(() => (db ? createContactsStore(db as unknown as ContactsDb) : null), [db])
10
+ }
@@ -9,10 +9,23 @@
9
9
  * Lifted from WalletConfigScreen.handleExportData so both screens share one
10
10
  * implementation: one export at a time, `exporting` for the spinner, failures
11
11
  * logged rather than surfaced (a dismissed share sheet is not an error).
12
+ *
13
+ * XR-086: exportAllWalletDatabases() writes the raw, unencrypted SQLite image
14
+ * straight to the OS share sheet — identity keys, certificate fields,
15
+ * transaction/derivation metadata and contacts, with no passphrase or
16
+ * authenticated-encryption step. Wrapping it in one would need a product
17
+ * decision this hook cannot make alone (how the *importing* device gets the
18
+ * key/passphrase back — see importDatabases.ts, which has no decrypt step
19
+ * either); that is recorded as a design delta on XR-086, not silently
20
+ * skipped. What actually ships here is the part that needs no such decision:
21
+ * an explicit warning naming what the file contains and that it is not
22
+ * encrypted, with a real chance to back out, shared by both call sites since
23
+ * they both go through this one hook.
12
24
  */
13
25
  import { useCallback, useRef, useState } from 'react'
14
- import { useWallet } from '@bsv/expo-wallet-toolbox'
26
+ import { i18n, useWallet } from '@bsv/expo-wallet-toolbox'
15
27
  import { exportAllWalletDatabases } from '../exportDatabases'
28
+ import { showAlert } from '../components/ui/AlertCard'
16
29
 
17
30
  export function useExportWalletData(): { exportData: () => Promise<void>; exporting: boolean } {
18
31
  const { storage } = useWallet()
@@ -24,8 +37,18 @@ export function useExportWalletData(): { exportData: () => Promise<void>; export
24
37
  const exportData = useCallback(async () => {
25
38
  if (inFlightRef.current) return
26
39
  inFlightRef.current = true
27
- setExporting(true)
28
40
  try {
41
+ const choice = await showAlert({
42
+ title: i18n.t('export_unencrypted_title'),
43
+ message: i18n.t('export_unencrypted_message'),
44
+ buttons: [
45
+ { text: i18n.t('cancel'), style: 'cancel', key: 'cancel' },
46
+ { text: i18n.t('export_wallet_data'), style: 'destructive', key: 'export' }
47
+ ]
48
+ })
49
+ if (choice !== 'export') return
50
+ // The spinner means "exporting", not "waiting for you to answer".
51
+ setExporting(true)
29
52
  await exportAllWalletDatabases(storage)
30
53
  } catch (e) {
31
54
  console.warn('[exportWalletData] Export failed:', e)
@@ -55,6 +55,20 @@ function loadExpoRouter(): ExpoRouterModule {
55
55
  return expoRouterMod
56
56
  }
57
57
 
58
+ /**
59
+ * Demo mode's runtime, or a constant `null` in anything but a dev bundle.
60
+ *
61
+ * Resolved once at module scope behind `__DEV__` so the demo folder is
62
+ * required only into a dev bundle: a release build inlines `__DEV__` as false
63
+ * and folds the require — and everything it reaches — out entirely. Same
64
+ * pattern as `utils/AgentationGate.tsx`. Called unconditionally below, because
65
+ * it is a hook and its identity must not change between renders.
66
+ */
67
+ const useDemoRuntime: () => MandalaRuntime | null = __DEV__
68
+ ? // eslint-disable-next-line @typescript-eslint/no-require-imports
69
+ (require('../../core/demo') as typeof import('../../core/demo')).useDemoMandalaRuntime
70
+ : () => null
71
+
58
72
  /** Injected runtime. `undefined` means "ask the wallet context"; `null` means "none". */
59
73
  const MandalaRuntimeContext = createContext<MandalaRuntime | null | undefined>(undefined)
60
74
 
@@ -74,11 +88,14 @@ export function MandalaProvider({
74
88
  * that render money want `useMandala()`.
75
89
  */
76
90
  export function useMandalaRuntime(): MandalaRuntime | null {
91
+ // Before everything else: in demo mode the stablecoin half of the wallet is
92
+ // the demo ledger, whatever the real wallet has built.
93
+ const demo = useDemoRuntime()
77
94
  const injected = useContext(MandalaRuntimeContext)
78
95
  // `undefined` on the context until the wallet is built, and on every chain
79
96
  // but mainnet — which IS the chain gate, not an error state.
80
97
  const fromWallet = useWallet()?.mandala ?? null
81
- const runtime = injected !== undefined ? injected : fromWallet
98
+ const runtime = demo ?? (injected !== undefined ? injected : fromWallet)
82
99
  // `available` is the runtime's own chain gate; a runtime that says it is not
83
100
  // available is the same as none at all for every surface below.
84
101
  return runtime && runtime.available ? runtime : null
@@ -1,8 +1,9 @@
1
- import { useEffect, useRef, useState } from 'react'
2
- import { getOnline, subscribeOnline } from '@bsv/expo-wallet-toolbox'
1
+ import { useEffect, useState } from 'react'
2
+ import { getOnline, probeOnline, subscribeOnline } from '@bsv/expo-wallet-toolbox'
3
3
 
4
4
  /**
5
- * How long a device must keep reporting offline before the UI says so.
5
+ * How long a device must keep reporting offline before the UI even asks whether
6
+ * it is.
6
7
  *
7
8
  * Connectivity flaps: NetInfo emits during handovers, on waking, and while a
8
9
  * native probe is still settling, and the first of those emissions can arrive
@@ -13,40 +14,84 @@ import { getOnline, subscribeOnline } from '@bsv/expo-wallet-toolbox'
13
14
  */
14
15
  export const OFFLINE_CONFIRM_MS = 2500
15
16
 
17
+ /**
18
+ * How often an offline claim is put to the network again while it stands.
19
+ *
20
+ * NetInfo will not emit again for a snapshot that is merely out of date, so
21
+ * left to NetInfo alone a wrong banner would stay until the next network
22
+ * change. This is what lets it clear itself.
23
+ */
24
+ export const OFFLINE_RECHECK_MS = 15_000
25
+
16
26
  /**
17
27
  * Starts optimistic. A first render that wrongly says "online" costs a failed
18
28
  * request; a first render that wrongly says "offline" hides the online payment
19
29
  * rails from a user who has signal, which is worse.
30
+ *
31
+ * NetInfo's offline verdict is a claim, not a fact. On iOS it is a cached
32
+ * reachability snapshot (the OS sends no callbacks while the app is suspended)
33
+ * plus an HTTP probe of a Google host, and either can read offline for a phone
34
+ * whose connection works. So once a report has held for `confirmMs`, a real
35
+ * request to the wallet's own hosts decides: only if that also fails does the
36
+ * UI say offline, and while it does the request is repeated every `recheckMs`.
20
37
  */
21
- export function useOnline(confirmMs: number = OFFLINE_CONFIRM_MS): boolean {
38
+ export function useOnline(confirmMs: number = OFFLINE_CONFIRM_MS, recheckMs: number = OFFLINE_RECHECK_MS): boolean {
22
39
  const [online, setOnline] = useState(true)
23
- // Held in a ref so a pending confirmation survives re-renders and is cleared
24
- // the moment connectivity returns.
25
- const pendingOffline = useRef<ReturnType<typeof setTimeout> | null>(null)
26
40
 
27
41
  useEffect(() => {
28
42
  let cancelled = false
43
+ /** NetInfo's latest verdict is offline: the claim being put to the network. */
44
+ let claimedOffline = false
45
+ let warned = false
46
+ let checking = false
47
+ let timer: ReturnType<typeof setTimeout> | null = null
29
48
 
30
- const clearPending = () => {
31
- if (pendingOffline.current !== null) {
32
- clearTimeout(pendingOffline.current)
33
- pendingOffline.current = null
49
+ const clearTimer = () => {
50
+ if (timer !== null) {
51
+ clearTimeout(timer)
52
+ timer = null
53
+ }
54
+ }
55
+
56
+ const schedule = (ms: number) => {
57
+ timer = setTimeout(() => {
58
+ timer = null
59
+ void verify()
60
+ }, ms)
61
+ }
62
+
63
+ /** Asks the network. Repeats for as long as NetInfo keeps insisting on offline. */
64
+ const verify = async () => {
65
+ checking = true
66
+ let reached = false
67
+ try {
68
+ reached = (await probeOnline()) === true
69
+ } catch {
70
+ // A probe that cannot even run is an offline answer, not a crash.
71
+ }
72
+ checking = false
73
+ // Superseded while the request was out: connectivity came back, or unmounted.
74
+ if (cancelled || !claimedOffline) return
75
+ if (reached && !warned) {
76
+ warned = true
77
+ console.warn('[net] NetInfo reports offline but a live request got through; treating as online')
34
78
  }
79
+ setOnline(reached)
80
+ schedule(recheckMs)
35
81
  }
36
82
 
37
- /** Online applies at once; offline only after it has held for `confirmMs`. */
38
83
  const apply = (next: boolean) => {
39
84
  if (cancelled) return
85
+ claimedOffline = !next
40
86
  if (next) {
41
- clearPending()
87
+ clearTimer()
88
+ warned = false
42
89
  setOnline(true)
43
90
  return
44
91
  }
45
- if (pendingOffline.current !== null) return
46
- pendingOffline.current = setTimeout(() => {
47
- pendingOffline.current = null
48
- if (!cancelled) setOnline(false)
49
- }, confirmMs)
92
+ // Already waiting out the window, or mid-request: that pass covers this report.
93
+ if (timer !== null || checking) return
94
+ schedule(confirmMs)
50
95
  }
51
96
 
52
97
  void getOnline()
@@ -61,10 +106,10 @@ export function useOnline(confirmMs: number = OFFLINE_CONFIRM_MS): boolean {
61
106
 
62
107
  return () => {
63
108
  cancelled = true
64
- clearPending()
109
+ clearTimer()
65
110
  unsubscribe()
66
111
  }
67
- }, [confirmMs])
112
+ }, [confirmMs, recheckMs])
68
113
 
69
114
  return online
70
115
  }