@bsv/expo-wallet-toolbox 0.1.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 (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Recipient state for the universal send form.
3
+ *
4
+ * Typed text goes through classifyRecipientInput; a scanned code goes through
5
+ * classifyScan. Both are pure and live in core/pay/rails. This hook only holds
6
+ * the resulting state and the identity search that free text turns into.
7
+ *
8
+ * Unrecognised junk in front of the camera is ignored and the scanner keeps
9
+ * looking; a malformed `peerpay:` code is different — it closes the scanner and
10
+ * reports the validator's message in the banner, as pasting the same string does.
11
+ *
12
+ * Grew out of useIdentitySearch (handle-only). The search machinery is the
13
+ * same; what is new is that an address is a first-class outcome and a nearby
14
+ * session is handed up to whoever mounted the form.
15
+ */
16
+ import { useCallback, useEffect, useRef, useState } from 'react'
17
+ import { Keyboard } from 'react-native'
18
+ import { IdentityClient } from '@bsv/sdk'
19
+ import type { DisplayableIdentity } from '@bsv/sdk'
20
+ import { searchIdentities } from '../../resolveIdentity'
21
+ import {
22
+ classifyRecipientInput,
23
+ classifyScan,
24
+ peerPayValidationMessage,
25
+ validatePeerPayURI,
26
+ type PayTarget,
27
+ type Session
28
+ } from '@bsv/expo-wallet-toolbox'
29
+
30
+ export { peerPayValidationMessage }
31
+
32
+ /** Any throw from the overlay lookup is an outage, not “no such person”. */
33
+ export function classifyIdentitySearchError(_e: unknown): boolean {
34
+ return true
35
+ }
36
+
37
+ export type RecipientTarget = Extract<PayTarget, { kind: 'handle' | 'address' }>
38
+ export type RecipientInlineError = 'invalid_bsv_address'
39
+
40
+ export interface UseRecipientInputOptions {
41
+ wallet: unknown
42
+ adminOriginator: string | undefined
43
+ /**
44
+ * A recipient known before the form opened (deep link, scan on the way in).
45
+ * Compared by content; a new object with the same fields does not re-adopt.
46
+ */
47
+ initialTarget?: RecipientTarget
48
+ /** A link or code named an amount too. */
49
+ onPeerPayAmount?: (sats: number) => void
50
+ /** A peerpay link that did not validate; the message is the validator's. */
51
+ onPeerPayError?: (message: string) => void
52
+ /** A nearby-session code was scanned: this form is the wrong surface for it. */
53
+ onNearbySession?: (session: Session) => void
54
+ }
55
+
56
+ const SEARCH_DEBOUNCE_MS = 400
57
+
58
+ function textFor(target: RecipientTarget): string {
59
+ return target.kind === 'handle' ? target.identityKey : target.address
60
+ }
61
+
62
+ export function useRecipientInput({
63
+ wallet,
64
+ adminOriginator,
65
+ initialTarget,
66
+ onPeerPayAmount,
67
+ onPeerPayError,
68
+ onNearbySession
69
+ }: UseRecipientInputOptions) {
70
+ const identityClientRef = useRef<IdentityClient | null>(null)
71
+ useEffect(() => {
72
+ if (!wallet) return
73
+ try {
74
+ identityClientRef.current = new IdentityClient(wallet as never, undefined, adminOriginator)
75
+ } catch {
76
+ // Identity search is decorative; a client that will not build leaves the form usable.
77
+ }
78
+ }, [wallet, adminOriginator])
79
+
80
+ const [inputText, setInputText] = useState(initialTarget ? textFor(initialTarget) : '')
81
+ const [target, setTarget] = useState<RecipientTarget | null>(initialTarget ?? null)
82
+ const [inlineError, setInlineError] = useState<RecipientInlineError | null>(null)
83
+ const [selectedIdentity, setSelectedIdentity] = useState<DisplayableIdentity | null>(null)
84
+ const [searchResults, setSearchResults] = useState<DisplayableIdentity[]>([])
85
+ const [isSearching, setIsSearching] = useState(false)
86
+ const [searchError, setSearchError] = useState(false)
87
+ const [scannerVisible, setScannerVisible] = useState(false)
88
+ const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
89
+
90
+ const stopSearch = useCallback(() => {
91
+ if (searchTimerRef.current) clearTimeout(searchTimerRef.current)
92
+ searchTimerRef.current = null
93
+ setSearchResults([])
94
+ setIsSearching(false)
95
+ }, [])
96
+
97
+ const setDirectTarget = useCallback(
98
+ (next: RecipientTarget) => {
99
+ stopSearch()
100
+ setInputText(textFor(next))
101
+ setTarget(next)
102
+ setSelectedIdentity(null)
103
+ setSearchError(false)
104
+ setInlineError(null)
105
+ },
106
+ [stopSearch]
107
+ )
108
+
109
+ const onChangeText = useCallback(
110
+ (text: string) => {
111
+ setInputText(text)
112
+ setSelectedIdentity(null)
113
+ setTarget(null)
114
+ setInlineError(null)
115
+ setSearchError(false)
116
+ if (searchTimerRef.current) clearTimeout(searchTimerRef.current)
117
+
118
+ const input = classifyRecipientInput(text)
119
+ switch (input.kind) {
120
+ case 'empty':
121
+ stopSearch()
122
+ return
123
+ case 'address':
124
+ stopSearch()
125
+ setTarget({ kind: 'address', address: input.address })
126
+ return
127
+ case 'invalid_address':
128
+ stopSearch()
129
+ setInlineError('invalid_bsv_address')
130
+ return
131
+ case 'handle':
132
+ stopSearch()
133
+ setTarget({
134
+ kind: 'handle',
135
+ identityKey: input.identityKey,
136
+ ...(input.messageBoxUrl ? { messageBoxUrl: input.messageBoxUrl } : {})
137
+ })
138
+ if (input.sats !== undefined) onPeerPayAmount?.(input.sats)
139
+ return
140
+ case 'invalid_link':
141
+ stopSearch()
142
+ onPeerPayError?.(input.message)
143
+ return
144
+ case 'search':
145
+ setSearchResults([])
146
+ setIsSearching(true)
147
+ searchTimerRef.current = setTimeout(async () => {
148
+ const client = identityClientRef.current
149
+ if (!client) {
150
+ setIsSearching(false)
151
+ return
152
+ }
153
+ try {
154
+ setSearchResults(await searchIdentities(client, input.query))
155
+ setSearchError(false)
156
+ } catch (error) {
157
+ console.error('Identity search error:', error)
158
+ if (classifyIdentitySearchError(error)) setSearchError(true)
159
+ setSearchResults([])
160
+ } finally {
161
+ setIsSearching(false)
162
+ }
163
+ }, SEARCH_DEBOUNCE_MS)
164
+ return
165
+ }
166
+ },
167
+ [onPeerPayAmount, onPeerPayError, stopSearch]
168
+ )
169
+
170
+ const selectIdentity = useCallback(
171
+ (identity: DisplayableIdentity) => {
172
+ stopSearch()
173
+ setSelectedIdentity(identity)
174
+ setTarget({ kind: 'handle', identityKey: identity.identityKey })
175
+ setInputText(identity.name || identity.abbreviatedKey)
176
+ setSearchError(false)
177
+ setInlineError(null)
178
+ Keyboard.dismiss()
179
+ },
180
+ [stopSearch]
181
+ )
182
+
183
+ const clearRecipient = useCallback(() => {
184
+ stopSearch()
185
+ setSelectedIdentity(null)
186
+ setTarget(null)
187
+ setInputText('')
188
+ setSearchError(false)
189
+ setInlineError(null)
190
+ }, [stopSearch])
191
+
192
+ // Compared by content, not reference: a caller may rebuild this object every
193
+ // render, and a re-render must never clobber what the user has typed. The ref
194
+ // carries the latest object so the effect can adopt it without depending on it.
195
+ // A link that was adopted and then withdrawn (a second, malformed link) must
196
+ // not leave the first recipient armed. Declared below clearRecipient, which it needs.
197
+ const initialTargetKey = initialTarget
198
+ ? `${initialTarget.kind}:${textFor(initialTarget)}:${initialTarget.kind === 'handle' ? (initialTarget.messageBoxUrl ?? '') : ''}`
199
+ : ''
200
+ const initialTargetRef = useRef(initialTarget)
201
+ initialTargetRef.current = initialTarget
202
+ const adoptedKeyRef = useRef('')
203
+ useEffect(() => {
204
+ const next = initialTargetRef.current
205
+ if (next) {
206
+ setDirectTarget(next)
207
+ adoptedKeyRef.current = initialTargetKey
208
+ } else if (adoptedKeyRef.current) {
209
+ adoptedKeyRef.current = ''
210
+ clearRecipient()
211
+ }
212
+ }, [initialTargetKey, setDirectTarget, clearRecipient])
213
+
214
+ const clearSearchError = useCallback(() => setSearchError(false), [])
215
+ const openScanner = useCallback(() => setScannerVisible(true), [])
216
+
217
+ const onScan = useCallback(
218
+ (data: string) => {
219
+ const scanned = classifyScan(data)
220
+ if (!scanned) {
221
+ // A code that names the peerpay scheme was recognised and rejected: silence in front of
222
+ // a live camera is a dead end, so say why and get out of the way. Anything else is
223
+ // unclassifiable junk — QRScanner is in multiScan mode and keeps looking.
224
+ const text = data.trim()
225
+ if (text.toLowerCase().startsWith('peerpay:')) {
226
+ const message = peerPayValidationMessage(validatePeerPayURI(text))
227
+ if (message) {
228
+ setScannerVisible(false)
229
+ onPeerPayError?.(message)
230
+ }
231
+ }
232
+ return
233
+ }
234
+ setScannerVisible(false)
235
+ if (scanned.kind === 'nearby') {
236
+ onNearbySession?.(scanned.session)
237
+ return
238
+ }
239
+ if (scanned.kind === 'handle') {
240
+ setDirectTarget({
241
+ kind: 'handle',
242
+ identityKey: scanned.identityKey,
243
+ ...(scanned.messageBoxUrl ? { messageBoxUrl: scanned.messageBoxUrl } : {})
244
+ })
245
+ if (scanned.sats !== undefined) onPeerPayAmount?.(scanned.sats)
246
+ return
247
+ }
248
+ setDirectTarget({ kind: 'address', address: scanned.address })
249
+ },
250
+ [onNearbySession, onPeerPayAmount, onPeerPayError, setDirectTarget]
251
+ )
252
+
253
+ return {
254
+ inputText,
255
+ target,
256
+ inlineError,
257
+ selectedIdentity,
258
+ searchResults,
259
+ isSearching,
260
+ searchError,
261
+ clearSearchError,
262
+ onChangeText,
263
+ selectIdentity,
264
+ clearRecipient,
265
+ scannerVisible,
266
+ setScannerVisible,
267
+ openScanner,
268
+ onScan
269
+ }
270
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The states the app previously had no way to show.
3
+ *
4
+ * Before the envelope, a failed key read was indistinguishable from having no
5
+ * wallet: the build silently bailed and the user landed in the browser as if
6
+ * they were new. Now that the OS genuinely holds the key, three outcomes need
7
+ * to be visible and told apart:
8
+ *
9
+ * - `lost` the OS destroyed the key (biometrics re-enrolled, screen
10
+ * lock removed, app reinstalled). Unrecoverable on-device.
11
+ * - `cancelled` the user dismissed the sheet. Nothing was touched; retry.
12
+ * - `unavailable` biometric lockout or no usable hardware.
13
+ *
14
+ * Nothing here wipes anything on its own. Restoring is an explicit, confirmed
15
+ * act, because the alternative — auto-wiping on a read failure — would destroy
16
+ * a wallet over a transient prompt error.
17
+ */
18
+ import React, { useCallback } from 'react'
19
+ import { View, Text, StyleSheet } from 'react-native'
20
+ import PressableScale from '../ui/PressableScale'
21
+ import { showAlert } from '../ui/AlertCard'
22
+ import { useTheme, spacing, radii, typography, useLocalStorage, i18n } from '@bsv/expo-wallet-toolbox'
23
+
24
+ const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
25
+
26
+ /**
27
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
28
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
29
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
30
+ * Loaded lazily, only when actually rendering, same pattern as the
31
+ * expo-router load just below.
32
+ */
33
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
34
+ let ioniconsComponent: IoniconsComponent | undefined
35
+ function loadIonicons(): IoniconsComponent {
36
+ if (!ioniconsComponent) {
37
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
38
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
39
+ }
40
+ return ioniconsComponent
41
+ }
42
+
43
+ /**
44
+ * expo-router's `router` singleton is required lazily (on first call from
45
+ * onRestore()), rather than imported statically, because this file is
46
+ * barrel-exported from the package's `ui` entry point — a static top-level
47
+ * `import` of expo-router pulls in its own untransformed JSX source
48
+ * (Navigator.js etc.), which Jest cannot parse for any consumer of the
49
+ * barrel, even one that never navigates. Same pattern as
50
+ * core/context/WalletContext.tsx's lazy expo-router load.
51
+ */
52
+ type ExpoRouterModule = typeof import('expo-router')
53
+ let expoRouterMod: ExpoRouterModule | undefined
54
+ function loadExpoRouter(): ExpoRouterModule {
55
+ if (!expoRouterMod) {
56
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
57
+ expoRouterMod = require('expo-router') as ExpoRouterModule
58
+ }
59
+ return expoRouterMod
60
+ }
61
+
62
+ export default function WalletLockNotice() {
63
+ const { colors } = useTheme()
64
+ const Ionicons = loadIonicons()
65
+ const { unlockState, unlock, deleteAllWalletKeys } = useLocalStorage()
66
+
67
+ const onRestore = useCallback(async () => {
68
+ const choice = await showAlert({
69
+ title: t('wallet_lost_title'),
70
+ message: t('wallet_lost_body'),
71
+ buttons: [
72
+ { text: t('wallet_lost_later'), style: 'cancel', key: 'cancel' },
73
+ { text: t('wallet_lost_restore'), style: 'destructive', key: 'restore' }
74
+ ]
75
+ })
76
+ if (choice !== 'restore') return
77
+ // The ciphertexts are already unopenable; clearing them is what lets
78
+ // onboarding start clean instead of tripping over an orphan sentinel.
79
+ await deleteAllWalletKeys()
80
+ loadExpoRouter().router.replace('/auth/mnemonic')
81
+ }, [deleteAllWalletKeys])
82
+
83
+ const status = unlockState.status
84
+ if (status !== 'lost' && status !== 'cancelled' && status !== 'unavailable') return null
85
+
86
+ const lost = status === 'lost'
87
+ const body = lost
88
+ ? t('wallet_lost_body')
89
+ : status === 'unavailable' && unlockState.reason === 'lockout'
90
+ ? t('wallet_lockout_body')
91
+ : status === 'unavailable'
92
+ ? t('wallet_no_biometrics_body')
93
+ : t('wallet_locked_body')
94
+
95
+ return (
96
+ <View style={[styles.card, { backgroundColor: colors.backgroundSecondary, borderColor: colors.separator }]}>
97
+ <Ionicons
98
+ name={lost ? 'alert-circle-outline' : 'lock-closed-outline'}
99
+ size={40}
100
+ color={lost ? colors.textPrimary : colors.textTertiary}
101
+ />
102
+ <Text style={[styles.title, { color: colors.textPrimary }]}>
103
+ {lost ? t('wallet_lost_title') : t('wallet_locked_title')}
104
+ </Text>
105
+ <Text style={[styles.body, { color: colors.textSecondary }]}>{body}</Text>
106
+
107
+ <PressableScale
108
+ haptic="confirm"
109
+ onPress={lost ? onRestore : unlock}
110
+ style={[styles.primary, { backgroundColor: colors.accent }]}
111
+ >
112
+ <Text style={styles.primaryText}>
113
+ {lost ? t('wallet_lost_restore') : t('wallet_unlock_retry')}
114
+ </Text>
115
+ </PressableScale>
116
+ </View>
117
+ )
118
+ }
119
+
120
+ const styles = StyleSheet.create({
121
+ card: {
122
+ alignItems: 'center',
123
+ gap: spacing.md,
124
+ padding: spacing.xl,
125
+ margin: spacing.lg,
126
+ borderRadius: radii.lg,
127
+ borderWidth: StyleSheet.hairlineWidth
128
+ },
129
+ title: { ...typography.title3, textAlign: 'center' },
130
+ body: { ...typography.subhead, textAlign: 'center' },
131
+ primary: {
132
+ paddingVertical: spacing.md,
133
+ paddingHorizontal: spacing.xl,
134
+ borderRadius: radii.pill,
135
+ marginTop: spacing.xs
136
+ },
137
+ primaryText: { ...typography.headline, color: '#fff' }
138
+ })
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Glass Alert Card (spec Part 2) — themed replacement for Alert.alert.
3
+ * Imperative promise API so plain utils can call it:
4
+ *
5
+ * const choice = await showAlert({
6
+ * title, message,
7
+ * buttons: [
8
+ * { text: t('cancel'), style: 'cancel', key: 'cancel' },
9
+ * { text: t('delete'), style: 'destructive', key: 'delete' },
10
+ * ],
11
+ * })
12
+ * if (choice === 'delete') { ... }
13
+ *
14
+ * <AlertHost /> must be mounted once, inside ThemeProvider (app/_layout.tsx).
15
+ * Background is near-solid sheetBackground — deliberately NOT BlurView/LiquidGlass
16
+ * (fractional-opacity-over-effect-view guardrail in context/theme/motion.ts).
17
+ */
18
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
19
+ import { Modal, Platform, Pressable, StyleSheet, Text, View } from 'react-native'
20
+ import Animated, {
21
+ useSharedValue,
22
+ useAnimatedStyle,
23
+ withSpring,
24
+ withTiming,
25
+ useReducedMotion,
26
+ } from 'react-native-reanimated'
27
+ import { useTheme, spacing, radii, typography, springs, durations, haptics } from '@bsv/expo-wallet-toolbox'
28
+
29
+ export interface AlertButton {
30
+ text: string
31
+ style?: 'default' | 'cancel' | 'destructive'
32
+ /** Resolution value. Defaults to lowercased text. */
33
+ key?: string
34
+ }
35
+
36
+ export interface AlertOptions {
37
+ title: string
38
+ message?: string
39
+ /** Defaults to a single OK button (key "ok"). Max 3; 2 render side-by-side, 3 stack. */
40
+ buttons?: AlertButton[]
41
+ }
42
+
43
+ type ActiveAlert = AlertOptions & { resolve: (key: string) => void }
44
+
45
+ let enqueue: ((a: ActiveAlert) => void) | null = null
46
+
47
+ export function showAlert(options: AlertOptions): Promise<string> {
48
+ return new Promise<string>(resolve => {
49
+ if (!enqueue) {
50
+ console.warn('[AlertCard] AlertHost not mounted; resolving "cancel"')
51
+ resolve('cancel')
52
+ return
53
+ }
54
+ enqueue({ ...options, resolve })
55
+ })
56
+ }
57
+
58
+ const DEFAULT_BUTTONS: AlertButton[] = [{ text: 'OK', key: 'ok' }]
59
+
60
+ export function AlertHost() {
61
+ const { colors } = useTheme()
62
+ const reducedMotion = useReducedMotion()
63
+ const [queue, setQueue] = useState<ActiveAlert[]>([])
64
+ const current = queue[0] ?? null
65
+
66
+ const progress = useSharedValue(0)
67
+ const exiting = useRef(false)
68
+ const lastHapticAlert = useRef<ActiveAlert | null>(null)
69
+
70
+ useEffect(() => {
71
+ enqueue = (a: ActiveAlert) => setQueue(q => [...q, a])
72
+ return () => {
73
+ enqueue = null
74
+ // Resolve all queued alerts with 'cancel' on unmount.
75
+ setQueue(q => {
76
+ q.forEach(a => a.resolve('cancel'))
77
+ return []
78
+ })
79
+ }
80
+ }, [])
81
+
82
+ useEffect(() => {
83
+ if (current) {
84
+ // Reset progress to 0 before animating in to avoid stale values.
85
+ progress.value = 0
86
+ // Fire warning haptic at most once per distinct alert object.
87
+ if (
88
+ current.buttons?.some(b => b.style === 'destructive') &&
89
+ lastHapticAlert.current !== current
90
+ ) {
91
+ lastHapticAlert.current = current
92
+ haptics.warning()
93
+ }
94
+ progress.value = reducedMotion
95
+ ? withTiming(1, { duration: durations.instant })
96
+ : withSpring(1, springs.snappy)
97
+ }
98
+ }, [current, progress, reducedMotion])
99
+
100
+ const dismiss = useCallback((key: string) => {
101
+ if (!current || exiting.current) return
102
+ exiting.current = true
103
+ current.resolve(key)
104
+ progress.value = withTiming(0, { duration: durations.instant })
105
+ // Unmount after the exit fade completes.
106
+ setTimeout(() => { exiting.current = false; setQueue(q => q.slice(1)) }, durations.instant)
107
+ }, [current, progress])
108
+
109
+ const backdropStyle = useAnimatedStyle(() => ({ opacity: progress.value }))
110
+ const cardStyle = useAnimatedStyle(() => ({
111
+ opacity: progress.value,
112
+ transform: [{ scale: 0.95 + 0.05 * progress.value }],
113
+ }))
114
+
115
+ if (!current) return null
116
+ const buttons = current.buttons?.length ? current.buttons : DEFAULT_BUTTONS
117
+ const sideBySide = buttons.length === 2
118
+
119
+ const buttonColor = (b: AlertButton) =>
120
+ b.style === 'destructive' ? colors.error
121
+ : b.style === 'cancel' ? colors.textSecondary
122
+ : colors.info
123
+
124
+ return (
125
+ <Modal
126
+ transparent
127
+ visible
128
+ animationType="none"
129
+ onRequestClose={() => dismiss('cancel')}
130
+ statusBarTranslucent={Platform.OS === 'android'}
131
+ navigationBarTranslucent={Platform.OS === 'android'}
132
+ >
133
+ <Animated.View style={[styles.backdrop, { backgroundColor: colors.scrim }, backdropStyle]}>
134
+ <Pressable style={StyleSheet.absoluteFill} onPress={() => dismiss('cancel')} />
135
+ <Animated.View
136
+ style={[
137
+ styles.card,
138
+ { backgroundColor: colors.sheetBackground, borderColor: colors.separator },
139
+ cardStyle,
140
+ ]}
141
+ >
142
+ <Text style={[styles.title, { color: colors.textPrimary }]}>{current.title}</Text>
143
+ {!!current.message && (
144
+ <Text style={[styles.message, { color: colors.textSecondary }]}>{current.message}</Text>
145
+ )}
146
+ <View style={[styles.buttonGroup, { borderTopColor: colors.separator }, !sideBySide && styles.buttonGroupStacked]}>
147
+ {buttons.map((b, i) => (
148
+ <Pressable
149
+ key={b.key ?? b.text}
150
+ onPress={() => dismiss(b.key ?? b.text.toLowerCase())}
151
+ style={({ pressed }) => [
152
+ styles.button,
153
+ // flex:1 only splits the two-up row; in the stacked column it
154
+ // resolves to a zero flex-basis and clips the label against
155
+ // minHeight, so stacked buttons size to their content instead.
156
+ sideBySide && styles.buttonRowItem,
157
+ sideBySide && i > 0 && { borderLeftWidth: StyleSheet.hairlineWidth, borderLeftColor: colors.separator },
158
+ !sideBySide && i > 0 && { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.separator },
159
+ pressed && { backgroundColor: colors.fillTertiary },
160
+ ]}
161
+ accessibilityRole="button"
162
+ >
163
+ <Text
164
+ style={[
165
+ styles.buttonText,
166
+ { color: buttonColor(b) },
167
+ (b.style === 'destructive' || b.style === 'cancel') && styles.buttonTextBold,
168
+ ]}
169
+ >
170
+ {b.text}
171
+ </Text>
172
+ </Pressable>
173
+ ))}
174
+ </View>
175
+ </Animated.View>
176
+ </Animated.View>
177
+ </Modal>
178
+ )
179
+ }
180
+
181
+ const styles = StyleSheet.create({
182
+ backdrop: {
183
+ flex: 1,
184
+ alignItems: 'center',
185
+ justifyContent: 'center',
186
+ },
187
+ card: {
188
+ width: 280,
189
+ borderRadius: radii.xl,
190
+ borderWidth: StyleSheet.hairlineWidth,
191
+ overflow: 'hidden',
192
+ paddingTop: spacing.xl,
193
+ },
194
+ title: {
195
+ ...typography.headline,
196
+ textAlign: 'center',
197
+ paddingHorizontal: spacing.xl,
198
+ },
199
+ message: {
200
+ ...typography.footnote,
201
+ textAlign: 'center',
202
+ paddingHorizontal: spacing.xl,
203
+ marginTop: spacing.xs,
204
+ },
205
+ buttonGroup: {
206
+ flexDirection: 'row',
207
+ marginTop: spacing.lg,
208
+ borderTopWidth: StyleSheet.hairlineWidth,
209
+ },
210
+ buttonGroupStacked: { flexDirection: 'column' },
211
+ button: {
212
+ minHeight: 44,
213
+ alignItems: 'center',
214
+ justifyContent: 'center',
215
+ paddingVertical: spacing.md,
216
+ // Keep long labels off the card edge / hairline divider so they wrap
217
+ // inside the button instead of touching (or escaping) the border.
218
+ paddingHorizontal: spacing.sm,
219
+ },
220
+ buttonRowItem: { flex: 1 },
221
+ buttonText: { ...typography.body, textAlign: 'center' },
222
+ buttonTextBold: { fontWeight: '600' },
223
+ })