@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,153 @@
1
+ /**
2
+ * A contact's activity: every interaction with one counterparty, every asset,
3
+ * both directions (Deggen ruling, 2026-09-17 design review).
4
+ *
5
+ * Three sources, merged and sorted by time, newest first:
6
+ *
7
+ * 1. Outbound BSV/peer sends — EXACT, via the label the handle and nearby
8
+ * rails both write on a sent action (`labels: ['peerpay'|'localpay', recipientKey]`).
9
+ * 2. Everything else a plain label filter can't reach (inbound payments,
10
+ * which carry the sender only on the output's `senderIdentityKey`, never
11
+ * as a label) — read from the most recent `RECENT_WINDOW` actions and
12
+ * matched client-side with `counterpartyOf()`. This is a bounded recent
13
+ * window, not full history: an old inbound payment outside it will not
14
+ * surface here. Documented limitation (see the 2026-09-18 spec) rather
15
+ * than a silent one.
16
+ * 3. Token transfers — EXACT, via `token_settlements.counterpartyKey`
17
+ * (`idx_token_settlements_counterpartyKey`).
18
+ *
19
+ * The address rail is never attributable to a contact (no key in its label)
20
+ * and is excluded here the same way it is everywhere else in the app.
21
+ */
22
+ import { counterpartyOf } from '../pay/counterparty'
23
+
24
+ /** The recent-window size for source (2) above. */
25
+ export const RECENT_WINDOW = 200
26
+
27
+ /** The slice of a wallet action this module reads. Matches what
28
+ * `listActionsSql` actually builds (see storage/methods/listActionsSql.ts). */
29
+ export interface ContactBsvAction {
30
+ txid?: string
31
+ satoshis: number
32
+ status: string
33
+ isOutgoing?: boolean
34
+ description?: string
35
+ labels?: string[]
36
+ senderIdentityKey?: string
37
+ created_at?: string | number
38
+ }
39
+
40
+ export interface ContactActivityWallet {
41
+ listActions(
42
+ args: { labels?: string[]; labelQueryMode?: 'any' | 'all'; limit?: number; includeLabels?: boolean },
43
+ originator?: string
44
+ ): Promise<{ actions: ContactBsvAction[] }>
45
+ }
46
+
47
+ /** The slice of `token_settlements` this module reads. */
48
+ export interface ContactSettlementRow {
49
+ txid: string
50
+ role: 'sent' | 'received'
51
+ assetId: string
52
+ state: string
53
+ counterpartyKey?: string
54
+ amountBaseUnits?: number
55
+ createdAt: string
56
+ }
57
+
58
+ export interface ContactSettlementsDb {
59
+ getAllAsync(sql: string, params: (string | number | null)[]): Promise<unknown[]>
60
+ }
61
+
62
+ export type ContactActivityItem = ({ kind: 'bsv' } & ContactBsvAction) | ({ kind: 'token' } & ContactSettlementRow)
63
+
64
+ function timeOf(item: ContactActivityItem): number {
65
+ const raw = item.kind === 'bsv' ? item.created_at : item.createdAt
66
+ if (raw === undefined || raw === null) return 0
67
+ const ts = new Date(raw as string).getTime()
68
+ return Number.isNaN(ts) ? 0 : ts
69
+ }
70
+
71
+ /** Token transfers with this counterparty. Exported separately so it can be
72
+ * unit-tested against a real in-memory SQLite (see `mandala/settlementStore.ts`'s
73
+ * own test pattern) without a wallet in the loop. */
74
+ export async function listTokenSettlementsByCounterparty(
75
+ db: ContactSettlementsDb,
76
+ counterpartyKey: string
77
+ ): Promise<ContactSettlementRow[]> {
78
+ const rows = (await db.getAllAsync(
79
+ 'SELECT txid, role, assetId, state, counterpartyKey, amountBaseUnits, createdAt FROM token_settlements WHERE counterpartyKey = ? ORDER BY createdAt DESC',
80
+ [counterpartyKey]
81
+ )) as {
82
+ txid: string
83
+ role: string
84
+ assetId: string
85
+ state: string
86
+ counterpartyKey: string | null
87
+ amountBaseUnits: number | null
88
+ createdAt: string
89
+ }[]
90
+ return rows.map(r => ({
91
+ txid: r.txid,
92
+ role: r.role as 'sent' | 'received',
93
+ assetId: r.assetId,
94
+ state: r.state,
95
+ counterpartyKey: r.counterpartyKey ?? undefined,
96
+ amountBaseUnits: r.amountBaseUnits ?? undefined,
97
+ createdAt: r.createdAt
98
+ }))
99
+ }
100
+
101
+ /**
102
+ * Every activity item with `identityKey`, merged and sorted newest first.
103
+ *
104
+ * `wallet` and `settlementsDb` are both optional so a caller that only has
105
+ * one half built (e.g. a token-less wallet) still gets what it can — same
106
+ * fail-open posture as `resolveIdentity.ts`.
107
+ */
108
+ export async function getContactActivity(args: {
109
+ wallet?: ContactActivityWallet
110
+ adminOriginator?: string
111
+ settlementsDb?: ContactSettlementsDb
112
+ identityKey: string
113
+ }): Promise<ContactActivityItem[]> {
114
+ const { wallet, adminOriginator, settlementsDb, identityKey } = args
115
+ const items: ContactActivityItem[] = []
116
+
117
+ if (wallet) {
118
+ try {
119
+ const outbound = await wallet.listActions(
120
+ { labels: [identityKey], labelQueryMode: 'any', limit: 500, includeLabels: true },
121
+ adminOriginator
122
+ )
123
+ const recent = await wallet.listActions({ limit: RECENT_WINDOW, includeLabels: true }, adminOriginator)
124
+ const seen = new Set<string>()
125
+ for (const action of [...outbound.actions, ...recent.actions]) {
126
+ const cp = counterpartyOf({
127
+ labels: action.labels,
128
+ senderIdentityKey: action.senderIdentityKey,
129
+ txid: action.txid
130
+ })
131
+ if (!cp || cp.kind !== 'identityKey' || cp.value !== identityKey) continue
132
+ const key = action.txid ?? `${action.description ?? ''}:${action.created_at ?? ''}`
133
+ if (seen.has(key)) continue
134
+ seen.add(key)
135
+ items.push({ kind: 'bsv', ...action })
136
+ }
137
+ } catch {
138
+ // Best-effort, same posture as resolveIdentity: a read failure here
139
+ // must not blank a screen that also shows token activity below.
140
+ }
141
+ }
142
+
143
+ if (settlementsDb) {
144
+ try {
145
+ const settlements = await listTokenSettlementsByCounterparty(settlementsDb, identityKey)
146
+ for (const row of settlements) items.push({ kind: 'token', ...row })
147
+ } catch {
148
+ // Same posture as above.
149
+ }
150
+ }
151
+
152
+ return items.sort((a, b) => timeOf(b) - timeOf(a))
153
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What a background refresh should write to a contact's cache columns.
3
+ *
4
+ * `refreshContactCache` replaces all three in one UPDATE — that is what keeps
5
+ * it a single statement and keeps `name` untouchable — so a caller that names
6
+ * only the avatar silently blanks the handle stored beside it. This decides
7
+ * the COMPLETE row instead, from what the contact already had and what this
8
+ * pass actually learned.
9
+ *
10
+ * An absent learned value means "not looked up this time" and keeps what is
11
+ * there; an EMPTY one means "looked, and there is none" and clears it. That
12
+ * distinction is the whole reason this is a function and not a spread: a
13
+ * registry 404 has to be able to remove a handle the contact no longer holds.
14
+ */
15
+ export interface ContactCache {
16
+ cachedHandle?: string
17
+ cachedAvatarUrl?: string
18
+ cachedCertifier?: string
19
+ }
20
+
21
+ function pick(current: string | undefined, learned: string | undefined): string | undefined {
22
+ if (learned === undefined) return current
23
+ return learned === '' ? undefined : learned
24
+ }
25
+
26
+ /** The row to write, or null when this pass learned nothing new. */
27
+ export function mergeContactCache(
28
+ current: ContactCache,
29
+ learned: { cachedHandle?: string; cachedAvatarUrl?: string }
30
+ ): ContactCache | null {
31
+ const merged: ContactCache = {
32
+ cachedHandle: pick(current.cachedHandle, learned.cachedHandle),
33
+ cachedAvatarUrl: pick(current.cachedAvatarUrl, learned.cachedAvatarUrl),
34
+ cachedCertifier: current.cachedCertifier
35
+ }
36
+ const unchanged =
37
+ merged.cachedHandle === current.cachedHandle &&
38
+ merged.cachedAvatarUrl === current.cachedAvatarUrl &&
39
+ merged.cachedCertifier === current.cachedCertifier
40
+ return unchanged ? null : merged
41
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * `ContactsStore` over the toolbox's own SQLite connection.
3
+ *
4
+ * Deliberately logic-free, same spirit as `mandala/settlementStore.ts`: every
5
+ * decision (what counts as a match, how activity is aggregated) lives in the
6
+ * callers of this module. What is here is statements.
7
+ *
8
+ * `name` is the one column this store treats as sacred: it is the user's own
9
+ * label for the counterparty, and no method here ever overwrites it except
10
+ * `renameContact`, which exists for exactly that. A background identity
11
+ * refresh calls `refreshContactCache` instead, which never touches `name`.
12
+ *
13
+ * Access pattern matches `settlementStore.ts`: the caller hands in
14
+ * `storage.sqliteDb` and this module only ever issues parameterised statements
15
+ * against it.
16
+ */
17
+
18
+ /** Everything these statements bind. */
19
+ export type ContactsBindValue = string | number | null
20
+
21
+ /** Structurally satisfied by expo-sqlite's `SQLiteDatabase` and by the
22
+ * `node:sqlite` adapter the tests use. */
23
+ export interface ContactsDb {
24
+ runAsync(sql: string, params: ContactsBindValue[]): Promise<{ changes: number }>
25
+ getAllAsync(sql: string, params: ContactsBindValue[]): Promise<unknown[]>
26
+ getFirstAsync(sql: string, params: ContactsBindValue[]): Promise<unknown>
27
+ }
28
+
29
+ /** How a contact entered the address book. */
30
+ export type ContactSource = 'manual' | 'qr' | 'pay' | 'search'
31
+
32
+ export interface ContactRow {
33
+ contactId: number
34
+ userId: number
35
+ identityKey: string
36
+ /** The user's own label. Never overwritten by a cache refresh. */
37
+ name: string
38
+ cachedHandle?: string
39
+ cachedAvatarUrl?: string
40
+ cachedCertifier?: string
41
+ source: ContactSource
42
+ createdAt: string
43
+ updatedAt: string
44
+ }
45
+
46
+ interface ContactDbRow {
47
+ contactId: number
48
+ userId: number
49
+ identityKey: string
50
+ name: string
51
+ cachedHandle: string | null
52
+ cachedAvatarUrl: string | null
53
+ cachedCertifier: string | null
54
+ source: string
55
+ created_at: string
56
+ updated_at: string
57
+ }
58
+
59
+ function toContact(row: ContactDbRow): ContactRow {
60
+ return {
61
+ contactId: row.contactId,
62
+ userId: row.userId,
63
+ identityKey: row.identityKey,
64
+ name: row.name,
65
+ cachedHandle: row.cachedHandle ?? undefined,
66
+ cachedAvatarUrl: row.cachedAvatarUrl ?? undefined,
67
+ cachedCertifier: row.cachedCertifier ?? undefined,
68
+ source: row.source as ContactSource,
69
+ createdAt: row.created_at,
70
+ updatedAt: row.updated_at
71
+ }
72
+ }
73
+
74
+ export interface ContactsStore {
75
+ listContacts(userId: number): Promise<ContactRow[]>
76
+ /** Case-insensitive substring match on `name` and `cachedHandle`. Forgiving,
77
+ * not scored — "fuzzy" in the design sense, not a ranked fuzzy algorithm. */
78
+ searchContacts(userId: number, query: string): Promise<ContactRow[]>
79
+ getContact(userId: number, identityKey: string): Promise<ContactRow | undefined>
80
+ /** Throws on a duplicate (userId, identityKey) — callers check `getContact` first when they need "already a contact" as a non-throwing fact. */
81
+ createContact(args: {
82
+ userId: number
83
+ identityKey: string
84
+ name: string
85
+ cachedHandle?: string
86
+ cachedAvatarUrl?: string
87
+ cachedCertifier?: string
88
+ source: ContactSource
89
+ }): Promise<ContactRow>
90
+ /** The user's own edit. The only method that may change `name`. */
91
+ renameContact(userId: number, identityKey: string, name: string): Promise<void>
92
+ /** A background identity refresh. Never touches `name`. */
93
+ refreshContactCache(
94
+ userId: number,
95
+ identityKey: string,
96
+ cache: { cachedHandle?: string; cachedAvatarUrl?: string; cachedCertifier?: string }
97
+ ): Promise<void>
98
+ deleteContact(userId: number, identityKey: string): Promise<void>
99
+ }
100
+
101
+ export function createContactsStore(db: ContactsDb): ContactsStore {
102
+ return {
103
+ async listContacts(userId) {
104
+ const rows = (await db.getAllAsync('SELECT * FROM contacts WHERE userId = ? ORDER BY name COLLATE NOCASE ASC', [
105
+ userId
106
+ ])) as ContactDbRow[]
107
+ return rows.map(toContact)
108
+ },
109
+
110
+ async searchContacts(userId, query) {
111
+ const needle = `%${query.trim().toLowerCase()}%`
112
+ if (query.trim() === '') return createContactsStore(db).listContacts(userId)
113
+ const rows = (await db.getAllAsync(
114
+ `SELECT * FROM contacts
115
+ WHERE userId = ?
116
+ AND (lower(name) LIKE ? OR lower(coalesce(cachedHandle, '')) LIKE ?)
117
+ ORDER BY name COLLATE NOCASE ASC`,
118
+ [userId, needle, needle]
119
+ )) as ContactDbRow[]
120
+ return rows.map(toContact)
121
+ },
122
+
123
+ async getContact(userId, identityKey) {
124
+ const row = (await db.getFirstAsync('SELECT * FROM contacts WHERE userId = ? AND identityKey = ?', [
125
+ userId,
126
+ identityKey
127
+ ])) as ContactDbRow | null
128
+ return row ? toContact(row) : undefined
129
+ },
130
+
131
+ async createContact(args) {
132
+ const now = new Date().toISOString()
133
+ await db.runAsync(
134
+ `INSERT INTO contacts
135
+ (created_at, updated_at, userId, identityKey, name, cachedHandle, cachedAvatarUrl, cachedCertifier, source)
136
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
137
+ [
138
+ now,
139
+ now,
140
+ args.userId,
141
+ args.identityKey,
142
+ args.name,
143
+ args.cachedHandle ?? null,
144
+ args.cachedAvatarUrl ?? null,
145
+ args.cachedCertifier ?? null,
146
+ args.source
147
+ ]
148
+ )
149
+ const created = await createContactsStore(db).getContact(args.userId, args.identityKey)
150
+ if (!created) throw new Error('contacts: insert did not persist')
151
+ return created
152
+ },
153
+
154
+ async renameContact(userId, identityKey, name) {
155
+ await db.runAsync('UPDATE contacts SET name = ?, updated_at = ? WHERE userId = ? AND identityKey = ?', [
156
+ name,
157
+ new Date().toISOString(),
158
+ userId,
159
+ identityKey
160
+ ])
161
+ },
162
+
163
+ async refreshContactCache(userId, identityKey, cache) {
164
+ await db.runAsync(
165
+ `UPDATE contacts
166
+ SET cachedHandle = ?, cachedAvatarUrl = ?, cachedCertifier = ?, updated_at = ?
167
+ WHERE userId = ? AND identityKey = ?`,
168
+ [
169
+ cache.cachedHandle ?? null,
170
+ cache.cachedAvatarUrl ?? null,
171
+ cache.cachedCertifier ?? null,
172
+ new Date().toISOString(),
173
+ userId,
174
+ identityKey
175
+ ]
176
+ )
177
+ },
178
+
179
+ async deleteContact(userId, identityKey) {
180
+ await db.runAsync('DELETE FROM contacts WHERE userId = ? AND identityKey = ?', [userId, identityKey])
181
+ }
182
+ }
183
+ }
@@ -1,10 +1,8 @@
1
1
  import { ReactNode, createContext, useEffect, useState } from 'react'
2
- import AsyncStorage from '@react-native-async-storage/async-storage'
3
2
  import { fallbackUsdToFiat } from '../displayCurrencies'
4
3
  import { loadUsdFxRates } from '../services/usdFxRates'
4
+ import { FALLBACK_RATE, getExchangeRate } from '../services/exchangeRate'
5
5
 
6
- const CACHE_KEY = 'cached_exchange_rate'
7
- const HARDCODED_USD_PER_BSV = 16
8
6
  const SATS_PER_BSV = 100_000_000
9
7
 
10
8
  interface ExchangeRateState {
@@ -12,8 +10,11 @@ interface ExchangeRateState {
12
10
  usdToFiat: Record<string, number>
13
11
  }
14
12
 
13
+ // Was its own hardcoded 16, disagreeing with exchangeRate.ts's 16.75 fallback
14
+ // (misc-p2-05) — both now read the ONE fallback constant, so the fiat-display
15
+ // UI and the wallet-build seed can never quote a different "no data yet" rate.
15
16
  const defaultState: ExchangeRateState = {
16
- satoshisPerUSD: SATS_PER_BSV / HARDCODED_USD_PER_BSV,
17
+ satoshisPerUSD: SATS_PER_BSV / FALLBACK_RATE,
17
18
  usdToFiat: fallbackUsdToFiat()
18
19
  }
19
20
 
@@ -27,39 +28,45 @@ export const ExchangeRateContextProvider: React.FC<{
27
28
 
28
29
  useEffect(() => {
29
30
  const init = async () => {
30
- // Tier 2: Try loading cached rate from AsyncStorage
31
+ // exchangeRate.ts owns the single timeout-guarded fetch, the single
32
+ // fallback constant, and the shared AsyncStorage cache key — this used
33
+ // to be a second, independent fetch/cache/fallback implementation that
34
+ // could (and did) disagree with it. getExchangeRate() reads the cache
35
+ // (or falls back) and kicks off its own background refresh for next
36
+ // time; it never hangs, so no separate timeout is needed here.
37
+ let refreshed: Promise<number | undefined> | undefined
31
38
  try {
32
- const cached = await AsyncStorage.getItem(CACHE_KEY)
33
- if (cached) {
34
- const { usdPerBsv } = JSON.parse(cached)
35
- if (typeof usdPerBsv === 'number' && usdPerBsv > 0) {
36
- setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / usdPerBsv }))
37
- }
39
+ const seed = await getExchangeRate()
40
+ refreshed = seed.refreshed
41
+ if (typeof seed.rate === 'number' && seed.rate > 0) {
42
+ setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / seed.rate }))
38
43
  }
39
44
  } catch (error) {
40
- console.error('Error loading cached exchange rate:', error)
45
+ console.error('Error loading exchange rate:', error)
41
46
  }
42
47
 
43
- const fxPromise = loadUsdFxRates()
44
- .then(usdToFiat => setState(prev => ({ ...prev, usdToFiat })))
45
- .catch(error => console.error('Error loading USD FX rates:', error))
46
-
47
- // Tier 1: Attempt live fetch from WhatsonChain
48
+ // The cached/fallback rate above is shown immediately; this is the SAME
49
+ // background refresh, not a second fetch. It used to be fire-and-forget
50
+ // from this screen's point of view — its result only ever reached the
51
+ // UI on the NEXT cold start, so a session that opened stale stayed
52
+ // stale until it was closed and reopened. `refreshed` never rejects
53
+ // (exchangeRate.ts's own contract), so this only ever raises the rate
54
+ // to a freshly fetched one, never drops it back to the fallback.
48
55
  try {
49
- const response = await fetch('https://api.whatsonchain.com/v1/bsv/main/exchangerate')
50
- const data = await response.json()
51
- const usdPerBsv = data?.rate
52
- if (typeof usdPerBsv === 'number' && usdPerBsv > 0) {
53
- setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / usdPerBsv }))
54
- // Cache the successful result
55
- await AsyncStorage.setItem(CACHE_KEY, JSON.stringify({ usdPerBsv, timestamp: new Date().toISOString() }))
56
+ const live = await refreshed
57
+ if (typeof live === 'number' && live > 0) {
58
+ setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / live }))
56
59
  }
57
60
  } catch (error) {
58
- console.error('Error fetching exchange rate from WhatsonChain:', error)
59
- // Tier 2/3 already loaded above -- state remains as cached or hardcoded default
61
+ console.error('Error applying the refreshed exchange rate:', error)
60
62
  }
61
63
 
62
- await fxPromise
64
+ try {
65
+ const usdToFiat = await loadUsdFxRates()
66
+ setState(prev => ({ ...prev, usdToFiat }))
67
+ } catch (error) {
68
+ console.error('Error loading USD FX rates:', error)
69
+ }
63
70
  }
64
71
 
65
72
  init()
@@ -1,12 +1,4 @@
1
- import React, {
2
- createContext,
3
- useCallback,
4
- useContext,
5
- useEffect,
6
- useMemo,
7
- useRef,
8
- useState
9
- } from 'react'
1
+ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
10
2
  import AsyncStorage from '@react-native-async-storage/async-storage'
11
3
  import i18n from '../i18n/translations'
12
4
  import {
@@ -52,7 +44,11 @@ export interface LocalStorageContextType {
52
44
  setRecoveredKey: (wif: string) => Promise<boolean>
53
45
  getRecoveredKey: () => Promise<string | null>
54
46
  deleteRecoveredKey: () => Promise<void>
55
- deleteAllWalletKeys: () => Promise<void>
47
+ /** Returns whether every legacy plaintext item was verified erased (XR-107).
48
+ * The caller MUST NOT treat "Delete Wallet" as complete when this is
49
+ * false — a persistent SecureStore delete failure means a legacy
50
+ * mnemonic/recoveredKey/password may still be readable on this device. */
51
+ deleteAllWalletKeys: () => Promise<boolean>
56
52
  /** Prompt-free existence check (mnemonic or recovered key) — no biometric,
57
53
  * no wallet build. For UI gating that must never wait on the wallet build,
58
54
  * e.g. "is there already a wallet on this device" before offering import. */
@@ -82,7 +78,8 @@ export const LocalStorageContext = createContext<LocalStorageContextType>({
82
78
  setRecoveredKey: async () => false,
83
79
  getRecoveredKey: async () => null,
84
80
  deleteRecoveredKey: async () => {},
85
- deleteAllWalletKeys: async () => {},
81
+ // Fail-closed default: outside a real provider, nothing was verified erased.
82
+ deleteAllWalletKeys: async () => false,
86
83
  hasStoredIdentity: async () => false,
87
84
 
88
85
  /* unlock */
@@ -134,10 +131,7 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
134
131
 
135
132
  /* --------------------------------- unlock -------------------------------- */
136
133
 
137
- const unlock = useCallback(
138
- () => unlockKek(i18n.t('biometric_unlock_wallet')),
139
- []
140
- )
134
+ const unlock = useCallback(() => unlockKek(i18n.t('biometric_unlock_wallet')), [])
141
135
 
142
136
  /**
143
137
  * The single implicit ceremony. Called on the read path so the returning
@@ -153,13 +147,16 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
153
147
 
154
148
  /* -------------------------------- secure --------------------------------- */
155
149
 
156
- const setMnemonic = useCallback(
157
- (mnemonic: string) => putSecret('mnemonic', mnemonic),
158
- []
159
- )
150
+ const setMnemonic = useCallback((mnemonic: string) => putSecret('mnemonic', mnemonic), [])
160
151
 
152
+ // XR-112: a failed migration must never hand back the legacy plaintext —
153
+ // that would let anyone who just declines/fails the biometric ceremony read
154
+ // a fully signing-capable secret with no authentication at all. A failed
155
+ // migration also never committed an envelope, so hasSecret() below already
156
+ // reports false for this state; retry happens on the next launch, when
157
+ // migration runs again.
161
158
  const getMnemonic = useCallback(async (): Promise<string | null> => {
162
- if (legacyFallback.current) return readLegacySecret('mnemonic')
159
+ if (legacyFallback.current) return null
163
160
  if (!(await hasSecret('mnemonic'))) return null
164
161
  if (!(await ensureUnlocked())) return null
165
162
  return getSecret('mnemonic')
@@ -167,13 +164,10 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
167
164
 
168
165
  const deleteMnemonic = useCallback(() => deleteSecret('mnemonic'), [])
169
166
 
170
- const setRecoveredKey = useCallback(
171
- (wif: string) => putSecret('recoveredKey', wif),
172
- []
173
- )
167
+ const setRecoveredKey = useCallback((wif: string) => putSecret('recoveredKey', wif), [])
174
168
 
175
169
  const getRecoveredKey = useCallback(async (): Promise<string | null> => {
176
- if (legacyFallback.current) return readLegacySecret('recoveredKey')
170
+ if (legacyFallback.current) return null
177
171
  if (!(await hasSecret('recoveredKey'))) return null
178
172
  if (!(await ensureUnlocked())) return null
179
173
  return getSecret('recoveredKey')
@@ -183,28 +177,37 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
183
177
 
184
178
  /** Wipes the secrets and the key protecting them, so the next launch reads as
185
179
  * a clean install instead of prompting for a wallet that no longer exists.
186
- * Works while locked or lost — deleting ciphertext needs no key. */
180
+ * Works while locked or lost — deleting ciphertext needs no key.
181
+ *
182
+ * Returns whether the legacy plaintext namespace was verified erased —
183
+ * see deleteAllSecrets (XR-107). The caller must check this before treating
184
+ * "Delete Wallet" as complete. */
187
185
  const deleteAllWalletKeys = useCallback(() => deleteAllSecrets(), [])
188
186
 
189
187
  const hasStoredIdentity = useCallback(async (): Promise<boolean> => {
190
- return (await hasAnySecret({ strict: true })) ||
188
+ return (
189
+ (await hasAnySecret({ strict: true })) ||
191
190
  (await readLegacySecret('mnemonic', { strict: true })) != null ||
192
191
  (await readLegacySecret('recoveredKey', { strict: true })) != null
192
+ )
193
193
  }, [])
194
194
 
195
- const createMnemonic = useCallback(async (mnemonic: string): Promise<boolean> => {
196
- // A failed migration cannot establish that storage is safely empty.
197
- if (!secretsReadyRef.current || legacyFallback.current || creatingMnemonic) return false
198
- creatingMnemonic = true
199
- try {
200
- if (await hasStoredIdentity()) return false
201
- // The provider may have unmounted while checking storage.
202
- if (!secretsReadyRef.current) return false
203
- return await putSecret('mnemonic', mnemonic)
204
- } finally {
205
- creatingMnemonic = false
206
- }
207
- }, [hasStoredIdentity])
195
+ const createMnemonic = useCallback(
196
+ async (mnemonic: string): Promise<boolean> => {
197
+ // A failed migration cannot establish that storage is safely empty.
198
+ if (!secretsReadyRef.current || legacyFallback.current || creatingMnemonic) return false
199
+ creatingMnemonic = true
200
+ try {
201
+ if (await hasStoredIdentity()) return false
202
+ // The provider may have unmounted while checking storage.
203
+ if (!secretsReadyRef.current) return false
204
+ return await putSecret('mnemonic', mnemonic)
205
+ } finally {
206
+ creatingMnemonic = false
207
+ }
208
+ },
209
+ [hasStoredIdentity]
210
+ )
208
211
 
209
212
  /* -------------------------------- output --------------------------------- */
210
213
 
@@ -5,11 +5,11 @@ export interface NativeHandlers {
5
5
  isFocused: () => Promise<boolean>
6
6
  onFocusRequested: () => Promise<void>
7
7
  onFocusRelinquished: () => Promise<void>
8
- onDownloadFile: (fileData: Blob, fileName: string) => Promise<boolean>
8
+ onDownloadFile?: (fileData: Blob, fileName: string) => Promise<boolean>
9
9
  }
10
10
 
11
11
  // Default no-op implementations for Tauri functions
12
- const defaultNativeHandlers: NativeHandlers = {
12
+ const defaultNativeHandlers: Required<NativeHandlers> = {
13
13
  isFocused: async () => false,
14
14
  onFocusRequested: async () => {},
15
15
  onFocusRelinquished: async () => {},
@@ -40,6 +40,14 @@ const defaultNativeHandlers: NativeHandlers = {
40
40
  }
41
41
  }
42
42
 
43
+ // Merges a host-supplied (possibly partial) NativeHandlers object over the
44
+ // defaults, per field, so omitting any single handler (e.g. onDownloadFile)
45
+ // falls back to its no-op/default implementation instead of leaving it
46
+ // undefined.
47
+ export function mergeNativeHandlers(partial?: Partial<NativeHandlers>): Required<NativeHandlers> {
48
+ return { ...defaultNativeHandlers, ...partial }
49
+ }
50
+
43
51
  // -----
44
52
  // UserContextProps Component Props
45
53
  // -----
@@ -83,7 +91,7 @@ export const UserContextProvider: React.FC<UserContextProps> = ({
83
91
  appVersion = 'unknown',
84
92
  appName = 'App',
85
93
  children,
86
- nativeHandlers = defaultNativeHandlers
94
+ nativeHandlers
87
95
  }) => {
88
96
  const [basketAccessModalOpen, setBasketAccessModalOpen] = useState(false)
89
97
  const [certificateAccessModalOpen, setCertificateAccessModalOpen] = useState(false)
@@ -92,12 +100,14 @@ export const UserContextProvider: React.FC<UserContextProps> = ({
92
100
  const [btmsAccessModalOpen, setBtmsAccessModalOpen] = useState(false)
93
101
  const [pageLoaded, setPageLoaded] = useState(false)
94
102
 
103
+ const handlers = useMemo(() => mergeNativeHandlers(nativeHandlers), [nativeHandlers])
104
+
95
105
  const userContext = useMemo(
96
106
  () => ({
97
- isFocused: nativeHandlers.isFocused,
98
- onFocusRequested: nativeHandlers.onFocusRequested,
99
- onFocusRelinquished: nativeHandlers.onFocusRelinquished,
100
- onDownloadFile: nativeHandlers.onDownloadFile,
107
+ isFocused: handlers.isFocused,
108
+ onFocusRequested: handlers.onFocusRequested,
109
+ onFocusRelinquished: handlers.onFocusRelinquished,
110
+ onDownloadFile: handlers.onDownloadFile,
101
111
  appVersion,
102
112
  appName,
103
113
  basketAccessModalOpen,
@@ -114,6 +124,7 @@ export const UserContextProvider: React.FC<UserContextProps> = ({
114
124
  setPageLoaded
115
125
  }),
116
126
  [
127
+ handlers,
117
128
  appVersion,
118
129
  appName,
119
130
  basketAccessModalOpen,