@bsv/expo-wallet-toolbox 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,385 @@
1
+ import { Beef } from '@bsv/sdk'
2
+ import type { PaymentFrame } from './codec'
3
+
4
+ export const PENDING_KEY = 'localpay_pending'
5
+ /**
6
+ * Counts written beside the queue so the home and pay screens can render their
7
+ * badge without parsing the queue itself. Every entry carries a full AtomicBEEF,
8
+ * and the badge was re-parsing all of them — on the JS thread, on both screens,
9
+ * on every status change — to learn a number.
10
+ */
11
+ export const PENDING_SUMMARY_KEY = 'localpay_pending_summary'
12
+ export const PEERPAY_PROTOCOL_ID: [number, string] = [2, '3241645161d8']
13
+ export const PEERPAY_LABEL = 'localpay'
14
+ export const PEERPAY_DESCRIPTION = 'Payment received from a nearby device'
15
+
16
+ export type PendingStatus = 'pending' | 'processing' | 'completed' | 'failed'
17
+
18
+ export interface PendingPayment {
19
+ id: string
20
+ receivedAt: string
21
+ frame: PaymentFrame
22
+ status: PendingStatus
23
+ failureReason?: string
24
+ lastAttemptAt?: string
25
+ /**
26
+ * Which transport this frame arrived over ('awdl' | 'nearby' | 'ble' | 'qr'),
27
+ * when the caller knows it. Threaded through so `processPending` can
28
+ * back-attribute the `offline_actions` row this internalize may create —
29
+ * see `attribute`.
30
+ */
31
+ receivedVia?: string
32
+ /** Failed internalize attempts. Absent on entries written before the ceiling. */
33
+ attempts?: number
34
+ }
35
+
36
+ /**
37
+ * How many times a received frame is re-internalized before the queue stops
38
+ * trying. Structurally bad frames used to be retried on every wallet build and
39
+ * every nearby settle, forever, each one re-validating a full BEEF — and the
40
+ * badge went on calling them "waiting", which they were not.
41
+ */
42
+ export const MAX_PENDING_ATTEMPTS = 3
43
+
44
+ export function isPendingExhausted(p: PendingPayment): boolean {
45
+ return p.status === 'failed' && (p.attempts ?? 0) >= MAX_PENDING_ATTEMPTS
46
+ }
47
+
48
+ export interface PendingSummary {
49
+ /** Still worth retrying. */
50
+ waiting: number
51
+ /** Out of attempts: real money this device could not credit. */
52
+ stuck: number
53
+ }
54
+
55
+ export interface KVStorage {
56
+ getKeyValue(k: string): Promise<string | undefined>
57
+ setKeyValue(k: string, v: string): Promise<void>
58
+ }
59
+
60
+ /** Thrown after a corrupt `PENDING_KEY` blob has been copied aside, never treated as empty. */
61
+ export class PendingCorruptError extends Error {
62
+ constructor(message = 'pending queue JSON is corrupt') {
63
+ super(message)
64
+ this.name = 'PendingCorruptError'
65
+ }
66
+ }
67
+
68
+ let pendingCorruptNotice = false
69
+
70
+ /** True after a quarantine until a later successful parse of `PENDING_KEY`. */
71
+ export function getPendingCorruptNotice(): boolean {
72
+ return pendingCorruptNotice
73
+ }
74
+
75
+ interface Serialised extends Omit<PendingPayment, 'frame'> {
76
+ frame: Omit<PaymentFrame, 'transaction'> & { transaction: number[] }
77
+ }
78
+
79
+ function toWire(p: PendingPayment): Serialised {
80
+ return { ...p, frame: { ...p.frame, transaction: Array.from(p.frame.transaction) } }
81
+ }
82
+
83
+ function fromWire(s: Serialised): PendingPayment {
84
+ return { ...s, frame: { ...s.frame, transaction: new Uint8Array(s.frame.transaction) } }
85
+ }
86
+
87
+ // All read-modify-write sequences on the queue share one storage key, so they
88
+ // must not interleave: a concurrent write built from a stale read silently
89
+ // drops entries. Every mutating path runs through this chain.
90
+ let queueLock: Promise<unknown> = Promise.resolve()
91
+
92
+ function withQueueLock<T>(fn: () => Promise<T>): Promise<T> {
93
+ const run = queueLock.then(fn, fn)
94
+ queueLock = run.catch(() => undefined)
95
+ return run
96
+ }
97
+
98
+ async function readAll(storage: KVStorage): Promise<PendingPayment[]> {
99
+ // A storage failure must NOT be reported as "empty" — callers write back
100
+ // what they read, so swallowing it here destroys the queue.
101
+ const raw = await storage.getKeyValue(PENDING_KEY)
102
+ if (!raw) {
103
+ pendingCorruptNotice = false
104
+ return []
105
+ }
106
+ try {
107
+ const parsed = JSON.parse(raw) as unknown
108
+ pendingCorruptNotice = false
109
+ return Array.isArray(parsed) ? (parsed as Serialised[]).map(fromWire) : []
110
+ } catch {
111
+ pendingCorruptNotice = true
112
+ try {
113
+ await storage.setKeyValue(`localpay_pending_corrupt_${Date.now()}`, raw)
114
+ // Repair only after a successful quarantine copy. Compare-and-swap: this
115
+ // path is not under withQueueLock (nesting would deadlock writers that
116
+ // already hold it), so only write [] while PENDING_KEY still equals the
117
+ // corrupt blob we observed — a stale peer must not wipe a later save.
118
+ const still = await storage.getKeyValue(PENDING_KEY)
119
+ if (still === raw) {
120
+ await storage.setKeyValue(PENDING_KEY, '[]')
121
+ // The summary describes the queue, so it must not outlive it: a stale
122
+ // count beside a quarantined blob would keep promising payments that
123
+ // are no longer in the live key.
124
+ await storage.setKeyValue(PENDING_SUMMARY_KEY, JSON.stringify({ waiting: 0, stuck: 0 }))
125
+ }
126
+ } catch {
127
+ // Quarantine/repair is best-effort; if copy or CAS fails, leave live key.
128
+ }
129
+ throw new PendingCorruptError()
130
+ }
131
+ }
132
+
133
+ function summarise(list: PendingPayment[]): PendingSummary {
134
+ let waiting = 0
135
+ let stuck = 0
136
+ for (const p of list) {
137
+ if (p.status === 'completed') continue
138
+ if (isPendingExhausted(p)) stuck++
139
+ else waiting++
140
+ }
141
+ return { waiting, stuck }
142
+ }
143
+
144
+ async function writeAll(storage: KVStorage, list: PendingPayment[]): Promise<void> {
145
+ const keep = list.filter(p => p.status !== 'completed')
146
+ await storage.setKeyValue(PENDING_KEY, JSON.stringify(keep.map(toWire)))
147
+ // Written after the queue, never before: a summary that ran ahead of the data
148
+ // would promise a payment the queue does not hold.
149
+ await storage.setKeyValue(PENDING_SUMMARY_KEY, JSON.stringify(summarise(keep)))
150
+ }
151
+
152
+ export async function savePending(
153
+ storage: KVStorage,
154
+ frame: PaymentFrame,
155
+ receivedVia?: string
156
+ ): Promise<PendingPayment> {
157
+ return withQueueLock(async () => {
158
+ const entry: PendingPayment = {
159
+ id: `${Date.now()}_${frame.senderIdentityKey.slice(0, 8)}`,
160
+ receivedAt: new Date().toISOString(),
161
+ frame,
162
+ status: 'pending',
163
+ receivedVia
164
+ }
165
+ let existing: PendingPayment[]
166
+ try {
167
+ existing = await readAll(storage)
168
+ } catch (e) {
169
+ // readAll already repaired PENDING_KEY to []; still throw so this call
170
+ // does not silently succeed while the notice should show.
171
+ if (e instanceof PendingCorruptError) throw e
172
+ throw e
173
+ }
174
+ await writeAll(storage, [...existing, entry])
175
+ return entry
176
+ })
177
+ }
178
+
179
+ export async function getPending(storage: KVStorage): Promise<PendingPayment[]> {
180
+ return readAll(storage)
181
+ }
182
+
183
+ /** `processing` is included: a crash mid-flight must not strand a payment. */
184
+ export async function getUnprocessed(storage: KVStorage): Promise<PendingPayment[]> {
185
+ return (await readAll(storage)).filter(p => p.status !== 'completed')
186
+ }
187
+
188
+ /** What `processPending` should attempt: unprocessed, minus what has given up. */
189
+ export async function getRetryable(storage: KVStorage): Promise<PendingPayment[]> {
190
+ return (await getUnprocessed(storage)).filter(p => !isPendingExhausted(p))
191
+ }
192
+
193
+ /**
194
+ * Home/Pay overlay: never treat a corrupt blob as an empty queue.
195
+ *
196
+ * Reads the summary key when there is one, so the common case costs a single
197
+ * small read instead of parsing every queued AtomicBEEF. Falls back to the
198
+ * queue itself — and writes the summary — for a store written before the
199
+ * summary existed.
200
+ */
201
+ export async function readUnprocessedPending(
202
+ storage: KVStorage
203
+ ): Promise<{ count: number; stuck: number; corrupt: boolean }> {
204
+ // Never let the cheap path answer for a queue already known to be corrupt:
205
+ // the notice is what puts the repair prompt in front of the user.
206
+ try {
207
+ const raw = getPendingCorruptNotice() ? undefined : await storage.getKeyValue(PENDING_SUMMARY_KEY)
208
+ if (raw) {
209
+ const parsed = JSON.parse(raw) as Partial<PendingSummary>
210
+ if (typeof parsed.waiting === 'number' && typeof parsed.stuck === 'number') {
211
+ return { count: parsed.waiting, stuck: parsed.stuck, corrupt: false }
212
+ }
213
+ }
214
+ } catch {
215
+ // Unreadable summary: fall through and rebuild it from the queue.
216
+ }
217
+ try {
218
+ const all = await getUnprocessed(storage)
219
+ const summary = summarise(all)
220
+ try {
221
+ await storage.setKeyValue(PENDING_SUMMARY_KEY, JSON.stringify(summary))
222
+ } catch {
223
+ // A summary that cannot be cached still answers this call.
224
+ }
225
+ return { count: summary.waiting, stuck: summary.stuck, corrupt: false }
226
+ } catch (e) {
227
+ if (e instanceof PendingCorruptError || getPendingCorruptNotice()) {
228
+ return { count: 0, stuck: 0, corrupt: true }
229
+ }
230
+ throw e
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Nearby pending can internalize while offline: `internalizeAction` parks the
236
+ * broadcast via the storage hold. Connectivity no longer gates the queue.
237
+ */
238
+ export function canInternalizePending(_online: boolean): boolean {
239
+ return true
240
+ }
241
+
242
+ export async function updateStatus(
243
+ storage: KVStorage,
244
+ id: string,
245
+ status: PendingStatus,
246
+ failureReason?: string
247
+ ): Promise<void> {
248
+ return withQueueLock(async () => {
249
+ let all: PendingPayment[]
250
+ try {
251
+ all = await readAll(storage)
252
+ } catch (e) {
253
+ if (e instanceof PendingCorruptError) throw e
254
+ throw e
255
+ }
256
+ const next = all.map(p =>
257
+ p.id === id
258
+ ? {
259
+ ...p,
260
+ status,
261
+ failureReason,
262
+ lastAttemptAt: new Date().toISOString(),
263
+ // Counted on failure only: 'processing' is set on the way in to
264
+ // every attempt, so counting there would burn the ceiling without
265
+ // anything having gone wrong.
266
+ attempts: status === 'failed' ? (p.attempts ?? 0) + 1 : p.attempts
267
+ }
268
+ : p
269
+ )
270
+ await writeAll(storage, next)
271
+ })
272
+ }
273
+
274
+ interface InternalizingWallet {
275
+ internalizeAction(args: unknown, originator?: string): Promise<unknown>
276
+ }
277
+
278
+ /**
279
+ * Backfills the identity of whoever handed over a payment, and how, onto the
280
+ * `offline_actions` row `internalizeAction` may have just created for it (only
281
+ * when this device was offline at the time — see `holdReqsOffline`, the sole
282
+ * writer of that row, which never sees the frame and so writes both columns
283
+ * null). Supplied by the caller rather than called directly from here: this
284
+ * module knows nothing about SQLite or the `offline_actions` table, only about
285
+ * the KV-backed queue in `PENDING_KEY`, and should stay that way.
286
+ */
287
+ type AttributePayment = (txid: string, info: { senderIdentityKey: string; receivedVia?: string }) => Promise<void>
288
+
289
+ export async function processPending(
290
+ wallet: InternalizingWallet,
291
+ storage: KVStorage,
292
+ originator: string,
293
+ attribute?: AttributePayment
294
+ ): Promise<{ id: string; success: boolean; error?: string }[]> {
295
+ const results: { id: string; success: boolean; error?: string }[] = []
296
+ for (const p of await getRetryable(storage)) {
297
+ await updateStatus(storage, p.id, 'processing')
298
+ try {
299
+ await wallet.internalizeAction(
300
+ {
301
+ tx: Array.from(p.frame.transaction),
302
+ outputs: [
303
+ {
304
+ outputIndex: p.frame.outputIndex,
305
+ protocol: 'wallet payment',
306
+ paymentRemittance: {
307
+ derivationPrefix: p.frame.derivationPrefix,
308
+ derivationSuffix: p.frame.derivationSuffix,
309
+ senderIdentityKey: p.frame.senderIdentityKey
310
+ }
311
+ }
312
+ ],
313
+ description: PEERPAY_DESCRIPTION,
314
+ labels: [PEERPAY_LABEL]
315
+ },
316
+ originator
317
+ )
318
+ await updateStatus(storage, p.id, 'completed')
319
+ results.push({ id: p.id, success: true })
320
+
321
+ // Best-effort, and deliberately isolated from the try/catch above: by
322
+ // this point the payment has already completed successfully, so a
323
+ // failure here — a bad frame, a locked db — must not retroactively turn
324
+ // it into a 'failed' entry, and must not stop the loop from reaching
325
+ // whatever else is queued behind it.
326
+ if (attribute) {
327
+ try {
328
+ // internalizeAction's own resolved value carries no txid (the SDK's
329
+ // InternalizeActionResult is just `{ accepted: true }`), so it has to
330
+ // be derived from the frame itself. `frame.transaction` is an
331
+ // AtomicBEEF (see codec.ts), and `atomicTxid` is exactly the subject
332
+ // txid `internalizeAction` used internally to build the request that
333
+ // `holdReqsOffline` may have queued — see Beef.d.ts / the toolbox's
334
+ // own `validateAtomicBeef`.
335
+ const txid = Beef.fromBinary(p.frame.transaction).atomicTxid
336
+ if (txid) {
337
+ await attribute(txid, {
338
+ senderIdentityKey: p.frame.senderIdentityKey,
339
+ receivedVia: p.receivedVia
340
+ })
341
+ }
342
+ } catch {
343
+ // Not a readable BEEF, or the attribution write itself failed.
344
+ // Either way this is silent: the payment already succeeded above.
345
+ }
346
+ }
347
+ } catch (e) {
348
+ const error = e instanceof Error ? e.message : String(e)
349
+ await updateStatus(storage, p.id, 'failed', error)
350
+ results.push({ id: p.id, success: false, error })
351
+ }
352
+ }
353
+ return results
354
+ }
355
+
356
+ export const SPENT_KEY = 'localpay_spent_sessions'
357
+
358
+ function sessionKey(sessionId: Uint8Array): string {
359
+ return Array.from(sessionId, b => b.toString(16).padStart(2, '0')).join('')
360
+ }
361
+
362
+ async function readSpent(storage: KVStorage): Promise<string[]> {
363
+ // Same as readAll: let storage errors propagate, swallow only parse failures.
364
+ const raw = await storage.getKeyValue(SPENT_KEY)
365
+ if (!raw) return []
366
+ try {
367
+ const parsed = JSON.parse(raw) as unknown
368
+ return Array.isArray(parsed) ? (parsed as string[]) : []
369
+ } catch {
370
+ return []
371
+ }
372
+ }
373
+
374
+ export async function markSessionSpent(storage: KVStorage, sessionId: Uint8Array): Promise<void> {
375
+ return withQueueLock(async () => {
376
+ const key = sessionKey(sessionId)
377
+ const spent = await readSpent(storage)
378
+ if (spent.includes(key)) return
379
+ await storage.setKeyValue(SPENT_KEY, JSON.stringify([...spent, key]))
380
+ })
381
+ }
382
+
383
+ export async function isSessionSpent(storage: KVStorage, sessionId: Uint8Array): Promise<boolean> {
384
+ return (await readSpent(storage)).includes(sessionKey(sessionId))
385
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Durable retry list for `abortAction` calls that failed after a decline.
3
+ *
4
+ * A failed abort is a stuck UTXO, not a lost payment. The decline still
5
+ * stands; the reference is retried on the next wallet build.
6
+ */
7
+ interface StorageLike {
8
+ getKeyValue: (key: string) => Promise<string | undefined>
9
+ setKeyValue: (key: string, value: string) => Promise<void>
10
+ }
11
+
12
+ export const PENDING_ABORTS_KEY = 'pending_aborts'
13
+
14
+ export interface PendingAbort {
15
+ reference: string
16
+ originator: string
17
+ }
18
+
19
+ export async function loadPendingAborts(storage: StorageLike): Promise<PendingAbort[]> {
20
+ try {
21
+ const raw = await storage.getKeyValue(PENDING_ABORTS_KEY)
22
+ if (!raw) return []
23
+ const parsed = JSON.parse(raw) as unknown
24
+ if (!Array.isArray(parsed)) return []
25
+ const out: PendingAbort[] = []
26
+ for (const item of parsed) {
27
+ if (!item || typeof item !== 'object') continue
28
+ const reference = (item as { reference?: unknown }).reference
29
+ const originator = (item as { originator?: unknown }).originator
30
+ if (typeof reference === 'string' && reference && typeof originator === 'string') {
31
+ out.push({ reference, originator })
32
+ }
33
+ }
34
+ return out
35
+ } catch {
36
+ return []
37
+ }
38
+ }
39
+
40
+ export async function queuePendingAbort(storage: StorageLike, item: PendingAbort): Promise<void> {
41
+ if (!item.reference) return
42
+ const all = await loadPendingAborts(storage)
43
+ if (all.some(a => a.reference === item.reference)) return
44
+ await storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify([...all, item]))
45
+ }
46
+
47
+ export async function replayPendingAborts(args: {
48
+ wallet: {
49
+ abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
50
+ }
51
+ storage: StorageLike
52
+ }): Promise<void> {
53
+ const pending = await loadPendingAborts(args.storage)
54
+ if (pending.length === 0) return
55
+ const kept: PendingAbort[] = []
56
+ for (const item of pending) {
57
+ try {
58
+ const result = await args.wallet.abortAction({ reference: item.reference }, item.originator)
59
+ if (result && typeof result === 'object' && result.aborted === false) {
60
+ kept.push(item)
61
+ }
62
+ } catch {
63
+ kept.push(item)
64
+ }
65
+ }
66
+ await args.storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify(kept))
67
+ }
@@ -0,0 +1,16 @@
1
+ import { QrHandoffRequired, type LocalPaymentTransport } from './types'
2
+
3
+ /**
4
+ * The QR path has no socket: the payer renders a frame and the payee scans it.
5
+ * The screen drives both halves directly, so these entry points exist only to
6
+ * satisfy the interface and must not be called.
7
+ */
8
+ export const qrTransport: LocalPaymentTransport = {
9
+ kind: 'qr',
10
+ receive() {
11
+ return Promise.reject(new QrHandoffRequired())
12
+ },
13
+ send() {
14
+ return Promise.reject(new QrHandoffRequired())
15
+ },
16
+ }