@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -52,16 +52,110 @@
52
52
  * shares nothing. What genuinely is shared — the `offline_actions` insert — is
53
53
  * reused directly via `insertOfflineAction`.
54
54
  */
55
- import { insertOfflineAction, updateOfflineAction } from '../storage/methods/offlineActions'
55
+ import { findOfflineActionByTxid, insertOfflineAction, updateOfflineAction } from '../storage/methods/offlineActions'
56
56
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
57
+ import { devLog } from '../logging'
58
+ import { createSettlementStore, type SettlementDb } from '../mandala/settlementStore'
59
+ import type { EvidenceFrame, TokenHandedOverHook } from '../mandala/types'
57
60
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
58
61
 
59
- export async function holdSentPaymentOffline(args: {
60
- storage: StorageExpoSQLite
61
- txid: string
62
- /** The full bsvpayf1: QR string, persisted so the code can be re-shown later. */
63
- framePayload?: string
64
- }): Promise<void> {
62
+ /**
63
+ * The PLAINTEXT frame and the hook that persists what it carries.
64
+ *
65
+ * `framePayload` is the frame SEALED with the nearby session's pre-shared key,
66
+ * and `offline/tokenFrames.ts` keeps that key IN MEMORY ONLY, deliberately — a
67
+ * durable copy of the key that opens every stored frame is exactly what nobody
68
+ * wants on disk. The consequence, until now, was that the payer's own
69
+ * `token_settlements` row existed only as a re-derivation from bytes it could
70
+ * no longer open after a restart: no row, and `processOfflineActions` reads the
71
+ * absence as "this is an ordinary BSV transaction" and broadcasts an unadmitted
72
+ * token tip.
73
+ *
74
+ * So the frame is handed over here, while it is still open, and the row plus
75
+ * its evidence are written from it. `tokenFrames.ts` stays exactly as it was —
76
+ * a best-effort fallback for the rows this process still holds a key for.
77
+ */
78
+ export interface TokenHandoverDeps {
79
+ /** The open frame this hand-over is for. Absent on the BSV rail. */
80
+ frame?: EvidenceFrame
81
+ /** Implemented by the Mandala runtime; writes the row and the evidence. */
82
+ onTokenHandedOver?: TokenHandedOverHook
83
+ /**
84
+ * The `createAction` reference of the action that built this tip
85
+ * (`BuiltPayment.reference`), recorded on the settlement row so an
86
+ * `abortAction` against it can be refused once the payee holds the frame.
87
+ * See `core/mandala/abortGuard.ts` — a token action stays `noSend` until the
88
+ * drain broadcasts it, so its reference is the one handle anything has on
89
+ * money that is already gone.
90
+ */
91
+ reference?: string
92
+ }
93
+
94
+ /**
95
+ * Advance this txid's settlement row `parked → handed_over` (§4.4, FIX F).
96
+ *
97
+ * The queue row's own `parked → queued` advance has a settlement twin, and it
98
+ * has to be issued explicitly for the same reason the queue one did:
99
+ * `upsertSettlement` never writes `state` on conflict (rule 1 in
100
+ * `settlementStore.ts`), so a hook re-running over an existing `parked` row
101
+ * leaves it `parked` — and `parked` is the one non-terminal state the drain
102
+ * refuses to submit, by design (FIX F). Without this the payer's optional
103
+ * submit (rule 6) could never start for a payment that was parked first.
104
+ *
105
+ * Best-effort, and it runs AFTER the queue row: the queue row is the durable
106
+ * fact, a settlement row is a re-derivable cache (FIX G), and the drain's own
107
+ * `reconcileSettlements` pass re-runs this population every tick. A wallet on a
108
+ * schema without these tables simply logs.
109
+ */
110
+ async function advanceToHandedOver(storage: StorageExpoSQLite, txid: string): Promise<void> {
111
+ const db = storage.sqliteDb
112
+ if (!db) return
113
+ try {
114
+ await createSettlementStore(db as unknown as SettlementDb).advanceSettlement(txid, ['parked'], 'handed_over')
115
+ } catch (e) {
116
+ devLog(`[payerHold] could not advance the settlement row for ${txid} to handed_over:`, e)
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Persist what the plaintext frame carries, for the state this call just put
122
+ * the payment in. Never throws: the queue row is already durable by the time
123
+ * this runs, and a payment that IS queued must not be reported as un-queued
124
+ * because a cache write failed.
125
+ */
126
+ async function journalHandover(
127
+ deps: TokenHandoverDeps,
128
+ txid: string,
129
+ state: 'parked' | 'handed_over'
130
+ ): Promise<void> {
131
+ if (!deps.frame?.token || !deps.onTokenHandedOver) return
132
+ try {
133
+ await deps.onTokenHandedOver(deps.frame, txid, state, deps.reference)
134
+ } catch (e) {
135
+ devLog(`[payerHold] could not journal the ${state} settlement for ${txid}:`, e)
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Statuses a second confirm may advance to 'queued'.
141
+ *
142
+ * 'parked' is the case FIX F names: the payer showed the code, walked away,
143
+ * came back and confirmed. 'queued' is included because re-confirming an
144
+ * already-queued payment must be a harmless no-op rather than a refusal.
145
+ * Everything past them — 'sent', 'rejected', 'acknowledged' — is a decided
146
+ * payment, and dragging one back to 'queued' would re-broadcast a transaction
147
+ * the wallet has already failed or cancelled.
148
+ */
149
+ const ADVANCEABLE_TO_QUEUED = new Set(['parked', 'queued'])
150
+
151
+ export async function holdSentPaymentOffline(
152
+ args: TokenHandoverDeps & {
153
+ storage: StorageExpoSQLite
154
+ txid: string
155
+ /** The full bsvpayf1: QR string, persisted so the code can be re-shown later. */
156
+ framePayload?: string
157
+ }
158
+ ): Promise<void> {
65
159
  const { storage, txid, framePayload } = args
66
160
  const db = storage.sqliteDb
67
161
  if (!db) throw new Error('the database is not open, cannot queue this payment for release')
@@ -80,9 +174,42 @@ export async function holdSentPaymentOffline(args: {
80
174
  const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
81
175
  if (!tx) throw new Error(`no transaction record for ${txid}, cannot queue it for release`)
82
176
 
177
+ // FIX F, part 1. `insertOfflineAction` is INSERT OR IGNORE on a UNIQUE txid:
178
+ // with a row already present it proves re-insert idempotency only, never a
179
+ // state advance. So a payer who parked, walked away, came back and confirmed
180
+ // had the insert silently ignored — the row stayed 'parked' forever while
181
+ // the promotion below still moved the transaction past 'nosend', leaving the
182
+ // payment neither drainable ('queued'/'posting' are all the drain reads) nor
183
+ // cancellable (`cancelParkedPayment` refuses anything past 'nosend'). An
184
+ // existing row is therefore ADVANCED rather than re-inserted.
185
+ const existing = await findOfflineActionByTxid(db, txid)
186
+ if (existing) {
187
+ if (!ADVANCEABLE_TO_QUEUED.has(existing.status)) {
188
+ // A decided payment. Neither the queue row nor the transaction may move.
189
+ devLog(`[holdSentPaymentOffline] ${txid} is already '${existing.status}', leaving it alone`)
190
+ return
191
+ }
192
+ // Same two writes and the same order as the insert path: the durable row
193
+ // first, the promotion after.
194
+ await updateOfflineAction(db, txid, { status: 'queued' })
195
+ TaskSendOffline.noteEnqueued()
196
+ await journalHandover(args, txid, 'handed_over')
197
+ await advanceToHandedOver(storage, txid)
198
+ // Only while still withheld: if the payee already broadcast and this device
199
+ // saw it, the transaction has moved on and this write would be a lie.
200
+ if (tx.status === 'nosend') await storage.updateTransactionStatus('unproven', tx.transactionId)
201
+ return
202
+ }
203
+
83
204
  // Insert before promote — see the ORDER MATTERS note above.
84
205
  await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload })
85
206
  TaskSendOffline.noteEnqueued()
207
+ // Queue row first, settlement second, for the reason the ORDER MATTERS note
208
+ // gives: the queue row is what the drain finds, and it is durable. The
209
+ // advance is issued even on this path because a row may already exist at
210
+ // `parked` from a park that never got its queue row written.
211
+ await journalHandover(args, txid, 'handed_over')
212
+ await advanceToHandedOver(storage, txid)
86
213
  await storage.updateTransactionStatus('unproven', tx.transactionId)
87
214
  }
88
215
 
@@ -102,11 +229,13 @@ export async function holdSentPaymentOffline(args: {
102
229
  * their side and this device sees it confirm. If they did not, the payer can
103
230
  * cancel and nothing was ever spent.
104
231
  */
105
- export async function parkSentPaymentOffline(args: {
106
- storage: StorageExpoSQLite
107
- txid: string
108
- framePayload?: string
109
- }): Promise<void> {
232
+ export async function parkSentPaymentOffline(
233
+ args: TokenHandoverDeps & {
234
+ storage: StorageExpoSQLite
235
+ txid: string
236
+ framePayload?: string
237
+ }
238
+ ): Promise<void> {
110
239
  const { storage, txid, framePayload } = args
111
240
  const db = storage.sqliteDb
112
241
  if (!db) throw new Error('the database is not open, cannot park this payment')
@@ -117,6 +246,12 @@ export async function parkSentPaymentOffline(args: {
117
246
  // No promote, and no TaskSendOffline.noteEnqueued(): both are what turn a
118
247
  // stored frame into a broadcast.
119
248
  await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload }, 'parked')
249
+ // The row is written at `parked`, which the drain will never submit (FIX F) —
250
+ // but it EXISTS, which is what `processOfflineActions` and
251
+ // `attemptToPostReqsToNetwork` both key their token branch on. That is the
252
+ // durability this call buys and the sealed `framePayload` cannot: after a
253
+ // restart the session PSK is gone and these bytes can no longer be opened.
254
+ await journalHandover(args, txid, 'parked')
120
255
  }
121
256
 
122
257
 
@@ -138,6 +273,11 @@ export async function releaseParkedPayment(args: { storage: StorageExpoSQLite; t
138
273
 
139
274
  await updateOfflineAction(db, txid, { status: 'queued' })
140
275
  TaskSendOffline.noteEnqueued()
276
+ // The settlement twin of the line above (§4.4). No frame is threaded here —
277
+ // this is the re-show-and-confirm path, and the row was already written from
278
+ // the plaintext frame when the payment was parked — so the state advance is
279
+ // the whole of it.
280
+ await advanceToHandedOver(storage, txid)
141
281
  // Already promoted if the payee broadcast and this device saw it; the write
142
282
  // is only correct while the transaction is still being withheld.
143
283
  if (tx.status === 'nosend') await storage.updateTransactionStatus('unproven', tx.transactionId)
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { dependencyOrder, descendantsOf, releaseOrder, type OrderableTx } from './order'
11
11
  import type { OfflineActionRow } from '../storage/methods/offlineActions'
12
- import type { ProvenTxReqStatus } from '@bsv/wallet-toolbox-mobile/out/src/sdk/types'
12
+ import type { ProvenTxReqStatus } from '../toolboxTypes'
13
13
 
14
14
  export type PostOutcome = 'success' | 'serviceError' | 'invalidTx' | 'doubleSpend'
15
15
 
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Turning the frames this device already holds durably into drain sources.
3
+ *
4
+ * This is the supply side of FIX G and FIX I. `processOfflineActions` calls
5
+ * `token.frames()` at the start of every pass and hands the result to
6
+ * `reconcileSettlements`, which re-derives the evidence cache and any missing
7
+ * `token_settlements` row. The two durable stores have very different shapes,
8
+ * so each gets its own reader:
9
+ *
10
+ * · `localpay_pending` (receiver) holds the frame ALREADY DECODED, so nothing
11
+ * is needed but the queue entries.
12
+ * · `offline_actions.framePayload` (payer) holds the SEALED `bsvpayf1:` QR
13
+ * string. Opening it needs the session pre-shared key, which the drain does
14
+ * not hold and should not — so the decoder is injected by whoever still has
15
+ * the session, and a row that cannot be opened is simply skipped. The payer
16
+ * losing its own settlement row is survivable in a way the recipient's is
17
+ * not: the recipient submits (rule 3), and the payer's optional submit
18
+ * (rule 6) is a race it is always safe to lose.
19
+ *
20
+ * **Deliberately NOT filtered by `MAX_PENDING_ATTEMPTS` (FIX I).** That ceiling
21
+ * governs `localpay_pending`'s own BSV-shaped internalize retry loop and burns
22
+ * an attempt on any failure, including a transient
23
+ * `Block header not found for height N` from a fresh-block BUMP this device has
24
+ * not caught up on. A token payment's state of record is `token_settlements`,
25
+ * not the pending queue — so an exhausted queue entry still contributes its
26
+ * frame here, the settlement row stays alive, and the row is abandoned only by
27
+ * an explicit `refused`/`orphaned` verdict from the overlay.
28
+ */
29
+ import { Beef, Transaction } from '@bsv/sdk'
30
+ import { MandalaToken } from '@bsv/templates'
31
+ import type { EvidenceFrame, TokenFrameSource } from '../mandala/drain'
32
+ import type { OfflineActionRow } from '../storage/methods/offlineActions'
33
+ import { frameBytesFromQr, unsealFrame } from '../localpay/codec'
34
+
35
+ /** Structurally satisfied by `localpay/pending`'s `PendingPayment`. */
36
+ export interface PendingLike {
37
+ frame: EvidenceFrame
38
+ status?: string
39
+ }
40
+
41
+ /**
42
+ * The subject txid of an AtomicBEEF — the same txid `internalizeAction` used
43
+ * internally, and therefore the one a `token_settlements` row is keyed by.
44
+ */
45
+ /**
46
+ * The token figure a frame moves: the amount in the PAYEE output's own script.
47
+ *
48
+ * Read off the atomic transaction rather than trusted from any body, and off
49
+ * `outputIndex` (0 when the frame does not say — the nearby build never
50
+ * randomises outputs) so the payer's own frame answers the payee's figure and
51
+ * never the change. `undefined` for anything that is not a readable token
52
+ * output: the settlement row then has no amount, which the activity list says
53
+ * out loud rather than inventing a number.
54
+ */
55
+ export function frameTokenAmount(frame: EvidenceFrame): number | undefined {
56
+ try {
57
+ const tx = Transaction.fromAtomicBEEF(Array.from(frame.transaction))
58
+ const script = tx.outputs[frame.outputIndex ?? 0]?.lockingScript
59
+ if (!script) return undefined
60
+ const amount = MandalaToken.decode(script).amount
61
+ return Number.isFinite(amount) && amount >= 0 ? amount : undefined
62
+ } catch {
63
+ return undefined
64
+ }
65
+ }
66
+
67
+ export function frameTxid(frame: EvidenceFrame): string | undefined {
68
+ try {
69
+ return Beef.fromBinary(frame.transaction).atomicTxid
70
+ } catch {
71
+ return undefined
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Receiver-side sources. Every non-completed entry with a token block, whether
77
+ * or not the pending queue has given up on it.
78
+ */
79
+ export function tokenFrameSourcesFromPending(entries: readonly PendingLike[]): TokenFrameSource[] {
80
+ const sources: TokenFrameSource[] = []
81
+ for (const entry of entries) {
82
+ if (!entry.frame?.token) continue
83
+ const txid = frameTxid(entry.frame)
84
+ if (!txid) continue
85
+ const amountBaseUnits = frameTokenAmount(entry.frame)
86
+ sources.push({
87
+ txid,
88
+ role: 'received',
89
+ frame: entry.frame,
90
+ ...(amountBaseUnits !== undefined ? { amountBaseUnits } : {})
91
+ })
92
+ }
93
+ return sources
94
+ }
95
+
96
+ /**
97
+ * Payer-side sources, for the rows whose sealed `framePayload` the caller can
98
+ * open. A row this device cannot decode contributes nothing rather than
99
+ * throwing: the drain must reach every other row in the same pass.
100
+ */
101
+ export function tokenFrameSourcesFromOfflineActions(
102
+ rows: readonly OfflineActionRow[],
103
+ decode: (framePayload: string) => EvidenceFrame | undefined
104
+ ): TokenFrameSource[] {
105
+ const sources: TokenFrameSource[] = []
106
+ for (const row of rows) {
107
+ if (!row.framePayload) continue
108
+ let frame: EvidenceFrame | undefined
109
+ try {
110
+ frame = decode(row.framePayload)
111
+ } catch {
112
+ continue
113
+ }
114
+ if (!frame?.token) continue
115
+ const amountBaseUnits = frameTokenAmount(frame)
116
+ sources.push({
117
+ txid: row.txid,
118
+ role: row.role,
119
+ frame,
120
+ // A parked row must keep its own state: it is the user's, not the
121
+ // drain's, and reconciliation may not promote it to a submittable one.
122
+ state: row.status === 'parked' ? 'parked' : undefined,
123
+ ...(amountBaseUnits !== undefined ? { amountBaseUnits } : {})
124
+ })
125
+ }
126
+ return sources
127
+ }
128
+
129
+ // ───────────────────── the payer's sealed-frame decoder ─────────────────────
130
+ //
131
+ // `offline_actions.framePayload` is the `bsvpayf1:` envelope around a frame
132
+ // SEALED with the nearby session's pre-shared key. The drain holds no session
133
+ // and should not: the PSK is a hand-over secret, not durable wallet state. So
134
+ // the keys of the sessions this process has actually taken part in are kept
135
+ // here, in memory only, and the decoder tries each of them.
136
+ //
137
+ // What "in memory only" costs is bounded and known: a payer that restarts
138
+ // before its own optional submit (rule 6) loses the ability to re-derive its
139
+ // `token_settlements` row from the frame. That is the race it is always safe
140
+ // to lose — the RECIPIENT submits (rule 3), and the payer's submit only makes
141
+ // its own change spendable sooner. What it buys is that a durable copy of the
142
+ // key that opens every stored frame is never written to disk.
143
+
144
+ /** How many session keys are remembered. Well past any plausible number of live hand-overs. */
145
+ export const MAX_REMEMBERED_SESSION_KEYS = 32
146
+
147
+ const sessionKeys: Uint8Array[] = []
148
+
149
+ /**
150
+ * Remember a nearby session's PSK for this process.
151
+ *
152
+ * Called by whoever mints or scans a session (the nearby flow), not by the
153
+ * drain. Idempotent per key, and bounded: the oldest key is dropped once the
154
+ * ring is full, which is correct because a hand-over's frame is reconciled on
155
+ * the very next online tick.
156
+ */
157
+ export function rememberSessionPsk(psk: Uint8Array): void {
158
+ if (!(psk instanceof Uint8Array) || psk.length !== 32) return
159
+ const already = sessionKeys.some(known => known.length === psk.length && known.every((b, i) => b === psk[i]))
160
+ if (already) return
161
+ sessionKeys.push(new Uint8Array(psk))
162
+ while (sessionKeys.length > MAX_REMEMBERED_SESSION_KEYS) sessionKeys.shift()
163
+ }
164
+
165
+ /** Drop every remembered key. Logout, network switch, and the tests. */
166
+ export function forgetSessionPsks(): void {
167
+ sessionKeys.length = 0
168
+ }
169
+
170
+ /**
171
+ * A decoder for `tokenFrameSourcesFromOfflineActions`.
172
+ *
173
+ * Tries each remembered session key in turn and returns the first frame that
174
+ * opens. Undefined — never a throw — for a truncated row, a foreign string, or
175
+ * a frame from a session this process no longer holds the key for: the drain
176
+ * must reach every other row in the same pass.
177
+ */
178
+ export function sealedFramePayloadDecoder(
179
+ keys: () => readonly Uint8Array[] = () => sessionKeys
180
+ ): (framePayload: string) => EvidenceFrame | undefined {
181
+ return framePayload => {
182
+ let bytes: Uint8Array
183
+ try {
184
+ bytes = frameBytesFromQr(framePayload)
185
+ } catch {
186
+ return undefined
187
+ }
188
+ for (const psk of keys()) {
189
+ try {
190
+ return unsealFrame(bytes, psk)
191
+ } catch {
192
+ // Wrong key for this frame (a GCM tag mismatch). Try the next.
193
+ }
194
+ }
195
+ return undefined
196
+ }
197
+ }
@@ -3,8 +3,17 @@ import { PublicKey } from '@bsv/sdk'
3
3
  /**
4
4
  * BRC-125 PeerPay URI (https://bsv.brc.dev/payments/0125).
5
5
  *
6
- * peerpay-URI = "peerpay:" identity-key [ "?" query ]
7
- * sats-param = "sats=" 1*DIGIT
6
+ * peerpay-URI = "peerpay:" identity-key [ "?" query ]
7
+ * sats-param = "sats=" 1*DIGIT
8
+ * asset-param = "asset=" 64HEXDIG "." 1*DIGIT ; the asset's genesis outpoint
9
+ * amount-param = "amount=" 1*DIGIT ; BASE UNITS of that asset
10
+ *
11
+ * `sats` is the BSV selector. `asset` names a token by its genesis outpoint —
12
+ * the one identifier every issuer's asset already has — and `amount` is a
13
+ * figure in that token's own base units, so it only means anything beside an
14
+ * `asset`. Both are optional: `asset` alone is an open token request, where
15
+ * the payer chooses the figure. A link mixing `sats` with either is refused
16
+ * rather than read in one money or the other (maintainer decision, 2026-09-15).
8
17
  *
9
18
  * Plus one extension parameter this app emits and reads: `url`, the payee's
10
19
  * message-box host, so a payer can skip the overlay lookup. Per BRC-125 an extension that does not parse
@@ -15,6 +24,10 @@ import { PublicKey } from '@bsv/sdk'
15
24
  export interface PeerPayParams {
16
25
  identityKey: string
17
26
  sats?: number
27
+ /** The token's genesis outpoint, `txid.vout`, lowercased. */
28
+ asset?: string
29
+ /** Base units of `asset`. Never present without it. */
30
+ amount?: number
18
31
  messageBoxUrl?: string
19
32
  }
20
33
 
@@ -22,16 +35,29 @@ export interface PeerPayValidationResult {
22
35
  isPeerPay: boolean
23
36
  identityKey?: string
24
37
  sats?: number
38
+ asset?: string
39
+ amount?: number
25
40
  /** Present only when the link carried a usable https `url` extension. */
26
41
  messageBoxUrl?: string
27
42
  errors: {
28
43
  identityKey?: string
29
44
  sats?: string
45
+ asset?: string
46
+ amount?: string
30
47
  }
31
48
  }
32
49
 
50
+ /** Any error at all — the one test every consumer of a validation result makes. */
51
+ export function peerPayHasErrors(result: PeerPayValidationResult): boolean {
52
+ return Object.values(result.errors).some(Boolean)
53
+ }
54
+
33
55
  const PEERPAY_SCHEME = 'peerpay:'
34
56
  const COMPRESSED_PUBLIC_KEY_REGEX = /^0[23][0-9a-fA-F]{64}$/
57
+ /** A genesis outpoint: 32-byte txid in hex, a dot, a decimal output index. */
58
+ const ASSET_OUTPOINT_REGEX = /^[0-9a-fA-F]{64}\.(0|[1-9][0-9]*)$/
59
+ /** A whole non-negative figure with no sign, point or leading zero. */
60
+ const WHOLE_FIGURE_REGEX = /^(0|[1-9][0-9]*)$/
35
61
  /**
36
62
  * https, a host, then an optional path/query/fragment with no whitespace. The
37
63
  * authority chunk excludes `@` and `\` so a `mb.trusted.example@evil.example`
@@ -41,10 +67,12 @@ const MESSAGE_BOX_URL_REGEX = /^https:\/\/[^\s/?#@\\]+(?:[/?#]\S*)?$/i
41
67
 
42
68
  export function parsePeerPayURI(uri: string): PeerPayParams | null {
43
69
  const result = validatePeerPayURI(uri)
44
- if (!result.isPeerPay || !result.identityKey || result.errors.identityKey || result.errors.sats) return null
70
+ if (!result.isPeerPay || !result.identityKey || peerPayHasErrors(result)) return null
45
71
  return {
46
72
  identityKey: result.identityKey,
47
- sats: result.sats,
73
+ ...(result.sats !== undefined ? { sats: result.sats } : {}),
74
+ ...(result.asset !== undefined ? { asset: result.asset } : {}),
75
+ ...(result.amount !== undefined ? { amount: result.amount } : {}),
48
76
  ...(result.messageBoxUrl ? { messageBoxUrl: result.messageBoxUrl } : {})
49
77
  }
50
78
  }
@@ -70,36 +98,61 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
70
98
  }
71
99
 
72
100
  let sats: number | undefined
101
+ let asset: string | undefined
102
+ let amount: number | undefined
73
103
  let messageBoxUrl: string | undefined
74
104
  if (queryPart) {
75
105
  const params = new URLSearchParams(queryPart)
76
106
  if (params.has('sats')) {
77
- const satsStr = params.get('sats') ?? ''
78
- if (/^(0|[1-9][0-9]*)$/.test(satsStr)) {
79
- const parsed = Number(satsStr)
80
- if (Number.isSafeInteger(parsed)) {
81
- if (parsed > 0) sats = parsed
82
- } else {
83
- errors.sats = 'PeerPay link contains an invalid sats amount'
84
- }
85
- } else {
86
- errors.sats = 'PeerPay link contains an invalid sats amount'
87
- }
107
+ const figure = wholeFigure(params.get('sats') ?? '')
108
+ if (figure === null) errors.sats = 'PeerPay link contains an invalid sats amount'
109
+ else if (figure > 0) sats = figure
110
+ }
111
+ if (params.has('asset')) {
112
+ const raw = (params.get('asset') ?? '').trim()
113
+ if (ASSET_OUTPOINT_REGEX.test(raw)) asset = raw.toLowerCase()
114
+ else errors.asset = 'PeerPay link names an invalid asset'
115
+ }
116
+ if (params.has('amount')) {
117
+ const figure = wholeFigure(params.get('amount') ?? '')
118
+ if (figure === null) errors.amount = 'PeerPay link contains an invalid amount'
119
+ else if (!params.has('asset')) errors.amount = 'PeerPay link names an amount without an asset'
120
+ else if (figure > 0) amount = figure
121
+ }
122
+ // Two selectors for two different monies: refused, never read as either.
123
+ if (params.has('sats') && (params.has('asset') || params.has('amount'))) {
124
+ errors.sats = 'PeerPay link mixes sats with a token request'
88
125
  }
89
126
  const url = (params.get('url') ?? '').trim().replace(/\/+$/, '')
90
127
  if (url && MESSAGE_BOX_URL_REGEX.test(url)) messageBoxUrl = url
91
128
  }
92
129
 
93
- return { isPeerPay: true, identityKey, sats, ...(messageBoxUrl ? { messageBoxUrl } : {}), errors }
130
+ return {
131
+ isPeerPay: true,
132
+ identityKey,
133
+ sats,
134
+ ...(asset !== undefined ? { asset } : {}),
135
+ ...(amount !== undefined ? { amount } : {}),
136
+ ...(messageBoxUrl ? { messageBoxUrl } : {}),
137
+ errors
138
+ }
94
139
  }
95
140
 
96
141
  /** The human-readable problem with a peerpay link, or null when there is none. */
97
142
  export function peerPayValidationMessage(result: PeerPayValidationResult | null): string | null {
98
143
  if (!result || !result.isPeerPay) return null
99
- const messages = [result.errors.identityKey, result.errors.sats].filter(Boolean)
144
+ const { identityKey, sats, asset, amount } = result.errors
145
+ const messages = [identityKey, sats, asset, amount].filter(Boolean)
100
146
  return messages.length ? messages.join('. ') : null
101
147
  }
102
148
 
149
+ /** A whole safe integer from a query value, or null for anything else. */
150
+ function wholeFigure(text: string): number | null {
151
+ if (!WHOLE_FIGURE_REGEX.test(text)) return null
152
+ const parsed = Number(text)
153
+ return Number.isSafeInteger(parsed) ? parsed : null
154
+ }
155
+
103
156
  /**
104
157
  * A 33-byte compressed secp256k1 key in hex, either case, on the curve. Round-trips through
105
158
  * PublicKey because the SDK reduces an out-of-range x mod p instead of throwing — parse success
@@ -27,6 +27,46 @@ import { isValidBsvAddress } from './index'
27
27
 
28
28
  export const BRC29_PROTOCOL_ID: WalletProtocol = [2, '3241645161d8']
29
29
 
30
+ /** Whether the address rail can carry a particular payment, and why not when it cannot. */
31
+ export type AddressRailAvailability = { kind: 'available' } | { kind: 'unavailable'; reason: string }
32
+
33
+ /**
34
+ * D4: the address rail cannot carry a Mandala token, ever.
35
+ *
36
+ * Not a policy and not a UI opinion — a protocol fact. A token output's owner
37
+ * key is ECDH-derived against the recipient's IDENTITY key
38
+ * (`MandalaToken.lockBRC29`), and the issuer's overlay refuses a transaction
39
+ * carrying an FT output whose owner it cannot name from a linkage. A base58
40
+ * address names a hash, not an identity, so there is nothing to derive against
41
+ * and nothing to reveal — the transaction would be refused if it were ever
42
+ * built, and the money would be locked to a script no one can spend if it
43
+ * were not.
44
+ *
45
+ * The reason text comes from the runtime (`recipientRefusal`, which is the
46
+ * lib's own `guardTokenRecipient`) rather than from a string here, so the
47
+ * wallet and the lib cannot come to say two different things about the same
48
+ * refusal. A caller with no runtime still gets a correct refusal, just a
49
+ * shorter one.
50
+ */
51
+ export function addressRailAvailability(args: {
52
+ address: string
53
+ /** Set when the payment is denominated in a token rather than in satoshis. */
54
+ assetId?: string
55
+ /** `MandalaRuntime.recipientRefusal`. */
56
+ recipientRefusal?: (recipient: string) => string | null
57
+ }): AddressRailAvailability {
58
+ if (args.assetId === undefined || args.assetId === '') {
59
+ return isValidBsvAddress(args.address) ? { kind: 'available' } : { kind: 'unavailable', reason: 'Invalid BSV address' }
60
+ }
61
+ const reason = args.recipientRefusal?.(args.address)
62
+ return {
63
+ kind: 'unavailable',
64
+ reason:
65
+ reason ??
66
+ 'Mandala tokens can only be sent to an identity key, not to an address — the token output is derived against the recipient identity and the overlay refuses anything else'
67
+ }
68
+ }
69
+
30
70
  export const LEGACY_DERIVATION_SUFFIX = Utils.toBase64(Utils.toArray('legacy', 'utf8'))
31
71
 
32
72
  /**
@@ -339,8 +379,15 @@ export async function sendToAddress(args: {
339
379
  adminOriginator: string
340
380
  address: string
341
381
  satoshis: number
382
+ /**
383
+ * The sender's own note for this outbound send. There is no counterparty
384
+ * channel on this rail — an address names no one to notify — so this is
385
+ * purely the payer's own record: it replaces the abbreviated-address
386
+ * description in their own activity list, nothing more.
387
+ */
388
+ note?: string
342
389
  }): Promise<{ paidSatoshis: number }> {
343
- const { wallet, adminOriginator, address, satoshis } = args
390
+ const { wallet, adminOriginator, address, satoshis, note } = args
344
391
  const sats = Math.round(Number(satoshis))
345
392
  if (!Number.isFinite(sats) || sats <= 0) throw new Error('Invalid amount')
346
393
  if (!isValidBsvAddress(address)) throw new Error('Invalid BSV address')
@@ -352,8 +399,9 @@ export async function sendToAddress(args: {
352
399
  const result = (await wallet.createAction(
353
400
  {
354
401
  // The recipient's address is the description so the activity list has a
355
- // name for the row without a lookup; the to: label is what lets it draw a face.
356
- description: abbreviateKey(address),
402
+ // name for the row without a lookup; the to: label is what lets it draw
403
+ // a face. A sender's own note overrides it, same as the other rails.
404
+ description: note?.trim() || abbreviateKey(address),
357
405
  outputs: [{ lockingScript, satoshis: sats, outputDescription: 'BSV for recipient address' }],
358
406
  labels: ['legacy', 'outbound', addressLabel(TO_ADDRESS_LABEL_PREFIX, address)],
359
407
  ...(isSendMax ? { options: { randomizeOutputs: false } } : {})