@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,831 @@
1
+ import React, { useCallback, useEffect, useMemo, useState } from 'react'
2
+ import {
3
+ View,
4
+ Text,
5
+ StyleSheet,
6
+ ScrollView,
7
+ TextInput,
8
+ TouchableOpacity,
9
+ Image,
10
+ Modal,
11
+ ActivityIndicator
12
+ } from 'react-native'
13
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
14
+ import { useTranslation } from 'react-i18next'
15
+ import validateTrust from '../validateTrust'
16
+ import { GroupedSection } from '../components/ui/GroupedList'
17
+ import { showAlert } from '../components/ui/AlertCard'
18
+ import { haptics, useTheme, spacing, radii, typography, useWallet } from '@bsv/expo-wallet-toolbox'
19
+
20
+ /**
21
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
22
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
23
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
24
+ * Ionicons is loaded lazily, only when actually rendering, same pattern as
25
+ * this package's other native-module-boundary fixes (expo-router, expo-blur).
26
+ */
27
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
28
+ let ioniconsComponent: IoniconsComponent | undefined
29
+ function loadIonicons(): IoniconsComponent {
30
+ if (!ioniconsComponent) {
31
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
32
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
33
+ }
34
+ return ioniconsComponent
35
+ }
36
+
37
+ /**
38
+ * expo-router is required lazily rather than imported at module scope: this
39
+ * file is barrel-exported from the package's `ui` entry point, and a static
40
+ * top-level `import` of expo-router pulls in its own untransformed JSX
41
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
42
+ * barrel, even one that never navigates. Same pattern as this package's other
43
+ * lazy expo-router loads (WalletHomeScreen.tsx, VaultScreen.tsx, etc.).
44
+ */
45
+ type ExpoRouterModule = typeof import('expo-router')
46
+ let expoRouterMod: ExpoRouterModule | undefined
47
+ function loadExpoRouter(): ExpoRouterModule {
48
+ if (!expoRouterMod) {
49
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
50
+ expoRouterMod = require('expo-router') as ExpoRouterModule
51
+ }
52
+ return expoRouterMod
53
+ }
54
+
55
+ // -------------------- Types --------------------
56
+ export type Certifier = {
57
+ name: string
58
+ description: string
59
+ icon?: string
60
+ identityKey: string
61
+ trust: number // 1..10
62
+ }
63
+
64
+ // -------------------- Helpers --------------------
65
+ const maskKey = (k: string) => (k?.length > 16 ? `${k.slice(0, 8)}...${k.slice(-8)}` : k)
66
+
67
+ const assignTrust = (certifiers: Certifier[]): Certifier[] =>
68
+ certifiers.map((c, i) => ({ ...c, trust: i < 9 ? 10 - i : 1 }))
69
+
70
+ const orderChanged = (a: Certifier[], b: Certifier[]): boolean => {
71
+ if (a.length !== b.length) return true
72
+ for (let i = 0; i < a.length; i++) {
73
+ if (a[i].identityKey !== b[i].identityKey) return true
74
+ }
75
+ return false
76
+ }
77
+
78
+ const fetchWithTimeout = async (url: string, ms: number) => {
79
+ const controller = new AbortController()
80
+ const id = setTimeout(() => controller.abort(), ms)
81
+ try {
82
+ const res = await fetch(url, { signal: controller.signal })
83
+ return res
84
+ } finally {
85
+ clearTimeout(id)
86
+ }
87
+ }
88
+
89
+ // -------------------- Main Screen --------------------
90
+ export function TrustScreen() {
91
+ const { t } = useTranslation()
92
+ const { colors } = useTheme()
93
+ const insets = useSafeAreaInsets()
94
+ const { router } = loadExpoRouter()
95
+ const Ionicons = loadIonicons()
96
+
97
+ const { settings, updateSettings } = useWallet()
98
+
99
+ // Source of truth from Settings — sort by trust descending so position matches priority
100
+ const initialTrusted: Certifier[] = useMemo(
101
+ () => [...(settings?.trustSettings?.trustedCertifiers || [])].sort((a, b) => b.trust - a.trust),
102
+ [settings?.trustSettings?.trustedCertifiers]
103
+ )
104
+
105
+ // Local working state
106
+ const [trustedEntities, setTrustedEntities] = useState<Certifier[]>(initialTrusted)
107
+ const [query, setQuery] = useState('')
108
+ const [saving, setSaving] = useState(false)
109
+ const [snack, setSnack] = useState<string | null>(null)
110
+ const [showAdd, setShowAdd] = useState(false)
111
+
112
+ // Detect unsaved changes — compare identity key arrays in order
113
+ const settingsNeedsUpdate = orderChanged(initialTrusted, trustedEntities)
114
+
115
+ // Save to settings
116
+ const handleSave = useCallback(async (): Promise<boolean> => {
117
+ try {
118
+ setSaving(true)
119
+ await updateSettings(
120
+ JSON.parse(
121
+ JSON.stringify({
122
+ ...settings,
123
+ trustSettings: {
124
+ trustLevel: 1,
125
+ trustedCertifiers: assignTrust(trustedEntities)
126
+ }
127
+ })
128
+ )
129
+ )
130
+ setSnack(t('trust_updated'))
131
+ return true
132
+ } catch (e: any) {
133
+ setSnack(e?.message || t('failed_to_save'))
134
+ return false
135
+ } finally {
136
+ setSaving(false)
137
+ }
138
+ }, [updateSettings, settings, trustedEntities, t])
139
+
140
+ // Search
141
+ const filtered = useMemo(() => {
142
+ if (!query.trim()) return trustedEntities
143
+ const q = query.toLowerCase()
144
+ return trustedEntities.filter(
145
+ e => e.name.toLowerCase().includes(q) || e.description?.toLowerCase?.().includes(q)
146
+ )
147
+ }, [trustedEntities, query])
148
+
149
+ const isSearching = query.trim().length > 0
150
+
151
+ const onMoveUp = (identityKey: string) => {
152
+ haptics.tap()
153
+ setTrustedEntities(prev => {
154
+ const idx = prev.findIndex(c => c.identityKey === identityKey)
155
+ if (idx <= 0) return prev
156
+ const next = [...prev]
157
+ ;[next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]
158
+ return next
159
+ })
160
+ }
161
+
162
+ const onMoveDown = (identityKey: string) => {
163
+ haptics.tap()
164
+ setTrustedEntities(prev => {
165
+ const idx = prev.findIndex(c => c.identityKey === identityKey)
166
+ if (idx < 0 || idx >= prev.length - 1) return prev
167
+ const next = [...prev]
168
+ ;[next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]
169
+ return next
170
+ })
171
+ }
172
+
173
+ const onRemove = async (identityKey: string) => {
174
+ const choice = await showAlert({
175
+ title: t('confirm_delete'),
176
+ message: t('confirm_delete_body'),
177
+ buttons: [
178
+ { text: t('cancel'), style: 'cancel', key: 'cancel' },
179
+ { text: t('delete'), style: 'destructive', key: 'delete' },
180
+ ],
181
+ })
182
+ if (choice !== 'delete') return
183
+ setTrustedEntities(prev => prev.filter(c => c.identityKey !== identityKey))
184
+ }
185
+
186
+ return (
187
+ <View style={{ flex: 1, backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }}>
188
+ {/* Header */}
189
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
190
+ <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
191
+ <Ionicons name="chevron-back" size={24} color={colors.textSecondary} />
192
+ </TouchableOpacity>
193
+ <Text style={[styles.headerTitle, { color: colors.textPrimary }]}>{t('trust_network')}</Text>
194
+ <View style={styles.backButton} />
195
+ </View>
196
+ <ScrollView
197
+ style={{ flex: 1 }}
198
+ contentContainerStyle={{
199
+ paddingTop: spacing.lg,
200
+ paddingBottom: settingsNeedsUpdate ? 80 : spacing.xxxl
201
+ }}
202
+ keyboardShouldPersistTaps="handled"
203
+ >
204
+ {/* Description */}
205
+ <Text style={[styles.description, { color: colors.textSecondary }]}>
206
+ {t('order_certifiers_hint')}
207
+ </Text>
208
+
209
+ {/* ── Certifiers ── */}
210
+ <GroupedSection header={t('certifiers')}>
211
+ {/* Search bar */}
212
+ <View style={[styles.searchRow, { borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.separator }]}>
213
+ <Ionicons name="search" size={16} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
214
+ <TextInput
215
+ style={[styles.searchInput, { color: colors.textPrimary }]}
216
+ placeholder={t('search')}
217
+ placeholderTextColor={colors.textSecondary}
218
+ value={query}
219
+ onChangeText={setQuery}
220
+ />
221
+ </View>
222
+
223
+ {filtered.length === 0 ? (
224
+ <View style={styles.emptyBox}>
225
+ <Text style={[styles.emptyText, { color: colors.textSecondary }]}>{t('no_certifiers')}</Text>
226
+ </View>
227
+ ) : (
228
+ filtered.map((item, idx) => {
229
+ // Find real index in full list for proper up/down logic
230
+ const realIdx = trustedEntities.findIndex(c => c.identityKey === item.identityKey)
231
+ const isFirst = realIdx === 0
232
+ const isLast = realIdx === trustedEntities.length - 1
233
+
234
+ return (
235
+ <View
236
+ key={item.identityKey}
237
+ style={[
238
+ styles.certifierCard,
239
+ idx < filtered.length - 1 && { borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.separator }
240
+ ]}
241
+ >
242
+ <View style={styles.certifierHeader}>
243
+ {item.icon ? (
244
+ <Image source={{ uri: item.icon }} style={styles.certifierIcon} />
245
+ ) : (
246
+ <View style={[styles.certifierIconPlaceholder, { backgroundColor: colors.accent }]}>
247
+ <Text style={{ color: colors.background, fontWeight: '700' }}>{item.name?.[0] || '?'}</Text>
248
+ </View>
249
+ )}
250
+ <View style={{ flex: 1 }}>
251
+ <Text style={[styles.certifierName, { color: colors.textPrimary }]} numberOfLines={1}>
252
+ {item.name}
253
+ </Text>
254
+ <Text style={[styles.certifierDesc, { color: colors.textSecondary }]} numberOfLines={2}>
255
+ {item.description}
256
+ </Text>
257
+ </View>
258
+ <View style={styles.actions}>
259
+ {!isFirst && !isSearching && (
260
+ <TouchableOpacity onPress={() => onMoveUp(item.identityKey)} style={styles.actionBtn}>
261
+ <Ionicons name="chevron-up" size={18} color={colors.textSecondary} />
262
+ </TouchableOpacity>
263
+ )}
264
+ {!isLast && !isSearching && (
265
+ <TouchableOpacity onPress={() => onMoveDown(item.identityKey)} style={styles.actionBtn}>
266
+ <Ionicons name="chevron-down" size={18} color={colors.textSecondary} />
267
+ </TouchableOpacity>
268
+ )}
269
+ <TouchableOpacity onPress={() => onRemove(item.identityKey)} style={styles.actionBtn}>
270
+ <Ionicons name="close" size={18} color={colors.error} />
271
+ </TouchableOpacity>
272
+ </View>
273
+ </View>
274
+ </View>
275
+ )
276
+ })
277
+ )}
278
+
279
+ {/* Add Provider button */}
280
+ <TouchableOpacity
281
+ style={[styles.addProviderBtn, { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.separator }]}
282
+ onPress={() => setShowAdd(true)}
283
+ >
284
+ <Ionicons name="add" size={18} color={colors.accent} style={{ marginRight: spacing.sm }} />
285
+ <Text style={[styles.addProviderText, { color: colors.accent }]}>{t('add_provider')}</Text>
286
+ </TouchableOpacity>
287
+ </GroupedSection>
288
+ </ScrollView>
289
+
290
+ {/* Save bar */}
291
+ {settingsNeedsUpdate && (
292
+ <View style={[styles.saveBar, { backgroundColor: colors.backgroundElevated, borderTopColor: colors.separator }]}>
293
+ <Text style={[styles.saveBarText, { color: colors.textSecondary }]}>{t('unsaved_changes')}</Text>
294
+ <TouchableOpacity
295
+ onPress={handleSave}
296
+ disabled={saving}
297
+ style={[styles.saveBtn, { backgroundColor: colors.accent, opacity: saving ? 0.6 : 1 }]}
298
+ >
299
+ {saving ? (
300
+ <ActivityIndicator size="small" color={colors.background} />
301
+ ) : (
302
+ <Text style={[styles.saveBtnText, { color: colors.background }]}>{t('save')}</Text>
303
+ )}
304
+ </TouchableOpacity>
305
+ </View>
306
+ )}
307
+
308
+ {/* Snackbar */}
309
+ {snack && (
310
+ <TouchableOpacity
311
+ activeOpacity={0.9}
312
+ onPress={() => setSnack(null)}
313
+ style={[styles.snack, { backgroundColor: colors.backgroundElevated, borderColor: colors.separator }]}
314
+ >
315
+ <Text style={{ color: colors.textPrimary }}>{snack}</Text>
316
+ </TouchableOpacity>
317
+ )}
318
+
319
+ {/* Add Provider Modal */}
320
+ <AddProviderModal
321
+ visible={showAdd}
322
+ onClose={() => setShowAdd(false)}
323
+ onAdd={(c) => {
324
+ if (trustedEntities.some(x => x.identityKey === c.identityKey)) {
325
+ setSnack(t('duplicate_key_error'))
326
+ return
327
+ }
328
+ setTrustedEntities(prev => [...prev, { ...c, trust: 1 }])
329
+ setShowAdd(false)
330
+ }}
331
+ colors={colors}
332
+ />
333
+ </View>
334
+ )
335
+ }
336
+
337
+ // -------------------- Add Provider Modal --------------------
338
+ function AddProviderModal({
339
+ visible,
340
+ onClose,
341
+ onAdd,
342
+ colors
343
+ }: {
344
+ visible: boolean
345
+ onClose: () => void
346
+ onAdd: (c: Omit<Certifier, 'trust'>) => void
347
+ colors: any
348
+ }) {
349
+ const { t } = useTranslation()
350
+ const Ionicons = loadIonicons()
351
+ const [advanced, setAdvanced] = useState(false)
352
+ const [domain, setDomain] = useState('')
353
+ const [name, setName] = useState('')
354
+ const [description, setDescription] = useState('')
355
+ const [icon, setIcon] = useState('')
356
+ const [identityKey, setIdentityKey] = useState('')
357
+ const [loading, setLoading] = useState(false)
358
+ const [fieldsValid, setFieldsValid] = useState(false)
359
+
360
+ const [domainError, setDomainError] = useState<string | null>(null)
361
+ const [nameError, setNameError] = useState<string | null>(null)
362
+ const [iconError, setIconError] = useState<string | null>(null)
363
+ const [keyError, setKeyError] = useState<string | null>(null)
364
+
365
+ useEffect(() => {
366
+ if (!visible) {
367
+ setAdvanced(false)
368
+ setDomain('')
369
+ setName('')
370
+ setDescription('')
371
+ setIcon('')
372
+ setIdentityKey('')
373
+ setFieldsValid(false)
374
+ setDomainError(null)
375
+ setNameError(null)
376
+ setIconError(null)
377
+ setKeyError(null)
378
+ }
379
+ }, [visible])
380
+
381
+ const handleDomainSubmit = async () => {
382
+ try {
383
+ if (!domain) return
384
+ setLoading(true)
385
+ setDomainError(null)
386
+ const url = domain.startsWith('http') ? `${domain}/manifest.json` : `https://${domain}/manifest.json`
387
+ let res: Response
388
+ try {
389
+ res = await fetchWithTimeout(url, 15000)
390
+ } catch (e: any) {
391
+ if (e?.name === 'AbortError') throw new Error('The domain did not respond within 15 seconds')
392
+ throw new Error('Could not fetch the trust data from that domain (it needs to follow the BRC-68 protocol)')
393
+ }
394
+ if (!res.ok) throw new Error('Failed to fetch trust manifest from that domain')
395
+ const json = await res.json()
396
+ const trust = json?.babbage?.trust
397
+ if (!json?.babbage || !trust || typeof trust !== 'object') {
398
+ throw new Error('This domain does not support importing a trust relationship (it needs to follow the BRC-68 protocol)')
399
+ }
400
+ await validateTrust(trust)
401
+ setName(trust.name)
402
+ setDescription(trust.note)
403
+ setIcon(trust.icon)
404
+ setIdentityKey(trust.publicKey)
405
+ setFieldsValid(true)
406
+ } catch (e: any) {
407
+ setFieldsValid(false)
408
+ setDomainError(e?.message || 'Failed to import trust relationship')
409
+ } finally {
410
+ setLoading(false)
411
+ }
412
+ }
413
+
414
+ const handleDirectValidate = async () => {
415
+ try {
416
+ setLoading(true)
417
+ setNameError(null)
418
+ setIconError(null)
419
+ setKeyError(null)
420
+ await validateTrust({ name, icon, publicKey: identityKey }, { skipNote: true })
421
+ setDescription(name)
422
+ setFieldsValid(true)
423
+ } catch (e: any) {
424
+ setFieldsValid(false)
425
+ if (e?.field === 'name') setNameError(e.message)
426
+ else if (e?.field === 'icon') setIconError(e.message)
427
+ else setKeyError(e?.message || 'Invalid public key')
428
+ } finally {
429
+ setLoading(false)
430
+ }
431
+ }
432
+
433
+ const descriptionInvalid = !description || description.length < 5 || description.length > 50
434
+
435
+ const ready = fieldsValid && !descriptionInvalid
436
+
437
+ return (
438
+ <Modal visible={visible} animationType="slide" transparent onRequestClose={onClose}>
439
+ <View style={styles.modalOverlay}>
440
+ <View style={[styles.modalCard, { backgroundColor: colors.backgroundElevated, borderColor: colors.separator }]}>
441
+ <View style={[styles.modalHeader]}>
442
+ <Text style={[styles.modalTitle, { color: colors.textPrimary }]}>{t('add_provider')}</Text>
443
+ <TouchableOpacity onPress={onClose}>
444
+ <Ionicons name="close" size={20} color={colors.textSecondary} />
445
+ </TouchableOpacity>
446
+ </View>
447
+
448
+ {!advanced ? (
449
+ <>
450
+ <Text style={[styles.modalDesc, { color: colors.textSecondary }]}>Enter the domain name for the provider you&apos;d like to add.</Text>
451
+ <View style={[styles.inputRow, { borderColor: colors.separator, backgroundColor: colors.fillTertiary }]}>
452
+ <Ionicons name="globe-outline" size={16} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
453
+ <TextInput
454
+ placeholder="trustedentity.com"
455
+ placeholderTextColor={colors.textSecondary}
456
+ value={domain}
457
+ onChangeText={t => {
458
+ setDomain(t)
459
+ setDomainError(null)
460
+ setFieldsValid(false)
461
+ }}
462
+ style={[styles.textInput, { color: colors.textPrimary }]}
463
+ autoCapitalize="none"
464
+ autoCorrect={false}
465
+ />
466
+ </View>
467
+ {!!domainError && <Text style={[styles.err, { color: colors.error }]}>{domainError}</Text>}
468
+ {loading ? (
469
+ <ActivityIndicator style={{ marginTop: spacing.md }} />
470
+ ) : (
471
+ <TouchableOpacity onPress={handleDomainSubmit} style={[styles.primaryBtn, { backgroundColor: colors.accent }]}>
472
+ <Ionicons name="document-text-outline" size={16} color={colors.background} />
473
+ <Text style={[styles.primaryBtnText, { color: colors.background }]}>{t('get_provider_details')}</Text>
474
+ </TouchableOpacity>
475
+ )}
476
+ </>
477
+ ) : (
478
+ <>
479
+ <Text style={[styles.modalDesc, { color: colors.textSecondary }]}>Directly enter the details for the provider you&apos;d like to add.</Text>
480
+
481
+ {/* Name */}
482
+ <View style={[styles.inputRow, { borderColor: colors.separator, backgroundColor: colors.fillTertiary }]}>
483
+ <Ionicons name="person-outline" size={16} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
484
+ <TextInput
485
+ placeholder="Entity Name"
486
+ placeholderTextColor={colors.textSecondary}
487
+ value={name}
488
+ onChangeText={t => {
489
+ setName(t)
490
+ setNameError(null)
491
+ setFieldsValid(false)
492
+ }}
493
+ style={[styles.textInput, { color: colors.textPrimary }]}
494
+ />
495
+ </View>
496
+ {!!nameError && <Text style={[styles.err, { color: colors.error }]}>{nameError}</Text>}
497
+
498
+ {/* Icon */}
499
+ <View style={[styles.inputRow, { borderColor: colors.separator, backgroundColor: colors.fillTertiary }]}>
500
+ <Ionicons name="image-outline" size={16} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
501
+ <TextInput
502
+ placeholder="https://trustedentity.com/icon.png"
503
+ placeholderTextColor={colors.textSecondary}
504
+ value={icon}
505
+ onChangeText={t => {
506
+ setIcon(t)
507
+ setIconError(null)
508
+ setFieldsValid(false)
509
+ }}
510
+ style={[styles.textInput, { color: colors.textPrimary }]}
511
+ autoCapitalize="none"
512
+ autoCorrect={false}
513
+ />
514
+ </View>
515
+ {!!iconError && <Text style={[styles.err, { color: colors.error }]}>{iconError}</Text>}
516
+
517
+ {/* Public key */}
518
+ <View style={[styles.inputRow, { borderColor: colors.separator, backgroundColor: colors.fillTertiary }]}>
519
+ <Ionicons name="key-outline" size={16} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
520
+ <TextInput
521
+ placeholder="0295bf1c7842d14b..."
522
+ placeholderTextColor={colors.textSecondary}
523
+ value={identityKey}
524
+ onChangeText={t => {
525
+ setIdentityKey(t)
526
+ setKeyError(null)
527
+ setFieldsValid(false)
528
+ }}
529
+ style={[styles.textInput, { color: colors.textPrimary }]}
530
+ autoCapitalize="none"
531
+ autoCorrect={false}
532
+ />
533
+ </View>
534
+ {!!keyError && <Text style={[styles.err, { color: colors.error }]}>{keyError}</Text>}
535
+
536
+ {loading ? (
537
+ <ActivityIndicator style={{ marginTop: spacing.md }} />
538
+ ) : (
539
+ <TouchableOpacity onPress={handleDirectValidate} style={[styles.primaryBtn, { backgroundColor: colors.accent }]}>
540
+ <Ionicons name="shield-checkmark-outline" size={16} color={colors.background} />
541
+ <Text style={[styles.primaryBtnText, { color: colors.background }]}>{t('validate_details')}</Text>
542
+ </TouchableOpacity>
543
+ )}
544
+ </>
545
+ )}
546
+
547
+ {/* Toggle advanced */}
548
+ <TouchableOpacity onPress={() => setAdvanced(v => !v)} style={styles.advancedBtn}>
549
+ <Ionicons name={advanced ? 'chevron-up-outline' : 'chevron-down-outline'} size={16} color={colors.textPrimary} />
550
+ <Text style={{ marginLeft: spacing.xs, color: colors.textPrimary }}>{advanced ? t('hide_advanced') : t('show_advanced')}</Text>
551
+ </TouchableOpacity>
552
+
553
+ {/* Preview + description edit */}
554
+ {fieldsValid && (
555
+ <View style={[styles.previewBox, { borderColor: colors.separator, backgroundColor: colors.fillTertiary }]}>
556
+ <View style={{ flexDirection: 'row', alignItems: 'center' }}>
557
+ {icon ? (
558
+ <Image source={{ uri: icon }} style={styles.previewIcon} />
559
+ ) : (
560
+ <View style={[styles.previewIcon, { backgroundColor: colors.accent, justifyContent: 'center', alignItems: 'center' }]}>
561
+ <Text style={{ color: colors.background, fontWeight: '700' }}>{name?.[0] || '?'}</Text>
562
+ </View>
563
+ )}
564
+ <View style={{ marginLeft: spacing.md, flex: 1 }}>
565
+ <Text style={{ fontWeight: '700', color: colors.textPrimary }}>{name}</Text>
566
+ <Text style={[styles.previewKey, { color: colors.textSecondary }]}>{maskKey(identityKey)}</Text>
567
+ </View>
568
+ </View>
569
+
570
+ <View style={[styles.inputRow, { marginTop: spacing.md, borderColor: colors.separator, backgroundColor: colors.fillTertiary }]}>
571
+ <Ionicons name="pricetag-outline" size={16} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
572
+ <TextInput
573
+ placeholder="Description"
574
+ placeholderTextColor={colors.textSecondary}
575
+ value={description}
576
+ onChangeText={setDescription}
577
+ style={[styles.textInput, { color: colors.textPrimary }]}
578
+ />
579
+ </View>
580
+ {descriptionInvalid && (
581
+ <Text style={[styles.err, { color: colors.error }]}>{t('description_length_error')}</Text>
582
+ )}
583
+ </View>
584
+ )}
585
+
586
+ {/* Footer Actions */}
587
+ <View style={styles.modalActions}>
588
+ <TouchableOpacity onPress={onClose} style={[styles.secondaryBtn, { borderColor: colors.separator }]}>
589
+ <Text style={{ color: colors.textPrimary }}>{t('cancel')}</Text>
590
+ </TouchableOpacity>
591
+ <TouchableOpacity
592
+ disabled={!ready}
593
+ onPress={() => onAdd({ name, description, icon, identityKey })}
594
+ style={[styles.saveBtn, { backgroundColor: colors.accent, opacity: ready ? 1 : 0.5, flex: 0 }]}
595
+ >
596
+ <Ionicons name="shield-checkmark-outline" size={16} color={colors.background} />
597
+ <Text style={[styles.saveBtnText, { color: colors.background }]}>Add</Text>
598
+ </TouchableOpacity>
599
+ </View>
600
+ </View>
601
+ </View>
602
+ </Modal>
603
+ )
604
+ }
605
+
606
+ // -------------------- Styles --------------------
607
+ const styles = StyleSheet.create({
608
+ header: {
609
+ flexDirection: 'row',
610
+ alignItems: 'center',
611
+ justifyContent: 'space-between',
612
+ paddingHorizontal: spacing.sm,
613
+ paddingVertical: spacing.md,
614
+ borderBottomWidth: StyleSheet.hairlineWidth,
615
+ },
616
+ backButton: {
617
+ width: 44,
618
+ height: 44,
619
+ alignItems: 'center',
620
+ justifyContent: 'center',
621
+ },
622
+ headerTitle: {
623
+ ...typography.headline,
624
+ },
625
+ description: {
626
+ ...typography.footnote,
627
+ paddingHorizontal: spacing.xl,
628
+ paddingBottom: spacing.lg,
629
+ },
630
+
631
+ // Search
632
+ searchRow: {
633
+ flexDirection: 'row',
634
+ alignItems: 'center',
635
+ paddingHorizontal: spacing.lg,
636
+ paddingVertical: spacing.md,
637
+ },
638
+ searchInput: {
639
+ flex: 1,
640
+ ...typography.body,
641
+ padding: 0,
642
+ },
643
+
644
+ // Certifier cards
645
+ certifierCard: {
646
+ paddingHorizontal: spacing.lg,
647
+ paddingVertical: spacing.md,
648
+ },
649
+ certifierHeader: {
650
+ flexDirection: 'row',
651
+ alignItems: 'center',
652
+ },
653
+ certifierIcon: {
654
+ width: 40,
655
+ height: 40,
656
+ borderRadius: radii.md,
657
+ marginRight: spacing.md,
658
+ },
659
+ certifierIconPlaceholder: {
660
+ width: 40,
661
+ height: 40,
662
+ borderRadius: radii.md,
663
+ marginRight: spacing.md,
664
+ justifyContent: 'center',
665
+ alignItems: 'center',
666
+ },
667
+ certifierName: {
668
+ ...typography.body,
669
+ fontWeight: '700',
670
+ },
671
+ certifierDesc: {
672
+ ...typography.footnote,
673
+ marginTop: spacing.xs,
674
+ },
675
+ actions: {
676
+ flexDirection: 'row',
677
+ alignItems: 'center',
678
+ marginLeft: spacing.sm,
679
+ },
680
+ actionBtn: {
681
+ padding: spacing.xs,
682
+ },
683
+ emptyBox: {
684
+ alignItems: 'center',
685
+ paddingVertical: spacing.xxl,
686
+ },
687
+ emptyText: {
688
+ ...typography.subhead,
689
+ },
690
+
691
+ // Add provider button
692
+ addProviderBtn: {
693
+ flexDirection: 'row',
694
+ alignItems: 'center',
695
+ justifyContent: 'center',
696
+ paddingVertical: spacing.md,
697
+ },
698
+ addProviderText: {
699
+ ...typography.body,
700
+ fontWeight: '600',
701
+ },
702
+
703
+ // Save bar
704
+ saveBar: {
705
+ borderTopWidth: 1,
706
+ paddingHorizontal: spacing.lg,
707
+ paddingVertical: spacing.md,
708
+ flexDirection: 'row',
709
+ alignItems: 'center',
710
+ justifyContent: 'space-between',
711
+ },
712
+ saveBarText: {
713
+ ...typography.subhead,
714
+ },
715
+ saveBtn: {
716
+ paddingHorizontal: spacing.lg,
717
+ paddingVertical: spacing.md,
718
+ borderRadius: radii.sm,
719
+ flexDirection: 'row',
720
+ alignItems: 'center',
721
+ justifyContent: 'center',
722
+ gap: spacing.xs,
723
+ },
724
+ saveBtnText: {
725
+ ...typography.subhead,
726
+ fontWeight: '700',
727
+ },
728
+
729
+ // Snackbar
730
+ snack: {
731
+ margin: spacing.lg,
732
+ marginTop: spacing.sm,
733
+ borderRadius: radii.sm,
734
+ borderWidth: 1,
735
+ padding: spacing.md,
736
+ alignItems: 'center',
737
+ },
738
+
739
+ // Modal
740
+ modalOverlay: {
741
+ flex: 1,
742
+ backgroundColor: 'rgba(0,0,0,0.5)',
743
+ justifyContent: 'center',
744
+ padding: spacing.lg,
745
+ },
746
+ modalCard: {
747
+ borderWidth: 1,
748
+ borderRadius: radii.md,
749
+ padding: spacing.lg,
750
+ },
751
+ modalHeader: {
752
+ flexDirection: 'row',
753
+ justifyContent: 'space-between',
754
+ alignItems: 'center',
755
+ marginBottom: spacing.md,
756
+ },
757
+ modalTitle: {
758
+ ...typography.headline,
759
+ fontWeight: '700',
760
+ },
761
+ modalDesc: {
762
+ ...typography.subhead,
763
+ marginBottom: spacing.sm,
764
+ },
765
+ inputRow: {
766
+ flexDirection: 'row',
767
+ alignItems: 'center',
768
+ borderWidth: 1,
769
+ borderRadius: radii.sm,
770
+ paddingHorizontal: spacing.md,
771
+ height: 40,
772
+ marginTop: spacing.sm,
773
+ },
774
+ textInput: {
775
+ flex: 1,
776
+ ...typography.subhead,
777
+ padding: 0,
778
+ },
779
+ primaryBtn: {
780
+ marginTop: spacing.md,
781
+ height: 44,
782
+ borderRadius: radii.sm,
783
+ flexDirection: 'row',
784
+ alignItems: 'center',
785
+ justifyContent: 'center',
786
+ },
787
+ primaryBtnText: {
788
+ marginLeft: spacing.xs,
789
+ ...typography.subhead,
790
+ fontWeight: '700',
791
+ },
792
+ secondaryBtn: {
793
+ height: 44,
794
+ borderRadius: radii.sm,
795
+ borderWidth: 1,
796
+ alignItems: 'center',
797
+ justifyContent: 'center',
798
+ paddingHorizontal: spacing.lg,
799
+ },
800
+ modalActions: {
801
+ marginTop: spacing.lg,
802
+ flexDirection: 'row',
803
+ justifyContent: 'flex-end',
804
+ alignItems: 'center',
805
+ gap: spacing.sm,
806
+ },
807
+ advancedBtn: {
808
+ marginTop: spacing.sm,
809
+ alignSelf: 'flex-start',
810
+ flexDirection: 'row',
811
+ alignItems: 'center',
812
+ },
813
+ previewBox: {
814
+ marginTop: spacing.md,
815
+ borderWidth: 1,
816
+ borderRadius: radii.sm,
817
+ padding: spacing.md,
818
+ },
819
+ previewIcon: {
820
+ width: 48,
821
+ height: 48,
822
+ borderRadius: radii.sm,
823
+ },
824
+ previewKey: {
825
+ ...typography.caption1,
826
+ },
827
+ err: {
828
+ ...typography.footnote,
829
+ marginTop: spacing.xs,
830
+ },
831
+ })