@bsv/expo-wallet-toolbox 0.3.0 → 0.4.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,251 @@
1
+ # Changelog
2
+
3
+ ## 0.4.0
4
+
5
+ ### Host-supplied configuration (breaking)
6
+
7
+ - Add `configureToolbox({ backupUrl, services })`, with `getBackupUrl`,
8
+ `getServiceConfig` and `isToolboxConfigured`. The host states its backup
9
+ endpoint and per-chain service URLs and keys once, at app entry.
10
+ - Remove `DEFAULT_BACKUP_URL` and every `process.env` read in the package.
11
+ Expo's Babel preset does not inline `EXPO_PUBLIC_*` for files under
12
+ `node_modules`, so those reads were `undefined` in the production bundle of
13
+ any host that installed this package from npm — disabling backup entirely
14
+ and leaving the WhatsOnChain/Taal key unset, while working in dev and in
15
+ hosts that consume the package from source.
16
+ - `backupUrl` is required and takes `null` to disable backup deliberately.
17
+ Reading configuration before `configureToolbox` runs throws, so an
18
+ unconfigured build fails loudly instead of imitating a disabled one.
19
+ - Backup URLs are validated as bare origins: a path, query or fragment is
20
+ rejected, since the BRC-103/104 handshake posts to the origin root.
21
+
22
+ ## 0.3.1
23
+
24
+ ### Wallet creation and backup
25
+
26
+ - Add `useLocalStorage().createMnemonic` for new wallets. It refuses to
27
+ replace an existing encrypted or legacy identity, waits for migration,
28
+ and blocks overlapping creation attempts. Identity checks propagate
29
+ storage errors instead of treating unreadable keys as an empty wallet.
30
+ - Wallet Home waits for migration and wallet construction before offering
31
+ creation or import. Backup reminders now require an explicit pending
32
+ record for a newly created identity; existing wallets without historical
33
+ backup metadata no longer receive a false warning.
34
+ - Add `backupAttestation.markPending` and `needsReminder`. Recording a
35
+ backup clears the pending reminder, and logout clears both record types.
36
+ - Advanced Settings replaces Copy Secret Words and Print Recovery Keys
37
+ with Backup Wallet Keys, linking to `/auth/mnemonic?flow=backup`, with
38
+ translations in all twelve supported languages.
39
+
40
+ ### Pairing
41
+
42
+ - Connections accepts both `bsv-wallet://` and `bsv-browser://` pairing
43
+ codes. Forwarded pairing parameters retain reserved characters in
44
+ topics, origins, protocol identifiers, and signatures.
45
+
46
+ ### Host app integration
47
+
48
+ - The mnemonic backup page and native URL registration remain owned by
49
+ the host app. Its `/auth/mnemonic?flow=backup` route must display the
50
+ existing identity, and new-wallet creation should use `createMnemonic`.
51
+ The confirmation delay, export actions, and back button are implemented
52
+ in the BSV Wallet app rather than shipped in this package.
53
+ - Hosts accepting both URL schemes must register them in their native
54
+ configuration and rebuild the app. BSV Wallet routes external pairing
55
+ links through `app/+native-intent.ts` to `/connections`.
56
+
57
+ ## 0.3.0
58
+
59
+ ### Breaking
60
+
61
+ - `INBOX_DESCRIPTION` is removed from `core/pay/creditInbox` (and so from the
62
+ `core` barrel). Inbound peer rows are now described by the sender's note or,
63
+ failing that, the sender's abbreviated identity key, so the fixed default
64
+ string has no remaining use.
65
+ - `internalizeIncoming` and `acceptWithRetry` in `core/pay/rails/handle` no
66
+ longer take a positional `description`. The signatures are now
67
+ `internalizeIncoming(wallet, client, adminOriginator, payment, repairBeef?)`
68
+ and `acceptWithRetry(client, messageBoxUrl, payment, internalize)`, with
69
+ `internalize: (p: IncomingPayment) => Promise<void>`. A JavaScript caller
70
+ still passing the old fifth argument would hand `acceptWithRetry` a string
71
+ where it expects the `internalize` function and every inbox credit would
72
+ throw; TypeScript callers see an arity error.
73
+
74
+ ### Activity
75
+
76
+ - Activity rows show a deterministic sigil avatar for the counterparty in the
77
+ tile where the direction arrow used to sit. The face is derived from the
78
+ counterparty's identity key when the row records one (a pubkey label on an
79
+ outbound peer payment, or `senderIdentityKey` on an inbound one), else the
80
+ address from a `to:`/`from:` label, else the txid, so two payments to the
81
+ same key wear the same face. Direction stays on the tile's border tint, and
82
+ a row with nothing to identify the other side keeps the arrow. The address
83
+ sweep's sentinel `senderIdentityKey` (the pubkey of private key 1) is not a
84
+ counterparty and falls through to the txid. Each face also has its own
85
+ colour: the hue is taken from the four bytes before the shape seed
86
+ (`counterpartyHue`), so shape and colour vary independently, and
87
+ `sigilPalette` turns it into a per-theme symbol and tile pair (pale tile
88
+ and deep symbol in light, deep tile and bright symbol in dark) that is
89
+ contrast-checked to at least 4.5:1 for every hue in both themes.
90
+ - Default action descriptions are now the payment note, else the resolved
91
+ name, else the abbreviated identity key or address, instead of a rail name.
92
+ - `listActions` rows expose `senderIdentityKey` (from
93
+ `outputs.senderIdentityKey`) alongside `reference` and `created_at`, and
94
+ `ActivityAction` declares it.
95
+ - Address-rail rows carry `to:` (outbound send) and `from:` (inbound sweep,
96
+ the payer's zeroth-input P2PKH address) labels, so the address rail has a
97
+ counterparty to show as well. The payload after the prefix is the address's
98
+ version byte and hash160 as 42 hex characters, built by `addressLabel` and
99
+ decoded back to base58 by `counterpartyOf`: the wallet folds every label to
100
+ lower case before storing it (`@bsv/sdk` `validateLabel`), which a base58
101
+ spelling does not survive but hex does.
102
+
103
+ ### Amounts
104
+
105
+ - Fiat amounts follow the satoshi sign convention: a leading minus for money
106
+ out and, where the caller asks for it, a leading plus for money in.
107
+ Accounting parentheses are gone. The sub-cent marker keeps its form with the
108
+ sign on the figure, e.g. `< -$0.01`.
109
+
110
+ ### Trust network
111
+
112
+ - Provider icons load through `expo-image` instead of React Native's core
113
+ `Image`, so a BRC-68 manifest that advertises an SVG icon (for example
114
+ `https://auth.sigmaidentity.com/manifest.json`) passes validation and
115
+ displays instead of failing with "icon image URL is invalid". `prefetch`'s
116
+ boolean result is preserved, so an unavailable image still rejects.
117
+ Contributed in #12 by @rohenaz. SVG icons themselves are drawn with
118
+ react-native-svg's parser (`SvgUri`) rather than handed to the platform
119
+ decoder: iOS's decoder ignores percentage-positioned `<text>`, which is how
120
+ Sigma's mark is authored, and rendered it as a black square.
121
+ - The built-in certifiers now show their icons. The screen kept a local
122
+ `Certifier` type that read `icon`, while the wallet's settings type and every
123
+ shipped default store the URL as `iconUrl`, so the defaults always fell to
124
+ the initial-letter placeholder. The screen now uses the settings type,
125
+ accepts entries an older build saved under `icon`, and writes `iconUrl` back
126
+ on save (`normaliseCertifier`).
127
+ - A certifier icon that fails to load falls back to the initial-letter tile
128
+ instead of an empty square. Two shipped defaults point at `.ico` favicons
129
+ the iOS decoder rejects, and any provider can move its file.
130
+ - Sigma Identity (`auth.sigmaidentity.com`) ships as a default certifier,
131
+ below the existing three in trust order. Two stores are involved: the Trust screen's list
132
+ is hydrated from AsyncStorage and an existing wallet keeps its saved list
133
+ there, while the wallet's identity resolution (`discoverByIdentityKey` and
134
+ `discoverByAttributes`) reads the toolbox's WalletSettingsManager store,
135
+ which this app never writes, so for resolution the shipped defaults,
136
+ Sigma included, apply to every wallet. That split predates this release.
137
+
138
+ ### Peer dependencies
139
+
140
+ - New peer `@urbit/sigil-js` (^2.2.0), imported only through its `./core`
141
+ entry. It ships CJS, so a consumer's Jest `transformIgnorePatterns` needs no
142
+ change; see the README's Jest configuration section.
143
+ - New peer `expo-image` (~55.0.11). Its package entry is raw TypeScript that
144
+ Jest does not transform, so the toolbox requires it lazily at render and
145
+ call time; a consumer's Jest config needs no change.
146
+
147
+ ## 0.2.2
148
+
149
+ ### Fixes
150
+
151
+ - `AppLogo`'s rotation now sets `isInteraction: false`. `Animated.timing`
152
+ registers an InteractionManager handle for the duration of the animation, and
153
+ `Animated.loop` means that duration never ends — so the handle was held for
154
+ as long as the component stayed mounted, and while any handle is held
155
+ `InteractionManager.runAfterInteractions` never fires for *anyone* in the
156
+ process. `Balance` renders `<AppLogo rotate />` whenever a balance is loading,
157
+ so this was reachable in normal use: `PayScreen`'s deferred proof sweep never
158
+ ran, and a host that defers real work the same way could hang indefinitely
159
+ with no error and no timeout. Long-standing; found by the bsv-browser session,
160
+ where a dApp's `listOutputs` hung forever behind a loading spinner.
161
+
162
+ ## 0.2.1
163
+
164
+ ### Payments
165
+
166
+ - The corrupt-pending-queue notice now has a body. `readUnprocessedPending`
167
+ quarantines an unparseable `localpay_pending` blob under a timestamped
168
+ `localpay_pending_corrupt_*` key and clears the live queue, but the card only
169
+ rendered a title ("Damaged payment data was found on this device"), so a user
170
+ carrying incoming payments was told nothing about what happened to them. The
171
+ new `pay_offline_kv_corrupt_body` (all twelve locales) says the payments were
172
+ set aside rather than deleted, and that a sender should be asked to send again
173
+ only if their payment is still missing — a quarantined entry may already have
174
+ been credited, and a blind re-send is the failure worth steering away from.
175
+
176
+ ## 0.2.0
177
+
178
+ Released from bsv-wallet master, tag `expo-wallet-toolbox-v0.2.0`. Contains
179
+ everything merged since 0.1.3, not only the API change below.
180
+
181
+ ### Breaking / API
182
+
183
+ - **`dismissTo` props are now typed `DismissTarget` (expo-router's `Href`)**
184
+ instead of `string`, on `PayScreen`, `PaymentSuccessOverlay`, `NearbyFlow`,
185
+ `AddressReceive`, `HandleReceive` and `UniversalSend`. A host with
186
+ `experiments.typedRoutes` enabled narrows `Href` globally to its own route
187
+ union, which made a `string` prop unassignable inside this package's own
188
+ files (TS2345); `skipLibCheck` cannot suppress it, because the package ships
189
+ raw `.ts`. Typed-routes hosts now get their route strings checked at the call
190
+ site; hosts without it see `Href` ~ `string`. `Href` also admits the object
191
+ form `{ pathname, params }`, so the accepted type widens — hence the minor
192
+ bump. `DismissTarget` is exported from the `ui` barrel.
193
+ - Note: the props still default to `'/'`. A typed-routes host with no `/`
194
+ route must pass its own value.
195
+
196
+ ### Wallet build and restore
197
+
198
+ - `WalletContext` destroys an unpublished `StorageExpoSQLite` when a backup
199
+ restore fails, so a retry does not open a second connection to the same
200
+ database file.
201
+ - The `SimpleWalletManager` builder rejects instead of resolving `null` on
202
+ failure. The manager authenticates on any resolution, so a failed restore
203
+ could previously mark a wallet built.
204
+ - A failed mnemonic build no longer falls back to a stored recovered key: only
205
+ genuinely missing mnemonic material allows the WIF path, so a partial replay
206
+ stays failed and retryable instead of being built over.
207
+ - `restoreFromBackup` intent is preserved across an automatic build (only an
208
+ explicit options object now overwrites it).
209
+ - `restoreOnImport` passes the device manifest through to the restore.
210
+ - `reconcileRestoredProofs` runs after a restore, so a replayed unsent request
211
+ cannot rebroadcast an already-completed transaction. It calls
212
+ `storage.findProvenTxReqs` and `storage.findProvenTxs` — a real widening of
213
+ what the `StorageExpoSQLite` argument must implement. Hosts passing a test
214
+ double or a narrower shim through a cast will need both.
215
+ - `RemoteSyncReader` pages the backup index (the server caps a page at 500
216
+ entries) and fails when the index ends before its advertised head, instead of
217
+ treating a truncated wallet as a successful restore. It publishes only a
218
+ fully verified index, advances only after both download and decryption
219
+ succeed, and prefetches at most one small (<= 1 MiB) chunk ahead, storing
220
+ failures as values so a stopped replay leaves no unhandled rejection.
221
+ - Backup client requests are bounded by a single deadline covering both the
222
+ request and the body read (React Native's XHR fetch resolves before its
223
+ Blob/FileReader conversion finishes), so a stalled transfer cannot strand the
224
+ monitor.
225
+
226
+ ### Payments
227
+
228
+ - `creditInboxOnce` rechecks the in-flight slot after each wait, so several
229
+ manual retries queue behind one pass rather than racing.
230
+ - The peerpay outbox serializes each storage's whole read-modify-write, not
231
+ just the final write, so a send and the background retry/prune task cannot
232
+ overwrite each other's checkpoints and tokens. Mutations fail closed on an
233
+ unreadable queue rather than treating it as empty, and payment IDs are chosen
234
+ against the live queue so same-millisecond sends stay distinct.
235
+ - localpay BLE transport wraps native calls in a promise helper; socket
236
+ transport reliability fixes.
237
+
238
+ ### Storage and UI
239
+
240
+ - `getLabelsForTransactionId` and `getTagsForOutputId` resolve their
241
+ associations in a single joined query instead of one bridge round trip per
242
+ row.
243
+ - `ActivityRow` compares every prop when memoizing, so a retained row cannot
244
+ invoke a previous network's handler or show a stale busy label.
245
+ - `useSpendableBalance` / `useVaultBalance` serialize reads and retain the
246
+ latest invalidation, never read or cache a previous chain's storage during a
247
+ network rebuild, and hide the old figure immediately on switch.
248
+
249
+ ## 0.1.3 and earlier
250
+
251
+ Not recorded here; see git history.
package/README.md CHANGED
@@ -155,6 +155,49 @@ dependencies.
155
155
  | --- | --- |
156
156
  | `react-native-yubikey` | Vault/hardware-key support. Absence is detected at runtime and vault features degrade gracefully. |
157
157
 
158
+ ## Configuration
159
+
160
+ Call `configureToolbox` once, at your app entry point, before anything from this
161
+ package renders or builds a wallet:
162
+
163
+ ```tsx
164
+ import { configureToolbox } from '@bsv/expo-wallet-toolbox'
165
+
166
+ configureToolbox({
167
+ backupUrl: process.env.EXPO_PUBLIC_BACKUP_URL ?? null,
168
+ services: {
169
+ main: {
170
+ arcUrl: process.env.EXPO_PUBLIC_ARC_URL,
171
+ arcApiKey: process.env.EXPO_PUBLIC_ARC_API_KEY,
172
+ chaintracksUrl: process.env.EXPO_PUBLIC_CHAINTRACKS_URL,
173
+ whatsOnChainApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY,
174
+ taalApiKey: process.env.EXPO_PUBLIC_WOC_API_KEY
175
+ }
176
+ }
177
+ })
178
+ ```
179
+
180
+ **The `EXPO_PUBLIC_*` reads must live in your app source, not in this package.**
181
+ Expo's Babel preset refuses to inline `EXPO_PUBLIC_*` for any file whose path
182
+ contains `node_modules` (`babel-preset-expo/build/common.js`: `!isNodeModule &&
183
+ ...`). A production bundle defines only `NODE_ENV` on `process.env`, so an env
184
+ read inside an installed copy of this package is `undefined` — silently, and
185
+ only in production, since Expo's dev serializer injects the variables at
186
+ runtime. That asymmetry is why this package reads no environment of its own.
187
+
188
+ `backupUrl` is required and accepts `null`, which disables backup entirely: no
189
+ monitor task is registered, nothing is sent, and the backup UI does not render.
190
+ It is not optional and has no default, so every build states its endpoint —
191
+ including stating that it has none. It must be a bare origin: the BRC-103/104
192
+ handshake posts to the origin root, so a path, query or fragment is rejected.
193
+
194
+ Every `services` field is optional and falls back to the built-in public
195
+ endpoint for that chain. Chains are `main`, `test` and `teratest`.
196
+
197
+ Reading configuration before `configureToolbox` has run **throws**. An
198
+ unconfigured build fails loudly rather than behaving like a deliberately
199
+ disabled one.
200
+
158
201
  ## Usage
159
202
 
160
203
  ```tsx
@@ -252,12 +295,12 @@ export { WalletHomeScreen as default } from '@bsv/expo-wallet-toolbox/ui'
252
295
  | `TrustScreen` | `app/trust.tsx` |
253
296
  | `LogsScreen` | `app/logs.tsx` |
254
297
 
255
- > **Note:** `ConnectionsScreen`'s OS-level deep-link pairing (a desktop
256
- > session opening the app directly) currently assumes the `bsv-wallet://`
257
- > URL scheme is hardcoded into its parsing and link-building. A consuming
258
- > app that registers a different scheme would need that deep-link path
259
- > updated to match. In-app QR-code scanning of a pairing code is unaffected
260
- > and works regardless of the consumer's own scheme.
298
+ > **Note:** `ConnectionsScreen` accepts pairing codes using `bsv-wallet://`
299
+ > or `bsv-browser://`. OS-level links also require native scheme registration
300
+ > in the host app. This repo routes external `pair` links to `/connections`
301
+ > through `app/+native-intent.ts`; in-app QR scanning uses the same pairing
302
+ > parameter validation. A consumer using another pairing scheme must update
303
+ > the parser and its own native registration together.
261
304
 
262
305
  Each route file is the one-line `export { XScreen as default } from '@bsv/expo-wallet-toolbox/ui'`
263
306
  pattern shown above — no other wiring needed per screen; navigation
@@ -300,7 +343,7 @@ vault/hardware-key support (i.e. installed `react-native-yubikey`); omit
300
343
  both if you didn't.
301
344
 
302
345
  Also add `CFBundleURLTypes` for **your own** deep-link scheme(s) — do not
303
- reuse `bsv-wallet://` or `peerpay://`, those are this repo's own app
346
+ reuse `bsv-wallet://`, `bsv-browser://`, or `peerpay://`, those are this repo's own app
304
347
  identity, not the package's:
305
348
 
306
349
  ```json
@@ -499,6 +542,15 @@ are required — both hard-won during this package's extraction:
499
542
 
500
543
  ## Breaking changes
501
544
 
545
+ **0.4.0:** the package no longer reads `process.env` at all. `DEFAULT_BACKUP_URL`
546
+ is removed, and the `EXPO_PUBLIC_*` service reads in `walletServiceConfig` are
547
+ gone. The host supplies these through `configureToolbox({ backupUrl, services })`
548
+ at app entry — see [Configuration](#configuration). Removing the export rather
549
+ than deprecating it is deliberate: a host that upgrades gets a build error, not
550
+ another empty string. Hosts that installed this package from npm were silently
551
+ running with backup disabled and WhatsOnChain/Taal unkeyed, because Expo does
552
+ not inline `EXPO_PUBLIC_*` inside `node_modules`.
553
+
502
554
  **0.1.1:** `react-native-localpay-transport` (unscoped, private, hand-synced
503
555
  out of this repo) became `@bsv/react-native-localpay-transport` (published
504
556
  independently). This is a native-module identity change, not just an npm
@@ -545,7 +597,7 @@ without an `exports` map, and Metro's own `exports` support has its own
545
597
  quirks worth re-testing explicitly rather than assuming Node's behavior
546
598
  carries over.
547
599
 
548
- `files` is `["core", "ui", "assets"]`; npm always includes `package.json`
600
+ `files` is `["core", "ui", "assets", "CHANGELOG.md"]`; npm always includes `package.json`
549
601
  and `README.md` regardless of `files`. `__tests__/` and `tsconfig.json`
550
602
  live at the package root, outside every `files` entry, so they are
551
603
  excluded from the published tarball — confirmed with `npm pack --dry-run`.
package/core/config.tsx CHANGED
@@ -23,25 +23,20 @@ export const DEFAULT_MESSAGEBOX_URL = 'https://gmb.bsvblockchain.tech'
23
23
  /**
24
24
  * Encrypted wallet-backup log.
25
25
  *
26
- * Deliberately separate from DEFAULT_STORAGE_URL, which stays 'local': this service is not
27
- * a wallet storage provider. It stores opaque ciphertext it cannot read, addressed by a
28
- * pseudonym derived from the wallet seed.
26
+ * The backup endpoint is no longer a constant here: it is supplied by the host app
27
+ * through `configureToolbox({ backupUrl })` and read back with `getBackupUrl()`.
28
+ * See `toolboxConfig.ts` for why (Expo does not inline `EXPO_PUBLIC_*` inside
29
+ * `node_modules`, so an env read in this package is empty in any host that
30
+ * installs it from npm).
29
31
  *
30
- * Empty disables backup entirely — no monitor task is registered and nothing is sent. That
31
- * is what a build with no EXPO_PUBLIC_BACKUP_URL gets, including a plain local `npm run ios`
32
- * with no .env.local: the value is not defaulted in code, so every build states its endpoint.
32
+ * The design intent is unchanged — the value is still not defaulted in code, so
33
+ * every build states its endpoint. Only the speaker changed, from this package's
34
+ * environment to the host's explicit call. `backupUrl: null` disables backup
35
+ * entirely: no monitor task is registered and nothing is sent.
33
36
  *
34
- * The EAS development, dev-physical and production profiles set it to the shared server at
35
- * https://backup.bsvblockchain.tech (see eas.json). preview-apk carries no env block at all,
36
- * so those builds have backup disabled along with every other EXPO_PUBLIC_* default.
37
- *
38
- * Set EXPO_PUBLIC_BACKUP_URL to point a build at a different server. EXPO_PUBLIC_* values are
39
- * inlined by Metro at bundle time, so changing it needs a Metro restart but not a native rebuild.
40
- * It must be an origin with no trailing slash and no path: the BRC-103/104 handshake is
41
- * posted to the origin root, so a path prefix makes every request fail authentication.
42
- *
43
- * EXPO_PUBLIC_BACKUP_URL=https://backup.example.com npm run ios
37
+ * The endpoint must be an origin with no trailing slash and no path: the
38
+ * BRC-103/104 handshake is posted to the origin root, so a path prefix makes
39
+ * every request fail authentication.
44
40
  */
45
- export const DEFAULT_BACKUP_URL = (process.env.EXPO_PUBLIC_BACKUP_URL ?? '').replace(/\/+$/, '')
46
41
  export const DEFAULT_CHAIN: AppChain = 'main'
47
42
  export const ADMIN_ORIGINATOR = 'admin.com'
@@ -27,6 +27,10 @@ import {
27
27
  type UnlockState
28
28
  } from '../services/secrets'
29
29
 
30
+ // The identity is shared storage, so overlapping provider mounts must share the
31
+ // guard too. Hold it through both the existence check and the completed write.
32
+ let creatingMnemonic = false
33
+
30
34
  /**
31
35
  * Wallet secrets are held by services/secrets, which wraps them in AES-256-GCM
32
36
  * under a key the OS will only release after a biometric match. This provider
@@ -40,6 +44,8 @@ import {
40
44
  */
41
45
  export interface LocalStorageContextType {
42
46
  /* secure */
47
+ /** Fresh onboarding only. Refuses to replace any existing wallet identity. */
48
+ createMnemonic: (mnemonic: string) => Promise<boolean>
43
49
  setMnemonic: (mnemonic: string) => Promise<boolean>
44
50
  getMnemonic: () => Promise<string | null>
45
51
  deleteMnemonic: () => Promise<void>
@@ -69,6 +75,7 @@ export interface LocalStorageContextType {
69
75
 
70
76
  export const LocalStorageContext = createContext<LocalStorageContextType>({
71
77
  /* secure */
78
+ createMnemonic: async () => false,
72
79
  setMnemonic: async () => false,
73
80
  getMnemonic: async () => null,
74
81
  deleteMnemonic: async () => {},
@@ -94,6 +101,7 @@ export const useLocalStorage = () => useContext(LocalStorageContext)
94
101
 
95
102
  export default function LocalStorageProvider({ children }: { children: React.ReactNode }) {
96
103
  const [secretsReady, setSecretsReady] = useState(false)
104
+ const secretsReadyRef = useRef(false)
97
105
  const [migration, setMigration] = useState<MigrationResult | null>(null)
98
106
  const [unlockState, setUnlockState] = useState<UnlockState>(getUnlockState)
99
107
  /** Set when migration failed: this session keeps serving the legacy plaintext
@@ -114,11 +122,13 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
114
122
  }
115
123
  if (cancelled) return
116
124
  legacyFallback.current = result.outcome === 'failed'
125
+ secretsReadyRef.current = true
117
126
  setMigration(result)
118
127
  setSecretsReady(true)
119
128
  })()
120
129
  return () => {
121
130
  cancelled = true
131
+ secretsReadyRef.current = false
122
132
  }
123
133
  }, [])
124
134
 
@@ -177,16 +187,30 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
177
187
  const deleteAllWalletKeys = useCallback(() => deleteAllSecrets(), [])
178
188
 
179
189
  const hasStoredIdentity = useCallback(async (): Promise<boolean> => {
180
- if (legacyFallback.current) {
181
- return (await readLegacySecret('mnemonic')) != null || (await readLegacySecret('recoveredKey')) != null
182
- }
183
- return hasAnySecret()
190
+ return (await hasAnySecret({ strict: true })) ||
191
+ (await readLegacySecret('mnemonic', { strict: true })) != null ||
192
+ (await readLegacySecret('recoveredKey', { strict: true })) != null
184
193
  }, [])
185
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])
208
+
186
209
  /* -------------------------------- output --------------------------------- */
187
210
 
188
211
  const value: LocalStorageContextType = useMemo(
189
212
  () => ({
213
+ createMnemonic,
190
214
  setMnemonic,
191
215
  getMnemonic,
192
216
  deleteMnemonic,
@@ -206,6 +230,7 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
206
230
  deleteItem: AsyncStorage.removeItem
207
231
  }),
208
232
  [
233
+ createMnemonic,
209
234
  setMnemonic,
210
235
  getMnemonic,
211
236
  deleteMnemonic,
@@ -135,7 +135,8 @@ const DEFAULT_SETTINGS: WalletSettings = {
135
135
  }
136
136
  }
137
137
  import type { AppChain } from '../config'
138
- import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, DEFAULT_BACKUP_URL, toWalletChain } from '../config'
138
+ import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
139
+ import { getBackupUrl } from '../toolboxConfig'
139
140
  import { DEFAULT_AUTO_APPROVE_THRESHOLD, AUTO_APPROVE_COOLDOWN_MS, AUTO_APPROVE_STORAGE_KEY } from '../constants'
140
141
  import AsyncStorage from '@react-native-async-storage/async-storage'
141
142
  import { UserContext } from './UserContext'
@@ -1188,7 +1189,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1188
1189
  primaryKey,
1189
1190
  chain: chainStr,
1190
1191
  identityKey,
1191
- baseUrl: DEFAULT_BACKUP_URL,
1192
+ baseUrl: getBackupUrl(),
1192
1193
  onProgress: (chunks, total) => setBackupRestore({ phase: 'restoring', chunks, total }),
1193
1194
  // reviewSpendableOutputs talks to Services through the Wallet, which
1194
1195
  // needs this storage attached first. Attach here (idempotent with the
@@ -1461,7 +1462,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1461
1462
  //
1462
1463
  // Reads chunks straight from phoneStorage rather than through
1463
1464
  // WalletStorageManager, whose sync lock would block all storage access.
1464
- if (DEFAULT_BACKUP_URL !== '') {
1465
+ if (getBackupUrl() !== '') {
1465
1466
  monitor.addTask(
1466
1467
  new TaskBackupPush(monitor, async () => {
1467
1468
  return await pushOnce({
@@ -1469,7 +1470,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1469
1470
  primaryKey,
1470
1471
  chain: backupChain,
1471
1472
  identityKey: keyDeriver.identityKey,
1472
- baseUrl: DEFAULT_BACKUP_URL
1473
+ baseUrl: getBackupUrl()
1473
1474
  })
1474
1475
  })
1475
1476
  )
@@ -606,6 +606,7 @@ const resources = {
606
606
  advanced: 'Advanced',
607
607
  copy_secret_words: 'Copy Secret Words',
608
608
  print_recovery_keys: 'Print Recovery Keys',
609
+ backup_wallet_keys: 'Backup Wallet Keys',
609
610
  log_out: 'Log Out',
610
611
  connect_to_app: 'Connect to App',
611
612
  no_connections_yet: 'No connections yet',
@@ -1251,6 +1252,7 @@ const resources = {
1251
1252
  advanced: '高级设置',
1252
1253
  copy_secret_words: '复制助记词',
1253
1254
  print_recovery_keys: '打印恢复密钥',
1255
+ backup_wallet_keys: '备份钱包密钥',
1254
1256
  log_out: '退出登录',
1255
1257
  connect_to_app: '连接应用',
1256
1258
  no_connections_yet: '暂无连接',
@@ -1901,6 +1903,7 @@ const resources = {
1901
1903
  advanced: 'उन्नत',
1902
1904
  copy_secret_words: 'गुप्त शब्द कॉपी करें',
1903
1905
  print_recovery_keys: 'रिकवरी कुंजियाँ प्रिंट करें',
1906
+ backup_wallet_keys: 'वॉलेट की कुंजियों का बैकअप लें',
1904
1907
  log_out: 'लॉग आउट',
1905
1908
  connect_to_app: 'ऐप से कनेक्ट करें',
1906
1909
  no_connections_yet: 'अभी तक कोई कनेक्शन नहीं',
@@ -2567,6 +2570,7 @@ const resources = {
2567
2570
  advanced: 'Avanzado',
2568
2571
  copy_secret_words: 'Copiar palabras secretas',
2569
2572
  print_recovery_keys: 'Imprimir claves de recuperación',
2573
+ backup_wallet_keys: 'Respaldar claves de la cartera',
2570
2574
  log_out: 'Cerrar sesión',
2571
2575
  connect_to_app: 'Conectar a una app',
2572
2576
  no_connections_yet: 'Aún no hay conexiones',
@@ -3238,6 +3242,7 @@ const resources = {
3238
3242
  advanced: 'Avancé',
3239
3243
  copy_secret_words: 'Copier les mots secrets',
3240
3244
  print_recovery_keys: 'Imprimer les clés de récupération',
3245
+ backup_wallet_keys: 'Sauvegarder les clés du portefeuille',
3241
3246
  log_out: 'Se déconnecter',
3242
3247
  connect_to_app: 'Connecter une app',
3243
3248
  no_connections_yet: "Aucune connexion pour l'instant",
@@ -3899,6 +3904,7 @@ const resources = {
3899
3904
  advanced: 'خيارات متقدمة',
3900
3905
  copy_secret_words: 'نسخ الكلمات السرية',
3901
3906
  print_recovery_keys: 'طباعة مفاتيح الاسترداد',
3907
+ backup_wallet_keys: 'نسخ مفاتيح المحفظة احتياطيًا',
3902
3908
  log_out: 'تسجيل الخروج',
3903
3909
  connect_to_app: 'الاتصال بتطبيق',
3904
3910
  no_connections_yet: 'لا اتصالات حتى الآن',
@@ -4556,6 +4562,7 @@ const resources = {
4556
4562
  advanced: 'Avançado',
4557
4563
  copy_secret_words: 'Copiar palavras secretas',
4558
4564
  print_recovery_keys: 'Imprimir chaves de recuperação',
4565
+ backup_wallet_keys: 'Fazer backup das chaves da carteira',
4559
4566
  log_out: 'Sair',
4560
4567
  connect_to_app: 'Conectar ao app',
4561
4568
  no_connections_yet: 'Nenhuma conexão ainda',
@@ -5218,6 +5225,7 @@ const resources = {
5218
5225
  advanced: 'উন্নত',
5219
5226
  copy_secret_words: 'গোপন শব্দ কপি করুন',
5220
5227
  print_recovery_keys: 'রিকভারি কী প্রিন্ট করুন',
5228
+ backup_wallet_keys: 'ওয়ালেটের কীগুলির ব্যাকআপ নিন',
5221
5229
  log_out: 'লগ আউট',
5222
5230
  connect_to_app: 'অ্যাপে সংযোগ করুন',
5223
5231
  no_connections_yet: 'এখনো কোনো সংযোগ নেই',
@@ -5882,6 +5890,7 @@ const resources = {
5882
5890
  advanced: 'Расширенные',
5883
5891
  copy_secret_words: 'Скопировать секретные слова',
5884
5892
  print_recovery_keys: 'Распечатать ключи восстановления',
5893
+ backup_wallet_keys: 'Резервная копия ключей кошелька',
5885
5894
  log_out: 'Выйти',
5886
5895
  connect_to_app: 'Подключить приложение',
5887
5896
  no_connections_yet: 'Нет подключений',
@@ -6545,6 +6554,7 @@ const resources = {
6545
6554
  advanced: 'Lanjutan',
6546
6555
  copy_secret_words: 'Salin Kata Rahasia',
6547
6556
  print_recovery_keys: 'Cetak Kunci Pemulihan',
6557
+ backup_wallet_keys: 'Cadangkan Kunci Dompet',
6548
6558
  log_out: 'Keluar',
6549
6559
  connect_to_app: 'Hubungkan ke Aplikasi',
6550
6560
  no_connections_yet: 'Belum ada koneksi',
@@ -7227,6 +7237,7 @@ const resources = {
7227
7237
  advanced: '詳細設定',
7228
7238
  copy_secret_words: 'シークレットワードをコピー',
7229
7239
  print_recovery_keys: 'リカバリーキーを印刷',
7240
+ backup_wallet_keys: 'ウォレットの鍵をバックアップ',
7230
7241
  log_out: 'ログアウト',
7231
7242
  connect_to_app: 'アプリに接続',
7232
7243
  no_connections_yet: 'まだ接続がありません',
@@ -7906,6 +7917,7 @@ const resources = {
7906
7917
  advanced: 'Zaawansowane',
7907
7918
  copy_secret_words: 'Kopiuj tajne słowa',
7908
7919
  print_recovery_keys: 'Drukuj klucze odzyskiwania',
7920
+ backup_wallet_keys: 'Utwórz kopię zapasową kluczy portfela',
7909
7921
  log_out: 'Wyloguj',
7910
7922
  connect_to_app: 'Połącz z aplikacją',
7911
7923
  no_connections_yet: 'Brak połączeń',
package/core/index.ts CHANGED
@@ -21,11 +21,21 @@ export {
21
21
  DEFAULT_WAB_URL,
22
22
  DEFAULT_STORAGE_URL,
23
23
  DEFAULT_MESSAGEBOX_URL,
24
- DEFAULT_BACKUP_URL,
25
24
  DEFAULT_CHAIN,
26
25
  ADMIN_ORIGINATOR
27
26
  } from './config'
28
27
 
28
+ // Host-supplied runtime configuration (backup endpoint, service URLs and keys).
29
+ // Must be installed by the host app before anything here renders — see toolboxConfig.ts.
30
+ export {
31
+ configureToolbox,
32
+ isToolboxConfigured,
33
+ getBackupUrl,
34
+ getServiceConfig,
35
+ resetToolboxConfig
36
+ } from './toolboxConfig'
37
+ export type { ToolboxConfig, ToolboxServiceConfig } from './toolboxConfig'
38
+
29
39
  // Theme tokens and providers
30
40
  export { ThemeProvider, useTheme } from './theme/ThemeContext'
31
41
  export { spacing, radii, typography, lightColors, darkColors, hitTargets } from './theme/tokens'
@@ -35,10 +35,11 @@ export type MigrationResult =
35
35
  /** Reads a legacy plaintext item. Prompt-free — these were always written
36
36
  * unauthenticated. Kept exported so the provider can still serve a session
37
37
  * whose migration failed, instead of showing the user an empty wallet. */
38
- export async function readLegacySecret(name: SecretName): Promise<string | null> {
38
+ export async function readLegacySecret(name: SecretName, options?: { strict?: boolean }): Promise<string | null> {
39
39
  try {
40
40
  return await SecureStore.getItemAsync(LEGACY_KEYS[name])
41
- } catch {
41
+ } catch (err) {
42
+ if (options?.strict) throw err
42
43
  return null
43
44
  }
44
45
  }