@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,106 @@
1
+ /**
2
+ * Re-fetch a payment's proof from WhatsOnChain when the one the sender shipped
3
+ * no longer verifies.
4
+ *
5
+ * A PeerPay token carries an AtomicBEEF minted at send time. Its merkle path
6
+ * proves an ancestor against the block that contained it *then*. If that block
7
+ * is later reorged out, the path is stale: the transaction is still perfectly
8
+ * real and still has the same txid, but no chain tracker will confirm its root,
9
+ * and `internalizeAction` rejects the whole thing as
10
+ * "The tx parameter must be valid AtomicBEEF" — an error about the proof,
11
+ * phrased as if the transaction were malformed.
12
+ *
13
+ * Re-fetching by txid repairs exactly that. What comes back is the same
14
+ * transaction — the txid pins it, so nothing about the outputs, the amount or
15
+ * the derivation can change under us — carrying whatever proof is current. The
16
+ * sender is not trusted any further than they already were: we ask the network
17
+ * for the ancestry of a transaction the sender named, and a mismatched or
18
+ * unusable answer is discarded rather than passed on.
19
+ *
20
+ * This CANNOT repair the offline case. When `isValidRootForHeight` refuses
21
+ * because the device has no network (OfflineFirstChaintracks.ts:55), a fetch
22
+ * cannot succeed either — that payment is retryable later, not repairable now,
23
+ * and `makeBeefRepair` declines rather than burning an attempt on it.
24
+ */
25
+ import { Beef, Utils } from '@bsv/sdk'
26
+ import type { WocConfig } from './rails/address'
27
+
28
+ /** Injectable for tests; production uses global fetch. */
29
+ export type FetchLike = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>
30
+
31
+ /**
32
+ * The current AtomicBEEF for `txid`, or undefined if the network cannot supply
33
+ * a usable one.
34
+ *
35
+ * Every failure returns undefined rather than throwing: the caller is already
36
+ * handling a failed payment, and a repair that cannot be made must leave that
37
+ * original failure intact rather than replacing it with a fetch error.
38
+ */
39
+ export async function refetchAtomicBeef(args: {
40
+ woc: WocConfig
41
+ txid: string
42
+ fetchImpl?: FetchLike
43
+ }): Promise<number[] | undefined> {
44
+ const { woc, txid } = args
45
+ const doFetch = args.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
46
+
47
+ let bytes: number[]
48
+ try {
49
+ const resp = await doFetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
50
+ // Checked, because the body of a 404 is prose. `Utils.toArray(prose, 'hex')`
51
+ // throws "Invalid hex string", and an empty body parses to a Beef whose
52
+ // magic check fails — both of which would surface as a confusing error from
53
+ // a code path the user never asked for.
54
+ if (!resp.ok) return undefined
55
+ const hex = (await resp.text()).trim()
56
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
57
+ bytes = Utils.toArray(hex, 'hex')
58
+ } catch {
59
+ return undefined
60
+ }
61
+
62
+ try {
63
+ const beef = new Beef()
64
+ beef.mergeBeef(bytes)
65
+ // findAtomicTransaction walks the beef and hangs every ancestor and merkle
66
+ // path off the transaction, which is what makes toAtomicBEEF able to emit a
67
+ // self-contained proof. It returns undefined if the service answered about
68
+ // some other transaction.
69
+ const tx = beef.findAtomicTransaction(txid)
70
+ if (!tx) return undefined
71
+
72
+ // Throws rather than emitting a partial beef when an input has no source
73
+ // transaction — precisely the ancestry gap we must not hand onward.
74
+ const atomic = tx.toAtomicBEEF()
75
+
76
+ // Do not return something that will fail the same way. This is the exact
77
+ // structural half of the toolbox's own check
78
+ // (signer/methods/internalizeAction.js:92, allowTxidOnly = false); the
79
+ // merkle roots are the wallet's chain tracker to judge, not ours.
80
+ const check = Beef.fromBinary(atomic)
81
+ if (check.atomicTxid !== txid) return undefined
82
+ if (!check.verifyValid(false).valid) return undefined
83
+
84
+ return atomic
85
+ } catch {
86
+ return undefined
87
+ }
88
+ }
89
+
90
+ /**
91
+ * A repair function for `internalizeIncoming`, or undefined when repair is not
92
+ * possible right now.
93
+ *
94
+ * `online` is consulted first so an offline device declines instead of
95
+ * attempting a fetch that must fail — see the note at the top of this file.
96
+ */
97
+ export function makeBeefRepair(args: {
98
+ woc: WocConfig
99
+ online: () => Promise<boolean>
100
+ fetchImpl?: FetchLike
101
+ }): (txid: string) => Promise<number[] | undefined> {
102
+ return async (txid: string) => {
103
+ if (!(await args.online())) return undefined
104
+ return refetchAtomicBeef({ woc: args.woc, txid, fetchImpl: args.fetchImpl })
105
+ }
106
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Why an incoming payment failed to credit.
3
+ *
4
+ * Double-spend and structural failures count toward the auto-accept ceiling
5
+ * and NACK the sender. Environmental failures (offline, headers behind,
6
+ * network) do not — they would otherwise burn both retries on a condition the
7
+ * sender cannot fix.
8
+ */
9
+ export type CreditFailureKind = 'environmental' | 'double_spend' | 'structural'
10
+
11
+ export function classifyCreditError(
12
+ e: unknown,
13
+ ctx?: { lastMissHeight?: number; offline?: boolean }
14
+ ): CreditFailureKind {
15
+ const message = e instanceof Error ? e.message : typeof e === 'string' ? e : ''
16
+ if (/invalid status failed|doubleSpend|double.?spend/i.test(message)) return 'double_spend'
17
+ // Headers behind or the device offline: any credit failure is treated as
18
+ // environmental, including "valid AtomicBEEF" which the chain tracker reports
19
+ // for a missing root. AtomicBEEF while online with no lastMissHeight is
20
+ // structural (bad ancestry) and falls through below.
21
+ if (ctx?.offline) return 'environmental'
22
+ if (ctx?.lastMissHeight != null) return 'environmental'
23
+ if (
24
+ /network request failed|timed? ?out|chaintracks|database is locked|database table is locked|database-locked|failed to retrieve messages|not found on refresh/i.test(
25
+ message
26
+ )
27
+ )
28
+ return 'environmental'
29
+ return 'structural'
30
+ }
31
+
32
+ /**
33
+ * Await getOnline once per pass. Peek last-miss at each failure, not at build.
34
+ *
35
+ * `getOnline()` is async: `offline: !getOnline()` is always false because a
36
+ * Promise is truthy. Peeking (not taking) last-miss lets a miss recorded
37
+ * during the pass classify the payment that failed because of it, and does
38
+ * not let a joining caller steal the marker.
39
+ */
40
+ export async function makeCreditClassifier(args: {
41
+ getOnline: () => boolean | Promise<boolean>
42
+ peekLastMissHeight: () => number | undefined
43
+ }): Promise<(e: unknown) => CreditFailureKind> {
44
+ const offline = !(await args.getOnline())
45
+ return e => classifyCreditError(e, { offline, lastMissHeight: args.peekLastMissHeight() })
46
+ }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * One credit pass over the PeerPay inbox.
3
+ *
4
+ * HandleReceive (focused 5s poll) and TaskCreditInbox (background) both call
5
+ * `creditInboxOnce`. The mutex lives here so a Retry cannot start a second
6
+ * internalize while a poll or the monitor task is already in the box.
7
+ */
8
+ import { Beef } from '@bsv/sdk'
9
+ import { type IncomingPayment, type PeerPayClient } from '@bsv/message-box-client'
10
+ import {
11
+ isPaymentTokenShape,
12
+ listDamagedInboxMessages,
13
+ type DamagedInboxMessage
14
+ } from './damagedInbox'
15
+ import {
16
+ autoAcceptInbox,
17
+ needsAttention,
18
+ type InboxAttempt
19
+ } from './rails/handle'
20
+ import type { CreditFailureKind } from './creditErrors'
21
+ import { sendControlMessage } from '../peerpay/control'
22
+ import { loadInboxAttempts, saveInboxAttempts } from '../peerpay/inboxAttempts'
23
+
24
+ /** Same default the receive screen used when the note was left blank. */
25
+ export const INBOX_DESCRIPTION = 'Identity Payment'
26
+
27
+ /** Placeholder token so unparseable inbox rows can share the IncomingPayment row UI. */
28
+ export const DAMAGED_TOKEN_PLACEHOLDER: IncomingPayment['token'] = {
29
+ customInstructions: { derivationPrefix: '', derivationSuffix: '' },
30
+ transaction: [],
31
+ amount: 0
32
+ }
33
+
34
+ interface StorageLike {
35
+ getKeyValue: (key: string) => Promise<string | undefined>
36
+ setKeyValue: (key: string, value: string) => Promise<void>
37
+ }
38
+
39
+ type ListMessagesClient = {
40
+ listMessages?(args: {
41
+ messageBox: string
42
+ host?: string
43
+ acceptPayments?: boolean
44
+ }): Promise<{ messageId: string; sender: string; body: unknown }[]>
45
+ }
46
+
47
+ export type CreditInboxClient = Pick<PeerPayClient, 'listIncomingPayments'> &
48
+ ListMessagesClient &
49
+ Partial<Pick<PeerPayClient, 'sendMessage'>>
50
+
51
+ export interface CreditInboxResult {
52
+ accepted: number
53
+ attempts: Record<string, InboxAttempt>
54
+ damaged: DamagedInboxMessage[]
55
+ payments: IncomingPayment[]
56
+ displayPayments: IncomingPayment[]
57
+ attentionCount: number
58
+ pending: boolean
59
+ }
60
+
61
+ let inFlight: Promise<CreditInboxResult> | null = null
62
+
63
+ export function isCreditInboxBusy(): boolean {
64
+ return inFlight !== null
65
+ }
66
+
67
+ export function resetCreditInboxForTests(): void {
68
+ inFlight = null
69
+ }
70
+
71
+ /** Outbox-matching txid when the token parses; otherwise the inbox message id. */
72
+ function paymentTxid(payment: IncomingPayment): string {
73
+ try {
74
+ const txid = Beef.fromBinary(Array.from(payment.token.transaction ?? [])).atomicTxid
75
+ if (txid) return txid
76
+ } catch {
77
+ // Unparseable AtomicBEEF: the inbox id still identifies the row.
78
+ }
79
+ return String(payment.messageId)
80
+ }
81
+
82
+ async function listRawInbox(
83
+ client: ListMessagesClient,
84
+ messageBoxUrl: string
85
+ ): Promise<{ messageId: string; sender: string; body: unknown }[]> {
86
+ try {
87
+ return (
88
+ (await client.listMessages?.({
89
+ messageBox: 'payment_inbox',
90
+ host: messageBoxUrl,
91
+ acceptPayments: false
92
+ })) ?? []
93
+ )
94
+ } catch {
95
+ return []
96
+ }
97
+ }
98
+
99
+ function attentionCountFor(
100
+ displayPayments: IncomingPayment[],
101
+ damaged: DamagedInboxMessage[],
102
+ attempts: Record<string, InboxAttempt>
103
+ ): number {
104
+ const ids = new Set(damaged.map(d => d.messageId))
105
+ for (const p of displayPayments) {
106
+ const id = String(p.messageId)
107
+ if (ids.has(id) || needsAttention(attempts[id]) || attempts[id]?.kind === 'environmental') {
108
+ ids.add(id)
109
+ }
110
+ }
111
+ return ids.size
112
+ }
113
+
114
+ async function runCreditInbox(args: {
115
+ client: CreditInboxClient
116
+ messageBoxUrl: string
117
+ storage?: StorageLike
118
+ force?: string[]
119
+ classify?: (e: unknown) => CreditFailureKind
120
+ accept: (payment: IncomingPayment) => Promise<void>
121
+ }): Promise<CreditInboxResult> {
122
+ const { client, messageBoxUrl, storage, force, classify, accept } = args
123
+ const list = await client.listIncomingPayments(messageBoxUrl)
124
+ const raw = await listRawInbox(client, messageBoxUrl)
125
+ const fromDiff = listDamagedInboxMessages({ raw, parsed: list })
126
+ const byId = new Map(fromDiff.map(d => [d.messageId, d]))
127
+ for (const p of list) {
128
+ const id = String(p.messageId)
129
+ if (!isPaymentTokenShape(p.token) && !byId.has(id)) {
130
+ byId.set(id, { messageId: id, sender: p.sender ?? '', reason: 'bad_shape' })
131
+ }
132
+ }
133
+ const damaged = [...byId.values()]
134
+ const damagedIdSet = new Set(damaged.map(d => d.messageId))
135
+ const extras: IncomingPayment[] = damaged
136
+ .filter(d => !list.some(p => String(p.messageId) === d.messageId))
137
+ .map(d => ({
138
+ messageId: d.messageId,
139
+ sender: d.sender,
140
+ token: DAMAGED_TOKEN_PLACEHOLDER
141
+ }))
142
+ const displayPayments = [...list, ...extras]
143
+ const creditable = list.filter(p => !damagedIdSet.has(String(p.messageId)))
144
+ const prior = storage ? await loadInboxAttempts(storage) : {}
145
+ const outcome = await autoAcceptInbox({
146
+ payments: creditable,
147
+ attempts: prior,
148
+ force,
149
+ classify,
150
+ onGiveUp: async (payment, kind) => {
151
+ if (!payment.sender) return
152
+ await sendControlMessage(client as Pick<PeerPayClient, 'sendMessage'>, {
153
+ recipient: payment.sender,
154
+ message: {
155
+ type: 'resend_request',
156
+ txid: paymentTxid(payment),
157
+ reason: kind === 'double_spend' ? 'double_spent' : 'uncreditible',
158
+ messageId: String(payment.messageId)
159
+ }
160
+ })
161
+ },
162
+ accept
163
+ })
164
+ if (storage) await saveInboxAttempts(storage, outcome.attempts)
165
+ const attentionCount = attentionCountFor(displayPayments, damaged, outcome.attempts)
166
+ const pending = Object.values(outcome.attempts).some(a => !needsAttention(a))
167
+ return {
168
+ accepted: outcome.accepted,
169
+ attempts: outcome.attempts,
170
+ damaged,
171
+ payments: list,
172
+ displayPayments,
173
+ attentionCount,
174
+ pending
175
+ }
176
+ }
177
+
178
+ /**
179
+ * List, diff damaged, auto-accept, persist attempts.
180
+ *
181
+ * A second caller without `force` joins the in-flight pass. A Retry with
182
+ * `force` waits for that pass, then runs its own.
183
+ */
184
+ export async function creditInboxOnce(args: {
185
+ client: CreditInboxClient
186
+ messageBoxUrl: string
187
+ storage?: StorageLike
188
+ force?: string[]
189
+ classify?: (e: unknown) => CreditFailureKind
190
+ accept: (payment: IncomingPayment) => Promise<void>
191
+ }): Promise<CreditInboxResult> {
192
+ const force = args.force ?? []
193
+ if (inFlight && force.length === 0) return inFlight
194
+ if (inFlight) await inFlight.catch(() => {})
195
+ const run = runCreditInbox(args)
196
+ inFlight = run
197
+ try {
198
+ return await run
199
+ } finally {
200
+ if (inFlight === run) inFlight = null
201
+ }
202
+ }
@@ -0,0 +1,64 @@
1
+ export type DamagedInboxReason = 'unparseable' | 'bad_shape'
2
+
3
+ export interface DamagedInboxMessage {
4
+ messageId: string
5
+ sender: string
6
+ reason: DamagedInboxReason
7
+ }
8
+
9
+ /** True when body looks like a PeerPay payment token. */
10
+ export function isPaymentTokenShape(body: unknown): boolean {
11
+ if (body === null || typeof body !== 'object') return false
12
+ const custom = (body as { customInstructions?: unknown }).customInstructions
13
+ if (custom === null || typeof custom !== 'object') return false
14
+ const { derivationPrefix, derivationSuffix } = custom as {
15
+ derivationPrefix?: unknown
16
+ derivationSuffix?: unknown
17
+ }
18
+ if (typeof derivationPrefix !== 'string' || typeof derivationSuffix !== 'string') return false
19
+ const transaction = (body as { transaction?: unknown }).transaction
20
+ if (!Array.isArray(transaction)) return false
21
+ return transaction.every(n => typeof n === 'number')
22
+ }
23
+
24
+ function reasonForBody(body: unknown): DamagedInboxReason {
25
+ if (typeof body === 'string') {
26
+ try {
27
+ JSON.parse(body)
28
+ return 'bad_shape'
29
+ } catch {
30
+ return 'unparseable'
31
+ }
32
+ }
33
+ if (body !== null && typeof body === 'object') return 'bad_shape'
34
+ return 'unparseable'
35
+ }
36
+
37
+ /**
38
+ * Diff raw payment_inbox messages against those listIncomingPayments kept.
39
+ * Missing ids and wrong-shaped bodies become attention rows.
40
+ */
41
+ export function listDamagedInboxMessages(args: {
42
+ raw: { messageId: string; sender: string; body: unknown }[]
43
+ parsed: { messageId: string }[]
44
+ }): DamagedInboxMessage[] {
45
+ const parsedIds = new Set(args.parsed.map(p => String(p.messageId)))
46
+ const damaged: DamagedInboxMessage[] = []
47
+
48
+ for (const msg of args.raw) {
49
+ const messageId = String(msg.messageId)
50
+ const sender = String(msg.sender ?? '')
51
+
52
+ if (!parsedIds.has(messageId)) {
53
+ damaged.push({ messageId, sender, reason: reasonForBody(msg.body) })
54
+ continue
55
+ }
56
+
57
+ // listIncomingPayments keeps any JSON; still shape-check object bodies.
58
+ if (msg.body !== null && typeof msg.body === 'object' && !isPaymentTokenShape(msg.body)) {
59
+ damaged.push({ messageId, sender, reason: 'bad_shape' })
60
+ }
61
+ }
62
+
63
+ return damaged
64
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Gate for the /pay proof-collection nudge.
3
+ *
4
+ * Frame size tracks unproven ancestry: a payer whose Monitor hasn't collected
5
+ * proofs recently ships a ballooned AtomicBEEF and lands on a slower rung —
6
+ * or past 64 KiB, fails outright. Navigating to /pay is the strongest signal
7
+ * a frame build is imminent, so we run one CheckForProofs pass there, at most
8
+ * once per interval, deferred so screen mount never blocks on it. The 2-hour
9
+ * background trigger (WalletContext) is unchanged; this only pulls it earlier.
10
+ */
11
+ export const PROOF_NUDGE_MIN_INTERVAL_MS = 10 * 60 * 1000
12
+
13
+ let lastGrantedMs = -Infinity
14
+
15
+ export function takeProofNudge(nowMs: number): boolean {
16
+ if (nowMs - lastGrantedMs < PROOF_NUDGE_MIN_INTERVAL_MS) return false
17
+ lastGrantedMs = nowMs
18
+ return true
19
+ }
20
+
21
+ export function resetProofNudgeForTests(): void {
22
+ lastGrantedMs = -Infinity
23
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Proven-tx write payload from a BUMP and the header hash that backs it.
3
+ * `headerHash` must be a real block hash — never persist `''`.
4
+ */
5
+ export function provenTxFromBump(args: {
6
+ merklePath: {
7
+ blockHeight: number
8
+ path: Array<Array<{ txid?: boolean; hash?: string; offset: number }>>
9
+ computeRoot: (txid: string) => string
10
+ toBinary: () => number[]
11
+ }
12
+ txid: string
13
+ headerHash: string
14
+ }): {
15
+ index: number
16
+ height: number
17
+ blockHash: string
18
+ merklePath: number[]
19
+ merkleRoot: string
20
+ } {
21
+ if (!args.headerHash) throw new Error('blockHash required')
22
+ const leaf = args.merklePath.path[0]?.find(l => l.txid === true && l.hash === args.txid)
23
+ if (!leaf) throw new Error('txid not found in BUMP path')
24
+ return {
25
+ index: leaf.offset,
26
+ height: args.merklePath.blockHeight,
27
+ blockHash: args.headerHash,
28
+ merklePath: args.merklePath.toBinary(),
29
+ merkleRoot: args.merklePath.computeRoot(args.txid)
30
+ }
31
+ }