@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Which host answers for a domain.
3
+ *
4
+ * Our own domain is pinned by configuration: the host was stated by the build,
5
+ * so asking DNS about it would only add a way to be told something else. Every
6
+ * other domain resolves the way Paymail does — DNSSEC-authenticated SRV, then
7
+ * the well-known capability document — because a foreign domain is the one
8
+ * place this feature trusts an answer it did not bring with it.
9
+ *
10
+ * The AD requirement has one exception, and it is not a loophole: an SRV whose
11
+ * target IS the domain names no new host, so an unauthenticated answer moves
12
+ * nothing that `https://<domain>` would not already have reached.
13
+ */
14
+ import { BRFC_LOOKUP, BRFC_REVERSE_LOOKUP, looksLikeDomain } from './rules'
15
+
16
+ /** The domain this build's own handles live under, and the host serving it. */
17
+ export interface RegistryPin {
18
+ readonly domain: string
19
+ readonly url: string
20
+ }
21
+
22
+ /** The two routes, already substituted and encoded. */
23
+ export interface RegistryEndpoints {
24
+ readonly domain: string
25
+ search(query: string): string
26
+ reverse(pubkey: string): string
27
+ /** True for the configured domain, which skipped discovery entirely. */
28
+ readonly pinned: boolean
29
+ }
30
+
31
+ export interface RegistryResolver {
32
+ resolve(domain: string): Promise<RegistryEndpoints | null>
33
+ /** Test seam, and the way a "try again" control forgets a failed lookup. */
34
+ clearCache(): void
35
+ }
36
+
37
+ export const REGISTRY_TIMEOUT_MS = 8000
38
+ export const RESOLVER_SUCCESS_TTL_MS = 10 * 60 * 1000
39
+ export const RESOLVER_FAILURE_TTL_MS = 60 * 1000
40
+ export const DOH_ENDPOINTS: readonly string[] = ['https://cloudflare-dns.com/dns-query', 'https://dns.google/resolve']
41
+
42
+ const SRV_TYPE = 33
43
+ const NOERROR = 0
44
+ const NXDOMAIN = 3
45
+
46
+ /**
47
+ * One attempt, bounded — headers AND body. There is no shared fetch helper in
48
+ * this codebase — every call site hand-rolls this — so this feature's two
49
+ * networking modules share exactly one copy of it rather than two.
50
+ *
51
+ * A caller's own signal is composed, not replaced: the deadline is ours to add,
52
+ * but a screen that cancels on unmount must still cancel the request rather than
53
+ * hold it to the full eight seconds. `core/backup/client.ts` links the two the
54
+ * same way — and, for the same reason it does, the deadline outlives the
55
+ * headers: every caller in this feature reads a JSON body, and a connection
56
+ * that delivers headers and then stalls (a captive portal, a half-closed load
57
+ * balancer, a mobile link that drops mid-body) leaves `json()` pending for
58
+ * ever. `registration.ts` serialises every write behind one promise, so a
59
+ * single stalled body would wedge every later write for the life of the
60
+ * process, with no toast and no timeout.
61
+ */
62
+ export async function fetchWithTimeout(fetchImpl: typeof fetch, url: string, init?: RequestInit): Promise<Response> {
63
+ const controller = new AbortController()
64
+ const caller = init?.signal ?? null
65
+ const onAbort = () => controller.abort(caller?.reason)
66
+ if (caller?.aborted) onAbort()
67
+ caller?.addEventListener('abort', onAbort)
68
+ const release = () => caller?.removeEventListener('abort', onAbort)
69
+ const startedAt = Date.now()
70
+ const timer = setTimeout(() => controller.abort(), REGISTRY_TIMEOUT_MS)
71
+ let response: Response
72
+ try {
73
+ response = await fetchImpl(url, { ...init, signal: controller.signal })
74
+ } catch (e) {
75
+ release()
76
+ throw e
77
+ } finally {
78
+ clearTimeout(timer)
79
+ }
80
+ const readJson = typeof response.json === 'function' ? response.json.bind(response) : null
81
+ if (!readJson) {
82
+ release()
83
+ return response
84
+ }
85
+ // Rebinding the reader rather than buffering the body here: what each caller
86
+ // asks for is all that is ever allocated. The abort is what stops a real
87
+ // stalled stream; the rejection is what stops a transport that ignores it.
88
+ response.json = async () => {
89
+ let bodyTimer: ReturnType<typeof setTimeout> | undefined
90
+ try {
91
+ return await new Promise((resolve, reject) => {
92
+ bodyTimer = setTimeout(
93
+ () => {
94
+ controller.abort()
95
+ reject(new Error(`handleRegistry: no body from ${url} after ${REGISTRY_TIMEOUT_MS}ms`))
96
+ },
97
+ Math.max(0, REGISTRY_TIMEOUT_MS - (Date.now() - startedAt))
98
+ )
99
+ void readJson().then(resolve, reject)
100
+ })
101
+ } finally {
102
+ if (bodyTimer !== undefined) clearTimeout(bodyTimer)
103
+ release()
104
+ }
105
+ }
106
+ return response
107
+ }
108
+
109
+ interface SrvRecord {
110
+ priority: number
111
+ weight: number
112
+ port: number
113
+ target: string
114
+ }
115
+
116
+ interface DohAnswer {
117
+ type?: number
118
+ data?: string
119
+ }
120
+
121
+ interface DohResponse {
122
+ Status?: number
123
+ AD?: boolean
124
+ Answer?: DohAnswer[]
125
+ }
126
+
127
+ function parseSrv(data: string): SrvRecord | null {
128
+ const parts = data.trim().split(/\s+/)
129
+ if (parts.length < 4) return null
130
+ const priority = Number(parts[0])
131
+ const weight = Number(parts[1])
132
+ const port = Number(parts[2])
133
+ const target = parts[3].replace(/\.$/, '').toLowerCase()
134
+ if (!Number.isFinite(priority) || !Number.isFinite(weight) || target === '') return null
135
+ // A port that cannot be dialled does not belong in a URL: `:70000`, `:-1` and
136
+ // `:44.3` are each read by some parser as something other than a port.
137
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null
138
+ return { priority, weight, port, target }
139
+ }
140
+
141
+ function templateOf(value: unknown, placeholder: string): string | null {
142
+ if (typeof value !== 'string' || !value.startsWith('https://')) return null
143
+ return value.includes(placeholder) ? value : null
144
+ }
145
+
146
+ export function createRegistryResolver(args: {
147
+ pinned?: RegistryPin
148
+ fetchImpl?: typeof fetch
149
+ now?: () => number
150
+ dohEndpoints?: readonly string[]
151
+ }): RegistryResolver {
152
+ const fetchImpl = args.fetchImpl ?? ((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init))
153
+ const now = args.now ?? (() => Date.now())
154
+ const dohEndpoints = args.dohEndpoints ?? DOH_ENDPOINTS
155
+ const pinnedDomain = args.pinned?.domain.trim().toLowerCase() ?? ''
156
+ const pinnedOrigin = args.pinned?.url.trim().replace(/\/+$/, '') ?? ''
157
+ const cache = new Map<string, { at: number; value: RegistryEndpoints | null }>()
158
+
159
+ const pinnedEndpoints: RegistryEndpoints | null =
160
+ pinnedDomain !== '' && pinnedOrigin !== ''
161
+ ? {
162
+ domain: pinnedDomain,
163
+ search: query => `${pinnedOrigin}/api/handle/${encodeURIComponent(query)}`,
164
+ reverse: pubkey => `${pinnedOrigin}/api/identityKey/${encodeURIComponent(pubkey)}`,
165
+ pinned: true
166
+ }
167
+ : null
168
+
169
+ /**
170
+ * The SRV answer, or the Paymail fallback, or null when DNS said nothing usable.
171
+ *
172
+ * Only NOERROR and NXDOMAIN are answers. Any other status — SERVFAIL, which
173
+ * is what a resolver returns for a DNSSEC-bogus zone under `do=1`, or REFUSED
174
+ * — carries no Answer either, so treating it as "no SRV" would quietly turn a
175
+ * DNSSEC failure into `https://<domain>`. It is a failure of that resolver
176
+ * instead, and the next one gets the question.
177
+ */
178
+ async function lookupSrv(domain: string): Promise<{ target: string; port: number } | null> {
179
+ const fallback = { target: domain, port: 443 }
180
+ for (const endpoint of dohEndpoints) {
181
+ let body: DohResponse
182
+ try {
183
+ const url = `${endpoint}?name=${encodeURIComponent(`_bsvalias._tcp.${domain}`)}&type=SRV&do=1`
184
+ const res = await fetchWithTimeout(fetchImpl, url, { headers: { accept: 'application/dns-json' } })
185
+ if (!res.ok) continue
186
+ body = (await res.json()) as DohResponse
187
+ } catch {
188
+ continue
189
+ }
190
+ if (body.Status !== NOERROR && body.Status !== NXDOMAIN) continue
191
+ const records = (body.Answer ?? [])
192
+ .filter(answer => answer.type === SRV_TYPE && typeof answer.data === 'string')
193
+ .map(answer => parseSrv(answer.data as string))
194
+ .filter((record): record is SrvRecord => record !== null)
195
+ if (body.Status === NXDOMAIN || records.length === 0) return fallback
196
+ records.sort((a, b) => a.priority - b.priority || b.weight - a.weight)
197
+ const best = records[0]
198
+ if (body.AD !== true && best.target !== domain) return null
199
+ return { target: best.target, port: best.port }
200
+ }
201
+ return null
202
+ }
203
+
204
+ async function discover(domain: string): Promise<RegistryEndpoints | null> {
205
+ const host = await lookupSrv(domain)
206
+ if (!host) return null
207
+ const origin = `https://${host.target}${host.port === 443 ? '' : `:${host.port}`}`
208
+ let capabilities: Record<string, unknown>
209
+ try {
210
+ const res = await fetchWithTimeout(fetchImpl, `${origin}/.well-known/bsvalias`, {
211
+ headers: { accept: 'application/json' }
212
+ })
213
+ if (!res.ok) return null
214
+ const body = (await res.json()) as { capabilities?: Record<string, unknown> }
215
+ capabilities = body?.capabilities ?? {}
216
+ } catch {
217
+ return null
218
+ }
219
+ const searchTemplate = templateOf(capabilities[BRFC_LOOKUP], '{query}')
220
+ const reverseTemplate = templateOf(capabilities[BRFC_REVERSE_LOOKUP], '{pubkey}')
221
+ if (!searchTemplate || !reverseTemplate) return null
222
+ return {
223
+ domain,
224
+ search: query => searchTemplate.replace('{query}', encodeURIComponent(query)),
225
+ reverse: pubkey => reverseTemplate.replace('{pubkey}', encodeURIComponent(pubkey)),
226
+ pinned: false
227
+ }
228
+ }
229
+
230
+ return {
231
+ async resolve(rawDomain) {
232
+ const domain = rawDomain.trim().toLowerCase()
233
+ if (pinnedEndpoints && domain === pinnedDomain) return pinnedEndpoints
234
+ // Ahead of the cache, not inside discovery: a half-typed domain is not an
235
+ // answer, and the cache has no eviction — search resolves as the user types.
236
+ if (!looksLikeDomain(domain)) return null
237
+ const hit = cache.get(domain)
238
+ if (hit && now() - hit.at < (hit.value ? RESOLVER_SUCCESS_TTL_MS : RESOLVER_FAILURE_TTL_MS)) return hit.value
239
+ const value = await discover(domain)
240
+ cache.set(domain, { at: now(), value })
241
+ return value
242
+ },
243
+ clearCache() {
244
+ cache.clear()
245
+ }
246
+ }
247
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Handle-registry rules — the constants, and the string checks that are pure.
3
+ *
4
+ * Every value here mirrors a rule the registry enforces on write
5
+ * (go-message-box-server `pkg/handles`, `pkg/profilecert`). Restating them on
6
+ * this side is not distrust of the server: a client that cannot tell a valid
7
+ * handle from an invalid one has to ask the network what the user just typed,
8
+ * once per keystroke.
9
+ *
10
+ * "Handle" already names the identity-key pay rail in this codebase
11
+ * (`RailId 'handle'`, core/pay/rails/handle.ts). Nothing here reuses that word
12
+ * as a rail — a handle is the local part of a `handle@domain` paymail.
13
+ */
14
+ import { Utils } from '@bsv/sdk'
15
+
16
+ /** base64(SHA-256("public profile lookup")) — the profile certificate's type. */
17
+ export const PROFILE_CERT_TYPE = 'SbatVXXssDW3AO0J9bxIljkHGbPBGCVAXg94gXFf0cE='
18
+ /** BRFC id of the `public profile lookup` capability — search. */
19
+ export const BRFC_LOOKUP = '0ace65da5987'
20
+ /** BRFC id of the `public profile reverse lookup` capability — key → profile. */
21
+ export const BRFC_REVERSE_LOOKUP = '43dcf83ddc5f'
22
+ /** There is no on-chain revocation: a profile is replaced or tombstoned. */
23
+ export const ZERO_OUTPOINT = `${'0'.repeat(64)}.0`
24
+
25
+ export const MAX_FIELDS = 32
26
+ /** Exclusive — go-sdk's own `CertificateFieldNameUnder50Bytes`. */
27
+ export const MAX_FIELD_NAME_BYTES = 50
28
+ export const MAX_FIELD_VALUE_BYTES = 1024
29
+ export const MAX_CERT_BODY_BYTES = 16384
30
+
31
+ /** Shorter than this and the search route answers nothing at all. */
32
+ export const SEARCH_MIN_QUERY_LENGTH = 2
33
+ /** Longer than this and the search route answers nothing at all. */
34
+ export const MAX_SEARCH_QUERY_LENGTH = 32
35
+ /**
36
+ * The most rows the search route ever answers with (`searchLimit` in
37
+ * go-message-box-server's own handler).
38
+ *
39
+ * Restated on this side because the host that answers a search is not always
40
+ * ours: a complete foreign domain the user typed is resolved and asked, and
41
+ * nothing binds it to our server's limit. Every row costs one ECDSA
42
+ * verification on the only thread the recipient field has, so an uncapped
43
+ * answer is an unbounded freeze rather than a long list.
44
+ */
45
+ export const MAX_SEARCH_RESULTS = 10
46
+
47
+ const HANDLE_FORMAT = /^[a-z0-9][a-z0-9._-]{1,30}[a-z0-9]$/
48
+ const DOMAIN_FORMAT = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/
49
+ const SEARCH_QUERY_FORMAT = /^[a-z0-9._-]+$/
50
+
51
+ /**
52
+ * Path segments a query must never become, because the search route never sees
53
+ * them. `GET /api/handle/available` is mounted ahead of
54
+ * `GET /api/handle/{query}` and answers `400 ERR_INVALID_LOOKUP`; `..` does not
55
+ * even leave the device intact, since the URL parser collapses a double-dot
56
+ * segment (`https://host/api/handle/..` is `https://host/api/`, which nothing
57
+ * serves) and encoding cannot rescue it — the spec reads `%2e%2e` as the same
58
+ * segment. Either one `search` would surface as "the registry is down", for an
59
+ * ordinary English word or for two dots. A lone `.` is already too short.
60
+ */
61
+ const RESERVED_QUERY_PATHS = new Set(['available', '..'])
62
+
63
+ /** 3-32 characters of a-z 0-9 . _ - beginning and ending with a letter or digit. */
64
+ export function isValidHandleFormat(handle: string): boolean {
65
+ return HANDLE_FORMAT.test(handle)
66
+ }
67
+
68
+ /** A dotted, all-lowercase domain. Says nothing about whether it resolves. */
69
+ export function looksLikeDomain(text: string): boolean {
70
+ return DOMAIN_FORMAT.test(text.trim().toLowerCase())
71
+ }
72
+
73
+ /**
74
+ * Whether the registry would actually search for this, rather than answer an
75
+ * empty array or a 400. Restating the server's own gate here is what keeps a
76
+ * routine word — a too-long paste, an accent, a slash — from costing a request
77
+ * and, for the reserved paths, from raising an outage banner.
78
+ */
79
+ export function isRoutableSearchQuery(query: string): boolean {
80
+ if (query.length < SEARCH_MIN_QUERY_LENGTH || query.length > MAX_SEARCH_QUERY_LENGTH) return false
81
+ if (!SEARCH_QUERY_FORMAT.test(query)) return false
82
+ return !RESERVED_QUERY_PATHS.has(query)
83
+ }
84
+
85
+ /**
86
+ * `handle@domain`, trimmed and lowercased, or null when it is not one.
87
+ *
88
+ * Lowercasing here is what makes a typed `Dee@Example.com` comparable with the
89
+ * exact-lowercase `paymail` field the registry stores — the comparison the
90
+ * trust model turns on.
91
+ */
92
+ export function parsePaymail(text: string): { handle: string; domain: string } | null {
93
+ const parts = text.trim().toLowerCase().split('@')
94
+ if (parts.length !== 2) return null
95
+ const [handle, domain] = parts
96
+ if (!isValidHandleFormat(handle) || !looksLikeDomain(domain)) return null
97
+ return { handle, domain }
98
+ }
99
+
100
+ /** UTF-8 length, the unit every server-side size limit counts in. `Buffer` does
101
+ * not exist in React Native, so this goes through the SDK's own encoder. */
102
+ export function utf8ByteLength(text: string): number {
103
+ return Utils.toArray(text, 'utf8').length
104
+ }
package/core/index.ts CHANGED
@@ -12,7 +12,7 @@ export { configureNewHeaderPolling } from './walletMonitor'
12
12
  export { TaskSendOffline } from './monitor/TaskSendOffline'
13
13
  export { TaskCreditInbox } from './monitor/TaskCreditInbox'
14
14
  export { TaskDrainOutbox, drainUnsentEntries } from './monitor/TaskDrainOutbox'
15
- export { getOnline, subscribeOnline } from './net/online'
15
+ export { getOnline, subscribeOnline, probeOnline } from './net/online'
16
16
  export * from './logging'
17
17
  export * from './diskSpace'
18
18
  export type { AppChain, WalletChain } from './config'
@@ -32,9 +32,14 @@ export {
32
32
  isToolboxConfigured,
33
33
  getBackupUrl,
34
34
  getServiceConfig,
35
+ getMandalaEndpoints,
36
+ getHandleRegistryConfig,
37
+ isMandalaAvailable,
38
+ isVaultEnabled,
39
+ isVaultAvailable,
35
40
  resetToolboxConfig
36
41
  } from './toolboxConfig'
37
- export type { ToolboxConfig, ToolboxServiceConfig } from './toolboxConfig'
42
+ export type { ToolboxConfig, ToolboxServiceConfig, MandalaEndpointConfig, HandleRegistryConfig } from './toolboxConfig'
38
43
 
39
44
  // Theme tokens and providers
40
45
  export { ThemeProvider, useTheme } from './theme/ThemeContext'
@@ -48,9 +53,11 @@ export { useThemeStyles } from './theme/useThemeStyles'
48
53
  export {
49
54
  formatAmount,
50
55
  formatAmountParts,
56
+ splitAmountFraction,
51
57
  formatAmountInInputUnit,
52
58
  formatSatoshisAsFiat,
53
59
  formatSatoshisAsBsv,
60
+ formatSatoshisExact,
54
61
  formatSatoshisAsBsvDecimal,
55
62
  parseDisplayToSatoshis,
56
63
  getUnitLabel,
@@ -94,18 +101,92 @@ export * from './offline/hold'
94
101
  export * from './offline/order'
95
102
  export * from './offline/plan'
96
103
  export * from './offline/payerHold'
104
+ export * from './offline/tokenFrames'
105
+ export {
106
+ cancelParkedPayment,
107
+ type CancelParkedOutcome,
108
+ type CancelParkedStorage,
109
+ type CancelParkedWallet,
110
+ type CancelParkedSettlementDeps
111
+ } from './offline/cancelParked'
112
+
113
+ // Mandala token settlement — the four evidence tables, and the
114
+ // submit-before-broadcast drain over them.
115
+ export * from './mandala/types'
116
+ export { createSettlementStore, type SettlementDb, type SqlSettlementStore } from './mandala/settlementStore'
117
+ // Guard #4: an abortAction may not release the inputs of a token payment the
118
+ // overlay already has (the 2026-09-15 incident).
119
+ export {
120
+ abortIsBlockedBy,
121
+ wrapAbortActionForSettlements,
122
+ ABORT_BLOCKED_SETTLEMENT_STATES,
123
+ type AbortableManager,
124
+ type SettlementStoreLookup
125
+ } from './mandala/abortGuard'
126
+ export {
127
+ deriveTokenEdges,
128
+ isRetriableInternalizeFailure,
129
+ listStuckSettlements,
130
+ populateEvidenceFromFrame,
131
+ postTokenStep,
132
+ reconcileSettlements,
133
+ NON_TERMINAL_SETTLEMENT_STATES,
134
+ TERMINAL_SETTLEMENT_STATES,
135
+ type EvidenceFrame,
136
+ type EvidencePopulated,
137
+ type EvidenceTokenBlock,
138
+ type EvidenceTrustAnchor,
139
+ type TokenFrameSource,
140
+ type TokenStepDeps
141
+ } from './mandala/drain'
142
+ // The runtime the UI consumes: its pure interface, and its one construction
143
+ // site. `useMandala()` reads `useWallet().mandala`; nothing above this line in
144
+ // an app may import `@bsv/mandala` itself.
145
+ export type {
146
+ MandalaRuntime,
147
+ TokenActivityRow,
148
+ TokenActivityStatus,
149
+ TokenAssetInfo,
150
+ TokenBalance,
151
+ TokenSendResult
152
+ } from './mandala/runtime'
153
+ export {
154
+ activityStatusOf,
155
+ bindOriginator,
156
+ createMandalaKvStorage,
157
+ createMandalaRuntime,
158
+ verdictFromError,
159
+ type CreateMandalaRuntimeArgs,
160
+ type MandalaKvStorage,
161
+ type MandalaMessageBox
162
+ } from './mandala/createRuntime'
163
+ export {
164
+ assembleBundle,
165
+ coverFromFrame,
166
+ tokenParentsOf,
167
+ type AdmissionBundle,
168
+ type BundleStore,
169
+ type CoverBundle,
170
+ type CoverTip,
171
+ type CoverVerifier
172
+ } from './mandala/bundle'
173
+
174
+ // Contacts
175
+ export { mergeContactCache, type ContactCache } from './contacts/contactCache'
97
176
 
98
177
  // Local SQLite storage layer
99
178
  export { StorageExpoSQLite } from './storage/StorageExpoSQLite'
100
- export type { StorageExpoSQLiteOptions } from './storage/StorageExpoSQLite'
101
- export { createTables, ensureOfflineActionsColumns } from './storage/schema/createTables'
179
+ export type { StorageExpoSQLiteOptions, TokenTransactionRepair } from './storage/StorageExpoSQLite'
180
+ export { createTables, ensureOfflineActionsColumns, ensureTokenSettlementColumns } from './storage/schema/createTables'
102
181
  export { initializeLocalStorage, isLocalStorage, getStorageDisplayName } from './storage/LocalStorageAdapter'
103
182
  export type { LocalStorageConfig } from './storage/LocalStorageAdapter'
104
- export { findOfflineActions, updateOfflineAction } from './storage/methods/offlineActions'
183
+ export { findOfflineActions, findOfflineActionByTxid, updateOfflineAction } from './storage/methods/offlineActions'
105
184
  export type { OfflineActionRow, OfflineActionStatus, BindValue } from './storage/methods/offlineActions'
106
185
  export { readWalletBalance } from './storage/methods/walletBalanceSql'
107
- export { processOfflineActions } from './storage/methods/processOfflineActions'
186
+ export { processOfflineActions, type OfflineTokenDeps } from './storage/methods/processOfflineActions'
187
+ export { createMandalaSettlementTables } from './storage/schema/createTables'
108
188
  export * from './storage/skipQueuedAncestors'
189
+ export { prepareSqliteImageForDeserialize } from './storage/dbImage'
109
190
 
110
191
  // Local secrets storage
111
192
  export {
@@ -234,6 +315,7 @@ export * from './services/walletServiceConfig'
234
315
  export * from './services/arcadeBroadcastProvider'
235
316
  export * from './services/walletArgLimits'
236
317
  export * from './services/capWalletArgs'
318
+ export * from './services/externalOrigin'
237
319
 
238
320
  // Encrypted wallet backup log
239
321
  export * from './backup/RemoteSyncReader'
@@ -251,9 +333,11 @@ export * from './backup/restoreOnImport'
251
333
  export * from './walletRepair/runWalletCheck'
252
334
  export { TaskBackupPush } from './monitor/TaskBackupPush'
253
335
 
254
- // Hardware vault: YubiKey PIV custody, ceremony state machine, K1 script,
255
- // sealing/session/derivation crypto, transfers (deposit/withdraw/sweep/
256
- // reclaim), persistence, passphrase policy, access guard, backup attestation.
336
+ // Hardware vault: YubiKey PIV custody (1-of-N P-256 comb vault, spec
337
+ // docs/superpowers/specs/2026-09-09-r1-comb-vault-design.md), ceremony state
338
+ // machine, the r1comb template module, session helper, transfers
339
+ // (deposit / withdraw / re-lock), wallet-and-chain-scoped SecureStore
340
+ // persistence, access guard, and backup attestation.
257
341
  //
258
342
  // 'driver.ts' and 'random.ts' both reach for a native module
259
343
  // (react-native-yubikey, expo-crypto) with a `require(...)` INSIDE a
@@ -265,10 +349,7 @@ export * from './services/vault/types'
265
349
  export * from './services/vault/driver'
266
350
  export * from './services/vault/session'
267
351
  export * from './services/vault/random'
268
- export * from './services/vault/sealing'
269
- export * from './services/vault/k1'
270
- export * from './services/vault/vaultDerivation'
271
- export * from './services/vault/vaultPassphrase'
352
+ export * from './services/vault/r1comb'
272
353
  export * from './services/vault/vaultStore'
273
354
  export * from './services/vault/mockYubiKey'
274
355
  export * from './services/vault/devMock'
@@ -277,6 +358,7 @@ export * from './services/vault/backupAttestation'
277
358
  export * from './services/vault/ceremony'
278
359
  export * from './services/vault/ceremonyHost'
279
360
  export * from './services/vault/VaultKeyService'
361
+ export * from './services/vault/pivReset'
280
362
  export * from './services/vault/transfers'
281
363
 
282
364
  // Connection/pairing state (QR-paired desktop sessions), the vault ceremony
@@ -315,6 +397,25 @@ export * from './hooks/useConfirmationSound'
315
397
  // takes an optional onToast prop (see WalletContext.tsx's WalletContextToast
316
398
  // type) rather than importing a ui Toast component directly — core must
317
399
  // never import from ui, same boundary as VaultContext's onToast above.
318
- export { WalletContextProvider, useWallet, WalletContext, WalletManagersContext, useWalletManagers } from './context/WalletContext'
319
- export type { WalletManagersSlice } from './context/WalletContext'
400
+ export {
401
+ WalletContextProvider,
402
+ useWallet,
403
+ WalletContext,
404
+ WalletManagersContext,
405
+ useWalletManagers,
406
+ useWalletStatus
407
+ } from './context/WalletContext'
408
+ export type { WalletManagersSlice, WalletStatusSlice } from './context/WalletContext'
320
409
  export { usePermissionQueue } from './hooks/usePermissionQueue'
410
+
411
+ export { getNumberLocale } from './numberFormat'
412
+
413
+ export {
414
+ getUserAvatarIcon,
415
+ loadUserAvatarIcon,
416
+ setUserAvatarIcon,
417
+ subscribeUserAvatar,
418
+ useUserAvatarIcon,
419
+ type AvatarIcon,
420
+ type AvatarIconFamily
421
+ } from './userAvatar'