@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,617 @@
1
+ /**
2
+ * The handle rail — remote, asynchronous payments addressed by identity key and
3
+ * delivered through a MessageBox (PeerPay).
4
+ *
5
+ * Ported from app/payments.tsx. The one invariant worth restating: the outbox
6
+ * write happens BEFORE delivery is attempted. The payment token holds the
7
+ * derivation data for a transaction that has already been broadcast, so losing
8
+ * it between broadcast and delivery loses the money — persisting first is what
9
+ * makes a crash recoverable.
10
+ */
11
+ import { PeerPayClient, type IncomingPayment } from '@bsv/message-box-client'
12
+ import { Beef, P2PKH, PublicKey, Random, Transaction, Utils } from '@bsv/sdk'
13
+ import { BRC29_PROTOCOL_ID } from './address'
14
+ import {
15
+ getOutboxEntries,
16
+ markOutboxSent,
17
+ removeOutboxEntry,
18
+ saveOutboxEntry,
19
+ updateOutboxEntry,
20
+ type OutboxEntry
21
+ } from '../../peerpay/outbox'
22
+ import type { CreditFailureKind } from '../creditErrors'
23
+ import { isDuplicateMessageError, sendControlMessage, type ResendReason } from '../../peerpay/control'
24
+ import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
25
+
26
+ export const MESSAGE_BOX_URL_KEY = 'message_box_url'
27
+ export const DEFAULT_MESSAGE_BOX_URL = 'https://gmb.bsvblockchain.tech'
28
+ /** The previous default. A saved preference equal to it is treated as "use the
29
+ * default", so existing installs follow the default forward. */
30
+ export const LEGACY_MESSAGE_BOX_URL = 'https://messagebox.babbage.systems'
31
+ /** The sentinel the config panel writes when the user opts out of a server. */
32
+ export const NO_MESSAGE_BOX = 'noMessageBox'
33
+
34
+ /** The message box outbound payments are delivered into. */
35
+ const PAYMENT_INBOX = 'payment_inbox'
36
+
37
+ /** Build a PeerPay client, or null when the host/wallet cannot be used. */
38
+ export function makePeerPayClient(args: {
39
+ wallet: ConstructorParameters<typeof PeerPayClient>[0]['walletClient'] | null | undefined
40
+ messageBoxUrl: string | null | undefined
41
+ originator?: string
42
+ }): PeerPayClient | null {
43
+ const { wallet, messageBoxUrl, originator } = args
44
+ if (!wallet || !messageBoxUrl || messageBoxUrl === NO_MESSAGE_BOX) return null
45
+ try {
46
+ return new PeerPayClient({
47
+ messageBoxHost: messageBoxUrl,
48
+ walletClient: wallet,
49
+ originator
50
+ })
51
+ } catch {
52
+ return null
53
+ }
54
+ }
55
+
56
+ interface StorageLike {
57
+ getKeyValue: (key: string) => Promise<string | undefined>
58
+ setKeyValue: (key: string, value: string) => Promise<void>
59
+ }
60
+
61
+ interface InternalizingWallet {
62
+ internalizeAction(args: unknown, originator?: string): Promise<unknown>
63
+ }
64
+
65
+ /**
66
+ * A shareable BRC-125 payment link for a handle.
67
+ *
68
+ * `peerpay:<key>[?sats=<n>][&url=<host>]`. The same form the app parses
69
+ * (parsePeerPayURI.ts) and routes (+native-intent.ts in the host app). A
70
+ * non-positive amount emits no `sats` — `sats=0` would be an invalid link,
71
+ * and an open request is exactly the absence of a figure. `url` is this
72
+ * app's extension: the payee's message-box host, so the payer can skip the
73
+ * overlay lookup. Omitted for the no-server sentinel and for blank.
74
+ */
75
+ export function peerPayLinkFor(identityKey: string, sats?: number, messageBoxUrl?: string): string {
76
+ const params: string[] = []
77
+ const amount = sats !== undefined ? Math.round(Number(sats)) : NaN
78
+ if (Number.isFinite(amount) && amount > 0) params.push(`sats=${amount}`)
79
+ const host = (messageBoxUrl ?? '').trim().replace(/\/+$/, '')
80
+ if (host && host !== NO_MESSAGE_BOX) params.push(`url=${encodeURIComponent(host)}`)
81
+ const base = `peerpay:${identityKey.toLowerCase()}`
82
+ return params.length ? `${base}?${params.join('&')}` : base
83
+ }
84
+
85
+ /**
86
+ * Credit an incoming payment, then acknowledge it. Never acknowledge first.
87
+ *
88
+ * `repairBeef` is the second chance. The token's AtomicBEEF was minted at send
89
+ * time, and a reorg between then and now invalidates its merkle path without
90
+ * touching the transaction itself — the toolbox reports that as
91
+ * "The tx parameter must be valid AtomicBEEF", which reads like a malformed
92
+ * payment and is nothing of the kind. Given a repair function, one failure is
93
+ * retried with a proof re-fetched by txid. Omit it and behaviour is unchanged.
94
+ */
95
+ export async function internalizeIncoming(
96
+ wallet: InternalizingWallet,
97
+ client: Pick<PeerPayClient, 'acknowledgeMessage'>,
98
+ adminOriginator: string,
99
+ payment: IncomingPayment,
100
+ description: string,
101
+ repairBeef?: (txid: string) => Promise<number[] | undefined>
102
+ ): Promise<void> {
103
+ // A note the sender attached to the token becomes the description the
104
+ // recipient's wallet records — same field the sender's action carries.
105
+ const note = (payment.token as { note?: unknown }).note
106
+ const noted = typeof note === 'string' && note.trim().length > 0 ? note.trim().slice(0, 500) : undefined
107
+
108
+ const argsFor = (tx: number[] | typeof payment.token.transaction) => ({
109
+ tx,
110
+ outputs: [
111
+ {
112
+ paymentRemittance: {
113
+ derivationPrefix: payment.token.customInstructions.derivationPrefix,
114
+ derivationSuffix: payment.token.customInstructions.derivationSuffix,
115
+ senderIdentityKey: payment.sender
116
+ },
117
+ outputIndex: payment.token.outputIndex ?? 0,
118
+ protocol: 'wallet payment'
119
+ }
120
+ ],
121
+ labels: ['peerpay'],
122
+ // Same rule as the sender's side: the note verbatim, space-padded to the
123
+ // 5-byte validation floor when it is shorter.
124
+ description: noted ? noted.padEnd(5) : description
125
+ })
126
+
127
+ try {
128
+ await wallet.internalizeAction(argsFor(payment.token.transaction), adminOriginator)
129
+ } catch (e) {
130
+ // The subject txid comes from the token's own AtomicBEEF rather than from
131
+ // the sender as a separate field, so a repair can only ever ask about the
132
+ // transaction this payment is actually for.
133
+ const txid = repairBeef ? safeAtomicTxid(payment.token.transaction) : undefined
134
+ const repaired = txid ? await repairBeef!(txid) : undefined
135
+ // Rethrow the ORIGINAL error when no repair was available: it is the one
136
+ // that describes why the payment could not be credited, and the inbox shows
137
+ // it to the user. A "could not re-fetch" message would bury it.
138
+ if (!repaired) throw e
139
+ await wallet.internalizeAction(argsFor(repaired), adminOriginator)
140
+ }
141
+
142
+ await acknowledgeCredited(client, String(payment.messageId))
143
+ }
144
+
145
+ /** Inbox ids whose credit succeeded but whose ack did not. Retry, do not NACK. */
146
+ const pendingCreditAcks = new Set<string>()
147
+
148
+ export function resetCreditAckQueueForTests(): void {
149
+ pendingCreditAcks.clear()
150
+ }
151
+
152
+ /**
153
+ * Ack after a successful internalize. A throw here is not a credit failure —
154
+ * the wallet already owns the payment.
155
+ */
156
+ async function acknowledgeCredited(
157
+ client: Pick<PeerPayClient, 'acknowledgeMessage'>,
158
+ messageId: string
159
+ ): Promise<void> {
160
+ pendingCreditAcks.add(messageId)
161
+ const ids = [...pendingCreditAcks]
162
+ try {
163
+ await client.acknowledgeMessage({ messageIds: ids })
164
+ for (const id of ids) pendingCreditAcks.delete(id)
165
+ } catch {
166
+ // Leave ids queued for a later successful credit. Do not throw: auto-accept
167
+ // would record a failed attempt and eventually NACK money this wallet holds.
168
+ }
169
+ }
170
+
171
+ /** The AtomicBEEF subject txid, or undefined if the bytes will not parse. */
172
+ function safeAtomicTxid(tx: number[]): string | undefined {
173
+ try {
174
+ return Beef.fromBinary(Array.from(tx)).atomicTxid
175
+ } catch {
176
+ return undefined
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Retry the same payment object once. Do not relist the inbox — a pass of N
182
+ * failures would otherwise listIncomingPayments per payment.
183
+ */
184
+ export async function acceptWithRetry(
185
+ client: Pick<PeerPayClient, 'listIncomingPayments'>,
186
+ messageBoxUrl: string,
187
+ payment: IncomingPayment,
188
+ description: string,
189
+ internalize: (p: IncomingPayment, d: string) => Promise<void>
190
+ ): Promise<void> {
191
+ void client
192
+ void messageBoxUrl
193
+ try {
194
+ await internalize(payment, description)
195
+ } catch {
196
+ await internalize(payment, description)
197
+ }
198
+ }
199
+
200
+ // ── The inbox ──
201
+ //
202
+ // An arriving payment is credited automatically. Accepting was never a decision
203
+ // a user could act on — the money is already theirs, the token is already in
204
+ // their box, and refusing it only leaves it there — so the tap it required was
205
+ // ceremony. What IS a decision is what to do about one the wallet cannot credit,
206
+ // and that is the only case the UI shows.
207
+
208
+ /** A payment the wallet has failed to credit, and how many times. */
209
+ export interface InboxAttempt {
210
+ attempts: number
211
+ error: string
212
+ /** Set when `autoAcceptInbox` was given a classifier. */
213
+ kind?: CreditFailureKind
214
+ }
215
+
216
+ /**
217
+ * How many times a payment is credited automatically before a human is asked.
218
+ *
219
+ * Two, not one: the common failure is transient (offline, a locked database, a
220
+ * stale token) and a second pass usually clears it. Not unbounded, because a
221
+ * structurally corrupt payment can never succeed, and retrying it every poll
222
+ * forever is a wallet write per tick against money that will never arrive.
223
+ */
224
+ export const MAX_AUTO_ATTEMPTS = 2
225
+
226
+ /** Whether this payment has stopped being retried and now needs a person. */
227
+ export function needsAttention(state: InboxAttempt | undefined): boolean {
228
+ return !!state && state.attempts >= MAX_AUTO_ATTEMPTS
229
+ }
230
+
231
+ /**
232
+ * Credit everything in the box that is still worth attempting.
233
+ *
234
+ * The credit itself is injected, so this function holds only the policy: what to
235
+ * attempt, what to leave alone, and what to remember. Returns a fresh attempt
236
+ * map rather than mutating, and that map is rebuilt from the payments actually
237
+ * present — a message that has left the box takes its state with it, so the map
238
+ * cannot grow without bound across a long-lived screen.
239
+ */
240
+ export async function autoAcceptInbox<T extends { messageId: string | number }>(args: {
241
+ payments: T[]
242
+ attempts: Record<string, InboxAttempt>
243
+ accept: (payment: T) => Promise<void>
244
+ /** Message ids to attempt even though they had given up — a user pressed Retry. */
245
+ force?: string[]
246
+ /** When omitted, every failure counts as structural (increments attempts). */
247
+ classify?: (e: unknown) => CreditFailureKind
248
+ /** Fired the first time a payment crosses into needsAttention. Do not ack. */
249
+ onGiveUp?: (payment: T, kind: CreditFailureKind) => void | Promise<void>
250
+ }): Promise<{ accepted: number; attempts: Record<string, InboxAttempt> }> {
251
+ const { payments, attempts, accept, classify, onGiveUp } = args
252
+ const forced = new Set(args.force ?? [])
253
+ const next: Record<string, InboxAttempt> = {}
254
+ let accepted = 0
255
+
256
+ for (const payment of payments) {
257
+ const id = String(payment.messageId)
258
+ const state = attempts[id]
259
+
260
+ // Already given up on, and nobody asked again: keep the row and its error
261
+ // exactly as it is. This is the line that stops the retry loop.
262
+ if (needsAttention(state) && !forced.has(id)) {
263
+ next[id] = state
264
+ continue
265
+ }
266
+
267
+ try {
268
+ await accept(payment)
269
+ accepted++
270
+ // Success clears the history: the payment is credited and acknowledged, so
271
+ // there is nothing left to show or retry.
272
+ } catch (e) {
273
+ const classified = classify?.(e)
274
+ const kind: CreditFailureKind = classified ?? 'structural'
275
+ const error = e instanceof Error && e.message ? e.message : String(e)
276
+ const counted = kind !== 'environmental'
277
+ const recorded: InboxAttempt = {
278
+ attempts: (state?.attempts ?? 0) + (counted ? 1 : 0),
279
+ error,
280
+ ...(classified ? { kind: classified } : {})
281
+ }
282
+ next[id] = recorded
283
+ if (counted && !needsAttention(state) && needsAttention(recorded) && onGiveUp) {
284
+ try {
285
+ await onGiveUp(payment, kind)
286
+ } catch {
287
+ // NACK is best-effort here; Discard will try again. The attempt is
288
+ // already recorded so a throw must not rewind the ceiling.
289
+ }
290
+ }
291
+ }
292
+ }
293
+
294
+ return { accepted, attempts: next }
295
+ }
296
+
297
+ /**
298
+ * Give up on a payment: NACK the sender, then acknowledge without crediting.
299
+ *
300
+ * Acknowledge-only discard deleted the only derivation data the receiver would
301
+ * ever see. The resend_request goes first so a failed NACK leaves the inbox
302
+ * row in place. `txid` on the wire is required; unparseable tokens use the
303
+ * message id so the sender can still match an outbox row later.
304
+ */
305
+ export async function discardIncoming(
306
+ client: Pick<PeerPayClient, 'acknowledgeMessage' | 'sendMessage'>,
307
+ payment: { messageId: string; sender?: string; token?: { transaction?: number[] } },
308
+ reason: ResendReason = 'uncreditible'
309
+ ): Promise<void> {
310
+ const txid = payment.token?.transaction ? safeAtomicTxid(payment.token.transaction) : undefined
311
+ if (payment.sender) {
312
+ await sendControlMessage(client, {
313
+ recipient: payment.sender,
314
+ message: {
315
+ type: 'resend_request',
316
+ txid: txid ?? String(payment.messageId),
317
+ reason,
318
+ messageId: String(payment.messageId)
319
+ }
320
+ })
321
+ }
322
+ await client.acknowledgeMessage({ messageIds: [payment.messageId] })
323
+ }
324
+
325
+ /** What the handle rail needs from the wallet: mint a noSend BRC-29 action,
326
+ * broadcast it later with sendWith, and abort it if the payment is cancelled. */
327
+ export interface HandleRailWallet {
328
+ getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
329
+ createAction(
330
+ args: unknown,
331
+ originator?: string
332
+ ): Promise<{ txid?: string; tx?: number[]; sendWithResults?: { txid?: string; status?: string }[] }>
333
+ listActions(args: unknown, originator?: string): Promise<{ actions: { txid?: string; reference?: string }[] }>
334
+ abortAction(args: unknown, originator?: string): Promise<unknown>
335
+ }
336
+
337
+ /** Broadcast a previously-minted noSend transaction. A createAction call whose
338
+ * only job is `options.sendWith` — no new outputs are created. */
339
+ async function broadcastNoSend(
340
+ wallet: Pick<HandleRailWallet, 'createAction'>,
341
+ adminOriginator: string,
342
+ txid: string
343
+ ): Promise<void> {
344
+ const result = (await wallet.createAction(
345
+ { description: 'PeerPay payment broadcast', options: { sendWith: [txid] } },
346
+ adminOriginator
347
+ )) as { sendWithResults?: { txid?: string; status?: string }[] }
348
+ const failed = result.sendWithResults?.find(o => o.txid === txid && o.status === 'failed')
349
+ if (failed) throw new Error('broadcast_failed')
350
+ }
351
+
352
+ /** Abort a PeerPay noSend by recovering its reference from listActions. */
353
+ async function abortPeerPayNosend(
354
+ wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>,
355
+ adminOriginator: string,
356
+ txid: string
357
+ ): Promise<boolean> {
358
+ // createAction returns no reference for a completed noSend action, so the
359
+ // abort handle is recovered from listActions by txid.
360
+ const { actions } = await wallet.listActions({ labels: ['peerpay'], limit: 1000 }, adminOriginator)
361
+ const match = actions.find(a => a.txid === txid)
362
+ if (!match?.reference) return false
363
+ await wallet.abortAction({ reference: match.reference }, adminOriginator)
364
+ return true
365
+ }
366
+
367
+ /**
368
+ * Pay a handle. Five steps, in this order:
369
+ * 1 mint the token with noSend (nothing hits the network yet)
370
+ * 2 persist it 3 deliver it 4 broadcast 5 mark sent
371
+ * The transaction is only broadcast once the recipient's message box has the
372
+ * token: a delivery failure therefore leaves nothing on-chain, and the entry
373
+ * can be retried — or cancelled, which aborts the action and frees its inputs.
374
+ * A throw from step 3 or 4 leaves an `unsent` entry with `delivered` recording
375
+ * how far it got, so retry re-attempts only what is still outstanding.
376
+ */
377
+ export async function sendViaHandle(args: {
378
+ wallet: HandleRailWallet
379
+ adminOriginator: string
380
+ client: Pick<PeerPayClient, 'sendMessage'>
381
+ storage: StorageLike
382
+ recipient: string
383
+ satoshis: number
384
+ messageBoxUrl: string
385
+ /** User's note for the payment. Becomes the action description and rides in
386
+ * the token, so the recipient's wallet can show it too. */
387
+ note?: string
388
+ /** Resolved display name, used only for the default description. */
389
+ recipientName?: string
390
+ /**
391
+ * The recipient's message-box host from a BRC-125 `url` extension. Passed
392
+ * as sendMessage's override so the overlay lookup is skipped, and stored on
393
+ * the entry so every retry goes to the same place.
394
+ */
395
+ recipientHost?: string
396
+ }): Promise<{ outboxId: string; satoshis: number }> {
397
+ const { wallet, adminOriginator, client, storage, recipient, messageBoxUrl, recipientName, recipientHost } = args
398
+ const sats = Math.round(Number(args.satoshis))
399
+ if (!Number.isFinite(sats) || sats <= 0) throw new Error('Invalid amount')
400
+ // No advertisement check. Anointing a host costs a transaction, so someone
401
+ // receiving BSV for the first time cannot have one — refusing to send to them
402
+ // would make an empty wallet unpayable. The client resolves the recipient's
403
+ // advertised host when there is one and otherwise falls back to the host this
404
+ // wallet is configured for, which is where both parties' apps look by default.
405
+
406
+ // The note IS the description when one was given — verbatim; otherwise
407
+ // "Pay <who>". BRC-100 requires 5–2000 bytes and the validator does not
408
+ // trim, so a very short note is padded with trailing spaces rather than
409
+ // decorated, and everything is clamped at the top end.
410
+ const note = args.note?.trim() || undefined
411
+ const description = (note ?? `Pay ${recipientName?.trim() || recipient.slice(0, 8)}`).slice(0, 500).padEnd(5)
412
+
413
+ // Standard BRC-29: fresh prefix/suffix, key derived toward the recipient.
414
+ const derivationPrefix = Utils.toBase64(Random(8))
415
+ const derivationSuffix = Utils.toBase64(Random(8))
416
+ const { publicKey } = await wallet.getPublicKey(
417
+ {
418
+ protocolID: BRC29_PROTOCOL_ID,
419
+ keyID: `${derivationPrefix} ${derivationSuffix}`,
420
+ counterparty: recipient
421
+ },
422
+ adminOriginator
423
+ )
424
+ const lockingScript = new P2PKH().lock(PublicKey.fromString(publicKey).toAddress()).toHex()
425
+
426
+ const car = await wallet.createAction(
427
+ {
428
+ description,
429
+ labels: ['peerpay', recipient],
430
+ outputs: [
431
+ {
432
+ lockingScript,
433
+ satoshis: sats,
434
+ outputDescription: 'PeerPay payment',
435
+ customInstructions: JSON.stringify({ derivationPrefix, derivationSuffix, type: 'BRC29' })
436
+ }
437
+ ],
438
+ // noSend: broadcast is deferred until the token is delivered. Output 0 is
439
+ // pinned so a send-max rewrite (maxPossibleSatoshis) can be read back.
440
+ options: { noSend: true, randomizeOutputs: false }
441
+ },
442
+ adminOriginator
443
+ )
444
+ if (!car.tx || !car.txid) throw new Error('Wallet did not return a signed transaction')
445
+
446
+ // Authoritative amount off the transaction itself — covers send-max, where
447
+ // the requested figure is the sentinel and the wallet wrote the real one.
448
+ const paid = Transaction.fromAtomicBEEF(car.tx).outputs[0]?.satoshis
449
+ if (typeof paid !== 'number' || paid <= 0) throw new Error('Could not determine paid amount')
450
+
451
+ const token = {
452
+ customInstructions: { derivationPrefix, derivationSuffix },
453
+ transaction: car.tx,
454
+ amount: paid,
455
+ // Not in the PaymentToken spec, but harmless extra JSON to wallets that
456
+ // ignore it — and this app's receive side shows it as the description.
457
+ ...(note ? { note } : {})
458
+ }
459
+ let outboxId: string | undefined
460
+ try {
461
+ outboxId = await saveOutboxEntry(storage, { recipient, token, messageBoxUrl, txid: car.txid, recipientHost })
462
+ } catch (e) {
463
+ try {
464
+ await abortPeerPayNosend(wallet, adminOriginator, car.txid)
465
+ } catch (abortErr) {
466
+ console.warn('[peerpay] abortPeerPayNosend failed:', abortErr instanceof Error ? abortErr.message : abortErr)
467
+ }
468
+ throw e
469
+ }
470
+ try {
471
+ // Checkpoint before the box round-trip: if we crash after the box accepted
472
+ // the token, cancel must not abort a payment the recipient may already hold.
473
+ await updateOutboxEntry(storage, outboxId, { delivering: true })
474
+ await client.sendMessage(
475
+ {
476
+ recipient,
477
+ messageBox: PAYMENT_INBOX,
478
+ body: JSON.stringify(token)
479
+ },
480
+ recipientHost
481
+ )
482
+ // Delivered is persisted before the broadcast is attempted: from here the
483
+ // recipient holds the token, so a retry must never re-mint or cancel-abort —
484
+ // only the broadcast is still outstanding.
485
+ await updateOutboxEntry(storage, outboxId, { delivered: true })
486
+ await broadcastNoSend(wallet, adminOriginator, car.txid)
487
+ await markOutboxSent(storage, outboxId)
488
+ } catch (e) {
489
+ const message = e instanceof Error ? e.message : String(e)
490
+ await updateOutboxEntry(storage, outboxId, {
491
+ lastAttemptAt: new Date().toISOString(),
492
+ lastError: message
493
+ })
494
+ TaskDrainOutbox.noteEnqueued()
495
+ throw e
496
+ }
497
+ return { outboxId, satoshis: paid }
498
+ }
499
+
500
+ /**
501
+ * Cancel or abandon an outbox entry.
502
+ *
503
+ * `undelivered` (default): abort the noSend action and remove the row. The
504
+ * stored row is re-read by `entry.id` before that abort — a stale snapshot
505
+ * is not authority. Missing row → no abort. Once `delivering` or `delivered`
506
+ * is set the token may already be in the recipient's box, so this mode
507
+ * refuses to abort and returns `needsAbandon`.
508
+ *
509
+ * `abandon` (delivered or delivering): tell the recipient via
510
+ * `payment_cancelled`, then abort if the action is still nosend, then remove.
511
+ * A failed control send leaves the row — the recipient would otherwise keep
512
+ * waiting. Legacy entries (no txid) were broadcast at creation; there is
513
+ * nothing to abort for them.
514
+ */
515
+ export async function cancelOutboxPayment(args: {
516
+ wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>
517
+ adminOriginator: string
518
+ storage: StorageLike
519
+ entry: Pick<OutboxEntry, 'id' | 'txid' | 'delivered' | 'delivering' | 'recipient' | 'recipientHost'>
520
+ client?: Pick<PeerPayClient, 'sendMessage'>
521
+ mode?: 'undelivered' | 'abandon'
522
+ }): Promise<{ aborted: boolean; needsAbandon?: boolean }> {
523
+ const { wallet, adminOriginator, storage, entry, client, mode = 'undelivered' } = args
524
+ if (mode !== 'abandon') {
525
+ const stored = (await getOutboxEntries(storage)).find(e => e.id === entry.id)
526
+ if (!stored) return { aborted: false }
527
+ if (stored.delivered === true || stored.delivering === true) {
528
+ return { aborted: false, needsAbandon: true }
529
+ }
530
+ }
531
+ if (mode === 'abandon') {
532
+ if (!client) throw new Error('client required to abandon')
533
+ if (entry.txid) {
534
+ // Same box the token went to — an entry minted for a link-named host must
535
+ // be cancelled there, or the payee never hears.
536
+ await sendControlMessage(
537
+ client,
538
+ {
539
+ recipient: entry.recipient,
540
+ message: { type: 'payment_cancelled', txid: entry.txid }
541
+ },
542
+ entry.recipientHost
543
+ )
544
+ }
545
+ }
546
+ let aborted = false
547
+ if (entry.txid) {
548
+ try {
549
+ aborted = await abortPeerPayNosend(wallet, adminOriginator, entry.txid)
550
+ } catch {
551
+ // The entry is still removed: the nosend row remains visible in wallet
552
+ // activity with its own abort control, so the money is never stranded
553
+ // invisibly.
554
+ }
555
+ }
556
+ await removeOutboxEntry(storage, entry.id)
557
+ return { aborted }
558
+ }
559
+
560
+ /**
561
+ * Whether an error from the handle rail means "the message box server could not
562
+ * be reached" rather than anything about the payment itself. The raw shapes —
563
+ * whatwg-fetch's `TypeError: Network request failed`, the auth middleware's
564
+ * "Network error while sending authenticated request to <host>/.well-known/auth",
565
+ * timeouts — all point the user at the same fix: the message box URL in
566
+ * settings. The UI maps this to that message instead of surfacing the raw text.
567
+ */
568
+ export function isMessageBoxNetworkError(e: unknown): boolean {
569
+ const message = e instanceof Error ? e.message : typeof e === 'string' ? e : ''
570
+ return /network request failed|network error|timed? ?out|timeout/i.test(message)
571
+ }
572
+
573
+ /**
574
+ * Retry a stuck entry, resuming from wherever it failed: deliver the token if
575
+ * the recipient never got it, then broadcast if the transaction is still
576
+ * noSend. Legacy entries (no txid) were broadcast at creation, so only their
577
+ * delivery is retried.
578
+ */
579
+ export async function retryDelivery(args: {
580
+ wallet: Pick<HandleRailWallet, 'createAction'>
581
+ adminOriginator: string
582
+ client: Pick<PeerPayClient, 'sendMessage'>
583
+ storage: StorageLike
584
+ entry: OutboxEntry
585
+ }): Promise<void> {
586
+ const { wallet, adminOriginator, client, storage, entry } = args
587
+ await updateOutboxEntry(storage, entry.id, { lastAttemptAt: new Date().toISOString() })
588
+ try {
589
+ if (entry.delivered !== true) {
590
+ await updateOutboxEntry(storage, entry.id, { delivering: true })
591
+ try {
592
+ await client.sendMessage(
593
+ {
594
+ recipient: entry.recipient,
595
+ messageBox: PAYMENT_INBOX,
596
+ body: JSON.stringify(entry.token)
597
+ },
598
+ entry.recipientHost
599
+ )
600
+ } catch (e) {
601
+ // The box already holds this token — the first attempt landed and only
602
+ // its response was lost. That is delivered, not failed: retrying it
603
+ // forever would strand a payment the recipient can already see.
604
+ if (!isDuplicateMessageError(e)) throw e
605
+ }
606
+ await updateOutboxEntry(storage, entry.id, { delivered: true })
607
+ }
608
+ if (entry.txid) {
609
+ await broadcastNoSend(wallet, adminOriginator, entry.txid)
610
+ }
611
+ await markOutboxSent(storage, entry.id)
612
+ } catch (e) {
613
+ const message = e instanceof Error ? e.message : String(e)
614
+ await updateOutboxEntry(storage, entry.id, { lastError: message })
615
+ throw e
616
+ }
617
+ }