@bsv/expo-wallet-toolbox 0.11.8 → 0.13.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 (62) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/core/backup/erase.ts +7 -1
  3. package/core/backup/preference.ts +12 -4
  4. package/core/backup/push.ts +8 -1
  5. package/core/backup/status.ts +6 -2
  6. package/core/config.tsx +1 -1
  7. package/core/context/WalletContext.tsx +904 -184
  8. package/core/i18n/translations.tsx +496 -12
  9. package/core/identity/handleRegistry/registration.ts +57 -3
  10. package/core/index.ts +26 -1
  11. package/core/mandala/createRuntime.ts +3 -3
  12. package/core/mandala/runtime.ts +7 -2
  13. package/core/mnemonicWallet.ts +46 -40
  14. package/core/monitor/MonitorSupervisor.ts +35 -1
  15. package/core/monitor/TaskCreditInbox.ts +24 -0
  16. package/core/pay/beefRepair.ts +8 -3
  17. package/core/pay/rails/address.ts +43 -3
  18. package/core/pay/rails/handle.ts +5 -3
  19. package/core/pay/sweeper.ts +39 -4
  20. package/core/peerpay/outbox.ts +11 -1
  21. package/core/profiles/assertProfileEmpty.ts +287 -0
  22. package/core/profiles/discovery.ts +84 -0
  23. package/core/profiles/profileLabel.ts +13 -0
  24. package/core/profiles/profileStore.ts +265 -0
  25. package/core/profiles/purgeProfile.ts +76 -0
  26. package/core/profiles/removeProfile.ts +257 -0
  27. package/core/push/events.ts +189 -0
  28. package/core/push/identities.ts +55 -0
  29. package/core/push/profilePush.ts +143 -0
  30. package/core/push/pushAdvisory.ts +33 -0
  31. package/core/push/registration.ts +391 -0
  32. package/core/push/types.ts +35 -0
  33. package/core/services/arcTokenStorage.ts +17 -2
  34. package/core/services/vault/transfers.ts +6 -1
  35. package/core/services/vault/vaultStore.ts +16 -3
  36. package/core/stores/ConnectionStore.ts +11 -7
  37. package/core/toolboxConfig.ts +31 -4
  38. package/core/userAvatar.ts +12 -5
  39. package/core/walletDbRegistry.ts +73 -0
  40. package/package.json +1 -1
  41. package/ui/backupShares.ts +2 -3
  42. package/ui/components/pay/HandleReceive.tsx +141 -16
  43. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  44. package/ui/components/pay/NotificationAdvisoryModal.tsx +124 -0
  45. package/ui/components/ui/PencilEditField.tsx +5 -2
  46. package/ui/components/wallet/Balance.tsx +3 -1
  47. package/ui/components/wallet/ProfileButton.tsx +92 -18
  48. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  49. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  50. package/ui/hooks/useSpendableBalance.ts +3 -1
  51. package/ui/index.ts +1 -0
  52. package/ui/printRecoveryShares.ts +6 -7
  53. package/ui/screens/PairScreen.tsx +2 -1
  54. package/ui/screens/PayScreen.tsx +53 -0
  55. package/ui/screens/ProfileScreen.tsx +195 -4
  56. package/ui/screens/SettingsScreen.tsx +80 -6
  57. package/ui/screens/VaultScreen.tsx +31 -2
  58. package/ui/screens/VaultTransferScreen.tsx +25 -2
  59. package/ui/screens/WalletCheckScreen.tsx +2 -1
  60. package/ui/screens/WalletConfigScreen.tsx +51 -21
  61. package/ui/screens/WalletHomeScreen.tsx +6 -3
  62. package/ui/tokenSeen.ts +13 -9
@@ -0,0 +1,287 @@
1
+ /**
2
+ * The proof that a profile holds nothing, which is what makes removing it safe.
3
+ *
4
+ * Removing a profile deletes its databases and stops monitoring it. The seed
5
+ * still derives the same keys, so nothing on chain is destroyed — but a coin,
6
+ * a half-sent payment or a payment not yet credited that lives only in that
7
+ * database would no longer be looked after by anything. So this answers one
8
+ * question, and answers it strictly: is there anything here a person could be
9
+ * owed, or owe?
10
+ *
11
+ * It runs on the OPEN storage of the profile being removed, and it fails
12
+ * closed. A check that threw says nothing about what is in the database, so
13
+ * every error becomes `check-failed` and never `ok`; the one way to get `ok`
14
+ * is for every check to have run and found nothing.
15
+ *
16
+ * The state lists are written the other way round from the spec's prose — as
17
+ * what is TERMINAL, with everything else blocking. For every status that exists
18
+ * today that is the same set, and a status added later blocks removal until
19
+ * somebody decides it should not, which is the safe direction to be wrong in.
20
+ *
21
+ * Read-only. The localpay queue in particular is read raw rather than through
22
+ * `getUnprocessed`: that reader repairs a corrupt queue as a side effect, and a
23
+ * check that cleaned up its own evidence would pass the second time it ran.
24
+ */
25
+ import type { BindValue } from '../storage/methods/offlineActions'
26
+ import { PENDING_JOURNAL_KEY } from '../identity/handleRegistry/registration'
27
+ import { PENDING_KEY } from '../localpay/pending'
28
+ import { getOutboxEntriesStrict, unsentEntries } from '../peerpay/outbox'
29
+
30
+ /** Why a profile cannot be removed. One code per thing found, for the UI to explain. */
31
+ export type RemovalBlocker =
32
+ /** A spendable output in any basket, tokens included. */
33
+ | 'spendable-outputs'
34
+ /** A transaction that is not yet completed or failed. */
35
+ | 'pending-transactions'
36
+ /** A payment queued, being posted, parked or held for review. */
37
+ | 'offline-queue'
38
+ /** A token payment that has not reached a final state. */
39
+ | 'token-settlements'
40
+ /** A token balance, or tokens still settling. */
41
+ | 'token-balance'
42
+ /** A received payment waiting to be credited — stuck or corrupt ones included. */
43
+ | 'localpay-pending'
44
+ /** A payment sent but not yet delivered to its recipient. */
45
+ | 'peerpay-outbox'
46
+ /** A handle write that was started and not finished. */
47
+ | 'handle-journal'
48
+ /** A payment in the MessageBox inbox that the credit pass could not finish. */
49
+ | 'inbox-pending'
50
+ /**
51
+ * Money or unfinished business in this profile's database for ANOTHER network
52
+ * (or an older file of it). Removal deletes every network's database, and only
53
+ * the open one was looked into by name.
54
+ */
55
+ | 'other-network'
56
+ /** Something could not be read, so nothing can be said. */
57
+ | 'check-failed'
58
+
59
+ export type ProfileEmptyResult = { ok: true } | { ok: false; reasons: RemovalBlocker[] }
60
+
61
+ /** The slice of `SQLiteDatabase` the checks need. */
62
+ export interface ProfileEmptyDb {
63
+ getFirstAsync(sql: string, params: BindValue[]): Promise<unknown>
64
+ }
65
+
66
+ /**
67
+ * Structurally satisfied by `StorageExpoSQLite`. `sqliteDb` is `undefined` once
68
+ * the storage has been destroyed, and that reads as `check-failed`.
69
+ */
70
+ export interface ProfileEmptyStorage {
71
+ readonly sqliteDb: ProfileEmptyDb | undefined
72
+ getKeyValue(key: string): Promise<string | undefined>
73
+ }
74
+
75
+ export interface AssertProfileEmptyDeps {
76
+ /**
77
+ * One forced pass over the MessageBox inbox, resolving when it has run to the
78
+ * end. It runs FIRST, so whatever it credits is already in the database when
79
+ * the checks below read it.
80
+ *
81
+ * `pending` is a payment still waiting to be credited; `attention` is one the
82
+ * pass gave up on or could not parse. Either is money this device was told
83
+ * about and does not hold yet. A pass that cannot run at all (offline, the
84
+ * box unreachable) rejects, and that is `check-failed`: an unread inbox is
85
+ * not an empty one. A wallet with no MessageBox host has nothing to drain and
86
+ * resolves `{ attention: 0, pending: false }`.
87
+ */
88
+ creditInbox: () => Promise<{ attention: number; pending: boolean }>
89
+ /**
90
+ * The Mandala runtime's `balances()`, when this wallet has one. Belt and
91
+ * braces only: the runtime's own token listing swallows its errors into an
92
+ * empty list, so a zero here proves less than it appears to. The SQL checks
93
+ * on outputs and settlements are what actually cover tokens, which is why
94
+ * this may be left out.
95
+ */
96
+ mandalaBalances?: () => Promise<ReadonlyArray<{ baseUnits: number; unsettledBaseUnits: number }>>
97
+ }
98
+
99
+ // Terminal lists, not blocking lists — see the header.
100
+ const SPENDABLE_OUTPUTS = 'SELECT 1 AS found FROM outputs WHERE userId = ? AND spendable <> 0 LIMIT 1'
101
+ const OPEN_TRANSACTIONS =
102
+ "SELECT 1 AS found FROM transactions WHERE userId = ? AND status NOT IN ('completed', 'failed') LIMIT 1"
103
+ // Equal to queued/posting/parked/import_hold for every status there is.
104
+ const OPEN_OFFLINE_ACTIONS =
105
+ "SELECT 1 AS found FROM offline_actions WHERE userId = ? AND status NOT IN ('sent', 'rejected', 'acknowledged') LIMIT 1"
106
+ // No userId column: this table is one database's worth, and a database is one profile's.
107
+ const OPEN_SETTLEMENTS =
108
+ "SELECT 1 AS found FROM token_settlements WHERE state NOT IN ('broadcast', 'admitted', 'refused', 'orphaned') LIMIT 1"
109
+ // A corrupt localpay queue is copied here and the live key reset (pending.ts `readAll`).
110
+ const QUARANTINED_PENDING =
111
+ "SELECT 1 AS found FROM key_value_store WHERE key LIKE 'localpay\\_pending\\_corrupt\\_%' ESCAPE '\\' LIMIT 1"
112
+
113
+ async function exists(db: ProfileEmptyDb | undefined, sql: string, params: BindValue[]): Promise<boolean> {
114
+ if (!db) throw new Error('assertProfileEmpty: the database is closed')
115
+ return (await db.getFirstAsync(sql, params)) != null
116
+ }
117
+
118
+ /** Any entry that is not finished, or a queue that cannot be understood. */
119
+ async function receivedPaymentsWaiting(storage: ProfileEmptyStorage): Promise<boolean> {
120
+ const raw = await storage.getKeyValue(PENDING_KEY)
121
+ if (raw) {
122
+ let parsed: unknown
123
+ try {
124
+ parsed = JSON.parse(raw)
125
+ } catch {
126
+ return true
127
+ }
128
+ if (!Array.isArray(parsed)) return true
129
+ // `completed` entries are credited already, so what they were worth is in
130
+ // `outputs`; the queue drops them on its next write anyway.
131
+ if (parsed.some(entry => (entry as { status?: unknown } | null)?.status !== 'completed')) return true
132
+ }
133
+ return await exists(storage.sqliteDb, QUARANTINED_PENDING, [])
134
+ }
135
+
136
+ export async function assertProfileEmpty(
137
+ storage: ProfileEmptyStorage,
138
+ userId: number,
139
+ deps: AssertProfileEmptyDeps
140
+ ): Promise<ProfileEmptyResult> {
141
+ // Bound into every query below: anything but a real row id would match
142
+ // nothing, and "matched nothing" is the answer this function must never give
143
+ // for a reason other than the profile being empty.
144
+ if (!Number.isInteger(userId) || userId <= 0) return { ok: false, reasons: ['check-failed'] }
145
+
146
+ const reasons: RemovalBlocker[] = []
147
+ const note = (reason: RemovalBlocker) => {
148
+ if (!reasons.includes(reason)) reasons.push(reason)
149
+ }
150
+ /** Every check runs even after one has failed, so the user is told all of it. */
151
+ const check = async (blocker: RemovalBlocker, blocked: () => Promise<boolean>) => {
152
+ try {
153
+ if (await blocked()) note(blocker)
154
+ } catch {
155
+ note('check-failed')
156
+ }
157
+ }
158
+
159
+ const db = storage.sqliteDb
160
+
161
+ await check('inbox-pending', async () => {
162
+ const pass = await deps.creditInbox()
163
+ return !(pass.pending === false && pass.attention === 0)
164
+ })
165
+ await check('spendable-outputs', () => exists(db, SPENDABLE_OUTPUTS, [userId]))
166
+ await check('pending-transactions', () => exists(db, OPEN_TRANSACTIONS, [userId]))
167
+ await check('offline-queue', () => exists(db, OPEN_OFFLINE_ACTIONS, [userId]))
168
+ await check('token-settlements', () => exists(db, OPEN_SETTLEMENTS, []))
169
+ await check('token-balance', async () => {
170
+ if (!deps.mandalaBalances) return false
171
+ const balances = await deps.mandalaBalances()
172
+ return balances.some(b => !(b.baseUnits === 0 && b.unsettledBaseUnits === 0))
173
+ })
174
+ await check('localpay-pending', () => receivedPaymentsWaiting(storage))
175
+ await check('peerpay-outbox', async () => unsentEntries(await getOutboxEntriesStrict(storage)).length > 0)
176
+ // Any value at all, not one parsed: `clearJournal` leaves `''` behind, and
177
+ // that is the only thing that means "nothing in flight".
178
+ await check('handle-journal', async () => !!(await storage.getKeyValue(PENDING_JOURNAL_KEY)))
179
+
180
+ return reasons.length === 0 ? { ok: true } : { ok: false, reasons }
181
+ }
182
+
183
+ /** Every blocker found by any of `results`, once each, in the order they were found. `ok` only when all are. */
184
+ export function combineEmpty(...results: ProfileEmptyResult[]): ProfileEmptyResult {
185
+ const reasons: RemovalBlocker[] = []
186
+ for (const result of results) {
187
+ if (result.ok) continue
188
+ for (const reason of result.reasons) if (!reasons.includes(reason)) reasons.push(reason)
189
+ }
190
+ return reasons.length === 0 ? { ok: true } : { ok: false, reasons }
191
+ }
192
+
193
+ /** A wallet database opened only to be read. The slice of `SQLiteDatabase` the checks use. */
194
+ export interface ClosedProfileDb extends ProfileEmptyDb {
195
+ closeAsync(): Promise<void>
196
+ }
197
+
198
+ export interface DatabasesEmptyDeps {
199
+ /** Every database file to look into: all those registered for the identity, minus any already checked. Rejects when the registry cannot be read. */
200
+ list(): Promise<readonly string[]>
201
+ /** Open one of them. Opening a file that is gone creates it empty, which reads as a database with nothing in it. */
202
+ open(filename: string): Promise<ClosedProfileDb>
203
+ }
204
+
205
+ const HAS_USERS_TABLE = "SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = 'users' LIMIT 1"
206
+ const USER_BY_IDENTITY = 'SELECT userId FROM users WHERE identityKey = ? LIMIT 1'
207
+
208
+ /** One file: every check but the inbox (which belongs to a wallet that is open, and none of these is). */
209
+ async function databaseEmpty(db: ClosedProfileDb, identityKey: string): Promise<ProfileEmptyResult> {
210
+ // No `users` table: a file that was never migrated, such as a registry entry
211
+ // whose file was gone and has just been created empty by opening it. Read from
212
+ // sqlite_master, so a database that could not be read at all still throws.
213
+ if (!(await exists(db, HAS_USERS_TABLE, []))) return { ok: true }
214
+ const row = (await db.getFirstAsync(USER_BY_IDENTITY, [identityKey])) as { userId?: unknown } | null
215
+ // Nothing in this file was ever written for this identity.
216
+ if (!row) return { ok: true }
217
+ const userId = Number(row.userId)
218
+ return assertProfileEmpty(
219
+ {
220
+ sqliteDb: db,
221
+ getKeyValue: async key =>
222
+ (
223
+ (await db.getFirstAsync('SELECT value FROM key_value_store WHERE key = ?', [key])) as {
224
+ value?: string
225
+ } | null
226
+ )?.value
227
+ },
228
+ userId,
229
+ // The MessageBox inbox is read through an open wallet, and none of these is one.
230
+ // What is waiting there stays on the server until a wallet for the identity reads it.
231
+ { creditInbox: async () => ({ attention: 0, pending: false }) }
232
+ )
233
+ }
234
+
235
+ /**
236
+ * Look into every database file `deps.list()` names for the same things
237
+ * `assertProfileEmpty` checks in the open one, each file on its own connection,
238
+ * closed again afterwards. Fails closed: a registry that cannot be read, a file
239
+ * that cannot be opened and any read that throws are all `check-failed`.
240
+ *
241
+ * Removal deletes a profile's databases on EVERY network, while the open
242
+ * storage proves one of them empty; this is what covers the rest, before the
243
+ * delete and again once the profile's own wallet is down.
244
+ */
245
+ export async function assertDatabasesEmpty(identityKey: string, deps: DatabasesEmptyDeps): Promise<ProfileEmptyResult> {
246
+ let files: readonly string[]
247
+ try {
248
+ files = await deps.list()
249
+ } catch {
250
+ return { ok: false, reasons: ['check-failed'] }
251
+ }
252
+ const results: ProfileEmptyResult[] = []
253
+ for (const filename of files) {
254
+ let db: ClosedProfileDb | undefined
255
+ try {
256
+ db = await deps.open(filename)
257
+ results.push(await databaseEmpty(db, identityKey))
258
+ } catch {
259
+ results.push({ ok: false, reasons: ['check-failed'] })
260
+ } finally {
261
+ try {
262
+ await db?.closeAsync()
263
+ } catch {
264
+ // A handle that will not close says nothing about what was in it.
265
+ }
266
+ }
267
+ }
268
+ return combineEmpty(...results)
269
+ }
270
+
271
+ /**
272
+ * `assertDatabasesEmpty` for the files of the networks that are NOT open. What it
273
+ * finds there is reported as `other-network`, since the person looking at an empty
274
+ * balance on the network they are on needs to be told where the rest is — every
275
+ * reason but `check-failed`, which stays what it is.
276
+ */
277
+ export async function assertOtherNetworksEmpty(
278
+ identityKey: string,
279
+ deps: DatabasesEmptyDeps
280
+ ): Promise<ProfileEmptyResult> {
281
+ const result = await assertDatabasesEmpty(identityKey, deps)
282
+ if (result.ok) return result
283
+ return combineEmpty({
284
+ ok: false,
285
+ reasons: result.reasons.map<RemovalBlocker>(reason => (reason === 'check-failed' ? reason : 'other-network'))
286
+ })
287
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Restore discovery: after a seed is imported, find the other profiles it backed up.
3
+ *
4
+ * The mnemonic says nothing about how many profiles were ever used, but each one
5
+ * pushed its history to its own remote-backup account (the pseudonym derives from
6
+ * that profile's primary key). So probe profile 1, 2, … in turn: a profile with a
7
+ * backup on any network exists; the first index with none on every network ends
8
+ * the search. Found profiles are only registered here — each replays its backup
9
+ * the first time the user switches to it, so an import never stalls on them.
10
+ *
11
+ * A profile removed on this device keeps its slot as a tombstone. Discovery
12
+ * leaves it exactly as it is: no probe, no registration, and it does not end the
13
+ * search, so the profiles after it are still found.
14
+ *
15
+ * Known gap: a profile that never backed anything up (unused, or backup turned
16
+ * off) stops the search, hiding any profile after it. Adding a profile again
17
+ * restores whatever exists at the next index.
18
+ */
19
+ import type { AppChain } from '../config'
20
+ import { BACKUP_CHAINS, type BackupChain } from '../backup/constants'
21
+ import { listBackups } from '../backup/restore'
22
+ import { deriveProfileKeys, hdFromMnemonic } from '../mnemonicWallet'
23
+ import { appendProfile, getProfilesState } from './profileStore'
24
+
25
+ /** Whether `primaryKey` has a remote backup on `chain`. May throw on a network error. */
26
+ export type ProfileProbe = (primaryKey: number[], chain: BackupChain) => Promise<boolean>
27
+
28
+ export interface DiscoverProfilesDeps {
29
+ mnemonic: string
30
+ probe: ProfileProbe
31
+ /** Record profile `index` as existing on `network`. Called in index order. */
32
+ register: (index: number, network: AppChain) => Promise<void>
33
+ /** Indices to pass over (profiles removed on this device): not probed, not registered, not a stop. */
34
+ skip?: (index: number) => boolean
35
+ /** First index to probe. Default 1 — profile 0 is the wallet being imported. */
36
+ startIndex?: number
37
+ /** Hard stop on the number of profiles probed. Default 50. */
38
+ maxProfiles?: number
39
+ }
40
+
41
+ /** Probe profiles from `startIndex` until the first one with no backup; returns how many were registered. */
42
+ export async function discoverProfiles(deps: DiscoverProfilesDeps): Promise<number> {
43
+ const start = deps.startIndex ?? 1
44
+ const max = deps.maxProfiles ?? 50
45
+ // One PBKDF2 for the whole search; every profile derives from the same root.
46
+ const hd = hdFromMnemonic(deps.mnemonic)
47
+ let registered = 0
48
+ for (let n = start; n < start + max; n++) {
49
+ if (deps.skip?.(n)) continue
50
+ const { primaryKey } = deriveProfileKeys(hd, n)
51
+ const found: BackupChain[] = []
52
+ try {
53
+ for (const chain of BACKUP_CHAINS) {
54
+ if (await deps.probe(primaryKey, chain)) found.push(chain)
55
+ }
56
+ } catch (err) {
57
+ // An outage is not evidence the profile is absent: stop without guessing,
58
+ // keeping what was already found. Add profile recovers the rest later.
59
+ console.warn(`[profiles] discovery stopped at profile ${n}:`, err)
60
+ break
61
+ }
62
+ if (found.length === 0) break
63
+ await deps.register(n, found.includes('main') ? 'main' : found[0])
64
+ registered++
65
+ }
66
+ return registered
67
+ }
68
+
69
+ /**
70
+ * Add a discovered profile to the store, awaiting its first restore. Idempotent:
71
+ * only the next free slot is appended, so an index the store already holds (live
72
+ * or removed) is left untouched and a second import of the same seed adds
73
+ * nothing. Slots are counted with tombstones, never without them.
74
+ */
75
+ export async function registerDiscoveredProfile(index: number, network: AppChain): Promise<void> {
76
+ if (index === getProfilesState().profiles.length) {
77
+ await appendProfile(network, { needsRestore: true })
78
+ }
79
+ }
80
+
81
+ /** The production probe: a non-empty backup manifest on the backup server. */
82
+ export function backupProbe(baseUrl: string): ProfileProbe {
83
+ return async (primaryKey, chain) => (await listBackups({ primaryKey, chain, baseUrl })).length > 0
84
+ }
@@ -0,0 +1,13 @@
1
+ import type { ProfileRecord } from './profileStore'
2
+
3
+ /**
4
+ * What the user calls a profile: the private name they gave it, else the
5
+ * default `profile<n+1>`. The number follows the derivation index, so removing
6
+ * a profile never renumbers the ones after it.
7
+ */
8
+ export function profileLabel(
9
+ record: Pick<ProfileRecord, 'index' | 'name'>,
10
+ t: (key: string, options?: Record<string, unknown>) => string
11
+ ): string {
12
+ return record.name || t('profile_label', { number: record.index + 1 })
13
+ }
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Wallet profiles: one mnemonic, many wallets.
3
+ *
4
+ * Profile n is the wallet whose primary key is m/0'/n' (see mnemonicWallet.ts
5
+ * profilePaths). Each one has its own identity, database, backup account and
6
+ * network; the seed, recovery shares and app-wide settings are shared.
7
+ *
8
+ * This store is the one place that says which profile is active and which
9
+ * network each runs on. It lives in AsyncStorage rather than a wallet database
10
+ * because it has to be read BEFORE any database opens — it is what picks the
11
+ * database. Memory is authoritative and synchronous (screens and key builders
12
+ * read it during render); every write is persisted best-effort.
13
+ *
14
+ * A removed profile stays in the list as a tombstone (`deleted: true`). The
15
+ * index is the derivation path m/0'/n' and the key suffix, so it can never be
16
+ * reused: the list stays dense, `appendProfile` keeps counting past tombstones,
17
+ * and nothing that is active ever points at one.
18
+ *
19
+ * Per-profile device state (balance cache, avatar, ARC/MessageBox overrides,
20
+ * auto-approve, connections, seen-token markers) keeps its existing AsyncStorage
21
+ * key through `profileScopedKey`: profile 0 uses the bare key, profile n appends
22
+ * `__p<n>`. The index is known before any build, which an identity key is not.
23
+ */
24
+ import { useSyncExternalStore } from 'react'
25
+ import AsyncStorage from '@react-native-async-storage/async-storage'
26
+ import { DEFAULT_CHAIN, type AppChain } from '../config'
27
+
28
+ export const PROFILES_STORAGE_KEY = 'wallet_profiles_v1'
29
+
30
+ /** Matches every key `profileScopedKey` produces for a profile other than 0. */
31
+ export const PROFILE_KEY_SUFFIX_RE = /__p\d+$/
32
+
33
+ /** A sanity bound, not a product limit: no index past this is ever stored. */
34
+ export const MAX_PROFILES = 100
35
+
36
+ /** Longest private profile name, in characters. */
37
+ export const MAX_PROFILE_NAME_LENGTH = 24
38
+
39
+ export interface ProfileRecord {
40
+ index: number
41
+ network: AppChain
42
+ /** Recorded after this profile's first successful build on this device. Public. */
43
+ identityKey?: string
44
+ /** Replay this profile's remote backup on its next build (set by discovery / add). */
45
+ needsRestore?: boolean
46
+ /**
47
+ * Private label, device-only (not backed up, never published). Trimmed, at most
48
+ * MAX_PROFILE_NAME_LENGTH characters; absent = the default `profile<n+1>`.
49
+ */
50
+ name?: string
51
+ /** Tombstone: removed on this device. Keeps its index and identityKey; never profile 0. */
52
+ deleted?: true
53
+ }
54
+
55
+ export interface ProfilesState {
56
+ active: number
57
+ profiles: ProfileRecord[]
58
+ }
59
+
60
+ const CHAINS: readonly AppChain[] = ['main', 'test', 'teratest']
61
+
62
+ export function defaultProfilesState(): ProfilesState {
63
+ return { active: 0, profiles: [{ index: 0, network: DEFAULT_CHAIN }] }
64
+ }
65
+
66
+ /** Trim and cap a profile name; undefined when nothing is left (the default label applies). */
67
+ export function normalizeProfileName(raw: unknown): string | undefined {
68
+ if (typeof raw !== 'string') return undefined
69
+ // By character, not UTF-16 unit, so the cap never splits an emoji in half.
70
+ const name = Array.from(raw.trim()).slice(0, MAX_PROFILE_NAME_LENGTH).join('').trim()
71
+ return name === '' ? undefined : name
72
+ }
73
+
74
+ /** The index of the live profile closest to `from` (lower index on a tie). Profile 0 is always live. */
75
+ function nearestLive(profiles: ProfileRecord[], from: number): number {
76
+ for (let d = 0; d < profiles.length; d++) {
77
+ for (const i of [from - d, from + d]) {
78
+ if (profiles[i] && !profiles[i].deleted) return i
79
+ }
80
+ }
81
+ return 0
82
+ }
83
+
84
+ /**
85
+ * Tolerant parse: anything unreadable becomes the default, and whatever is
86
+ * readable is normalised into a dense list 0..count-1 so an index always names
87
+ * exactly one record.
88
+ */
89
+ export function parseProfilesState(raw: string | null): ProfilesState {
90
+ if (!raw) return defaultProfilesState()
91
+ let parsed: unknown
92
+ try {
93
+ parsed = JSON.parse(raw)
94
+ } catch {
95
+ return defaultProfilesState()
96
+ }
97
+ const obj = parsed as Partial<ProfilesState> | null
98
+ if (!obj || !Array.isArray(obj.profiles)) return defaultProfilesState()
99
+
100
+ const byIndex = new Map<number, ProfileRecord>()
101
+ for (const entry of obj.profiles as unknown[]) {
102
+ const r = entry as Partial<ProfileRecord> | null
103
+ if (!r || !Number.isInteger(r.index) || (r.index as number) < 0 || (r.index as number) >= MAX_PROFILES) continue
104
+ if (byIndex.has(r.index as number)) continue
105
+ const name = normalizeProfileName(r.name)
106
+ byIndex.set(r.index as number, {
107
+ index: r.index as number,
108
+ network: CHAINS.includes(r.network as AppChain) ? (r.network as AppChain) : DEFAULT_CHAIN,
109
+ ...(typeof r.identityKey === 'string' ? { identityKey: r.identityKey } : {}),
110
+ ...(r.needsRestore === true ? { needsRestore: true } : {}),
111
+ ...(name ? { name } : {}),
112
+ // Profile 0 anchors the seed (vault, discovery, the bare keys): it is never a tombstone.
113
+ ...(r.deleted === true && r.index !== 0 ? { deleted: true as const } : {})
114
+ })
115
+ }
116
+ // Dense from 0: a gap would leave an index the switcher cannot name.
117
+ const profiles: ProfileRecord[] = []
118
+ for (let i = 0; byIndex.has(i); i++) profiles.push(byIndex.get(i)!)
119
+ if (profiles.length === 0) return defaultProfilesState()
120
+
121
+ const stored =
122
+ Number.isInteger(obj.active) && (obj.active as number) < profiles.length && (obj.active as number) >= 0
123
+ ? (obj.active as number)
124
+ : 0
125
+ // Never rest on a tombstone: a crash between a removal's switch and its
126
+ // tombstone, or a store edited elsewhere, must still open a live wallet.
127
+ return { active: profiles[stored].deleted ? nearestLive(profiles, stored) : stored, profiles }
128
+ }
129
+
130
+ let state: ProfilesState = defaultProfilesState()
131
+ const listeners = new Set<() => void>()
132
+
133
+ function publish(next: ProfilesState): void {
134
+ state = next
135
+ listeners.forEach(l => l())
136
+ }
137
+
138
+ async function persist(): Promise<void> {
139
+ try {
140
+ await AsyncStorage.setItem(PROFILES_STORAGE_KEY, JSON.stringify(state))
141
+ } catch (err) {
142
+ console.warn('[profiles] persist failed', err)
143
+ }
144
+ }
145
+
146
+ /** Read the stored state into memory. Call before the first wallet build. */
147
+ export async function loadProfiles(): Promise<ProfilesState> {
148
+ let raw: string | null = null
149
+ try {
150
+ raw = await AsyncStorage.getItem(PROFILES_STORAGE_KEY)
151
+ } catch (err) {
152
+ console.warn('[profiles] load failed', err)
153
+ }
154
+ publish(parseProfilesState(raw))
155
+ return state
156
+ }
157
+
158
+ export function getProfilesState(): ProfilesState {
159
+ return state
160
+ }
161
+
162
+ export function getActiveProfileIndex(): number {
163
+ return state.active
164
+ }
165
+
166
+ export function getActiveProfile(): ProfileRecord {
167
+ const record = state.profiles[state.active]
168
+ if (record && !record.deleted) return record
169
+ return state.profiles[nearestLive(state.profiles, state.active)]
170
+ }
171
+
172
+ /** The profiles that have not been removed, in index order. Defaults to the current state. */
173
+ export function liveProfiles(from: ProfilesState = state): ProfileRecord[] {
174
+ return from.profiles.filter(p => !p.deleted)
175
+ }
176
+
177
+ export async function setActiveProfile(n: number): Promise<void> {
178
+ if (!state.profiles[n]) throw new Error(`Unknown profile index: ${n}`)
179
+ if (state.profiles[n].deleted) throw new Error(`Profile ${n} was removed`)
180
+ if (state.active === n) return
181
+ publish({ ...state, active: n })
182
+ await persist()
183
+ }
184
+
185
+ /** Append the next profile (index = current count). Does not activate it. */
186
+ export async function appendProfile(
187
+ network: AppChain = DEFAULT_CHAIN,
188
+ opts: { needsRestore?: boolean } = {}
189
+ ): Promise<ProfileRecord> {
190
+ const index = state.profiles.length
191
+ if (index >= MAX_PROFILES) throw new Error('Too many profiles')
192
+ const record: ProfileRecord = { index, network, ...(opts.needsRestore ? { needsRestore: true } : {}) }
193
+ publish({ ...state, profiles: [...state.profiles, record] })
194
+ await persist()
195
+ return record
196
+ }
197
+
198
+ export async function updateProfile(n: number, patch: Partial<Omit<ProfileRecord, 'index'>>): Promise<void> {
199
+ const current = state.profiles[n]
200
+ if (!current) return
201
+ if (patch.deleted) {
202
+ // Both would break an invariant the rest of the app leans on. A removal
203
+ // switches away first, so neither is a legitimate request.
204
+ if (n === 0) throw new Error('Profile 0 cannot be removed')
205
+ if (n === state.active) throw new Error('The active profile cannot be removed')
206
+ }
207
+ const next: ProfileRecord = { ...current, ...patch, index: n }
208
+ if (!next.needsRestore) delete next.needsRestore
209
+ if (!next.deleted) delete next.deleted
210
+ const name = normalizeProfileName(next.name)
211
+ if (name) next.name = name
212
+ else delete next.name
213
+ if (
214
+ next.network === current.network &&
215
+ next.identityKey === current.identityKey &&
216
+ next.name === current.name &&
217
+ !!next.deleted === !!current.deleted &&
218
+ !!next.needsRestore === !!current.needsRestore
219
+ ) {
220
+ return
221
+ }
222
+ const profiles = state.profiles.slice()
223
+ profiles[n] = next
224
+ publish({ ...state, profiles })
225
+ await persist()
226
+ }
227
+
228
+ /** Back to a single profile 0 and no stored record (Delete Wallet). */
229
+ export async function resetProfiles(): Promise<void> {
230
+ publish(defaultProfilesState())
231
+ try {
232
+ await AsyncStorage.removeItem(PROFILES_STORAGE_KEY)
233
+ } catch (err) {
234
+ console.warn('[profiles] reset failed', err)
235
+ }
236
+ }
237
+
238
+ export function subscribeProfiles(listener: () => void): () => void {
239
+ listeners.add(listener)
240
+ return () => {
241
+ listeners.delete(listener)
242
+ }
243
+ }
244
+
245
+ export function useProfiles(): ProfilesState {
246
+ return useSyncExternalStore(subscribeProfiles, getProfilesState, getProfilesState)
247
+ }
248
+
249
+ export function useActiveProfileIndex(): number {
250
+ return useSyncExternalStore(subscribeProfiles, getActiveProfileIndex, getActiveProfileIndex)
251
+ }
252
+
253
+ /**
254
+ * The AsyncStorage / SecureStore key for per-profile state. Profile 0 keeps the
255
+ * bare key; profile n appends `__p<n>` (SecureStore allows only [A-Za-z0-9._-]).
256
+ */
257
+ export function profileScopedKey(base: string, index: number = state.active): string {
258
+ return index === 0 ? base : `${base}__p${index}`
259
+ }
260
+
261
+ /** Test-only: forget memory and listeners. */
262
+ export function __resetProfilesForTests(): void {
263
+ state = defaultProfilesState()
264
+ listeners.clear()
265
+ }