@bsv/expo-wallet-toolbox 0.19.0 → 0.20.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 (135) hide show
  1. package/CHANGELOG.md +121 -30
  2. package/README.md +79 -79
  3. package/core/backup/RemoteSyncReader.ts +26 -24
  4. package/core/backup/appData.ts +9 -8
  5. package/core/backup/codec.ts +21 -18
  6. package/core/backup/constants.ts +5 -5
  7. package/core/backup/contactsBackup.ts +8 -8
  8. package/core/backup/cursor.ts +12 -7
  9. package/core/backup/derive.ts +3 -3
  10. package/core/backup/deviceId.ts +2 -2
  11. package/core/backup/erase.ts +2 -2
  12. package/core/backup/preference.ts +2 -2
  13. package/core/backup/push.ts +10 -12
  14. package/core/backup/restore.ts +22 -14
  15. package/core/backup/restoreOnImport.ts +3 -2
  16. package/core/config.tsx +17 -13
  17. package/core/constants.ts +34 -11
  18. package/core/contacts/contactsStore.ts +4 -3
  19. package/core/context/WalletConnectionContext.tsx +294 -212
  20. package/core/context/WalletContext.tsx +132 -97
  21. package/core/context/defaultWalletSettings.ts +4 -2
  22. package/core/demo/demoLedger.ts +1 -5
  23. package/core/directpay/DirectPayProvider.tsx +15 -24
  24. package/core/directpay/receive.ts +2 -1
  25. package/core/headers/checkpoints.ts +10 -1
  26. package/core/headers/headerStore.ts +13 -2
  27. package/core/hooks/useConfirmationSound.ts +3 -3
  28. package/core/hooks/useHaptics.ts +23 -6
  29. package/core/i18n/translations.tsx +269 -125
  30. package/core/index.ts +2 -0
  31. package/core/localpay/codec.ts +12 -6
  32. package/core/localpay/deviceCaps.ts +4 -14
  33. package/core/localpay/pending.ts +2 -1
  34. package/core/localpay/qr.ts +1 -1
  35. package/core/localpay/settlementAck.ts +1 -4
  36. package/core/localpay/transport/ble.ts +2 -2
  37. package/core/localpay/transport/socket.ts +1 -1
  38. package/core/mandala/abortGuard.ts +1 -1
  39. package/core/mandala/drain.ts +3 -0
  40. package/core/mandala/permissionModule.ts +3 -2
  41. package/core/mandala/resendTransfer.ts +4 -1
  42. package/core/mandala/runtime.ts +4 -4
  43. package/core/monitor/TaskBackupPush.ts +10 -13
  44. package/core/net/chainMatch.ts +8 -5
  45. package/core/networks.ts +145 -0
  46. package/core/parsePeerPayURI.ts +4 -1
  47. package/core/pay/beefRepair.ts +6 -3
  48. package/core/pay/creditErrors.ts +37 -1
  49. package/core/pay/rails/address.ts +10 -6
  50. package/core/pay/rails/handle.ts +84 -11
  51. package/core/pay/rails/index.ts +18 -2
  52. package/core/pay/receiveHistory.ts +8 -8
  53. package/core/peerpay/handleResendRequests.ts +11 -18
  54. package/core/peerpay/inboxAttempts.ts +1 -4
  55. package/core/peerpay/rebuildToken.ts +12 -9
  56. package/core/profiles/profileStore.ts +2 -1
  57. package/core/profiles/removalProblems.ts +3 -1
  58. package/core/services/arcTokenStorage.ts +2 -1
  59. package/core/services/arcadeBroadcastProvider.ts +7 -17
  60. package/core/services/secrets/envelope.ts +1 -6
  61. package/core/services/secrets/hkdf.ts +1 -6
  62. package/core/services/secrets/index.ts +3 -22
  63. package/core/services/usdFxRates.ts +1 -4
  64. package/core/services/vault/VaultKeyService.ts +2 -1
  65. package/core/services/vault/chainRecovery.ts +48 -21
  66. package/core/services/vault/metaAuthority.ts +4 -1
  67. package/core/services/vault/r1comb.ts +113 -51
  68. package/core/services/vault/session.ts +5 -1
  69. package/core/services/vault/transfers.ts +699 -576
  70. package/core/services/vault/vaultStore.ts +12 -10
  71. package/core/services/walletArgLimits.ts +1 -2
  72. package/core/services/walletConnectionValidation.ts +44 -28
  73. package/core/services/walletServiceConfig.ts +9 -40
  74. package/core/storage/StorageExpoSQLite.ts +7 -21
  75. package/core/storage/methods/listActionsSql.ts +81 -67
  76. package/core/storage/methods/listOutputsSql.ts +21 -16
  77. package/core/storage/methods/reviewStatusSql.ts +1 -4
  78. package/core/stores/ConnectionStore.ts +1 -1
  79. package/core/theme/ThemeContext.tsx +12 -16
  80. package/core/theme/motion.ts +3 -3
  81. package/core/theme/tokens.ts +6 -6
  82. package/core/toolboxConfig.ts +23 -0
  83. package/core/walletDbRegistry.ts +7 -5
  84. package/core/walletRepair/runWalletCheck.ts +1 -4
  85. package/package.json +2 -2
  86. package/ui/components/pay/AddressReceive.tsx +3 -3
  87. package/ui/components/pay/HandleReceive.tsx +15 -15
  88. package/ui/components/pay/MessageBoxConfig.tsx +46 -20
  89. package/ui/components/pay/NearbyFlow.tsx +575 -507
  90. package/ui/components/pay/OfflineNotice.tsx +1 -3
  91. package/ui/components/pay/PayCellRow.tsx +1 -4
  92. package/ui/components/pay/PayForm.tsx +1 -3
  93. package/ui/components/pay/RequestHub.tsx +14 -6
  94. package/ui/components/pay/UniversalSend.tsx +79 -27
  95. package/ui/components/pay/tokenSendCopy.ts +1 -2
  96. package/ui/components/pay/useRecipientInput.ts +2 -2
  97. package/ui/components/security/WalletLockNotice.tsx +1 -3
  98. package/ui/components/ui/AlertCard.tsx +44 -45
  99. package/ui/components/ui/BlurChrome.tsx +4 -15
  100. package/ui/components/ui/Celebration.tsx +3 -3
  101. package/ui/components/ui/ChoiceSheet.ts +1 -3
  102. package/ui/components/ui/ErrorBoundary.tsx +2 -6
  103. package/ui/components/ui/GroupedList.tsx +13 -31
  104. package/ui/components/ui/IconButton.tsx +6 -9
  105. package/ui/components/ui/ListRow.tsx +19 -25
  106. package/ui/components/ui/PresenceRow.tsx +4 -4
  107. package/ui/components/ui/PressableScale.tsx +24 -20
  108. package/ui/components/ui/Toast.tsx +23 -16
  109. package/ui/components/vault/KeyChooser.tsx +9 -6
  110. package/ui/components/vault/VaultBackdrop.tsx +1 -8
  111. package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
  112. package/ui/components/wallet/ActivityRow.tsx +3 -2
  113. package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
  114. package/ui/components/wallet/Balance.tsx +4 -1
  115. package/ui/components/wallet/ContactActivityList.tsx +7 -7
  116. package/ui/components/wallet/IconPickerSheet.tsx +1 -5
  117. package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
  118. package/ui/components/wallet/tokenEviction.ts +4 -1
  119. package/ui/hooks/useMandala.ts +1 -7
  120. package/ui/hooks/useOfflineNoticeActions.ts +21 -27
  121. package/ui/hooks/useSpendableBalance.ts +2 -2
  122. package/ui/hooks/useVaultCoverage.ts +7 -1
  123. package/ui/index.ts +9 -1
  124. package/ui/resolveIdentity.ts +20 -8
  125. package/ui/screens/ConnectionsScreen.tsx +44 -18
  126. package/ui/screens/LogsScreen.tsx +24 -22
  127. package/ui/screens/PairScreen.tsx +85 -54
  128. package/ui/screens/PayScreen.tsx +5 -1
  129. package/ui/screens/ProfileScreen.tsx +0 -3
  130. package/ui/screens/TrustScreen.tsx +125 -80
  131. package/ui/screens/VaultScreen.tsx +19 -7
  132. package/ui/screens/VaultTransferScreen.tsx +5 -1
  133. package/ui/screens/WalletCheckScreen.tsx +14 -17
  134. package/ui/screens/WalletConfigScreen.tsx +414 -376
  135. package/ui/screens/WalletHomeScreen.tsx +47 -42
@@ -14,7 +14,7 @@ import { MAX_INDEX_ENTRIES, type BackupChain } from './constants'
14
14
  import type { RequestSyncChunkArgs, SyncChunk } from '../toolboxTypes'
15
15
 
16
16
  export class BackupChainError extends Error {
17
- constructor (message: string) {
17
+ constructor(message: string) {
18
18
  super(message)
19
19
  this.name = 'BackupChainError'
20
20
  }
@@ -27,21 +27,21 @@ const INDEX_PAGE_SIZE = 500
27
27
  // current chunk. Large chunks remain sequential to bound mobile memory use.
28
28
  const PREFETCH_MAX_BYTES = 1024 * 1024
29
29
 
30
- type BlobResult = { bytes: Uint8Array, error?: never } | { bytes?: never, error: unknown }
30
+ type BlobResult = { bytes: Uint8Array; error?: never } | { bytes?: never; error: unknown }
31
31
 
32
32
  export class RemoteSyncReader {
33
33
  private entries: LogEntry[] | null = null
34
34
  private next = 0
35
- private prefetched: { seq: number, result: Promise<BlobResult> } | null = null
35
+ private prefetched: { seq: number; result: Promise<BlobResult> } | null = null
36
36
  /** Decoded once, keyed by seq, so verifiedComplete's own look-ahead at the newest entry
37
37
  * never re-fetches or re-decrypts it when replay later reaches that same entry. */
38
- private decodedCache: { seq: number, decoded: DecodedEntry } | null = null
38
+ private decodedCache: { seq: number; decoded: DecodedEntry } | null = null
39
39
  private verifiedCompletePromise: Promise<boolean> | null = null
40
40
  /** The most recent (i.e. furthest along in replay order) appData snapshot seen on any
41
41
  * entry so far — see the `appData` getter below. */
42
42
  private lastAppData: AppDataSnapshot | undefined
43
43
 
44
- constructor (
44
+ constructor(
45
45
  private readonly client: BackupClient,
46
46
  private readonly wallet: CompletedProtoWallet,
47
47
  private readonly chain: BackupChain,
@@ -52,7 +52,7 @@ export class RemoteSyncReader {
52
52
  ) {}
53
53
 
54
54
  /** Settings for the storage being restored into. */
55
- async makeAvailable (): Promise<TableSettings> {
55
+ async makeAvailable(): Promise<TableSettings> {
56
56
  return this.settings
57
57
  }
58
58
 
@@ -61,7 +61,7 @@ export class RemoteSyncReader {
61
61
  * replay) and verifiedComplete (which only needs to know how many entries exist and what
62
62
  * the last one is).
63
63
  */
64
- private async ensureIndex (): Promise<LogEntry[]> {
64
+ private async ensureIndex(): Promise<LogEntry[]> {
65
65
  if (this.entries == null) {
66
66
  const entries: LogEntry[] = []
67
67
  let page = await this.client.index(this.deviceId, this.generation)
@@ -89,7 +89,7 @@ export class RemoteSyncReader {
89
89
  return this.entries
90
90
  }
91
91
 
92
- private async fetchAndDecode (entry: LogEntry): Promise<DecodedEntry> {
92
+ private async fetchAndDecode(entry: LogEntry): Promise<DecodedEntry> {
93
93
  if (this.decodedCache?.seq === entry.seq) return this.decodedCache.decoded
94
94
  let ciphertext: Uint8Array
95
95
  if (this.prefetched?.seq === entry.seq) {
@@ -133,7 +133,7 @@ export class RemoteSyncReader {
133
133
  * Every entry is an ordinary chunk (see codec.ts's DecodedEntry) — a seal, when present,
134
134
  * rides alongside a chunk rather than replacing it, so nothing here needs to be swallowed.
135
135
  */
136
- async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
136
+ async getSyncChunk(_args: RequestSyncChunkArgs): Promise<SyncChunk> {
137
137
  await this.ensureIndex()
138
138
  const entries = this.entries!
139
139
 
@@ -154,15 +154,21 @@ export class RemoteSyncReader {
154
154
  // reader after either fails must retry the same entry rather than lose it.
155
155
  this.next++
156
156
  const following = entries[this.next]
157
- if (following && entry.size > 0 && entry.size <= PREFETCH_MAX_BYTES &&
158
- following.size > 0 && following.size <= PREFETCH_MAX_BYTES &&
159
- this.decodedCache?.seq !== following.seq) {
157
+ if (
158
+ following &&
159
+ entry.size > 0 &&
160
+ entry.size <= PREFETCH_MAX_BYTES &&
161
+ following.size > 0 &&
162
+ following.size <= PREFETCH_MAX_BYTES &&
163
+ this.decodedCache?.seq !== following.seq
164
+ ) {
160
165
  this.prefetched = {
161
166
  seq: following.seq,
162
167
  // Store failures as values until consumed, so a stopped replay never
163
168
  // leaves an unhandled rejection from a speculative download.
164
169
  result: this.client.blob(this.deviceId, this.generation, following.seq).then(
165
- bytes => ({ bytes }), error => ({ error })
170
+ bytes => ({ bytes }),
171
+ error => ({ error })
166
172
  )
167
173
  }
168
174
  }
@@ -171,7 +177,7 @@ export class RemoteSyncReader {
171
177
  }
172
178
 
173
179
  /** Number of chunks in this generation, once the index has been read. */
174
- get length (): number {
180
+ get length(): number {
175
181
  return this.entries?.length ?? 0
176
182
  }
177
183
 
@@ -181,7 +187,7 @@ export class RemoteSyncReader {
181
187
  * reflects the newest chunk that carried the field — undefined for a log written entirely
182
188
  * before this feature shipped, or one with genuinely nothing app-owned to carry.
183
189
  */
184
- get appData (): AppDataSnapshot | undefined {
190
+ get appData(): AppDataSnapshot | undefined {
185
191
  return this.lastAppData
186
192
  }
187
193
 
@@ -202,14 +208,14 @@ export class RemoteSyncReader {
202
208
  * false the moment a new chunk becomes the newest entry — a generation is not "un-verified"
203
209
  * by continuing to receive backups.
204
210
  */
205
- async verifiedComplete (): Promise<boolean> {
211
+ async verifiedComplete(): Promise<boolean> {
206
212
  if (this.verifiedCompletePromise == null) {
207
213
  this.verifiedCompletePromise = this.computeVerifiedComplete()
208
214
  }
209
215
  return await this.verifiedCompletePromise
210
216
  }
211
217
 
212
- private async computeVerifiedComplete (): Promise<boolean> {
218
+ private async computeVerifiedComplete(): Promise<boolean> {
213
219
  const entries = await this.ensureIndex()
214
220
  if (entries.length === 0) return false
215
221
 
@@ -235,18 +241,14 @@ export class RemoteSyncReader {
235
241
  * A restore that silently stops halfway is worse than one that fails: the wallet would
236
242
  * look healthy while missing the outputs it needs to spend.
237
243
  */
238
- private verifyChain (entries: LogEntry[], start = 0): void {
244
+ private verifyChain(entries: LogEntry[], start = 0): void {
239
245
  for (let i = start; i < entries.length; i++) {
240
246
  const expectedSeq = i + 1
241
247
  if (entries[i].seq !== expectedSeq) {
242
- throw new BackupChainError(
243
- `backup chain has a gap: expected sequence ${expectedSeq}, found ${entries[i].seq}`
244
- )
248
+ throw new BackupChainError(`backup chain has a gap: expected sequence ${expectedSeq}, found ${entries[i].seq}`)
245
249
  }
246
250
  if (i > 0 && entries[i].prevSha256 !== entries[i - 1].sha256) {
247
- throw new BackupChainError(
248
- `backup chain is forked at sequence ${entries[i].seq}: previous hash does not match`
249
- )
251
+ throw new BackupChainError(`backup chain is forked at sequence ${entries[i].seq}: previous hash does not match`)
250
252
  }
251
253
  }
252
254
  }
@@ -51,15 +51,15 @@ import type { AppDataSnapshot } from './codec'
51
51
  import { mergeContacts } from './contactsBackup'
52
52
 
53
53
  export interface KVStorage {
54
- getKeyValue (k: string): Promise<string | undefined>
55
- setKeyValue (k: string, v: string): Promise<void>
54
+ getKeyValue(k: string): Promise<string | undefined>
55
+ setKeyValue(k: string, v: string): Promise<void>
56
56
  }
57
57
 
58
58
  /** True for `undefined` or a snapshot carrying nothing at all — the common "nothing queued,
59
59
  * nothing to add" case, which must produce no `appData` field at all (see codec.ts's
60
60
  * encodeChunk docs on why an unsealed/appData-less chunk must serialise byte-for-byte as the
61
61
  * old-format envelope). */
62
- export function isEmptyAppData (appData: AppDataSnapshot | undefined): boolean {
62
+ export function isEmptyAppData(appData: AppDataSnapshot | undefined): boolean {
63
63
  return (
64
64
  appData == null ||
65
65
  (appData.localpayPending === undefined &&
@@ -75,7 +75,7 @@ export function isEmptyAppData (appData: AppDataSnapshot | undefined): boolean {
75
75
  * send. Never called on its own cadence — see codec.ts's encodeChunk docs on why appData
76
76
  * only ever rides an already-non-empty chunk.
77
77
  */
78
- export async function captureAppDataSnapshot (storage: KVStorage): Promise<AppDataSnapshot> {
78
+ export async function captureAppDataSnapshot(storage: KVStorage): Promise<AppDataSnapshot> {
79
79
  const [localpayPending, peerpayOutbox, receiveIssuedDates] = await Promise.all([
80
80
  storage.getKeyValue(PENDING_KEY),
81
81
  storage.getKeyValue(OUTBOX_KEY),
@@ -95,7 +95,7 @@ export async function captureAppDataSnapshot (storage: KVStorage): Promise<AppDa
95
95
  * a newer one already landed (e.g. re-running an interrupted restore) can never regress a
96
96
  * row that a later chunk already updated in this same pass.
97
97
  */
98
- export async function applyAppData (storage: KVStorage, snapshot: AppDataSnapshot): Promise<void> {
98
+ export async function applyAppData(storage: KVStorage, snapshot: AppDataSnapshot): Promise<void> {
99
99
  if (snapshot.localpayPending !== undefined) await storage.setKeyValue(PENDING_KEY, snapshot.localpayPending)
100
100
  if (snapshot.peerpayOutbox !== undefined) await storage.setKeyValue(OUTBOX_KEY, snapshot.peerpayOutbox)
101
101
  if (snapshot.receiveIssuedDates !== undefined && snapshot.receiveIssuedDates.length > 0) {
@@ -105,7 +105,8 @@ export async function applyAppData (storage: KVStorage, snapshot: AppDataSnapsho
105
105
 
106
106
  /** Parses a KV row's raw JSON text into an array of plain objects, never throwing — a
107
107
  * corrupt or missing blob merges as if it were empty rather than failing the whole restore. */
108
- function parseJsonArray (raw: string | undefined): Array<Record<string, unknown>> { // eslint-disable-line @typescript-eslint/array-type
108
+ function parseJsonArray(raw: string | undefined): Array<Record<string, unknown>> {
109
+ // eslint-disable-line @typescript-eslint/array-type
109
110
  if (raw === undefined) return []
110
111
  try {
111
112
  const parsed = JSON.parse(raw) as unknown
@@ -130,7 +131,7 @@ function parseJsonArray (raw: string | undefined): Array<Record<string, unknown>
130
131
  * `${timestamp}_${keyPrefix}`-derived per device), but keeps the merge total rather than
131
132
  * throwing on a theoretical collision.
132
133
  */
133
- function mergeJsonArrayById (a: string | undefined, b: string | undefined): string | undefined {
134
+ function mergeJsonArrayById(a: string | undefined, b: string | undefined): string | undefined {
134
135
  if (a === undefined) return b
135
136
  if (b === undefined) return a
136
137
  const merged = new Map<string, Record<string, unknown>>()
@@ -147,7 +148,7 @@ function mergeJsonArrayById (a: string | undefined, b: string | undefined): stri
147
148
  * together this way before the single `applyAppData` call that actually reaches storage, so
148
149
  * no one device's snapshot can clobber another's.
149
150
  */
150
- export function mergeAppData (a: AppDataSnapshot | undefined, b: AppDataSnapshot | undefined): AppDataSnapshot {
151
+ export function mergeAppData(a: AppDataSnapshot | undefined, b: AppDataSnapshot | undefined): AppDataSnapshot {
151
152
  return {
152
153
  localpayPending: mergeJsonArrayById(a?.localpayPending, b?.localpayPending),
153
154
  peerpayOutbox: mergeJsonArrayById(a?.peerpayOutbox, b?.peerpayOutbox),
@@ -16,10 +16,7 @@
16
16
  */
17
17
  import type { CompletedProtoWallet } from '@bsv/sdk'
18
18
  import { Utils } from '@bsv/sdk'
19
- import {
20
- parseJsonRpc,
21
- stringifyJsonRpc
22
- } from '@bsv/wallet-toolbox-mobile'
19
+ import { parseJsonRpc, stringifyJsonRpc } from '@bsv/wallet-toolbox-mobile'
23
20
  import { BACKUP_PROTOCOL, backupKeyId, type BackupChain } from './constants'
24
21
  import type { SyncChunk } from '../toolboxTypes'
25
22
 
@@ -44,7 +41,7 @@ const PACK_MIN_LENGTH = 32
44
41
  * Uint8Array back to `number[]`. An array that merely looked byte-like — small integer ids,
45
42
  * say — round-trips to exactly the values it started with.
46
43
  */
47
- function packBytes (value: unknown): unknown {
44
+ function packBytes(value: unknown): unknown {
48
45
  if (Array.isArray(value)) {
49
46
  const isByteArray =
50
47
  value.length >= PACK_MIN_LENGTH &&
@@ -74,7 +71,7 @@ function packBytes (value: unknown): unknown {
74
71
  * payload blocked the JS thread for ~50s per attempt on device; the point is to never do
75
72
  * that work, not merely to avoid the failed upload at the end of it.
76
73
  */
77
- export function estimateEncodedBytes (chunk: SyncChunk): number {
74
+ export function estimateEncodedBytes(chunk: SyncChunk): number {
78
75
  let bytes = 0
79
76
  const walk = (value: unknown): void => {
80
77
  if (typeof value === 'string') {
@@ -111,9 +108,10 @@ export function estimateEncodedBytes (chunk: SyncChunk): number {
111
108
  * strings and an underestimate only in the same way estimateEncodedBytes' own walk is (JSON
112
109
  * quoting/escaping is ignored).
113
110
  */
114
- export function estimateAppDataBytes (appData: AppDataSnapshot | undefined): number {
111
+ export function estimateAppDataBytes(appData: AppDataSnapshot | undefined): number {
115
112
  if (appData == null) return 0
116
- let bytes = (appData.localpayPending?.length ?? 0) + (appData.peerpayOutbox?.length ?? 0) + (appData.contacts?.length ?? 0)
113
+ let bytes =
114
+ (appData.localpayPending?.length ?? 0) + (appData.peerpayOutbox?.length ?? 0) + (appData.contacts?.length ?? 0)
117
115
  for (const d of appData.receiveIssuedDates ?? []) bytes += d.length
118
116
  return bytes
119
117
  }
@@ -126,7 +124,7 @@ const DATE_KEYS = new Set(['created_at', 'updated_at'])
126
124
 
127
125
  /** Inverse of packBytes: every Uint8Array becomes the `number[]` the toolbox
128
126
  * expects, and date columns come back as Date instances. */
129
- function unpackBytes (value: unknown, key?: string): unknown {
127
+ function unpackBytes(value: unknown, key?: string): unknown {
130
128
  if (value instanceof Uint8Array) return Array.from(value)
131
129
  if (typeof value === 'string' && key != null && DATE_KEYS.has(key)) {
132
130
  const d = new Date(value)
@@ -183,7 +181,7 @@ export interface AppDataSnapshot {
183
181
  * has ever appended — this type exists mainly so RemoteSyncReader can read `seal`/`appData`
184
182
  * off an entry without re-decoding it a second time.
185
183
  */
186
- export type DecodedEntry = { kind: 'chunk', chunk: SyncChunk, seal?: BackupSeal, appData?: AppDataSnapshot }
184
+ export type DecodedEntry = { kind: 'chunk'; chunk: SyncChunk; seal?: BackupSeal; appData?: AppDataSnapshot }
187
185
 
188
186
  /**
189
187
  * Serialise and encrypt a sync chunk, optionally sealing a generation in the same envelope.
@@ -211,7 +209,7 @@ export type DecodedEntry = { kind: 'chunk', chunk: SyncChunk, seal?: BackupSeal,
211
209
  * log (see push.ts's own docs) — an intentionally-empty-of-entities appended entry would
212
210
  * make a live restore stop early and silently drop whatever was appended after it.
213
211
  */
214
- export async function encodeChunk (
212
+ export async function encodeChunk(
215
213
  wallet: CompletedProtoWallet,
216
214
  chunk: SyncChunk,
217
215
  chain: BackupChain,
@@ -238,7 +236,7 @@ export async function encodeChunk (
238
236
  * — decodes unchanged: `envelope.seal`/`envelope.appData` is `undefined`, so each is omitted
239
237
  * from the result exactly as it always was.
240
238
  */
241
- export async function decodeEntry (
239
+ export async function decodeEntry(
242
240
  wallet: CompletedProtoWallet,
243
241
  ciphertext: number[],
244
242
  chain: BackupChain
@@ -262,7 +260,7 @@ export async function decodeEntry (
262
260
  }
263
261
  let seal: BackupSeal | undefined
264
262
  if (envelope.seal != null) {
265
- const s = envelope.seal as { generation?: unknown, initialChunkCount?: unknown }
263
+ const s = envelope.seal as { generation?: unknown; initialChunkCount?: unknown }
266
264
  if (typeof s.generation !== 'number' || typeof s.initialChunkCount !== 'number') {
267
265
  throw new Error('backup seal is malformed')
268
266
  }
@@ -275,9 +273,14 @@ export async function decodeEntry (
275
273
  /** Validates a decrypted envelope's `appData` field. Throws rather than silently dropping a
276
274
  * malformed field: an app-owned recovery row that failed to decode as claimed must stop the
277
275
  * restore, not quietly disappear (same failure posture as a malformed seal, above). */
278
- function decodeAppData (raw: unknown): AppDataSnapshot | undefined {
276
+ function decodeAppData(raw: unknown): AppDataSnapshot | undefined {
279
277
  if (raw == null) return undefined
280
- const a = raw as { localpayPending?: unknown, peerpayOutbox?: unknown, receiveIssuedDates?: unknown, contacts?: unknown }
278
+ const a = raw as {
279
+ localpayPending?: unknown
280
+ peerpayOutbox?: unknown
281
+ receiveIssuedDates?: unknown
282
+ contacts?: unknown
283
+ }
281
284
  if (a.localpayPending !== undefined && typeof a.localpayPending !== 'string') {
282
285
  throw new Error('backup appData.localpayPending is malformed')
283
286
  }
@@ -309,7 +312,7 @@ function decodeAppData (raw: unknown): AppDataSnapshot | undefined {
309
312
  * so it can also read a chunk's seal, but this stays exported with its original signature
310
313
  * and behaviour so existing callers (and the codec round-trip tests) are unaffected.
311
314
  */
312
- export async function decodeChunk (
315
+ export async function decodeChunk(
313
316
  wallet: CompletedProtoWallet,
314
317
  ciphertext: number[],
315
318
  chain: BackupChain
@@ -340,7 +343,7 @@ export const CHUNK_ENTITIES = [
340
343
  * The toolbox treats an all-empty chunk as the completion sentinel, so this doubles as
341
344
  * "nothing left to push" and "restore is finished".
342
345
  */
343
- export function isEmptyChunk (chunk: SyncChunk): boolean {
346
+ export function isEmptyChunk(chunk: SyncChunk): boolean {
344
347
  const c = chunk as unknown as Record<string, unknown[] | undefined>
345
348
  return CHUNK_ENTITIES.every(name => (c[name]?.length ?? 0) === 0)
346
349
  }
@@ -351,7 +354,7 @@ export function isEmptyChunk (chunk: SyncChunk): boolean {
351
354
  * All twelve must exist as arrays: the toolbox's consumer loops forever on an `undefined`
352
355
  * entity array rather than treating it as empty.
353
356
  */
354
- export function emptyChunk (from: string, to: string, userIdentityKey: string): SyncChunk {
357
+ export function emptyChunk(from: string, to: string, userIdentityKey: string): SyncChunk {
355
358
  const chunk: Record<string, unknown> = {
356
359
  fromStorageIdentityKey: from,
357
360
  toStorageIdentityKey: to,
@@ -4,13 +4,14 @@
4
4
  * @see docs/superpowers/specs/2026-08-14-encrypted-wallet-backup-log-design.md
5
5
  */
6
6
  import type { WalletProtocol } from '@bsv/sdk'
7
+ import { APP_CHAINS, type AppChain } from '../networks'
7
8
 
8
9
  /**
9
10
  * The networks a wallet can run on, as WalletContext names them. Each gets its own backup
10
11
  * derivation and therefore its own server account — see backupKeyId.
11
12
  */
12
- export type BackupChain = 'main' | 'test' | 'teratest'
13
- export const BACKUP_CHAINS: readonly BackupChain[] = ['main', 'test', 'teratest'] as const
13
+ export type BackupChain = AppChain
14
+ export const BACKUP_CHAINS: readonly BackupChain[] = APP_CHAINS
14
15
 
15
16
  /**
16
17
  * FROZEN. Do not change the protocol tuple or the keyID scheme, ever.
@@ -36,7 +37,7 @@ export const BACKUP_PROTOCOL: WalletProtocol = [2, 'wallet backup log']
36
37
  * accounts, so a testnet wallet's manifest never even lists mainnet blobs) and three
37
38
  * unrelated encryption keys (so a mainnet blob would not decrypt on testnet regardless).
38
39
  */
39
- export function backupKeyId (chain: BackupChain): string {
40
+ export function backupKeyId(chain: BackupChain): string {
40
41
  return `1 ${chain}`
41
42
  }
42
43
 
@@ -111,7 +112,6 @@ export const DEVICE_ID_KEY = 'backupDeviceId'
111
112
  // Exported separately from cursorKey so a caller that wants EVERY device's cursor for one
112
113
  // identity — e.g. a Wallet Check that must not see a different (departed) wallet's leftover
113
114
  // cursor on the same install — can scan by prefix without needing this device's own id.
114
- export const cursorKeyPrefix = (chain: BackupChain, pseudonym: string): string =>
115
- `backupCursor-${chain}-${pseudonym}-`
115
+ export const cursorKeyPrefix = (chain: BackupChain, pseudonym: string): string => `backupCursor-${chain}-${pseudonym}-`
116
116
  export const cursorKey = (chain: BackupChain, pseudonym: string, deviceId: string): string =>
117
117
  `${cursorKeyPrefix(chain, pseudonym)}${deviceId}`
@@ -44,7 +44,7 @@ interface Row {
44
44
  }
45
45
 
46
46
  /** Every contact of a local user, removed ones included, as JSON; undefined when there are none. */
47
- export async function captureContacts (db: ContactsDb, userId: number): Promise<string | undefined> {
47
+ export async function captureContacts(db: ContactsDb, userId: number): Promise<string | undefined> {
48
48
  const rows = (await db.getAllAsync(
49
49
  'SELECT identityKey, name, cachedHandle, cachedAvatarUrl, cachedCertifier, source, created_at, updated_at, favourite, removedAt FROM contacts WHERE userId = ?',
50
50
  [userId]
@@ -66,7 +66,7 @@ export async function captureContacts (db: ContactsDb, userId: number): Promise<
66
66
  }
67
67
 
68
68
  /** The contacts in a snapshot, never throwing: anything malformed is left out. */
69
- export function parseContacts (raw: string | undefined): BackedUpContact[] {
69
+ export function parseContacts(raw: string | undefined): BackedUpContact[] {
70
70
  if (raw === undefined) return []
71
71
  let parsed: unknown
72
72
  try {
@@ -91,7 +91,7 @@ export function parseContacts (raw: string | undefined): BackedUpContact[] {
91
91
  * changed them last (a rename, a star or a removal made on one phone wins over the older
92
92
  * state on the other).
93
93
  */
94
- export function mergeContacts (a: string | undefined, b: string | undefined): string | undefined {
94
+ export function mergeContacts(a: string | undefined, b: string | undefined): string | undefined {
95
95
  if (a === undefined) return b
96
96
  if (b === undefined) return a
97
97
  const byKey = new Map<string, BackedUpContact>()
@@ -108,13 +108,13 @@ export function mergeContacts (a: string | undefined, b: string | undefined): st
108
108
  * (label, star, removal, dates); someone already here is updated only when the backup's copy
109
109
  * is newer, so re-running an interrupted restore never rolls an edit back.
110
110
  */
111
- export async function applyContacts (db: ContactsDb, userId: number, raw: string | undefined): Promise<number> {
111
+ export async function applyContacts(db: ContactsDb, userId: number, raw: string | undefined): Promise<number> {
112
112
  let written = 0
113
113
  for (const c of parseContacts(raw)) {
114
- const had = (await db.getFirstAsync('SELECT updated_at FROM contacts WHERE userId = ? AND identityKey = ?', [userId, c.identityKey])) as
115
- | { updated_at: string }
116
- | null
117
- | undefined
114
+ const had = (await db.getFirstAsync('SELECT updated_at FROM contacts WHERE userId = ? AND identityKey = ?', [
115
+ userId,
116
+ c.identityKey
117
+ ])) as { updated_at: string } | null | undefined
118
118
  const values = [
119
119
  c.name,
120
120
  c.cachedHandle ?? null,
@@ -86,7 +86,7 @@ export interface PushCursor {
86
86
  maxObservedWallClock?: string
87
87
  }
88
88
 
89
- export function freshCursor (generation = 1): PushCursor {
89
+ export function freshCursor(generation = 1): PushCursor {
90
90
  return {
91
91
  since: undefined,
92
92
  offsets: zeroOffsets(),
@@ -100,7 +100,7 @@ export function freshCursor (generation = 1): PushCursor {
100
100
  }
101
101
  }
102
102
 
103
- export function zeroOffsets (): Record<EntityName, number> {
103
+ export function zeroOffsets(): Record<EntityName, number> {
104
104
  const out = {} as Record<EntityName, number>
105
105
  for (const name of ENTITY_NAMES) out[name] = 0
106
106
  return out
@@ -108,11 +108,11 @@ export function zeroOffsets (): Record<EntityName, number> {
108
108
 
109
109
  /** Offsets in the array-of-pairs shape `RequestSyncChunkArgs` expects. */
110
110
  // eslint-disable-next-line @typescript-eslint/array-type -- matches the SDK's own signature
111
- export function offsetsToArgs (offsets: Record<EntityName, number>): Array<{ name: string, offset: number }> {
111
+ export function offsetsToArgs(offsets: Record<EntityName, number>): Array<{ name: string; offset: number }> {
112
112
  return ENTITY_NAMES.map(name => ({ name, offset: offsets[name] ?? 0 }))
113
113
  }
114
114
 
115
- export async function loadCursor (chain: BackupChain, pseudonym: string, deviceId: string): Promise<PushCursor> {
115
+ export async function loadCursor(chain: BackupChain, pseudonym: string, deviceId: string): Promise<PushCursor> {
116
116
  const raw = await AsyncStorage.getItem(cursorKey(chain, pseudonym, deviceId))
117
117
  if (raw == null) return freshCursor()
118
118
 
@@ -144,11 +144,16 @@ export async function loadCursor (chain: BackupChain, pseudonym: string, deviceI
144
144
  }
145
145
  }
146
146
 
147
- export async function saveCursor (chain: BackupChain, pseudonym: string, deviceId: string, c: PushCursor): Promise<void> {
147
+ export async function saveCursor(
148
+ chain: BackupChain,
149
+ pseudonym: string,
150
+ deviceId: string,
151
+ c: PushCursor
152
+ ): Promise<void> {
148
153
  await AsyncStorage.setItem(cursorKey(chain, pseudonym, deviceId), JSON.stringify(c))
149
154
  }
150
155
 
151
- export async function clearCursor (chain: BackupChain, pseudonym: string, deviceId: string): Promise<void> {
156
+ export async function clearCursor(chain: BackupChain, pseudonym: string, deviceId: string): Promise<void> {
152
157
  await AsyncStorage.removeItem(cursorKey(chain, pseudonym, deviceId))
153
158
  }
154
159
 
@@ -160,7 +165,7 @@ export async function clearCursor (chain: BackupChain, pseudonym: string, device
160
165
  * server has never heard of instead of starting a fresh generation. Scoped by prefix so a
161
166
  * second wallet on the same device keeps its own bookkeeping.
162
167
  */
163
- export async function clearCursorsForPseudonym (chain: BackupChain, pseudonym: string): Promise<void> {
168
+ export async function clearCursorsForPseudonym(chain: BackupChain, pseudonym: string): Promise<void> {
164
169
  const prefix = cursorKey(chain, pseudonym, '')
165
170
  const keys = (await AsyncStorage.getAllKeys()).filter(k => k.startsWith(prefix))
166
171
  if (keys.length > 0) await AsyncStorage.multiRemove(keys)
@@ -24,12 +24,12 @@ import { BACKUP_PROTOCOL, backupKeyId, type BackupChain } from './constants'
24
24
  * of WalletPermissionsManager, so it can never raise a protocol-permission prompt or a
25
25
  * spending-authorisation gate.
26
26
  */
27
- export function deriveBackupWallet (primaryKey: number[], chain: BackupChain): CompletedProtoWallet {
27
+ export function deriveBackupWallet(primaryKey: number[], chain: BackupChain): CompletedProtoWallet {
28
28
  return new CompletedProtoWallet(deriveBackupKey(primaryKey, chain))
29
29
  }
30
30
 
31
31
  /** The private key behind the backup identity for one network. */
32
- export function deriveBackupKey (primaryKey: number[], chain: BackupChain): PrivateKey {
32
+ export function deriveBackupKey(primaryKey: number[], chain: BackupChain): PrivateKey {
33
33
  const deriver = new KeyDeriver(new PrivateKey(primaryKey))
34
34
  return deriver.derivePrivateKey(BACKUP_PROTOCOL, backupKeyId(chain), 'self')
35
35
  }
@@ -41,6 +41,6 @@ export function deriveBackupKey (primaryKey: number[], chain: BackupChain): Priv
41
41
  * account — there is no identity field anywhere in the API. One seed yields a DIFFERENT
42
42
  * pseudonym per network, so mainnet and testnet logs live in separate server accounts.
43
43
  */
44
- export function backupPseudonym (primaryKey: number[], chain: BackupChain): string {
44
+ export function backupPseudonym(primaryKey: number[], chain: BackupChain): string {
45
45
  return deriveBackupKey(primaryKey, chain).toPublicKey().toString()
46
46
  }
@@ -12,7 +12,7 @@ import { DEVICE_ID_KEY } from './constants'
12
12
  let cached: string | null = null
13
13
 
14
14
  /** 32 lowercase hex characters, matching the server's device-id pattern. */
15
- export async function getDeviceId (): Promise<string> {
15
+ export async function getDeviceId(): Promise<string> {
16
16
  if (cached != null) return cached
17
17
 
18
18
  const existing = await AsyncStorage.getItem(DEVICE_ID_KEY)
@@ -28,6 +28,6 @@ export async function getDeviceId (): Promise<string> {
28
28
  }
29
29
 
30
30
  /** Test seam. */
31
- export function resetDeviceIdCache (): void {
31
+ export function resetDeviceIdCache(): void {
32
32
  cached = null
33
33
  }
@@ -49,7 +49,7 @@ export interface EraseResult {
49
49
  deleted: number
50
50
  }
51
51
 
52
- export async function eraseRemoteBackup (deps: EraseDeps): Promise<EraseResult> {
52
+ export async function eraseRemoteBackup(deps: EraseDeps): Promise<EraseResult> {
53
53
  const client = resolveClient(deps)
54
54
 
55
55
  // Step 1 — before anything is deleted. See the module doc.
@@ -64,7 +64,7 @@ export async function eraseRemoteBackup (deps: EraseDeps): Promise<EraseResult>
64
64
  return { deleted }
65
65
  }
66
66
 
67
- function resolveClient (deps: EraseDeps): BackupClient {
67
+ function resolveClient(deps: EraseDeps): BackupClient {
68
68
  if (deps.client != null) return deps.client
69
69
  if (deps.baseUrl == null || deps.baseUrl === '') {
70
70
  throw new Error('eraseRemoteBackup requires either a client or a baseUrl')
@@ -27,7 +27,7 @@ import { profileScopedKey } from '../profiles/profileStore'
27
27
  export const BACKUP_PUSH_ENABLED_KEY = 'backupPushEnabled'
28
28
 
29
29
  /** True unless the user has explicitly opted out. Never throws. */
30
- export async function isBackupPushEnabled (profileIndex?: number): Promise<boolean> {
30
+ export async function isBackupPushEnabled(profileIndex?: number): Promise<boolean> {
31
31
  try {
32
32
  return (await AsyncStorage.getItem(profileScopedKey(BACKUP_PUSH_ENABLED_KEY, profileIndex))) !== 'false'
33
33
  } catch {
@@ -36,6 +36,6 @@ export async function isBackupPushEnabled (profileIndex?: number): Promise<boole
36
36
  }
37
37
  }
38
38
 
39
- export async function setBackupPushEnabled (enabled: boolean, profileIndex?: number): Promise<void> {
39
+ export async function setBackupPushEnabled(enabled: boolean, profileIndex?: number): Promise<void> {
40
40
  await AsyncStorage.setItem(profileScopedKey(BACKUP_PUSH_ENABLED_KEY, profileIndex), enabled ? 'true' : 'false')
41
41
  }
@@ -84,7 +84,7 @@ export interface PushResult {
84
84
  * without yielding, so a long pass would stall the JS thread. Successive passes drain the
85
85
  * backlog.
86
86
  */
87
- export async function pushOnce (deps: PushDeps): Promise<PushResult> {
87
+ export async function pushOnce(deps: PushDeps): Promise<PushResult> {
88
88
  // Checked FIRST, ahead of even reading the local database: the opt-out means no wallet
89
89
  // data leaves this device, and the cheapest way to guarantee that is to do nothing at
90
90
  // all. The cursor is left untouched, so opting back in resumes from where the log
@@ -115,9 +115,7 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
115
115
  cursor = {
116
116
  ...cursor,
117
117
  maxObservedWallClock:
118
- cursor.maxObservedWallClock != null && cursor.maxObservedWallClock > nowIso
119
- ? cursor.maxObservedWallClock
120
- : nowIso
118
+ cursor.maxObservedWallClock != null && cursor.maxObservedWallClock > nowIso ? cursor.maxObservedWallClock : nowIso
121
119
  }
122
120
 
123
121
  // Back-fill: this cursor's window closed at least once (since is set) with real chunks
@@ -270,9 +268,9 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
270
268
  * identity key every auth proof signs toward — so constructing a fresh client
271
269
  * each pass would re-fetch it every minute for no reason.
272
270
  */
273
- let cachedClient: { key: string, client: BackupClient } | undefined
271
+ let cachedClient: { key: string; client: BackupClient } | undefined
274
272
 
275
- function resolveClient (deps: PushDeps): BackupClient {
273
+ function resolveClient(deps: PushDeps): BackupClient {
276
274
  if (deps.client != null) return deps.client
277
275
  if (deps.baseUrl == null || deps.baseUrl === '') {
278
276
  throw new Error('pushOnce requires either a client or a baseUrl')
@@ -310,7 +308,7 @@ function resolveClient (deps: PushDeps): BackupClient {
310
308
  * backwards could still orphan a record, but that was equally true of `>=` and is not
311
309
  * something a timestamp cursor can defend against.)
312
310
  */
313
- function nextInstant (iso: string | undefined): string | undefined {
311
+ function nextInstant(iso: string | undefined): string | undefined {
314
312
  if (iso == null) return undefined
315
313
  const t = Date.parse(iso)
316
314
  // An unparseable timestamp must not silently reset the window to the epoch; leaving it
@@ -320,7 +318,7 @@ function nextInstant (iso: string | undefined): string | undefined {
320
318
  }
321
319
 
322
320
  /** Per-entity consumed counts grow by what this chunk carried. */
323
- function advanceOffsets (cursor: PushCursor, chunk: SyncChunk): PushCursor['offsets'] {
321
+ function advanceOffsets(cursor: PushCursor, chunk: SyncChunk): PushCursor['offsets'] {
324
322
  const c = chunk as unknown as Record<string, unknown[] | undefined>
325
323
  const next = { ...cursor.offsets }
326
324
  for (const name of ENTITY_NAMES) {
@@ -330,7 +328,7 @@ function advanceOffsets (cursor: PushCursor, chunk: SyncChunk): PushCursor['offs
330
328
  }
331
329
 
332
330
  /** Greatest `updated_at` across everything in this chunk. */
333
- function maxUpdatedAt (current: string | undefined, chunk: SyncChunk): string | undefined {
331
+ function maxUpdatedAt(current: string | undefined, chunk: SyncChunk): string | undefined {
334
332
  const c = chunk as unknown as Record<string, Array<Record<string, unknown>> | undefined> // eslint-disable-line @typescript-eslint/array-type
335
333
  let max = current
336
334
 
@@ -351,12 +349,12 @@ function maxUpdatedAt (current: string | undefined, chunk: SyncChunk): string |
351
349
  * A generation is meant to be a coherent snapshot, so starting one mid-window would leave a
352
350
  * partially written generation that a restore could not trust.
353
351
  */
354
- function shouldRotate (cursor: PushCursor): boolean {
352
+ function shouldRotate(cursor: PushCursor): boolean {
355
353
  return cursor.chunksInGeneration >= GENERATION_CHUNK_THRESHOLD
356
354
  }
357
355
 
358
356
  /** Begin a new generation: a full snapshot, from sequence one, with no `since` filter. */
359
- function rotate (cursor: PushCursor): PushCursor {
357
+ function rotate(cursor: PushCursor): PushCursor {
360
358
  return freshCursor(cursor.generation + 1)
361
359
  }
362
360
 
@@ -367,7 +365,7 @@ function rotate (cursor: PushCursor): PushCursor {
367
365
  * remote log already covers, start a fresh generation — one extra full snapshot is cheap
368
366
  * next to a restore with a hole in it.
369
367
  */
370
- async function resyncFromServer (
368
+ async function resyncFromServer(
371
369
  client: BackupClient,
372
370
  _pseudonym: string,
373
371
  deviceId: string,