@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,392 @@
1
+ import { P2PKH, PublicKey, Transaction } from '@bsv/sdk'
2
+ import { FRAME_VERSION, type PaymentFrame } from './codec'
3
+ import { isRequestableAmount, type Session } from './session'
4
+ import { PEERPAY_LABEL, PEERPAY_PROTOCOL_ID } from './pending'
5
+ import type { Ack } from './types'
6
+ import { getOnline } from '../net/online'
7
+
8
+ /** The toolbox's per-txid verdict on a `sendWith` release. */
9
+ type SendWithStatus = 'unproven' | 'sending' | 'failed'
10
+
11
+ interface CreateActionOutcome {
12
+ tx?: number[]
13
+ txid?: string
14
+ signableTransaction?: { reference: string }
15
+ sendWithResults?: { txid: string; status: string }[]
16
+ }
17
+
18
+ interface PayingWallet {
19
+ getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
20
+ createAction(args: unknown, originator?: string): Promise<CreateActionOutcome>
21
+ signAction(args: unknown, originator?: string): Promise<{ tx?: number[]; txid?: string }>
22
+ /**
23
+ * Releases the inputs a `noSend` action is holding. Required, not optional:
24
+ * without it an abandoned build locks `amount + fee` in the payer's wallet
25
+ * permanently — see BuiltPayment.reference.
26
+ */
27
+ abortAction(args: { reference: string }, originator?: string): Promise<{ aborted: boolean }>
28
+ }
29
+
30
+ /** A signed, undelivered payment plus the handles needed to unwind or release it. */
31
+ export interface BuiltPayment {
32
+ frame: PaymentFrame
33
+ /**
34
+ * The `createAction` reference, for `abortAction`.
35
+ *
36
+ * The action is created `noSend`, which marks its inputs `spendable: false`.
37
+ * The storage sweeper (`TaskFailAbandoned`) only reaps `unprocessed` and
38
+ * `unsigned` actions — NOT `nosend` — so a build that is never delivered
39
+ * locks `amount + fee` forever and silently. Callers MUST abort on every
40
+ * path where the frame provably never left the device, and MUST NOT abort
41
+ * once delivery is even possible: the payee may still broadcast, and
42
+ * aborting frees inputs the payer's wallet would then respend.
43
+ *
44
+ * Undefined only if a wallet finalises `createAction` itself without
45
+ * surfacing a reference; nothing can be aborted in that case.
46
+ */
47
+ reference?: string
48
+ /**
49
+ * The txid of the signed `noSend` transaction, for `broadcastPayment`.
50
+ *
51
+ * `options.sendWith` addresses a withheld action by txid, not by reference,
52
+ * so this is the only handle that can release it. Undefined only if a wallet
53
+ * returns no txid from either `createAction` or `signAction`; the action then
54
+ * cannot be broadcast by the payer at all.
55
+ */
56
+ txid?: string
57
+ /**
58
+ * The real satoshis locked into `frame.outputIndex`, read off the signed
59
+ * transaction rather than the requested `amount` — the two differ under
60
+ * send-max, where `amount` carries the sentinel and the wallet rewrites the
61
+ * output to whatever it could fund. Callers displaying "amount sent" must
62
+ * use this, not the value they asked `buildPaymentFrame` for.
63
+ */
64
+ satoshis: number
65
+ }
66
+
67
+ /**
68
+ * What became of a delivered payment, from the payer's side.
69
+ *
70
+ * `broadcast: 'pending'` is NOT a failed payment. It means the payee acked
71
+ * positively — the money is durably queued there and will be internalized —
72
+ * but this device could not get the transaction out itself.
73
+ */
74
+ export type DeliveryOutcome =
75
+ | { kind: 'sent'; broadcast: 'ok' | 'pending'; detail?: string }
76
+ | { kind: 'declined'; reason?: string }
77
+
78
+ /**
79
+ * Builds the frame a payer sends. BRC-29: the output locks to a key derived
80
+ * for the payee from the session's derivation nonces.
81
+ *
82
+ * The transaction is AtomicBEEF on both transports. The QR path was originally
83
+ * specified as bare rawtx to shrink the symbol, but the payee needs ancestry to
84
+ * internalize offline, and the fountain removed the symbol-size ceiling that
85
+ * made a smaller QR payload worth having — so one encoding serves both paths.
86
+ *
87
+ * `amount` is passed in rather than read off the session because the session's
88
+ * own amount is optional: on an open request the payer chooses. Making it an
89
+ * explicit argument means the one figure that becomes a real output — and the
90
+ * one the payee binds its settle check to — is chosen at exactly one call site
91
+ * and cannot silently fall back to `undefined` satoshis. It is validated here
92
+ * rather than trusted, since a fractional or negative value reaching
93
+ * createAction is a malformed transaction, not a UI glitch.
94
+ */
95
+ export async function buildPaymentFrame(
96
+ wallet: PayingWallet,
97
+ session: Session,
98
+ originator: string,
99
+ amount: number
100
+ ): Promise<BuiltPayment> {
101
+ if (!isRequestableAmount(amount)) {
102
+ throw new Error('amount must be a positive whole number of satoshis')
103
+ }
104
+ // A payee that named a figure is stating a binding term of the request, and
105
+ // its settle path refuses anything else. Catching the disagreement here — on
106
+ // the payer, before an action exists — turns a burnt build and a remote
107
+ // decline into a plain refusal with nothing to unwind.
108
+ if (session.amount !== undefined && session.amount !== amount) {
109
+ throw new Error('amount does not match the payee’s request')
110
+ }
111
+
112
+ const { publicKey: senderIdentityKey } = await wallet.getPublicKey({ identityKey: true }, originator)
113
+
114
+ const { publicKey: derived } = await wallet.getPublicKey(
115
+ {
116
+ protocolID: PEERPAY_PROTOCOL_ID,
117
+ keyID: `${session.derivationPrefix} ${session.derivationSuffix}`,
118
+ counterparty: session.identityKey,
119
+ forSelf: false
120
+ },
121
+ originator
122
+ )
123
+
124
+ const lockingScript = new P2PKH().lock(PublicKey.fromString(derived).toAddress()).toHex()
125
+
126
+ let result = await wallet.createAction(
127
+ {
128
+ description: 'Payment to a nearby device',
129
+ // The payee's identity key rides as a label, and the derivation data as
130
+ // the output's customInstructions — exactly what the handle rail writes.
131
+ // Both rails derive to BRC-29 (`counterparty: identityKey`, keyID
132
+ // `prefix suffix`), so a nearby payment whose code was never scanned can
133
+ // be rebuilt and re-delivered through the message box later, from the
134
+ // transaction's own row. Without these two fields nothing on this device
135
+ // remembers who the payment was for: the sealed frame needs the payee's
136
+ // session PSK to read, and that dies with the session.
137
+ labels: [PEERPAY_LABEL, session.identityKey],
138
+ outputs: [
139
+ {
140
+ lockingScript,
141
+ satoshis: amount,
142
+ outputDescription: 'Nearby payment',
143
+ customInstructions: JSON.stringify({
144
+ derivationPrefix: session.derivationPrefix,
145
+ derivationSuffix: session.derivationSuffix,
146
+ type: 'BRC29'
147
+ })
148
+ }
149
+ ],
150
+ // `signAndProcess: false` is what makes the action abortable.
151
+ //
152
+ // WalletPermissionsManager forces signAndProcess=false on the underlying
153
+ // wallet regardless, so the transaction built here is byte-identical
154
+ // either way. What changes is who finalises it: left unset, the manager
155
+ // calls signAction itself and returns `signableTransaction: undefined`,
156
+ // discarding the only reference the wallet ever emits. Asking for the
157
+ // deferred result keeps that reference, so an abandoned build can release
158
+ // its inputs instead of locking them forever.
159
+ options: { randomizeOutputs: false, noSend: true, signAndProcess: false }
160
+ },
161
+ originator
162
+ )
163
+
164
+ const reference = result.signableTransaction?.reference
165
+
166
+ // With signAndProcess disabled, createAction returns an unsigned
167
+ // `signableTransaction` rather than a final `tx`. We have no caller-supplied
168
+ // inputs — all inputs are wallet-funded — so finalize by signing with empty
169
+ // `spends`. noSend stays true: the payee internalizes and broadcasts, not
170
+ // the payer.
171
+ if (!result.tx && result.signableTransaction) {
172
+ const signed = await wallet.signAction(
173
+ {
174
+ reference: result.signableTransaction.reference,
175
+ spends: {},
176
+ options: { noSend: true }
177
+ },
178
+ originator
179
+ )
180
+ result = { ...result, ...signed }
181
+ }
182
+
183
+ if (!result.tx) throw new Error('createAction returned no transaction')
184
+
185
+ // Authoritative amount off the transaction itself — covers send-max, where
186
+ // `amount` was the sentinel and the wallet wrote the real figure to output 0.
187
+ const paid = Transaction.fromAtomicBEEF(result.tx).outputs[0]?.satoshis
188
+ if (typeof paid !== 'number' || paid <= 0) throw new Error('Could not determine paid amount')
189
+
190
+ return {
191
+ frame: {
192
+ version: FRAME_VERSION,
193
+ kind: 'bsv' as const,
194
+ senderIdentityKey,
195
+ outputIndex: 0,
196
+ derivationPrefix: session.derivationPrefix,
197
+ derivationSuffix: session.derivationSuffix,
198
+ transaction: new Uint8Array(result.tx)
199
+ },
200
+ reference,
201
+ txid: result.txid,
202
+ satoshis: paid
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Releases the `noSend` payment identified by `txid` so this device broadcasts it.
208
+ *
209
+ * BRC-100 releases a previously withheld action by naming its txid in
210
+ * `options.sendWith` on a follow-up `createAction` that creates nothing of its
211
+ * own. Verified end to end in @bsv/wallet-toolbox-mobile / @bsv/sdk:
212
+ *
213
+ * · sdk validationHelpers.js:458-460 — `isSendWith = sendWith.length > 0`, and
214
+ * `isNewTx` stays FALSE when there are no inputs and no outputs, so this
215
+ * builds nothing. `description` is still mandatory (5–2000 bytes, :438).
216
+ * · signer/methods/createAction.js:10-46 — with `isNewTx` false it skips
217
+ * straight to `processAction`, whose args carry `sendWith` and a null
218
+ * reference/txid/rawTx.
219
+ * · storage/methods/processAction.js:26 — the sendWith txids become
220
+ * `txidsOfReqsToShareWithWorld` and go to `shareReqsWithWorld`.
221
+ * · storage/storageProviderHelpers.js:14 — `readyToSendStatuses` includes
222
+ * 'nosend', so a withheld req classifies as `readyToSend` (:28-35) →
223
+ * `SendWithResult.status = 'sending'` (processAction.js:64-66).
224
+ * · processAction.js:127-136 — on the default delayed path the req moves to
225
+ * 'unsent' and the transaction to 'sending'. That is the escape from
226
+ * 'nosend': monitor/tasks/TaskFailAbandoned.js:35 only ever sweeps
227
+ * ['unprocessed', 'unsigned'], so nothing else would have moved it.
228
+ *
229
+ * Reaching this through WalletPermissionsManager raises no prompt and cannot
230
+ * abort the action: with no inputs or outputs the underlying createAction
231
+ * returns no `signableTransaction`, and the manager returns at
232
+ * WalletPermissionsManager.js:2856 before its spending-authorization gate.
233
+ *
234
+ * Throws when the toolbox reports 'failed' for this txid. Callers must treat
235
+ * that as retryable, never as a failed payment — see finalizeDelivery.
236
+ */
237
+ export async function broadcastPayment(
238
+ wallet: PayingWallet,
239
+ txid: string,
240
+ originator: string
241
+ ): Promise<SendWithStatus | undefined> {
242
+ const result = await wallet.createAction(
243
+ {
244
+ // Mandatory even though this creates nothing; must be 5–2000 bytes.
245
+ description: 'Broadcast a nearby payment',
246
+ options: { sendWith: [txid] }
247
+ },
248
+ originator
249
+ )
250
+ const status = result.sendWithResults?.find(r => r.txid === txid)?.status
251
+ if (status === 'failed') {
252
+ throw new Error(`the wallet could not broadcast ${txid}`)
253
+ }
254
+ return status === 'unproven' || status === 'sending' ? status : undefined
255
+ }
256
+
257
+ /**
258
+ * The payer's post-delivery decision. Extracted from the screen so the whole
259
+ * state machine is testable, because it is the point where real money is
260
+ * either released or reclaimed.
261
+ *
262
+ * POSITIVE ack — the payee has DURABLY QUEUED the payment. Broadcast now.
263
+ * Never abort: the payee holds a copy and will internalize it, and freeing
264
+ * the inputs here lets this wallet respend them into a conflict.
265
+ *
266
+ * NEGATIVE ack — the payee provably queued nothing (see DeclineReason).
267
+ * Abort to release the inputs, and never broadcast.
268
+ *
269
+ * NO ack (a throw from the transport) — not this function's business. The
270
+ * caller must neither abort nor broadcast: a lost ack does not prove
271
+ * non-delivery, so the frame may still be with the payee.
272
+ *
273
+ * A broadcast failure after a positive ack returns `broadcast: 'pending'`, not
274
+ * a failure. The money is safe at the payee; what is stuck is this device's
275
+ * copy of the transaction, which is a retryable notice, not a failed payment.
276
+ *
277
+ * A positive ack always persists first (`deps.hold`) — including when online.
278
+ * Online Done used to `sendWith` with no queue row and no `framePayload`, which
279
+ * discarded the only copy of the derivation nonces. The drain already posts
280
+ * when online; `sendWith` below runs only after that row exists.
281
+ *
282
+ * OFFLINE: with no network there is nothing to broadcast to, so a positive ack
283
+ * enqueues and returns. The transaction is promoted from `nosend` to `unproven` by
284
+ * the hold, which is what lets the payer fund a SECOND offline payment from this
285
+ * one's change — `allocateChangeInput` excludes `nosend`
286
+ * (storage/StorageExpoSQLite.ts:1284). The outcome is the existing
287
+ * `broadcast: 'pending'`, which the UI already renders as "queued", so no new
288
+ * state reaches the screens. `deps` is injected — not read from `@/utils/net/online`
289
+ * or a database directly — so this stays unit-testable without either; the real
290
+ * app supplies both at the NearbyFlow call site.
291
+ */
292
+ export async function finalizeDelivery(
293
+ wallet: PayingWallet,
294
+ built: BuiltPayment,
295
+ ack: Ack,
296
+ originator: string,
297
+ /**
298
+ * Required, and so is `hold` inside it, because the offline branch cannot
299
+ * honestly report a queue it has no way to make. A call site that omitted it
300
+ * would leave the transaction at `nosend` — change unspendable, no queue row,
301
+ * no monitor task that sweeps it — while telling the user it was waiting to be
302
+ * broadcast. `online` stays optional: its default is the real probe, and
303
+ * getting that wrong costs a retry rather than a stranded payment.
304
+ */
305
+ deps: {
306
+ online?: () => Promise<boolean>
307
+ /** Promotes the transaction to `unproven` and queues the txid for release. */
308
+ hold: (txid: string) => Promise<void>
309
+ /** Persist a failed decline-abort so wallet build can retry it. */
310
+ queueFailedAbort?: (reference: string) => Promise<void>
311
+ }
312
+ ): Promise<DeliveryOutcome> {
313
+ if (!ack.ok) {
314
+ if (built.reference) {
315
+ // A failed abort is a stuck UTXO, not a lost payment, and must not
316
+ // displace the decline reason the caller is about to show. `{ aborted:
317
+ // false }` is a failure too — queue it for replay on the next wallet build.
318
+ try {
319
+ const result = await wallet.abortAction({ reference: built.reference }, originator)
320
+ if (result?.aborted === false) throw new Error('abortAction returned aborted:false')
321
+ } catch (e: unknown) {
322
+ console.warn('[localpay] abortAction failed:', messageOf(e))
323
+ if (deps.queueFailedAbort) {
324
+ await deps.queueFailedAbort(built.reference).catch(() => undefined)
325
+ }
326
+ }
327
+ }
328
+ return { kind: 'declined', reason: ack.error }
329
+ }
330
+
331
+ if (!built.txid) {
332
+ return { kind: 'sent', broadcast: 'pending', detail: 'the wallet returned no txid to broadcast' }
333
+ }
334
+
335
+ const online = deps?.online ?? getOnline
336
+ // A failed connectivity probe must not change what this function does: assume
337
+ // online and fall through to the ordinary broadcast, which is exactly what ran
338
+ // before this branch existed. If the device is genuinely offline, that attempt
339
+ // fails on its own and lands on the same `broadcast: 'pending'` the hold would
340
+ // have returned anyway — so a probe failure costs nothing either way. This
341
+ // mirrors the same guard already used around every other call to `getOnline`
342
+ // in this codebase (`StorageExpoSQLite.attemptToPostReqsToNetwork`,
343
+ // `processOfflineActions.probeOnline`).
344
+ let isOnline = true
345
+ try {
346
+ isOnline = await online()
347
+ } catch (e) {
348
+ console.warn('[localpay] connectivity probe failed, assuming online:', messageOf(e))
349
+ }
350
+
351
+ // Persist before any sendWith, online or off. Skipping this on the online
352
+ // path discarded the sealed frame after Done.
353
+ if (typeof deps?.hold === 'function') {
354
+ try {
355
+ await deps.hold(built.txid)
356
+ } catch (e) {
357
+ // The payee holds a copy and will internalize it, so this is still a sent
358
+ // payment — never a failure. sendWith runs only after the queue row
359
+ // exists: broadcasting here would drop the only sealed-frame copy.
360
+ // Nothing re-drives a hold that threw before its writes landed. See
361
+ // `holdSentPaymentOffline` for why its queue-row insert runs before its
362
+ // status promotion, which is what keeps a partial failure recoverable.
363
+ return { kind: 'sent', broadcast: 'pending', detail: messageOf(e) }
364
+ }
365
+ } else if (!isOnline) {
366
+ // The signature requires `hold`; this catches a JS caller or a cast that
367
+ // got past it. Reported rather than ignored, and deliberately NOT fallen
368
+ // through to the broadcast: offline, a delayed `sendWith` comes back
369
+ // 'sending', which this function reports as `broadcast: 'ok'` — green on
370
+ // the payer's screen for a transaction nothing has.
371
+ return {
372
+ kind: 'sent',
373
+ broadcast: 'pending',
374
+ detail: 'offline, and no hold was supplied to queue this payment with'
375
+ }
376
+ }
377
+
378
+ if (!isOnline) {
379
+ return { kind: 'sent', broadcast: 'pending', detail: 'offline — queued until this device reconnects' }
380
+ }
381
+
382
+ try {
383
+ await broadcastPayment(wallet, built.txid, originator)
384
+ return { kind: 'sent', broadcast: 'ok' }
385
+ } catch (e) {
386
+ return { kind: 'sent', broadcast: 'pending', detail: messageOf(e) }
387
+ }
388
+ }
389
+
390
+ function messageOf(e: unknown): string {
391
+ return e instanceof Error && e.message ? e.message : String(e)
392
+ }