@bsv/expo-wallet-toolbox 0.19.0 → 0.20.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 (135) hide show
  1. package/CHANGELOG.md +121 -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/DirectPayProvider.tsx +15 -24
  24. package/core/directpay/receive.ts +2 -1
  25. package/core/headers/checkpoints.ts +10 -1
  26. package/core/headers/headerStore.ts +13 -2
  27. package/core/hooks/useConfirmationSound.ts +3 -3
  28. package/core/hooks/useHaptics.ts +23 -6
  29. package/core/i18n/translations.tsx +269 -125
  30. package/core/index.ts +2 -0
  31. package/core/localpay/codec.ts +12 -6
  32. package/core/localpay/deviceCaps.ts +4 -14
  33. package/core/localpay/pending.ts +2 -1
  34. package/core/localpay/qr.ts +1 -1
  35. package/core/localpay/settlementAck.ts +1 -4
  36. package/core/localpay/transport/ble.ts +2 -2
  37. package/core/localpay/transport/socket.ts +1 -1
  38. package/core/mandala/abortGuard.ts +1 -1
  39. package/core/mandala/drain.ts +3 -0
  40. package/core/mandala/permissionModule.ts +3 -2
  41. package/core/mandala/resendTransfer.ts +4 -1
  42. package/core/mandala/runtime.ts +4 -4
  43. package/core/monitor/TaskBackupPush.ts +10 -13
  44. package/core/net/chainMatch.ts +8 -5
  45. package/core/networks.ts +145 -0
  46. package/core/parsePeerPayURI.ts +4 -1
  47. package/core/pay/beefRepair.ts +6 -3
  48. package/core/pay/creditErrors.ts +37 -1
  49. package/core/pay/rails/address.ts +10 -6
  50. package/core/pay/rails/handle.ts +84 -11
  51. package/core/pay/rails/index.ts +18 -2
  52. package/core/pay/receiveHistory.ts +8 -8
  53. package/core/peerpay/handleResendRequests.ts +11 -18
  54. package/core/peerpay/inboxAttempts.ts +1 -4
  55. package/core/peerpay/rebuildToken.ts +12 -9
  56. package/core/profiles/profileStore.ts +2 -1
  57. package/core/profiles/removalProblems.ts +3 -1
  58. package/core/services/arcTokenStorage.ts +2 -1
  59. package/core/services/arcadeBroadcastProvider.ts +7 -17
  60. package/core/services/secrets/envelope.ts +1 -6
  61. package/core/services/secrets/hkdf.ts +1 -6
  62. package/core/services/secrets/index.ts +3 -22
  63. package/core/services/usdFxRates.ts +1 -4
  64. package/core/services/vault/VaultKeyService.ts +2 -1
  65. package/core/services/vault/chainRecovery.ts +48 -21
  66. package/core/services/vault/metaAuthority.ts +4 -1
  67. package/core/services/vault/r1comb.ts +113 -51
  68. package/core/services/vault/session.ts +5 -1
  69. package/core/services/vault/transfers.ts +699 -576
  70. package/core/services/vault/vaultStore.ts +12 -10
  71. package/core/services/walletArgLimits.ts +1 -2
  72. package/core/services/walletConnectionValidation.ts +44 -28
  73. package/core/services/walletServiceConfig.ts +9 -40
  74. package/core/storage/StorageExpoSQLite.ts +7 -21
  75. package/core/storage/methods/listActionsSql.ts +81 -67
  76. package/core/storage/methods/listOutputsSql.ts +21 -16
  77. package/core/storage/methods/reviewStatusSql.ts +1 -4
  78. package/core/stores/ConnectionStore.ts +1 -1
  79. package/core/theme/ThemeContext.tsx +12 -16
  80. package/core/theme/motion.ts +3 -3
  81. package/core/theme/tokens.ts +6 -6
  82. package/core/toolboxConfig.ts +23 -0
  83. package/core/walletDbRegistry.ts +7 -5
  84. package/core/walletRepair/runWalletCheck.ts +1 -4
  85. package/package.json +2 -2
  86. package/ui/components/pay/AddressReceive.tsx +3 -3
  87. package/ui/components/pay/HandleReceive.tsx +15 -15
  88. package/ui/components/pay/MessageBoxConfig.tsx +46 -20
  89. package/ui/components/pay/NearbyFlow.tsx +575 -507
  90. package/ui/components/pay/OfflineNotice.tsx +1 -3
  91. package/ui/components/pay/PayCellRow.tsx +1 -4
  92. package/ui/components/pay/PayForm.tsx +1 -3
  93. package/ui/components/pay/RequestHub.tsx +14 -6
  94. package/ui/components/pay/UniversalSend.tsx +79 -27
  95. package/ui/components/pay/tokenSendCopy.ts +1 -2
  96. package/ui/components/pay/useRecipientInput.ts +2 -2
  97. package/ui/components/security/WalletLockNotice.tsx +1 -3
  98. package/ui/components/ui/AlertCard.tsx +44 -45
  99. package/ui/components/ui/BlurChrome.tsx +4 -15
  100. package/ui/components/ui/Celebration.tsx +3 -3
  101. package/ui/components/ui/ChoiceSheet.ts +1 -3
  102. package/ui/components/ui/ErrorBoundary.tsx +2 -6
  103. package/ui/components/ui/GroupedList.tsx +13 -31
  104. package/ui/components/ui/IconButton.tsx +6 -9
  105. package/ui/components/ui/ListRow.tsx +19 -25
  106. package/ui/components/ui/PresenceRow.tsx +4 -4
  107. package/ui/components/ui/PressableScale.tsx +24 -20
  108. package/ui/components/ui/Toast.tsx +23 -16
  109. package/ui/components/vault/KeyChooser.tsx +9 -6
  110. package/ui/components/vault/VaultBackdrop.tsx +1 -8
  111. package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
  112. package/ui/components/wallet/ActivityRow.tsx +3 -2
  113. package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
  114. package/ui/components/wallet/Balance.tsx +4 -1
  115. package/ui/components/wallet/ContactActivityList.tsx +7 -7
  116. package/ui/components/wallet/IconPickerSheet.tsx +1 -5
  117. package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
  118. package/ui/components/wallet/tokenEviction.ts +4 -1
  119. package/ui/hooks/useMandala.ts +1 -7
  120. package/ui/hooks/useOfflineNoticeActions.ts +21 -27
  121. package/ui/hooks/useSpendableBalance.ts +2 -2
  122. package/ui/hooks/useVaultCoverage.ts +7 -1
  123. package/ui/index.ts +9 -1
  124. package/ui/resolveIdentity.ts +20 -8
  125. package/ui/screens/ConnectionsScreen.tsx +44 -18
  126. package/ui/screens/LogsScreen.tsx +24 -22
  127. package/ui/screens/PairScreen.tsx +85 -54
  128. package/ui/screens/PayScreen.tsx +5 -1
  129. package/ui/screens/ProfileScreen.tsx +0 -3
  130. package/ui/screens/TrustScreen.tsx +125 -80
  131. package/ui/screens/VaultScreen.tsx +19 -7
  132. package/ui/screens/VaultTransferScreen.tsx +5 -1
  133. package/ui/screens/WalletCheckScreen.tsx +14 -17
  134. package/ui/screens/WalletConfigScreen.tsx +414 -376
  135. package/ui/screens/WalletHomeScreen.tsx +47 -42
@@ -28,14 +28,26 @@ export type { ConnectParams } from '../services/walletConnectionValidation'
28
28
  // ── Constants ─────────────────────────────────────────────────────────────────
29
29
 
30
30
  export const IMPLEMENTED_METHODS = new Set([
31
- 'getPublicKey', 'listOutputs', 'listCertificates', 'createAction', 'signAction',
32
- 'listActions', 'internalizeAction', 'acquireCertificate',
33
- 'relinquishCertificate', 'revealCounterpartyKeyLinkage', 'createHmac', 'verifyHmac',
34
- 'encrypt', 'decrypt', 'createSignature', 'verifySignature',
31
+ 'getPublicKey',
32
+ 'listOutputs',
33
+ 'listCertificates',
34
+ 'createAction',
35
+ 'signAction',
36
+ 'listActions',
37
+ 'internalizeAction',
38
+ 'acquireCertificate',
39
+ 'relinquishCertificate',
40
+ 'revealCounterpartyKeyLinkage',
41
+ 'createHmac',
42
+ 'verifyHmac',
43
+ 'encrypt',
44
+ 'decrypt',
45
+ 'createSignature',
46
+ 'verifySignature'
35
47
  ])
36
48
 
37
- const NAV_TIMEOUT_MS = 5 * 60 * 1000 // 5 min — navigated away from pair screen
38
- const APP_STATE_TIMEOUT_MS = 12 * 60 * 1000 // 12 min — app backgrounded
49
+ const NAV_TIMEOUT_MS = 5 * 60 * 1000 // 5 min — navigated away from pair screen
50
+ const APP_STATE_TIMEOUT_MS = 12 * 60 * 1000 // 12 min — app backgrounded
39
51
 
40
52
  export const lastSeqKey = (topic: string) => `wallet_pairing_lastseq_${topic}`
41
53
 
@@ -43,28 +55,28 @@ export const lastSeqKey = (topic: string) => `wallet_pairing_lastseq_${topic}`
43
55
 
44
56
  export type ConnectionStatus = 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error'
45
57
 
46
- type RpcRequest = { id: string; seq: number; method: string; params: unknown }
58
+ type RpcRequest = { id: string; seq: number; method: string; params: unknown }
47
59
  type RpcResponse = { id: string; seq: number; result?: unknown; error?: { code: number; message: string } }
48
60
  type WireEnvelope = { topic: string; ciphertext: string; mobileIdentityKey?: string }
49
61
 
50
62
  export interface SessionMeta {
51
- topic: string
52
- origin: string
53
- relay: string
63
+ topic: string
64
+ origin: string
65
+ relay: string
54
66
  backendIdentityKey: string
55
- mobileIdentityKey: string
56
- protocolID: WalletProtocol
67
+ mobileIdentityKey: string
68
+ protocolID: WalletProtocol
57
69
  }
58
70
 
59
71
  interface WalletConnectionContextValue {
60
- status: ConnectionStatus
61
- sessionMeta: SessionMeta | null
62
- errorMsg: string | null
63
- connect: (params: ConnectParams, wallet: WalletClient) => Promise<void>
64
- reconnect: (connection: Connection, wallet: WalletClient) => Promise<void>
65
- disconnect: () => void
66
- startNavTimer: () => void
67
- cancelNavTimer: () => void
72
+ status: ConnectionStatus
73
+ sessionMeta: SessionMeta | null
74
+ errorMsg: string | null
75
+ connect: (params: ConnectParams, wallet: WalletClient) => Promise<void>
76
+ reconnect: (connection: Connection, wallet: WalletClient) => Promise<void>
77
+ disconnect: () => void
78
+ startNavTimer: () => void
79
+ cancelNavTimer: () => void
68
80
  }
69
81
 
70
82
  // ── Helpers ───────────────────────────────────────────────────────────────────
@@ -74,7 +86,7 @@ async function encryptPayload(
74
86
  protocolID: WalletProtocol,
75
87
  keyID: string,
76
88
  counterparty: string,
77
- payload: string,
89
+ payload: string
78
90
  ): Promise<string> {
79
91
  const plaintext = Array.from(new TextEncoder().encode(payload))
80
92
  const { ciphertext } = await wallet.encrypt({ protocolID, keyID, counterparty, plaintext })
@@ -86,7 +98,7 @@ async function decryptPayload(
86
98
  protocolID: WalletProtocol,
87
99
  keyID: string,
88
100
  counterparty: string,
89
- ciphertextB64: string,
101
+ ciphertextB64: string
90
102
  ): Promise<string> {
91
103
  const ciphertext = Array.from(Buffer.from(ciphertextB64, 'base64url'))
92
104
  const { plaintext } = await wallet.decrypt({ protocolID, keyID, counterparty, ciphertext })
@@ -99,11 +111,11 @@ async function verifyQrSignature(params: Required<ConnectParams>): Promise<void>
99
111
  const payload = Array.from(new TextEncoder().encode(buildPairingSignatureMessage(params)))
100
112
  const signature = Utils.toArray(params.sig.replace(/-/g, '+').replace(/_/g, '/'), 'base64') as number[]
101
113
  const { valid } = await anyoneWallet.verifySignature({
102
- data: payload,
114
+ data: payload,
103
115
  signature,
104
- protocolID: [0, 'qr pairing'],
105
- keyID: params.topic,
106
- counterparty: params.backendIdentityKey,
116
+ protocolID: [0, 'qr pairing'],
117
+ keyID: params.topic,
118
+ counterparty: params.backendIdentityKey
107
119
  })
108
120
  if (!valid) throw new Error('QR code signature is invalid — do not connect')
109
121
  }
@@ -217,15 +229,15 @@ interface WalletConnectionProviderProps {
217
229
  }
218
230
 
219
231
  export function WalletConnectionProvider({ children, walletName = 'App' }: WalletConnectionProviderProps) {
220
- const [status, setStatus] = useState<ConnectionStatus>('idle')
221
- const [sessionMeta, setSessionMeta] = useState<SessionMeta | null>(null)
222
- const [errorMsg, setErrorMsg] = useState<string | null>(null)
232
+ const [status, setStatus] = useState<ConnectionStatus>('idle')
233
+ const [sessionMeta, setSessionMeta] = useState<SessionMeta | null>(null)
234
+ const [errorMsg, setErrorMsg] = useState<string | null>(null)
223
235
 
224
236
  // Internal refs — changes here don't trigger re-renders
225
- const wsRef = useRef<WebSocket | null>(null)
226
- const lastSeqRef = useRef(0)
227
- const navTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
228
- const appStateTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
237
+ const wsRef = useRef<WebSocket | null>(null)
238
+ const lastSeqRef = useRef(0)
239
+ const navTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
240
+ const appStateTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
229
241
  const intentionalCloseRef = useRef(false)
230
242
  // XR-018: bumped every time an existing socket is torn down (disconnect(),
231
243
  // or connect()/reconnect() superseding a prior live session). wireSocket
@@ -238,8 +250,10 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
238
250
  // already moved on to a different (or no) session.
239
251
  const connectionGenerationRef = useRef(0)
240
252
  // Snapshot of sessionMeta for use inside async WS callbacks
241
- const sessionMetaRef = useRef<SessionMeta | null>(null)
242
- useEffect(() => { sessionMetaRef.current = sessionMeta }, [sessionMeta])
253
+ const sessionMetaRef = useRef<SessionMeta | null>(null)
254
+ useEffect(() => {
255
+ sessionMetaRef.current = sessionMeta
256
+ }, [sessionMeta])
243
257
 
244
258
  // ── Disconnect ─────────────────────────────────────────────────────────────
245
259
 
@@ -252,11 +266,15 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
252
266
  connectionGenerationRef.current++
253
267
  if (wsRef.current === ws) wsRef.current = null
254
268
  if (!ws) return
255
- ws.onopen = null
269
+ ws.onopen = null
256
270
  ws.onmessage = null
257
- ws.onerror = null
258
- ws.onclose = null
259
- try { ws.close() } catch { /* already closing/closed */ }
271
+ ws.onerror = null
272
+ ws.onclose = null
273
+ try {
274
+ ws.close()
275
+ } catch {
276
+ /* already closing/closed */
277
+ }
260
278
  }, [])
261
279
 
262
280
  /** XR-018: this provider models exactly one live paired session at a time
@@ -275,8 +293,14 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
275
293
  connectionStore.setStatus(topic, 'disconnected')
276
294
  }
277
295
  closeAndDetachSocket(wsRef.current)
278
- if (navTimerRef.current) { clearTimeout(navTimerRef.current); navTimerRef.current = null }
279
- if (appStateTimerRef.current) { clearTimeout(appStateTimerRef.current); appStateTimerRef.current = null }
296
+ if (navTimerRef.current) {
297
+ clearTimeout(navTimerRef.current)
298
+ navTimerRef.current = null
299
+ }
300
+ if (appStateTimerRef.current) {
301
+ clearTimeout(appStateTimerRef.current)
302
+ appStateTimerRef.current = null
303
+ }
280
304
  }, [closeAndDetachSocket])
281
305
 
282
306
  const disconnect = useCallback(() => {
@@ -291,7 +315,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
291
315
  // unmount stops a stale/unmounted provider's disconnect from being called.
292
316
  useEffect(() => {
293
317
  activeDisconnect = disconnect
294
- return () => { if (activeDisconnect === disconnect) activeDisconnect = null }
318
+ return () => {
319
+ if (activeDisconnect === disconnect) activeDisconnect = null
320
+ }
295
321
  }, [disconnect])
296
322
 
297
323
  // ── Nav timer (pair screen lifecycle) ─────────────────────────────────────
@@ -305,7 +331,10 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
305
331
  }, [disconnect])
306
332
 
307
333
  const cancelNavTimer = useCallback(() => {
308
- if (navTimerRef.current) { clearTimeout(navTimerRef.current); navTimerRef.current = null }
334
+ if (navTimerRef.current) {
335
+ clearTimeout(navTimerRef.current)
336
+ navTimerRef.current = null
337
+ }
309
338
  }, [])
310
339
 
311
340
  // ── AppState timer (app backgrounded) ────────────────────────────────────
@@ -319,7 +348,10 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
319
348
  if (wsRef.current) disconnect()
320
349
  }, APP_STATE_TIMEOUT_MS)
321
350
  } else if (nextState === 'active') {
322
- if (appStateTimerRef.current) { clearTimeout(appStateTimerRef.current); appStateTimerRef.current = null }
351
+ if (appStateTimerRef.current) {
352
+ clearTimeout(appStateTimerRef.current)
353
+ appStateTimerRef.current = null
354
+ }
323
355
  }
324
356
  })
325
357
  return () => sub.remove()
@@ -327,16 +359,15 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
327
359
 
328
360
  // ── RPC dispatch ──────────────────────────────────────────────────────────
329
361
 
330
- async function handleRpc(
331
- request: RpcRequest,
332
- meta: SessionMeta,
333
- ws: WebSocket,
334
- wallet: WalletClient,
335
- ): Promise<void> {
362
+ async function handleRpc(request: RpcRequest, meta: SessionMeta, ws: WebSocket, wallet: WalletClient): Promise<void> {
336
363
  const sendResponse = async (response: RpcResponse) => {
337
364
  try {
338
365
  const ciphertext = await encryptPayload(
339
- wallet, meta.protocolID, meta.topic, meta.backendIdentityKey, JSON.stringify(response),
366
+ wallet,
367
+ meta.protocolID,
368
+ meta.topic,
369
+ meta.backendIdentityKey,
370
+ JSON.stringify(response)
340
371
  )
341
372
  ws.send(JSON.stringify({ topic: meta.topic, ciphertext } satisfies WireEnvelope))
342
373
  } catch (err) {
@@ -345,8 +376,11 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
345
376
  }
346
377
 
347
378
  if (!IMPLEMENTED_METHODS.has(request.method)) {
348
- await sendResponse({ id: request.id, seq: request.seq,
349
- error: { code: 501, message: `Method "${request.method}" is not implemented` } })
379
+ await sendResponse({
380
+ id: request.id,
381
+ seq: request.seq,
382
+ error: { code: 501, message: `Method "${request.method}" is not implemented` }
383
+ })
350
384
  return
351
385
  }
352
386
 
@@ -365,9 +399,8 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
365
399
  error = { code, message }
366
400
  }
367
401
 
368
- await sendResponse(error
369
- ? { id: request.id, seq: request.seq, error }
370
- : { id: request.id, seq: request.seq, result },
402
+ await sendResponse(
403
+ error ? { id: request.id, seq: request.seq, error } : { id: request.id, seq: request.seq, result }
371
404
  )
372
405
  }
373
406
 
@@ -385,9 +418,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
385
418
  // from a socket superseded in the meantime is guarded exactly like
386
419
  // onmessage/onerror/onclose below.
387
420
  myGeneration: number,
388
- onFirstMessage: () => void,
421
+ onFirstMessage: () => void
389
422
  ) {
390
- wsRef.current = ws
423
+ wsRef.current = ws
391
424
  lastSeqRef.current = initialSeq
392
425
  let firstMessageFired = false
393
426
  let inFlightRpc = 0
@@ -428,7 +461,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
428
461
  // attempted — decoding the ciphertext into a number[] alone already
429
462
  // allocates memory proportional to its size, before the wallet can
430
463
  // authenticate it.
431
- const estimatedBytes = Math.floor(envelope.ciphertext.length * 3 / 4)
464
+ const estimatedBytes = Math.floor((envelope.ciphertext.length * 3) / 4)
432
465
  if (inFlightBytes + estimatedBytes > MAX_IN_FLIGHT_RPC_BYTES) {
433
466
  console.warn('[WalletConnection] dropping message: too many in-flight bytes')
434
467
  return
@@ -439,7 +472,11 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
439
472
  let plaintext: string
440
473
  try {
441
474
  plaintext = await decryptPayload(
442
- wallet, meta.protocolID, meta.topic, meta.backendIdentityKey, envelope.ciphertext,
475
+ wallet,
476
+ meta.protocolID,
477
+ meta.topic,
478
+ meta.backendIdentityKey,
479
+ envelope.ciphertext
443
480
  )
444
481
  } catch (err) {
445
482
  console.warn('[WalletConnection] decryptPayload failed:', err)
@@ -447,9 +484,8 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
447
484
  }
448
485
 
449
486
  const msg = JSON.parse(plaintext) as RpcRequest | RpcResponse
450
- const sequence = msg !== null && typeof msg === 'object' && !Array.isArray(msg)
451
- ? (msg as { seq?: unknown }).seq
452
- : undefined
487
+ const sequence =
488
+ msg !== null && typeof msg === 'object' && !Array.isArray(msg) ? (msg as { seq?: unknown }).seq : undefined
453
489
  if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence <= lastSeqRef.current) {
454
490
  console.warn('[WalletConnection] dropping message: seq', sequence, '<= lastSeq', lastSeqRef.current)
455
491
  return
@@ -502,8 +538,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
502
538
  }
503
539
 
504
540
  if ('method' in msg && msg.method === 'pairing_ack') return
505
- if ('method' in msg && typeof msg.method === 'string' &&
506
- typeof msg.id === 'string' && msg.id.length > 0 && msg.id.length <= 128) {
541
+ if (
542
+ 'method' in msg &&
543
+ typeof msg.method === 'string' &&
544
+ typeof msg.id === 'string' &&
545
+ msg.id.length > 0 &&
546
+ msg.id.length <= 128
547
+ ) {
507
548
  await handleRpc(msg as RpcRequest, meta, ws, wallet)
508
549
  }
509
550
  } catch {
@@ -545,8 +586,14 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
545
586
  }
546
587
  wsRef.current = null
547
588
  lastSeqRef.current = 0
548
- if (navTimerRef.current) { clearTimeout(navTimerRef.current); navTimerRef.current = null }
549
- if (appStateTimerRef.current) { clearTimeout(appStateTimerRef.current); appStateTimerRef.current = null }
589
+ if (navTimerRef.current) {
590
+ clearTimeout(navTimerRef.current)
591
+ navTimerRef.current = null
592
+ }
593
+ if (appStateTimerRef.current) {
594
+ clearTimeout(appStateTimerRef.current)
595
+ appStateTimerRef.current = null
596
+ }
550
597
  setSessionMeta(null)
551
598
  // Don't override the 'idle' status that disconnect() already set
552
599
  if (!wasIntentional) {
@@ -563,169 +610,204 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
563
610
 
564
611
  // ── connect (fresh pairing) ───────────────────────────────────────────────
565
612
 
566
- const connect = useCallback(async (params: ConnectParams, wallet: WalletClient) => {
567
- setStatus('connecting')
568
- setErrorMsg(null)
613
+ const connect = useCallback(
614
+ async (params: ConnectParams, wallet: WalletClient) => {
615
+ setStatus('connecting')
616
+ setErrorMsg(null)
569
617
 
570
- let relay: string
571
- let validated: ReturnType<typeof validateConnectParams>
572
- try {
573
- // This provider is a public embedding boundary. Validate every field here
574
- // even when a host screen already parsed the QR.
575
- validated = validateConnectParams(params)
576
- // Verify QR signature before trusting the origin or opening any connection
577
- await verifyQrSignature(validated.params)
578
-
579
- // Fetch relay URL from origin over HTTPS — TLS cert is the trust anchor
580
- relay = await fetchRelay(validated.external.origin, validated.params.topic)
581
- } catch (err) {
582
- setErrorMsg(err instanceof Error ? err.message : 'Connection failed')
583
- setStatus('error')
584
- throw err
585
- }
586
-
587
- const protocolID = validated.protocolID
588
- const identityResult = await wallet.getPublicKey({ identityKey: true })
589
- const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
590
-
591
- // XR-018: tear down any live socket for a DIFFERENT prior session before
592
- // wiring this one — see supersedeExistingSocket for why. myGeneration is
593
- // allocated right after, so this connection's onopen AND wireSocket's
594
- // handlers all guard against the same supersede event.
595
- supersedeExistingSocket()
596
- const myGeneration = ++connectionGenerationRef.current
618
+ let relay: string
619
+ let validated: ReturnType<typeof validateConnectParams>
620
+ try {
621
+ // This provider is a public embedding boundary. Validate every field here
622
+ // even when a host screen already parsed the QR.
623
+ validated = validateConnectParams(params)
624
+ // Verify QR signature before trusting the origin or opening any connection
625
+ await verifyQrSignature(validated.params)
626
+
627
+ // Fetch relay URL from origin over HTTPS — TLS cert is the trust anchor
628
+ relay = await fetchRelay(validated.external.origin, validated.params.topic)
629
+ } catch (err) {
630
+ setErrorMsg(err instanceof Error ? err.message : 'Connection failed')
631
+ setStatus('error')
632
+ throw err
633
+ }
597
634
 
598
- const meta: SessionMeta = {
599
- topic: validated.params.topic, origin: validated.external.origin, relay,
600
- backendIdentityKey: validated.params.backendIdentityKey, mobileIdentityKey,
601
- protocolID,
602
- }
603
- setSessionMeta(meta)
635
+ const protocolID = validated.protocolID
636
+ const identityResult = await wallet.getPublicKey({ identityKey: true })
637
+ const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
638
+
639
+ // XR-018: tear down any live socket for a DIFFERENT prior session before
640
+ // wiring this one — see supersedeExistingSocket for why. myGeneration is
641
+ // allocated right after, so this connection's onopen AND wireSocket's
642
+ // handlers all guard against the same supersede event.
643
+ supersedeExistingSocket()
644
+ const myGeneration = ++connectionGenerationRef.current
645
+
646
+ const meta: SessionMeta = {
647
+ topic: validated.params.topic,
648
+ origin: validated.external.origin,
649
+ relay,
650
+ backendIdentityKey: validated.params.backendIdentityKey,
651
+ mobileIdentityKey,
652
+ protocolID
653
+ }
654
+ setSessionMeta(meta)
604
655
 
605
- const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.params.topic))
656
+ const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.params.topic))
606
657
 
607
- ws.onopen = async () => {
608
- // XR-018: this connection attempt may already have been superseded by
609
- // a later connect()/reconnect()/disconnect() while relay/verify above
610
- // were in flight — a stale send here must not touch the new session's
611
- // state, and must not fire on an already-detached socket.
612
- if (connectionGenerationRef.current !== myGeneration) return
613
- try {
614
- const payload = JSON.stringify({
615
- id: crypto.randomUUID(), seq: 1, method: 'pairing_approved',
616
- params: {
617
- mobileIdentityKey,
618
- protocolID: validated.params.protocolID,
619
- walletMeta: { name: walletName, platform: 'mobile' },
620
- permissions: Array.from(IMPLEMENTED_METHODS),
621
- },
622
- })
623
- const ciphertext = await encryptPayload(
624
- wallet, protocolID, validated.params.topic, validated.params.backendIdentityKey, payload
625
- )
626
- if (connectionGenerationRef.current !== myGeneration) return
627
- ws.send(JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope))
628
- } catch {
658
+ ws.onopen = async () => {
659
+ // XR-018: this connection attempt may already have been superseded by
660
+ // a later connect()/reconnect()/disconnect() while relay/verify above
661
+ // were in flight — a stale send here must not touch the new session's
662
+ // state, and must not fire on an already-detached socket.
629
663
  if (connectionGenerationRef.current !== myGeneration) return
630
- setErrorMsg('Failed to send pairing message')
631
- setStatus('error')
664
+ try {
665
+ const payload = JSON.stringify({
666
+ id: crypto.randomUUID(),
667
+ seq: 1,
668
+ method: 'pairing_approved',
669
+ params: {
670
+ mobileIdentityKey,
671
+ protocolID: validated.params.protocolID,
672
+ walletMeta: { name: walletName, platform: 'mobile' },
673
+ permissions: Array.from(IMPLEMENTED_METHODS)
674
+ }
675
+ })
676
+ const ciphertext = await encryptPayload(
677
+ wallet,
678
+ protocolID,
679
+ validated.params.topic,
680
+ validated.params.backendIdentityKey,
681
+ payload
682
+ )
683
+ if (connectionGenerationRef.current !== myGeneration) return
684
+ ws.send(
685
+ JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope)
686
+ )
687
+ } catch {
688
+ if (connectionGenerationRef.current !== myGeneration) return
689
+ setErrorMsg('Failed to send pairing message')
690
+ setStatus('error')
691
+ }
632
692
  }
633
- }
634
693
 
635
- wireSocket(ws, wallet, meta, 0, myGeneration, () => {
636
- connectionStore.add({
637
- sessionId: validated.params.topic, origin: validated.external.origin, relay,
638
- backendIdentityKey: validated.params.backendIdentityKey, mobileIdentityKey,
639
- protocolID: validated.params.protocolID,
640
- connectedAt: Date.now(), status: 'active',
694
+ wireSocket(ws, wallet, meta, 0, myGeneration, () => {
695
+ connectionStore.add({
696
+ sessionId: validated.params.topic,
697
+ origin: validated.external.origin,
698
+ relay,
699
+ backendIdentityKey: validated.params.backendIdentityKey,
700
+ mobileIdentityKey,
701
+ protocolID: validated.params.protocolID,
702
+ connectedAt: Date.now(),
703
+ status: 'active'
704
+ })
705
+ setStatus('connected')
641
706
  })
642
- setStatus('connected')
643
- })
644
- }, [walletName, supersedeExistingSocket]) // eslint-disable-line react-hooks/exhaustive-deps
707
+ },
708
+ [walletName, supersedeExistingSocket]
709
+ ) // eslint-disable-line react-hooks/exhaustive-deps
645
710
 
646
711
  // ── reconnect (resume from stored session) ────────────────────────────────
647
712
 
648
- const reconnect = useCallback(async (connection: Connection, wallet: WalletClient) => {
649
- setStatus('connecting')
650
- setErrorMsg(null)
651
-
652
- // Stored connection data is untrusted after import or database tampering.
653
- const validated = validateStoredConnectionFields(connection)
654
- const identityResult = await wallet.getPublicKey({ identityKey: true })
655
- const currentMobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
656
- if (currentMobileIdentityKey !== validated.mobileIdentityKey) {
657
- throw new Error('Stored connection belongs to a different wallet identity')
658
- }
659
- // Fetch relay URL from origin over HTTPS — relay may have moved since last connection
660
- const relay = await fetchRelay(validated.external.origin, validated.topic)
661
-
662
- const protocolID = validated.protocolID
663
- const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
664
- const initialSeq = validateStoredConnectionSequence(storedSeq)
665
-
666
- // XR-018: tear down any live socket for a DIFFERENT prior session before
667
- // wiring this one — see supersedeExistingSocket for why. myGeneration is
668
- // allocated right after, so this connection's onopen AND wireSocket's
669
- // handlers all guard against the same supersede event.
670
- supersedeExistingSocket()
671
- const myGeneration = ++connectionGenerationRef.current
672
-
673
- const meta: SessionMeta = {
674
- topic: validated.topic, origin: validated.external.origin, relay,
675
- backendIdentityKey: validated.backendIdentityKey,
676
- mobileIdentityKey: validated.mobileIdentityKey,
677
- protocolID,
678
- }
679
- setSessionMeta(meta)
713
+ const reconnect = useCallback(
714
+ async (connection: Connection, wallet: WalletClient) => {
715
+ setStatus('connecting')
716
+ setErrorMsg(null)
717
+
718
+ // Stored connection data is untrusted after import or database tampering.
719
+ const validated = validateStoredConnectionFields(connection)
720
+ const identityResult = await wallet.getPublicKey({ identityKey: true })
721
+ const currentMobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
722
+ if (currentMobileIdentityKey !== validated.mobileIdentityKey) {
723
+ throw new Error('Stored connection belongs to a different wallet identity')
724
+ }
725
+ // Fetch relay URL from origin over HTTPS — relay may have moved since last connection
726
+ const relay = await fetchRelay(validated.external.origin, validated.topic)
727
+
728
+ const protocolID = validated.protocolID
729
+ const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
730
+ const initialSeq = validateStoredConnectionSequence(storedSeq)
731
+
732
+ // XR-018: tear down any live socket for a DIFFERENT prior session before
733
+ // wiring this one — see supersedeExistingSocket for why. myGeneration is
734
+ // allocated right after, so this connection's onopen AND wireSocket's
735
+ // handlers all guard against the same supersede event.
736
+ supersedeExistingSocket()
737
+ const myGeneration = ++connectionGenerationRef.current
738
+
739
+ const meta: SessionMeta = {
740
+ topic: validated.topic,
741
+ origin: validated.external.origin,
742
+ relay,
743
+ backendIdentityKey: validated.backendIdentityKey,
744
+ mobileIdentityKey: validated.mobileIdentityKey,
745
+ protocolID
746
+ }
747
+ setSessionMeta(meta)
680
748
 
681
- const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.topic))
749
+ const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.topic))
682
750
 
683
- ws.onopen = async () => {
684
- // XR-018: see the identical guard in connect()'s onopen.
685
- if (connectionGenerationRef.current !== myGeneration) return
686
- try {
687
- const payload = JSON.stringify({
688
- id: crypto.randomUUID(), seq: initialSeq + 1, method: 'pairing_approved',
689
- params: {
690
- mobileIdentityKey: validated.mobileIdentityKey,
691
- protocolID: validated.protocolIDRaw,
692
- walletMeta: { name: walletName, platform: 'mobile' },
693
- permissions: Array.from(IMPLEMENTED_METHODS),
694
- },
695
- })
696
- const ciphertext = await encryptPayload(
697
- wallet, protocolID, validated.topic, validated.backendIdentityKey, payload,
698
- )
751
+ ws.onopen = async () => {
752
+ // XR-018: see the identical guard in connect()'s onopen.
699
753
  if (connectionGenerationRef.current !== myGeneration) return
700
- ws.send(JSON.stringify({
701
- topic: validated.topic,
702
- mobileIdentityKey: validated.mobileIdentityKey,
703
- ciphertext,
704
- } satisfies WireEnvelope))
705
- } catch {
706
- if (connectionGenerationRef.current !== myGeneration) return
707
- setErrorMsg('Failed to send reconnect message')
708
- setStatus('error')
754
+ try {
755
+ const payload = JSON.stringify({
756
+ id: crypto.randomUUID(),
757
+ seq: initialSeq + 1,
758
+ method: 'pairing_approved',
759
+ params: {
760
+ mobileIdentityKey: validated.mobileIdentityKey,
761
+ protocolID: validated.protocolIDRaw,
762
+ walletMeta: { name: walletName, platform: 'mobile' },
763
+ permissions: Array.from(IMPLEMENTED_METHODS)
764
+ }
765
+ })
766
+ const ciphertext = await encryptPayload(
767
+ wallet,
768
+ protocolID,
769
+ validated.topic,
770
+ validated.backendIdentityKey,
771
+ payload
772
+ )
773
+ if (connectionGenerationRef.current !== myGeneration) return
774
+ ws.send(
775
+ JSON.stringify({
776
+ topic: validated.topic,
777
+ mobileIdentityKey: validated.mobileIdentityKey,
778
+ ciphertext
779
+ } satisfies WireEnvelope)
780
+ )
781
+ } catch {
782
+ if (connectionGenerationRef.current !== myGeneration) return
783
+ setErrorMsg('Failed to send reconnect message')
784
+ setStatus('error')
785
+ }
709
786
  }
710
- }
711
787
 
712
- wireSocket(ws, wallet, meta, initialSeq, myGeneration, () => {
713
- connectionStore.setStatus(validated.topic, 'active')
714
- setStatus('connected')
715
- })
716
- }, [walletName, supersedeExistingSocket]) // eslint-disable-line react-hooks/exhaustive-deps
788
+ wireSocket(ws, wallet, meta, initialSeq, myGeneration, () => {
789
+ connectionStore.setStatus(validated.topic, 'active')
790
+ setStatus('connected')
791
+ })
792
+ },
793
+ [walletName, supersedeExistingSocket]
794
+ ) // eslint-disable-line react-hooks/exhaustive-deps
717
795
 
718
796
  // ── Provider ──────────────────────────────────────────────────────────────
719
797
 
720
- const value = useMemo<WalletConnectionContextValue>(() => ({
721
- status, sessionMeta, errorMsg,
722
- connect, reconnect, disconnect,
723
- startNavTimer, cancelNavTimer,
724
- }), [status, sessionMeta, errorMsg, connect, reconnect, disconnect, startNavTimer, cancelNavTimer])
725
-
726
- return (
727
- <WalletConnectionContext.Provider value={value}>
728
- {children}
729
- </WalletConnectionContext.Provider>
798
+ const value = useMemo<WalletConnectionContextValue>(
799
+ () => ({
800
+ status,
801
+ sessionMeta,
802
+ errorMsg,
803
+ connect,
804
+ reconnect,
805
+ disconnect,
806
+ startNavTimer,
807
+ cancelNavTimer
808
+ }),
809
+ [status, sessionMeta, errorMsg, connect, reconnect, disconnect, startNavTimer, cancelNavTimer]
730
810
  )
811
+
812
+ return <WalletConnectionContext.Provider value={value}>{children}</WalletConnectionContext.Provider>
731
813
  }