@bsv/expo-wallet-toolbox 0.26.0 → 0.28.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.
@@ -0,0 +1,542 @@
1
+ /**
2
+ * The paymail rail: pay a legacy paymail (HandCash and similar) with BSV.
3
+ *
4
+ * Same shape as `sendViaHandle`: mint with noSend, write the outbox row, hand
5
+ * the receiver the transaction, then broadcast with sendWith. The receiver gets
6
+ * plain BEEF (HandCash refuses AtomicBEEF with a 503).
7
+ *
8
+ * A receiver that answers with an error may still hold the payment (HandCash
9
+ * sends a malformed-transaction refusal as 503), so nothing is aborted until
10
+ * the network has been asked twice and has not seen the txid. Arcade is never
11
+ * asked: it does not know transactions it did not broadcast.
12
+ */
13
+ import { Transaction } from '@bsv/sdk'
14
+ import type { LegacyPaymailClient, PostBeefResult } from '../paymail/client'
15
+ import {
16
+ NETWORK_CALL_DEADLINE_MS,
17
+ networkKnowsTxid,
18
+ withDeadline,
19
+ type NetworkVerdict,
20
+ type StatusFn
21
+ } from '../paymail/networkCheck'
22
+ import {
23
+ markOutboxSent,
24
+ removeOutboxEntry,
25
+ savePaymailOutboxEntry,
26
+ updateOutboxEntry,
27
+ getOutboxEntries,
28
+ type PaymailOutboxEntry
29
+ } from '../../peerpay/outbox'
30
+ import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
31
+ import { abortNosendByTxid, broadcastNoSend, findActionByTxid, type HandleRailWallet } from './handle'
32
+
33
+ export const PAYMAIL_LABEL = 'paymail'
34
+
35
+ export function paymailAddressLabel(paymail: string): string {
36
+ return `paymail:${paymail.toLowerCase()}`
37
+ }
38
+
39
+ export type PaymailFailure = 'not_sent' | 'refused' | 'maybe_sent' | 'abort_failed'
40
+
41
+ export class PaymailSendError extends Error {
42
+ constructor(
43
+ readonly kind: PaymailFailure,
44
+ message: string,
45
+ readonly code: string
46
+ ) {
47
+ super(message)
48
+ this.name = 'PaymailSendError'
49
+ }
50
+ }
51
+
52
+ export interface PaymailRailWallet extends Pick<HandleRailWallet, 'createAction' | 'listActions' | 'abortAction'> {}
53
+
54
+ export interface PaymailRailDeps {
55
+ wallet: PaymailRailWallet
56
+ adminOriginator: string
57
+ storage: {
58
+ getKeyValue(key: string): Promise<string | undefined>
59
+ setKeyValue(key: string, value: string): Promise<void>
60
+ }
61
+ client: LegacyPaymailClient
62
+ getStatusForTxids: StatusFn
63
+ /** Wait between the two network checks. Default 4000 ms. Tests pass 0. */
64
+ recheckDelayMs?: number
65
+ sleep?: (ms: number) => Promise<void>
66
+ }
67
+
68
+ export interface PaymailSendResult {
69
+ outboxId: string
70
+ txid: string
71
+ satoshis: number
72
+ broadcastPending: boolean
73
+ }
74
+
75
+ const DEFAULT_RECHECK_DELAY_MS = 4000
76
+ /** Largest amount a wallet can hold. Above this is the send-max sentinel. */
77
+ const MAX_SATOSHIS = 2_099_999_999_999_998
78
+
79
+ const defaultSleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
80
+
81
+ const inFlight = new Set<string>()
82
+
83
+ /** Run `work` only if no other flow holds `txid`. Returns undefined at once when it is held. */
84
+ export async function withTxidLock<T>(txid: string, work: () => Promise<T>): Promise<T | undefined> {
85
+ if (inFlight.has(txid)) return undefined
86
+ inFlight.add(txid)
87
+ try {
88
+ return await work()
89
+ } finally {
90
+ inFlight.delete(txid)
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Two network checks with a delay between them. 'known' if either says known,
96
+ * 'error' if either errors, else 'unknown'. A first error returns at once, so a
97
+ * hung status service costs one deadline, not two.
98
+ */
99
+ export async function confirmUnknown(
100
+ deps: Pick<PaymailRailDeps, 'getStatusForTxids' | 'recheckDelayMs' | 'sleep'>,
101
+ txid: string
102
+ ): Promise<NetworkVerdict> {
103
+ const first = await networkKnowsTxid(deps.getStatusForTxids, txid)
104
+ if (first !== 'unknown') return first
105
+ await (deps.sleep ?? defaultSleep)(deps.recheckDelayMs ?? DEFAULT_RECHECK_DELAY_MS)
106
+ return networkKnowsTxid(deps.getStatusForTxids, txid)
107
+ }
108
+
109
+ function errMessage(e: unknown): string {
110
+ return e instanceof Error ? e.message : String(e)
111
+ }
112
+
113
+ /**
114
+ * Record a failed attempt and make sure the drain looks at the row again.
115
+ * Best effort: the caller is about to throw a typed error, and a storage fault
116
+ * here must not replace it with a plain one.
117
+ */
118
+ async function noteAttempt(deps: PaymailRailDeps, entry: PaymailOutboxEntry, lastError: string, extra = {}) {
119
+ try {
120
+ await updateOutboxEntry(deps.storage, entry.id, {
121
+ lastAttemptAt: new Date().toISOString(),
122
+ lastError,
123
+ ...extra
124
+ })
125
+ } catch (e) {
126
+ console.warn('[paymail] could not record the attempt:', errMessage(e))
127
+ }
128
+ TaskDrainOutbox.noteEnqueued()
129
+ }
130
+
131
+ /**
132
+ * Whether a noSend action for `txid` is still live (it can still be broadcast
133
+ * or aborted). A search that cannot prove absence (the label has more actions
134
+ * than the pages searched) answers true: unknown is treated as live.
135
+ */
136
+ async function nosendActionIsLive(
137
+ wallet: Pick<PaymailRailWallet, 'listActions'>,
138
+ adminOriginator: string,
139
+ txid: string
140
+ ): Promise<boolean> {
141
+ const { match, complete } = await findActionByTxid(wallet, adminOriginator, txid, PAYMAIL_LABEL)
142
+ if (!complete) return true
143
+ return match != null && match.status !== 'failed'
144
+ }
145
+
146
+ /**
147
+ * Free the inputs held by the noSend action for `txid`, inside the deadline.
148
+ * True when the abort landed or the action is already gone. An abort that
149
+ * times out or throws may still land late, so the action is looked up again
150
+ * before the funds are called stuck. False only when it is still live.
151
+ */
152
+ async function releaseNosend(
153
+ deps: Pick<PaymailRailDeps, 'wallet' | 'adminOriginator'>,
154
+ txid: string
155
+ ): Promise<boolean> {
156
+ try {
157
+ if (
158
+ await withDeadline(
159
+ abortNosendByTxid(deps.wallet, deps.adminOriginator, txid, PAYMAIL_LABEL),
160
+ NETWORK_CALL_DEADLINE_MS
161
+ )
162
+ ) {
163
+ return true
164
+ }
165
+ } catch {
166
+ // fall through to the look-up
167
+ }
168
+ try {
169
+ return !(await withDeadline(nosendActionIsLive(deps.wallet, deps.adminOriginator, txid), NETWORK_CALL_DEADLINE_MS))
170
+ } catch {
171
+ return false
172
+ }
173
+ }
174
+
175
+ /**
176
+ * The receiver has the payment (or the network does). Broadcast ours. If the
177
+ * broadcast is not confirmed but the network already knows the txid, the
178
+ * payment is complete: mark the row sent so the drain does not loop on it.
179
+ */
180
+ async function broadcastOrSettle(
181
+ deps: PaymailRailDeps,
182
+ entry: PaymailOutboxEntry
183
+ ): Promise<{ broadcastPending: boolean }> {
184
+ try {
185
+ await broadcastNoSend(deps.wallet, deps.adminOriginator, entry.txid)
186
+ await markOutboxSent(deps.storage, entry.id)
187
+ return { broadcastPending: false }
188
+ } catch (e) {
189
+ const verdict = await networkKnowsTxid(deps.getStatusForTxids, entry.txid)
190
+ if (verdict === 'known') {
191
+ await markOutboxSent(deps.storage, entry.id)
192
+ await updateOutboxEntry(deps.storage, entry.id, { lastError: 'broadcast_not_confirmed' })
193
+ return { broadcastPending: false }
194
+ }
195
+ await noteAttempt(deps, entry, errMessage(e))
196
+ return { broadcastPending: true }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Act on the receiver's answer. Shared by send, retry and cancel. `allowAbort`
202
+ * is true only for the first send; a retry never frees the inputs.
203
+ */
204
+ export async function settlePaymailPost(
205
+ deps: PaymailRailDeps,
206
+ entry: PaymailOutboxEntry,
207
+ post: PostBeefResult,
208
+ opts: { allowAbort?: boolean } = {}
209
+ ): Promise<{ broadcastPending: boolean }> {
210
+ const allowAbort = opts.allowAbort ?? true
211
+
212
+ if (post.kind === 'accepted') {
213
+ await updateOutboxEntry(deps.storage, entry.id, {
214
+ delivered: true,
215
+ delivering: false,
216
+ receiverTxid: post.txid,
217
+ receiverNote: post.note
218
+ })
219
+ if (post.txid.toLowerCase() !== entry.txid.toLowerCase()) {
220
+ console.warn('[paymail] receiver txid differs from ours', { ours: entry.txid, theirs: post.txid })
221
+ }
222
+ return broadcastOrSettle(deps, entry)
223
+ }
224
+
225
+ if (post.kind === 'network') {
226
+ const code = post.message === 'unreadable_receipt' ? 'unreadable_receipt' : 'no_answer'
227
+ await noteAttempt(deps, entry, post.message)
228
+ throw new PaymailSendError('maybe_sent', 'The receiver did not answer. The payment may have gone through.', code)
229
+ }
230
+
231
+ // An HTTP answer that is not 2xx: a probable refusal, but a 5xx is not proof.
232
+ const verdict = await confirmUnknown(deps, entry.txid)
233
+ if (verdict === 'error') {
234
+ await noteAttempt(deps, entry, 'status_unavailable')
235
+ throw new PaymailSendError(
236
+ 'maybe_sent',
237
+ 'Could not check the network. The payment may have gone through.',
238
+ 'status_unavailable'
239
+ )
240
+ }
241
+ if (verdict === 'known') {
242
+ await updateOutboxEntry(deps.storage, entry.id, { delivered: true, delivering: false })
243
+ return broadcastOrSettle(deps, entry)
244
+ }
245
+
246
+ if (!allowAbort) {
247
+ await updateOutboxEntry(deps.storage, entry.id, {
248
+ refused: true,
249
+ lastAttemptAt: new Date().toISOString(),
250
+ lastError: 'recipient_refused'
251
+ })
252
+ throw new PaymailSendError(
253
+ 'maybe_sent',
254
+ 'The receiver refused the payment. Cancel it to free the funds.',
255
+ 'refused_unconfirmed'
256
+ )
257
+ }
258
+
259
+ const aborted = await releaseNosend(deps, entry.txid)
260
+ if (aborted) {
261
+ await removeOutboxEntry(deps.storage, entry.id)
262
+ throw new PaymailSendError('refused', post.message, 'recipient_refused')
263
+ }
264
+ // The abort may still land late. Mark the row refused so the drain never posts
265
+ // it again over inputs that may be freed; only a Cancel resolves it.
266
+ await noteAttempt(deps, entry, 'abort_failed', { refused: true })
267
+ throw new PaymailSendError(
268
+ 'abort_failed',
269
+ 'The receiver refused the payment, but the funds could not be freed.',
270
+ 'abort_failed'
271
+ )
272
+ }
273
+
274
+ export async function sendViaPaymail(
275
+ args: PaymailRailDeps & { paymail: string; satoshis: number; note?: string }
276
+ ): Promise<PaymailSendResult> {
277
+ const { wallet, adminOriginator, storage, client, paymail, note } = args
278
+
279
+ const sats = Math.round(Number(args.satoshis))
280
+ if (!Number.isFinite(sats) || sats <= 0) {
281
+ throw new PaymailSendError('not_sent', 'Enter an amount above zero.', 'invalid_amount')
282
+ }
283
+ if (sats > MAX_SATOSHIS) {
284
+ throw new PaymailSendError('not_sent', 'Send all is not supported for this address.', 'send_all_unsupported')
285
+ }
286
+
287
+ const dest = await client.getP2pDestination(paymail, sats)
288
+ if (dest.kind === 'failed') throw new PaymailSendError('not_sent', dest.message, dest.reason)
289
+ const destination = dest.destination
290
+
291
+ let created: Awaited<ReturnType<PaymailRailWallet['createAction']>>
292
+ try {
293
+ created = await wallet.createAction(
294
+ {
295
+ description: (note?.trim() || paymail).slice(0, 500).padEnd(5),
296
+ labels: [PAYMAIL_LABEL, paymailAddressLabel(paymail)],
297
+ outputs: destination.outputs.map(o => ({
298
+ lockingScript: o.script,
299
+ satoshis: o.satoshis,
300
+ outputDescription: 'Paymail payment'
301
+ })),
302
+ options: { noSend: true, randomizeOutputs: false }
303
+ },
304
+ adminOriginator
305
+ )
306
+ } catch (e) {
307
+ throw new PaymailSendError('not_sent', errMessage(e), 'mint_failed')
308
+ }
309
+ if (!created?.tx || !created.txid) {
310
+ throw new PaymailSendError('not_sent', 'The wallet did not return a transaction.', 'mint_failed')
311
+ }
312
+ const txid = created.txid
313
+
314
+ const abortQuietly = async () => {
315
+ try {
316
+ await abortNosendByTxid(wallet, adminOriginator, txid, PAYMAIL_LABEL)
317
+ } catch (abortErr) {
318
+ console.warn('[paymail] abort of the unsent payment failed:', errMessage(abortErr))
319
+ }
320
+ }
321
+
322
+ const createdTx = created.tx
323
+ const settled = await withTxidLock(txid, async () => {
324
+ let beefHex: string
325
+ try {
326
+ const tx = Transaction.fromAtomicBEEF(createdTx)
327
+ const matches =
328
+ tx.id('hex') === txid &&
329
+ destination.outputs.every((o, i) => {
330
+ const out = tx.outputs[i]
331
+ return (
332
+ out != null &&
333
+ out.satoshis === o.satoshis &&
334
+ out.lockingScript.toHex().toLowerCase() === o.script.toLowerCase()
335
+ )
336
+ })
337
+ if (!matches) {
338
+ await abortQuietly()
339
+ throw new PaymailSendError('not_sent', 'The wallet built a different payment than asked.', 'mint_failed')
340
+ }
341
+ beefHex = tx.toHexBEEF()
342
+ } catch (e) {
343
+ if (e instanceof PaymailSendError) throw e
344
+ await abortQuietly()
345
+ throw new PaymailSendError('not_sent', 'The wallet returned a transaction that could not be read.', 'mint_failed')
346
+ }
347
+ const total = destination.outputs.reduce((sum, o) => sum + o.satoshis, 0)
348
+
349
+ let outboxId: string
350
+ try {
351
+ outboxId = await savePaymailOutboxEntry(storage, {
352
+ paymail,
353
+ endpoint: destination.beefEndpoint,
354
+ paymailReference: destination.reference,
355
+ beefHex,
356
+ satoshis: total,
357
+ txid,
358
+ note: note?.trim() || undefined
359
+ })
360
+ } catch (e) {
361
+ await abortQuietly()
362
+ throw e
363
+ }
364
+
365
+ // From here the row exists and the receiver may hold the payment. Whatever
366
+ // fails must reach the caller as a typed error, so the UI blocks a second
367
+ // payment instead of reporting "not sent".
368
+ try {
369
+ await updateOutboxEntry(storage, outboxId, { delivering: true })
370
+ const post = await client.postBeef({
371
+ endpoint: destination.beefEndpoint,
372
+ beefHex,
373
+ reference: destination.reference
374
+ })
375
+ const entry = (await getOutboxEntries(storage)).find(e => e.id === outboxId) as PaymailOutboxEntry | undefined
376
+ if (!entry) {
377
+ // The receiver may hold the payment but the row is gone: nothing to settle against.
378
+ throw new PaymailSendError(
379
+ 'maybe_sent',
380
+ 'The payment record is missing. The payment may have gone through.',
381
+ 'outbox_missing'
382
+ )
383
+ }
384
+ const result = await settlePaymailPost(args, entry, post, { allowAbort: true })
385
+ return { outboxId, satoshis: total, broadcastPending: result.broadcastPending }
386
+ } catch (e) {
387
+ if (e instanceof PaymailSendError) throw e
388
+ TaskDrainOutbox.noteEnqueued()
389
+ throw new PaymailSendError(
390
+ 'maybe_sent',
391
+ 'The wallet could not save the payment state. The payment may have gone through.',
392
+ 'storage_error'
393
+ )
394
+ }
395
+ })
396
+ if (!settled) {
397
+ throw new PaymailSendError('maybe_sent', 'This payment is already being handled.', 'in_progress')
398
+ }
399
+ return { outboxId: settled.outboxId, txid, satoshis: settled.satoshis, broadcastPending: settled.broadcastPending }
400
+ }
401
+
402
+ async function findPaymailRow(
403
+ storage: PaymailRailDeps['storage'],
404
+ id: string
405
+ ): Promise<PaymailOutboxEntry | undefined> {
406
+ const found = (await getOutboxEntries(storage)).find(e => e.id === id)
407
+ return found && found.kind === 'paymail' ? found : undefined
408
+ }
409
+
410
+ /**
411
+ * Retry a stuck paymail row: post the same BEEF again if the receiver never
412
+ * accepted it, then broadcast. It never aborts. A refusal sets `refused` on the
413
+ * row and only an explicit Cancel can free the funds.
414
+ */
415
+ export async function retryPaymailDelivery(args: PaymailRailDeps & { entry: PaymailOutboxEntry }): Promise<void> {
416
+ const { storage, client, entry } = args
417
+ if (entry.status !== 'unsent' || entry.refused === true) return
418
+
419
+ // XR-048: the stored txid is not authenticated. Re-derive it from the BEEF.
420
+ let ownTxid: string | undefined
421
+ try {
422
+ ownTxid = Transaction.fromHexBEEF(entry.beefHex).id('hex')
423
+ } catch {
424
+ ownTxid = undefined
425
+ }
426
+ if (!ownTxid || ownTxid.toLowerCase() !== entry.txid.toLowerCase()) {
427
+ throw new Error('outbox_txid_mismatch')
428
+ }
429
+
430
+ // XR-052: a Cancel can remove the row between awaits. Re-read before each side effect.
431
+ const stillPending = async (): Promise<PaymailOutboxEntry | undefined> => {
432
+ const row = await findPaymailRow(storage, entry.id)
433
+ return row && row.status === 'unsent' && row.refused !== true ? row : undefined
434
+ }
435
+
436
+ await withTxidLock(entry.txid, async () => {
437
+ if (!(await stillPending())) return
438
+ await updateOutboxEntry(storage, entry.id, { lastAttemptAt: new Date().toISOString() })
439
+ try {
440
+ if (entry.delivered === true) {
441
+ const row = await stillPending()
442
+ if (!row) return
443
+ const result = await broadcastOrSettle(args, row)
444
+ if (result.broadcastPending) throw new Error('broadcast_not_confirmed')
445
+ return
446
+ }
447
+ if (!(await stillPending())) return
448
+ await updateOutboxEntry(storage, entry.id, { delivering: true })
449
+ const post = await client.postBeef({
450
+ endpoint: entry.endpoint,
451
+ beefHex: entry.beefHex,
452
+ reference: entry.paymailReference
453
+ })
454
+ const row = await stillPending()
455
+ if (!row) return
456
+ const result = await settlePaymailPost(args, row, post, { allowAbort: false })
457
+ if (result.broadcastPending) throw new Error('broadcast_not_confirmed')
458
+ } catch (e) {
459
+ if (!(e instanceof PaymailSendError)) {
460
+ const row = await findPaymailRow(storage, entry.id)
461
+ if (row) await updateOutboxEntry(storage, entry.id, { lastError: errMessage(e) })
462
+ }
463
+ throw e
464
+ }
465
+ })
466
+ }
467
+
468
+ const statusUnavailable = () =>
469
+ new PaymailSendError(
470
+ 'maybe_sent',
471
+ 'Could not check the network. The payment may have gone through.',
472
+ 'status_unavailable'
473
+ )
474
+
475
+ const abortFailed = () =>
476
+ new PaymailSendError('abort_failed', 'The funds could not be freed. Try again later.', 'abort_failed')
477
+
478
+ /**
479
+ * Cancel a paymail payment on the user's say. The network answer decides: a
480
+ * payment the network knows is finished, not cancelled.
481
+ */
482
+ export async function cancelPaymailPayment(
483
+ args: PaymailRailDeps & { entry: PaymailOutboxEntry }
484
+ ): Promise<{ aborted: boolean; sent: boolean }> {
485
+ const { storage, entry } = args
486
+ const stored = await findPaymailRow(storage, entry.id)
487
+ if (!stored) return { aborted: false, sent: false }
488
+ if (stored.delivered === true) {
489
+ throw new PaymailSendError(
490
+ 'maybe_sent',
491
+ 'The receiver has this payment. It cannot be cancelled. Finish it instead.',
492
+ 'already_delivered'
493
+ )
494
+ }
495
+ const result = await withTxidLock(stored.txid, async () => {
496
+ const maybePosted = stored.delivering === true || stored.lastAttemptAt != null
497
+ const verdict = maybePosted
498
+ ? await confirmUnknown(args, stored.txid)
499
+ : await networkKnowsTxid(args.getStatusForTxids, stored.txid)
500
+ if (verdict === 'error') throw statusUnavailable()
501
+ if (verdict === 'known') {
502
+ const settled = await broadcastOrSettle(args, stored)
503
+ // The network already knows this txid, so the payment is out of our hands.
504
+ // Mark the row sent even when our own broadcast is still pending: leaving
505
+ // it unsent would let the drain re-POST a payment that cannot be cancelled.
506
+ if (settled.broadcastPending) await markOutboxSent(storage, stored.id)
507
+ return { aborted: false, sent: true }
508
+ }
509
+ if (await releaseNosend(args, stored.txid)) {
510
+ await removeOutboxEntry(storage, stored.id)
511
+ return { aborted: true, sent: false }
512
+ }
513
+ await noteAttempt(args, stored, 'abort_failed')
514
+ throw abortFailed()
515
+ })
516
+ if (!result) throw new PaymailSendError('maybe_sent', 'This payment is already being handled.', 'in_progress')
517
+ return result
518
+ }
519
+
520
+ /**
521
+ * A noSend `paymail` action with no outbox row (a crash between the mint and
522
+ * the row save, or a restore: key_value_store is not in the backup). The
523
+ * network decides, as in a cancel.
524
+ */
525
+ export async function resolveOrphanPaymailAction(
526
+ args: Pick<PaymailRailDeps, 'wallet' | 'adminOriginator' | 'getStatusForTxids' | 'recheckDelayMs' | 'sleep'> & {
527
+ txid: string
528
+ }
529
+ ): Promise<{ aborted: boolean; sent: boolean }> {
530
+ const result = await withTxidLock(args.txid, async () => {
531
+ const verdict = await confirmUnknown(args, args.txid)
532
+ if (verdict === 'error') throw statusUnavailable()
533
+ if (verdict === 'known') {
534
+ await broadcastNoSend(args.wallet, args.adminOriginator, args.txid)
535
+ return { aborted: false, sent: true }
536
+ }
537
+ if (await releaseNosend(args, args.txid)) return { aborted: true, sent: false }
538
+ throw abortFailed()
539
+ })
540
+ if (!result) throw new PaymailSendError('maybe_sent', 'This payment is already being handled.', 'in_progress')
541
+ return result
542
+ }
@@ -1,7 +1,7 @@
1
1
  import { Beef } from '@bsv/sdk'
2
2
  import { PUBKEY_LABEL } from '../pay/counterparty'
3
3
  import { ackControlMessages, isDuplicateMessageError, listControlMessages, parseControlMessage } from './control'
4
- import { getOutboxEntries, getOutboxEntriesStrict, type OutboxEntry } from './outbox'
4
+ import { getOutboxEntries, getOutboxEntriesStrict, isPeerPayEntry, type PeerPayOutboxEntry } from './outbox'
5
5
  import { instructionsFromOutput, rebuildPeerPayToken } from './rebuildToken'
6
6
 
7
7
  /** The message box outbound payments are delivered into. Same name as handle.ts. */
@@ -204,12 +204,12 @@ function recipientFromLabels(labels: string[] | undefined): string | undefined {
204
204
  return labels?.find(l => PUBKEY_LABEL.test(l))
205
205
  }
206
206
 
207
- function outboxTxid(entry: OutboxEntry): string | undefined {
207
+ function outboxTxid(entry: PeerPayOutboxEntry): string | undefined {
208
208
  if (typeof entry.txid === 'string' && entry.txid.length > 0) return entry.txid
209
209
  return outboxTokenTxid(entry)
210
210
  }
211
211
 
212
- function outboxTokenTxid(entry: OutboxEntry): string | undefined {
212
+ function outboxTokenTxid(entry: PeerPayOutboxEntry): string | undefined {
213
213
  try {
214
214
  const txid = Beef.fromBinary(Array.from(entry.token.transaction)).atomicTxid
215
215
  return typeof txid === 'string' && txid.length > 0 ? txid : undefined
@@ -218,7 +218,7 @@ function outboxTokenTxid(entry: OutboxEntry): string | undefined {
218
218
  }
219
219
  }
220
220
 
221
- function actionFromOutbox(entry: OutboxEntry, txid: string): PeerPayActionLike {
221
+ function actionFromOutbox(entry: PeerPayOutboxEntry, txid: string): PeerPayActionLike {
222
222
  return {
223
223
  txid,
224
224
  labels: ['peerpay'],
@@ -285,7 +285,7 @@ async function resolveResendRecipient(
285
285
  txid: string,
286
286
  listPeerPayAction?: (txid: string) => Promise<PeerPayActionLike | undefined>
287
287
  ): Promise<string | undefined> {
288
- const entries = await getOutboxEntries(storage)
288
+ const entries = (await getOutboxEntries(storage)).filter(isPeerPayEntry)
289
289
  const entry = entries.find(e => outboxTxid(e) === txid)
290
290
  if (entry?.recipient) return entry.recipient
291
291
  const listed = listPeerPayAction ? await listPeerPayAction(txid) : undefined
@@ -403,7 +403,7 @@ async function rebuildAndDeliver(args: {
403
403
  decryptMetadata?: (value: string) => Promise<string>
404
404
  }): Promise<ResendOutcome> {
405
405
  // An unreadable queue cannot establish that this transaction is not held.
406
- const entries = await getOutboxEntriesStrict(args.storage)
406
+ const entries = (await getOutboxEntriesStrict(args.storage)).filter(isPeerPayEntry)
407
407
  // Resending hands the signed payment to its recipient just like a retry.
408
408
  // A held import must pass the reviewed release flow first; neither another
409
409
  // history row for this txid nor the action-metadata fallback may bypass it.