@bsv/expo-wallet-toolbox 0.17.0 → 0.19.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,287 @@
1
+ /**
2
+ * The direct rail: pay an identity key over a live link (`@bsv/webrtpay`), and finish through
3
+ * the message box when the link cannot. The live half of the handle rail: the same token, the
4
+ * same outbox row, the same drain.
5
+ *
6
+ * One payment is one transaction and one outbox row (`via: 'direct'`). The token is minted by
7
+ * `mintPeerPayToken`, exactly as `sendViaHandle` mints it, so when the link cannot finish a
8
+ * payment the row is an ordinary unsent handle-rail row: `TaskDrainOutbox` delivers the same
9
+ * token to the recipient's message box and broadcasts it, and the recipient's wallet credits it
10
+ * once (its inbox shares the direct-pay seen store; see `core/directpay/receive.ts`).
11
+ *
12
+ * Nine steps, in this order:
13
+ * 1 dial and authenticate the recipient (nothing exists yet)
14
+ * 2 mint the token with noSend 3 check it can be delivered 4 persist it
15
+ * 5 mark it delivering 6 send it over the link and wait for the ack
16
+ * 7 mark it delivered 8 broadcast 9 mark it sent
17
+ *
18
+ * Broadcast after the ack. BSV Desktop broadcasts before it sends over the link. Here the
19
+ * handle rail's order holds (`handle.ts`, `sendViaHandle`: deliver, then broadcast), so a
20
+ * payment that never reached the recipient leaves nothing on chain, and a stop before step 6
21
+ * can still abort the action and free its inputs. The recipient's wallet takes an unbroadcast
22
+ * transaction from the link as it already does from the inbox, where the token arrives before
23
+ * the broadcast too; webrtpay verifies a payment against the derived key, not the network. The
24
+ * price: between the ack and step 8 the recipient holds a transaction the network has not seen,
25
+ * and a broadcast that fails then is retried by the drain from the `delivered` row.
26
+ *
27
+ * What a failure leaves:
28
+ * - Steps 1–5: nothing was sent. A `NotSentError` (from `core/directpay/payFlow`), after the
29
+ * minted action is aborted and its row removed; a dial failure carries why, so `payIdentity`
30
+ * can offer the message box.
31
+ * - Step 6 throws, or the recipient answers `rejected`: the recipient may hold a signed,
32
+ * spendable copy, so the payment can only go forward, never be aborted (SEC2-031, as for an
33
+ * abandoned handle-rail row). The row stays `delivering`; the drain sends the same token to
34
+ * the message box and broadcasts it. Throws {@link DirectDeliveryUnconfirmedError}, which
35
+ * `payIdentity` reads as "may already have been sent".
36
+ * - Steps 7–9 after a good ack: the recipient has it. Returns `broadcast: 'pending'`; the drain
37
+ * broadcasts from the `delivered` row.
38
+ *
39
+ * A wallet with the message box turned off cannot pay live: a link that drops after step 6
40
+ * would leave a payment with no way to finish it.
41
+ *
42
+ * Race, as on the handle rail: a drain that runs while a payment is between steps 4 and 9 sees
43
+ * an unsent row and may deliver it through the message box at the same time. That costs a
44
+ * second delivery of the same token (credited once) and can put the broadcast before the ack;
45
+ * it never makes a second transaction.
46
+ */
47
+ import {
48
+ abortPeerPayNosend,
49
+ broadcastNoSend,
50
+ cancelOutboxPayment,
51
+ mintPeerPayToken,
52
+ NO_MESSAGE_BOX,
53
+ type HandleRailWallet,
54
+ type MintedPeerPayToken
55
+ } from './handle'
56
+ import { markOutboxSent, saveOutboxEntry, updateOutboxEntry } from '../../peerpay/outbox'
57
+ import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
58
+ import { NotSentError } from '../../directpay/payFlow'
59
+ import { dialFailure } from '../../directpay/dialFailure'
60
+ import type { DirectPayClientLike, DirectPaymentAck, DirectPeer, WebRTPayModule } from '../../directpay/webrtpay'
61
+
62
+ interface StorageLike {
63
+ getKeyValue: (key: string) => Promise<string | undefined>
64
+ setKeyValue: (key: string, value: string) => Promise<void>
65
+ }
66
+
67
+ /** How a direct payment ended when the recipient answered. */
68
+ export interface DirectSendResult {
69
+ outboxId: string
70
+ txid: string
71
+ /** What the transaction pays the recipient. */
72
+ satoshis: number
73
+ /** `accepted`: in the recipient's wallet; `received`: kept on their device until it can be. */
74
+ ackStatus: 'accepted' | 'received'
75
+ /** `pending`: the broadcast after the ack failed; the outbox drain retries it. */
76
+ broadcast: 'sent' | 'pending'
77
+ }
78
+
79
+ /**
80
+ * The payment was sent over the link, but the recipient did not confirm it (`no_ack`) or
81
+ * refused it (`rejected`). It may already be theirs, so it is not cancelled: the outbox drain
82
+ * delivers the same transaction through the message box. Never pay it again by hand.
83
+ */
84
+ export class DirectDeliveryUnconfirmedError extends Error {
85
+ constructor(
86
+ message: string,
87
+ readonly outboxId: string,
88
+ readonly why: 'no_ack' | 'rejected',
89
+ readonly reason = ''
90
+ ) {
91
+ super(message)
92
+ this.name = 'DirectDeliveryUnconfirmedError'
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Pays `recipient` over a live link (see the file header for the order and what each failure
98
+ * leaves). `client` is the open wallet's `DirectPayClient`; `signal` cancels the dial, and
99
+ * stops the payment before it is made. `signalingDown` says whether this wallet's own way of
100
+ * reaching others is down (no network, or its relay cannot be reached): a dial nobody answered
101
+ * then says nothing about the recipient, and fails as `unavailable` rather than `offline`.
102
+ */
103
+ export async function sendViaDirect(args: {
104
+ wallet: HandleRailWallet
105
+ adminOriginator: string
106
+ client: Pick<DirectPayClientLike, 'connect' | 'sendPayment'>
107
+ webrtpay: Pick<WebRTPayModule, 'validatePaymentToken' | 'MAX_DIRECT_TRANSACTION_BYTES'>
108
+ storage: StorageLike
109
+ recipient: string
110
+ satoshis: number
111
+ /** This wallet's message box host, where the drain finishes a payment the link could not. */
112
+ messageBoxUrl: string
113
+ /** The recipient's message-box host from a BRC-125 `url` extension, for the drain. */
114
+ recipientHost?: string
115
+ note?: string
116
+ recipientName?: string
117
+ signal?: AbortSignal
118
+ signalingDown?: () => boolean | Promise<boolean>
119
+ }): Promise<DirectSendResult> {
120
+ const { wallet, adminOriginator, client, storage, recipient, messageBoxUrl, recipientHost, signal } = args
121
+ if (!messageBoxUrl || messageBoxUrl === NO_MESSAGE_BOX) {
122
+ throw new NotSentError('A live payment needs a message box to finish through', 'The message box is turned off.')
123
+ }
124
+ const satoshis = Math.round(Number(args.satoshis))
125
+ if (!Number.isFinite(satoshis) || satoshis <= 0) throw new NotSentError('Invalid amount')
126
+
127
+ const peer = await dial(client, recipient, signal, args.signalingDown)
128
+ try {
129
+ // The dial pins the recipient; a different key here would be a bug, not a payee.
130
+ if (peer.peerIdentityKey !== recipient) throw new NotSentError('The connected wallet is not the recipient')
131
+ if (signal?.aborted) throw new NotSentError('Cancelled', '', 'aborted')
132
+
133
+ let minted: MintedPeerPayToken
134
+ try {
135
+ minted = await mintPeerPayToken({ ...args, satoshis })
136
+ } catch (e) {
137
+ // createAction refused (not enough funds, a denied permission): nothing exists.
138
+ throw new NotSentError('The wallet could not make the payment', messageOf(e))
139
+ }
140
+ const { txid, token } = minted
141
+ const note = token.note?.slice(0, 500)
142
+
143
+ const refusal = whyNotDeliverable(args.webrtpay, peer, token, note, signal)
144
+ if (refusal) {
145
+ await abortMinted(wallet, adminOriginator, txid)
146
+ throw refusal
147
+ }
148
+
149
+ let outboxId: string
150
+ try {
151
+ outboxId = await saveOutboxEntry(storage, { recipient, token, messageBoxUrl, txid, recipientHost, via: 'direct' })
152
+ } catch (e) {
153
+ await abortMinted(wallet, adminOriginator, txid)
154
+ throw new NotSentError('The payment could not be saved', messageOf(e))
155
+ }
156
+
157
+ try {
158
+ // Checkpoint before the link round-trip: from here the recipient may hold the token, so
159
+ // cancel must never abort it (see cancelOutboxPayment).
160
+ await updateOutboxEntry(storage, outboxId, { delivering: true })
161
+ } catch (e) {
162
+ try {
163
+ await cancelOutboxPayment({ wallet, adminOriginator, storage, entry: { id: outboxId, txid, recipient } })
164
+ } catch (cancelErr) {
165
+ console.warn('[direct] could not cancel an unsent payment:', messageOf(cancelErr))
166
+ }
167
+ throw new NotSentError('The payment could not be saved', messageOf(e))
168
+ }
169
+
170
+ let ack: DirectPaymentAck
171
+ try {
172
+ ack = await client.sendPayment(peer, token, note ? { note } : undefined)
173
+ } catch (e) {
174
+ await leaveForMessageBox(storage, outboxId, `No answer over the link: ${messageOf(e)}`)
175
+ throw new DirectDeliveryUnconfirmedError(
176
+ "The recipient's wallet did not confirm the payment; it will be delivered through the message box.",
177
+ outboxId,
178
+ 'no_ack'
179
+ )
180
+ }
181
+ if (ack.status === 'rejected') {
182
+ await leaveForMessageBox(storage, outboxId, `Refused over the link: ${ack.reason || 'no reason given'}`)
183
+ throw new DirectDeliveryUnconfirmedError(
184
+ "The recipient's wallet refused the payment; it will be delivered through the message box.",
185
+ outboxId,
186
+ 'rejected',
187
+ ack.reason ?? ''
188
+ )
189
+ }
190
+
191
+ let broadcast: DirectSendResult['broadcast'] = 'sent'
192
+ try {
193
+ await updateOutboxEntry(storage, outboxId, { delivered: true })
194
+ await broadcastNoSend(wallet, adminOriginator, txid)
195
+ await markOutboxSent(storage, outboxId)
196
+ } catch (e) {
197
+ broadcast = 'pending'
198
+ await leaveForMessageBox(storage, outboxId, messageOf(e))
199
+ }
200
+ return { outboxId, txid, satoshis: minted.satoshis, ackStatus: ack.status, broadcast }
201
+ } finally {
202
+ peer.close()
203
+ }
204
+ }
205
+
206
+ /** Any dial failure happens before the payment exists. */
207
+ async function dial(
208
+ client: Pick<DirectPayClientLike, 'connect'>,
209
+ recipient: string,
210
+ signal: AbortSignal | undefined,
211
+ signalingDown: (() => boolean | Promise<boolean>) | undefined
212
+ ): Promise<DirectPeer> {
213
+ try {
214
+ return await client.connect(recipient, signal ? { signal } : undefined)
215
+ } catch (error) {
216
+ // Checked here rather than read from the error's wording (see dialFailure.ts).
217
+ if (signal?.aborted) throw new NotSentError('Dial cancelled', messageOf(error), 'aborted')
218
+ let failure = dialFailure(error)
219
+ if (failure === 'offline' && (await isDown(signalingDown))) failure = 'unavailable'
220
+ // The user sees a short prompt; the log keeps what actually failed.
221
+ const e = error as { code?: unknown; reason?: unknown } | null
222
+ console.warn('[direct] dial failed', { failure, code: e?.code, reason: e?.reason, message: messageOf(error) })
223
+ throw new NotSentError(`The recipient could not be reached directly (${failure})`, messageOf(error), failure)
224
+ }
225
+ }
226
+
227
+ async function isDown(signalingDown: (() => boolean | Promise<boolean>) | undefined): Promise<boolean> {
228
+ try {
229
+ return (await signalingDown?.()) === true
230
+ } catch {
231
+ return false
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Why `token` must not be sent over `peer`, checked as the recipient will check it, or
237
+ * undefined when it may. A closed link fails like a dial whose link did not come up, so the
238
+ * message box can be offered for a fresh payment.
239
+ */
240
+ function whyNotDeliverable(
241
+ webrtpay: Pick<WebRTPayModule, 'validatePaymentToken' | 'MAX_DIRECT_TRANSACTION_BYTES'>,
242
+ peer: DirectPeer,
243
+ token: MintedPeerPayToken['token'],
244
+ note: string | undefined,
245
+ signal: AbortSignal | undefined
246
+ ): NotSentError | undefined {
247
+ if (signal?.aborted) return new NotSentError('Cancelled', '', 'aborted')
248
+ const bytes = token.transaction.length
249
+ if (bytes > webrtpay.MAX_DIRECT_TRANSACTION_BYTES) {
250
+ return new NotSentError(
251
+ 'This payment is too large to deliver directly',
252
+ `${bytes} bytes; at most ${webrtpay.MAX_DIRECT_TRANSACTION_BYTES} can go over the link`
253
+ )
254
+ }
255
+ try {
256
+ webrtpay.validatePaymentToken(token, note)
257
+ } catch (e) {
258
+ return new NotSentError("The recipient's wallet would refuse this payment", messageOf(e))
259
+ }
260
+ if (!peer.isOpen) {
261
+ return new NotSentError("The recipient's wallet closed the connection before the payment was sent", '', 'unknown')
262
+ }
263
+ return undefined
264
+ }
265
+
266
+ /** Frees a minted payment nobody else has seen. Best effort: a failure is logged, not thrown. */
267
+ async function abortMinted(wallet: HandleRailWallet, adminOriginator: string, txid: string): Promise<void> {
268
+ try {
269
+ if (!(await abortPeerPayNosend(wallet, adminOriginator, txid))) {
270
+ console.warn('[direct] the minted payment was not aborted:', txid)
271
+ }
272
+ } catch (e) {
273
+ console.warn('[direct] abortPeerPayNosend failed:', messageOf(e))
274
+ }
275
+ }
276
+
277
+ /** Records why the link did not finish the payment and wakes the outbox drain. Never throws. */
278
+ async function leaveForMessageBox(storage: StorageLike, outboxId: string, why: string): Promise<void> {
279
+ try {
280
+ await updateOutboxEntry(storage, outboxId, { lastAttemptAt: new Date().toISOString(), lastError: why })
281
+ } catch {
282
+ // The row is unsent either way; the drain finds it.
283
+ }
284
+ TaskDrainOutbox.noteEnqueued()
285
+ }
286
+
287
+ const messageOf = (e: unknown) => (e instanceof Error ? e.message : String(e))
@@ -26,6 +26,7 @@ import { isDuplicateMessageError, sendControlMessage, type ResendReason } from '
26
26
  import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
27
27
  import type { MandalaRuntime, TokenSendResult } from '../../mandala/runtime'
28
28
  import { trimTrailingSlashes } from '../../net/trimTrailingSlashes'
29
+ import { paymentKey } from '../../directpay/paymentKey'
29
30
 
30
31
  export const MESSAGE_BOX_URL_KEY = 'message_box_url'
31
32
  export const DEFAULT_MESSAGE_BOX_URL = 'https://messagebox.bsvblockchain.tech'
@@ -104,6 +105,20 @@ export function peerPayLinkFor(
104
105
  return params.length ? `${base}?${params.join('&')}` : base
105
106
  }
106
107
 
108
+ /**
109
+ * Which payments this wallet already credited, by `paymentKey`
110
+ * (`core/directpay/paymentKey.ts`): the seen store direct payments share with the
111
+ * inbox, so one payment that arrives both live and through the message box is
112
+ * credited, and announced, once. `@bsv/webrtpay`'s `SeenStore` has this shape.
113
+ */
114
+ export interface CreditSeenStore {
115
+ has(key: string): boolean | Promise<boolean>
116
+ add(key: string): void | Promise<void>
117
+ }
118
+
119
+ /** What crediting an inbox payment came to: newly credited, or already credited (live). */
120
+ export type CreditOutcome = 'credited' | 'duplicate'
121
+
107
122
  /**
108
123
  * Credit an incoming payment, then acknowledge it. Never acknowledge first.
109
124
  *
@@ -119,22 +134,27 @@ export function peerPayLinkFor(
119
134
  * "The tx parameter must be valid AtomicBEEF", which reads like a malformed
120
135
  * payment and is nothing of the kind. Given a repair function, one failure is
121
136
  * retried with a proof re-fetched by txid. Omit it and behaviour is unchanged.
137
+ *
138
+ * `seen` is the direct-pay seen store. A payment it already has (taken live,
139
+ * or credited from the inbox before) is acknowledged without crediting it again
140
+ * and comes back `duplicate`, so the caller does not announce it twice; one
141
+ * credited here is added to it. Omit it and every payment is credited, as before.
122
142
  */
123
143
  export async function internalizeIncoming(
124
144
  wallet: InternalizingWallet,
125
145
  client: Pick<PeerPayClient, 'acknowledgeMessage'>,
126
146
  adminOriginator: string,
127
147
  payment: IncomingPayment,
128
- repairBeef?: (txid: string) => Promise<number[] | undefined>
129
- ): Promise<void> {
130
- // A note the sender attached to the token becomes the description the
131
- // recipient's wallet records, the same field the sender's action carries.
132
- const note = (payment.token as { note?: unknown }).note
133
- const noted = typeof note === 'string' && note.trim().length > 0 ? note.trim().slice(0, 500) : undefined
134
- // Same rule as the sender's side: the note verbatim, space-padded to the
135
- // 5-byte validation floor when it is shorter. The abbreviated key is 13
136
- // characters, so it never needs padding.
137
- const description = noted ? noted.padEnd(5) : abbreviateKey(payment.sender)
148
+ repairBeef?: (txid: string) => Promise<number[] | undefined>,
149
+ seen?: CreditSeenStore
150
+ ): Promise<CreditOutcome> {
151
+ const key = seen ? inboxPaymentKey(payment) : undefined
152
+ if (seen && key && (await isSeen(seen, key))) {
153
+ await acknowledgeCredited(client, String(payment.messageId))
154
+ return 'duplicate'
155
+ }
156
+
157
+ const description = creditDescription((payment.token as { note?: unknown }).note, payment.sender)
138
158
 
139
159
  const argsFor = (tx: number[] | typeof payment.token.transaction) => ({
140
160
  tx,
@@ -168,7 +188,48 @@ export async function internalizeIncoming(
168
188
  await wallet.internalizeAction(argsFor(repaired), adminOriginator)
169
189
  }
170
190
 
191
+ if (seen && key) {
192
+ try {
193
+ await seen.add(key)
194
+ } catch {
195
+ // The wallet has the payment. A lost record only means a live copy that
196
+ // arrives later is offered to the wallet again, which keeps the output it has.
197
+ }
198
+ }
171
199
  await acknowledgeCredited(client, String(payment.messageId))
200
+ return 'credited'
201
+ }
202
+
203
+ /**
204
+ * The description a received payment is recorded with. A note the sender
205
+ * attached becomes the description, the same field the sender's action
206
+ * carries: verbatim, space-padded to the 5-byte validation floor when it is
207
+ * shorter. Without one, the sender's abbreviated key (13 characters, so it
208
+ * never needs padding). One rule for the inbox and for direct payments.
209
+ */
210
+ export function creditDescription(note: unknown, sender: string): string {
211
+ const noted = typeof note === 'string' && note.trim().length > 0 ? note.trim().slice(0, 500) : undefined
212
+ return noted ? noted.padEnd(5) : abbreviateKey(sender)
213
+ }
214
+
215
+ /**
216
+ * The `paymentKey` of an inbox payment, or undefined when its AtomicBEEF does
217
+ * not parse (such a payment is never a duplicate: it cannot be credited at all).
218
+ */
219
+ export function inboxPaymentKey(payment: Pick<IncomingPayment, 'token'>): string | undefined {
220
+ const txid = payment.token?.transaction ? safeAtomicTxid(payment.token.transaction) : undefined
221
+ const derivation = payment.token?.customInstructions
222
+ if (!txid || !derivation) return undefined
223
+ return paymentKey(txid, payment.token.outputIndex ?? 0, derivation.derivationPrefix, derivation.derivationSuffix)
224
+ }
225
+
226
+ /** A seen store that cannot be read counts as not seen: the wallet keeps an output it already has. */
227
+ async function isSeen(seen: CreditSeenStore, key: string): Promise<boolean> {
228
+ try {
229
+ return (await seen.has(key)) === true
230
+ } catch {
231
+ return false
232
+ }
172
233
  }
173
234
 
174
235
  /** Inbox ids whose credit succeeded but whose ack did not. Retry, do not NACK. */
@@ -210,18 +271,18 @@ function safeAtomicTxid(tx: AtomicBEEF): string | undefined {
210
271
  * Retry the same payment object once. Do not relist the inbox — a pass of N
211
272
  * failures would otherwise listIncomingPayments per payment.
212
273
  */
213
- export async function acceptWithRetry(
274
+ export async function acceptWithRetry<R = void>(
214
275
  client: Pick<PeerPayClient, 'listIncomingPayments'>,
215
276
  messageBoxUrl: string,
216
277
  payment: IncomingPayment,
217
- internalize: (p: IncomingPayment) => Promise<void>
218
- ): Promise<void> {
278
+ internalize: (p: IncomingPayment) => Promise<R>
279
+ ): Promise<R> {
219
280
  void client
220
281
  void messageBoxUrl
221
282
  try {
222
- await internalize(payment)
283
+ return await internalize(payment)
223
284
  } catch {
224
- await internalize(payment)
285
+ return await internalize(payment)
225
286
  }
226
287
  }
227
288
 
@@ -268,7 +329,12 @@ export function needsAttention(state: InboxAttempt | undefined): boolean {
268
329
  export async function autoAcceptInbox<T extends { messageId: string | number }>(args: {
269
330
  payments: T[]
270
331
  attempts: Record<string, InboxAttempt>
271
- accept: (payment: T) => Promise<void>
332
+ /**
333
+ * Credits one payment. `'duplicate'` means it was already credited (it arrived
334
+ * live first): it leaves the box like any other, but is not counted in
335
+ * `accepted`, so it is not announced twice.
336
+ */
337
+ accept: (payment: T) => Promise<void | CreditOutcome>
272
338
  /** Message ids to attempt even though they had given up — a user pressed Retry. */
273
339
  force?: string[]
274
340
  /** When omitted, every failure counts as structural (increments attempts). */
@@ -293,8 +359,7 @@ export async function autoAcceptInbox<T extends { messageId: string | number }>(
293
359
  }
294
360
 
295
361
  try {
296
- await accept(payment)
297
- accepted++
362
+ if ((await accept(payment)) !== 'duplicate') accepted++
298
363
  // Success clears the history: the payment is credited and acknowledged, so
299
364
  // there is nothing left to show or retry.
300
365
  } catch (e) {
@@ -374,7 +439,7 @@ export interface HandleRailWallet {
374
439
  * failure path leaves the outbox entry unsent and retryable rather than
375
440
  * marking a possibly-still-reserved transaction as sent.
376
441
  */
377
- async function broadcastNoSend(
442
+ export async function broadcastNoSend(
378
443
  wallet: Pick<HandleRailWallet, 'createAction'>,
379
444
  adminOriginator: string,
380
445
  txid: string
@@ -406,7 +471,7 @@ async function broadcastNoSend(
406
471
  * the result keeps that row (and the reservation) in place until an abort
407
472
  * actually lands.
408
473
  */
409
- async function abortPeerPayNosend(
474
+ export async function abortPeerPayNosend(
410
475
  wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>,
411
476
  adminOriginator: string,
412
477
  txid: string
@@ -452,15 +517,81 @@ export async function sendViaHandle(args: {
452
517
  */
453
518
  recipientHost?: string
454
519
  }): Promise<{ outboxId: string; satoshis: number }> {
455
- const { wallet, adminOriginator, client, storage, recipient, messageBoxUrl, recipientName, recipientHost } = args
456
- const sats = Math.round(Number(args.satoshis))
457
- if (!Number.isFinite(sats) || sats <= 0) throw new Error('Invalid amount')
520
+ const { wallet, adminOriginator, client, storage, recipient, messageBoxUrl, recipientHost } = args
458
521
  // No advertisement check. Anointing a host costs a transaction, so someone
459
522
  // receiving BSV for the first time cannot have one — refusing to send to them
460
523
  // would make an empty wallet unpayable. The client resolves the recipient's
461
524
  // advertised host when there is one and otherwise falls back to the host this
462
525
  // wallet is configured for, which is where both parties' apps look by default.
526
+ const minted = await mintPeerPayToken(args)
527
+ const { txid, token, satoshis: paid } = minted
528
+ let outboxId: string | undefined
529
+ try {
530
+ outboxId = await saveOutboxEntry(storage, { recipient, token, messageBoxUrl, txid, recipientHost })
531
+ } catch (e) {
532
+ try {
533
+ await abortPeerPayNosend(wallet, adminOriginator, txid)
534
+ } catch (abortErr) {
535
+ console.warn('[peerpay] abortPeerPayNosend failed:', abortErr instanceof Error ? abortErr.message : abortErr)
536
+ }
537
+ throw e
538
+ }
539
+ try {
540
+ // Checkpoint before the box round-trip: if we crash after the box accepted
541
+ // the token, cancel must not abort a payment the recipient may already hold.
542
+ await updateOutboxEntry(storage, outboxId, { delivering: true })
543
+ await client.sendMessage(
544
+ {
545
+ recipient,
546
+ messageBox: PAYMENT_INBOX,
547
+ body: JSON.stringify(token)
548
+ },
549
+ recipientHost
550
+ )
551
+ // Delivered is persisted before the broadcast is attempted: from here the
552
+ // recipient holds the token, so a retry must never re-mint or cancel-abort —
553
+ // only the broadcast is still outstanding.
554
+ await updateOutboxEntry(storage, outboxId, { delivered: true })
555
+ await broadcastNoSend(wallet, adminOriginator, txid)
556
+ await markOutboxSent(storage, outboxId)
557
+ } catch (e) {
558
+ const message = e instanceof Error ? e.message : String(e)
559
+ await updateOutboxEntry(storage, outboxId, {
560
+ lastAttemptAt: new Date().toISOString(),
561
+ lastError: message
562
+ })
563
+ TaskDrainOutbox.noteEnqueued()
564
+ throw e
565
+ }
566
+ return { outboxId, satoshis: paid }
567
+ }
568
+
569
+ /** A payment minted with noSend: signed, saved by the caller, not yet broadcast. */
570
+ export interface MintedPeerPayToken {
571
+ txid: string
572
+ token: OutboxEntry['token']
573
+ /** What output 0 pays the recipient, read off the transaction (covers send-max). */
574
+ satoshis: number
575
+ }
463
576
 
577
+ /**
578
+ * Step 1 of a handle (or direct) payment: mint the BRC-29 token with noSend, so
579
+ * nothing reaches the network yet. Shared by `sendViaHandle` and the direct
580
+ * rail (`rails/direct.ts`), so one payment is minted the same way whichever
581
+ * way it is delivered, and a direct payment's token can go to the message box
582
+ * as it is.
583
+ */
584
+ export async function mintPeerPayToken(args: {
585
+ wallet: Pick<HandleRailWallet, 'getPublicKey' | 'createAction'>
586
+ adminOriginator: string
587
+ recipient: string
588
+ satoshis: number
589
+ note?: string
590
+ recipientName?: string
591
+ }): Promise<MintedPeerPayToken> {
592
+ const { wallet, adminOriginator, recipient, recipientName } = args
593
+ const sats = Math.round(Number(args.satoshis))
594
+ if (!Number.isFinite(sats) || sats <= 0) throw new Error('Invalid amount')
464
595
  // The note IS the description when one was given, verbatim; otherwise the
465
596
  // recipient's name, or their abbreviated key. No "Pay" prefix: the activity
466
597
  // row already shows the direction, and the receive side records the sender
@@ -517,45 +648,7 @@ export async function sendViaHandle(args: {
517
648
  // ignore it — and this app's receive side shows it as the description.
518
649
  ...(note ? { note } : {})
519
650
  }
520
- let outboxId: string | undefined
521
- try {
522
- outboxId = await saveOutboxEntry(storage, { recipient, token, messageBoxUrl, txid: car.txid, recipientHost })
523
- } catch (e) {
524
- try {
525
- await abortPeerPayNosend(wallet, adminOriginator, car.txid)
526
- } catch (abortErr) {
527
- console.warn('[peerpay] abortPeerPayNosend failed:', abortErr instanceof Error ? abortErr.message : abortErr)
528
- }
529
- throw e
530
- }
531
- try {
532
- // Checkpoint before the box round-trip: if we crash after the box accepted
533
- // the token, cancel must not abort a payment the recipient may already hold.
534
- await updateOutboxEntry(storage, outboxId, { delivering: true })
535
- await client.sendMessage(
536
- {
537
- recipient,
538
- messageBox: PAYMENT_INBOX,
539
- body: JSON.stringify(token)
540
- },
541
- recipientHost
542
- )
543
- // Delivered is persisted before the broadcast is attempted: from here the
544
- // recipient holds the token, so a retry must never re-mint or cancel-abort —
545
- // only the broadcast is still outstanding.
546
- await updateOutboxEntry(storage, outboxId, { delivered: true })
547
- await broadcastNoSend(wallet, adminOriginator, car.txid)
548
- await markOutboxSent(storage, outboxId)
549
- } catch (e) {
550
- const message = e instanceof Error ? e.message : String(e)
551
- await updateOutboxEntry(storage, outboxId, {
552
- lastAttemptAt: new Date().toISOString(),
553
- lastError: message
554
- })
555
- TaskDrainOutbox.noteEnqueued()
556
- throw e
557
- }
558
- return { outboxId, satoshis: paid }
651
+ return { txid: car.txid, token, satoshis: paid }
559
652
  }
560
653
 
561
654
  /**
@@ -71,6 +71,13 @@ export interface OutboxEntry {
71
71
  * retry re-sends (HMAC message id is idempotent).
72
72
  */
73
73
  delivering?: boolean
74
+ /**
75
+ * `'direct'`: minted for a live (WebRTC) payment (`rails/direct.ts`). The
76
+ * same token goes to the message box when the link could not finish it, so
77
+ * a retry, cancel or drain treats the row exactly like a handle-rail one.
78
+ * Absent for a payment sent through the message box from the start.
79
+ */
80
+ via?: 'direct'
74
81
  }
75
82
 
76
83
  interface StorageLike {
@@ -158,9 +165,10 @@ export async function saveOutboxEntry(
158
165
  messageBoxUrl: string
159
166
  txid?: string
160
167
  recipientHost?: string
168
+ via?: OutboxEntry['via']
161
169
  }
162
170
  ): Promise<string> {
163
- const { recipient, token, messageBoxUrl, txid, recipientHost } = params
171
+ const { recipient, token, messageBoxUrl, txid, recipientHost, via } = params
164
172
  const id = `${Date.now()}_${recipient.slice(0, 8)}`
165
173
  const entry: OutboxEntry = {
166
174
  id,
@@ -170,7 +178,8 @@ export async function saveOutboxEntry(
170
178
  messageBoxUrl,
171
179
  status: 'unsent',
172
180
  ...(txid ? { txid } : {}),
173
- ...(recipientHost ? { recipientHost } : {})
181
+ ...(recipientHost ? { recipientHost } : {}),
182
+ ...(via ? { via } : {})
174
183
  }
175
184
  return withOutboxLock(storage, async () => {
176
185
  const all = await readEntries(storage)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -37,6 +37,7 @@
37
37
  "@bsv/react-native-localpay-transport": "*",
38
38
  "@bsv/sdk": "^2.8.11",
39
39
  "@bsv/templates": "^2.0.0",
40
+ "@bsv/webrtpay": "^0.2.1",
40
41
  "@bsv/wallet-toolbox-mobile": "^2.14.3",
41
42
  "@expo/vector-icons": "^15.0.3",
42
43
  "@noble/curves": "^2.3.0",
@@ -83,6 +84,9 @@
83
84
  "react-native-yubikey": "*"
84
85
  },
85
86
  "peerDependenciesMeta": {
87
+ "@bsv/webrtpay": {
88
+ "optional": true
89
+ },
86
90
  "react-native-yubikey": {
87
91
  "optional": true
88
92
  }