@bsv/expo-wallet-toolbox 0.16.0 → 0.18.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,544 @@
1
+ /**
2
+ * Receiving a direct (live) payment: verify it pays this wallet, take it into the wallet at
3
+ * once, and answer the payer. Ported from BSV Desktop's `directPayments.ts` (receive half).
4
+ *
5
+ * A payment is internalized like an inbox payment: protocol `wallet payment`, label `peerpay`,
6
+ * and the sender's note (else their abbreviated key) as the description (`creditDescription`),
7
+ * so a payment reads the same in Activity whichever way it came.
8
+ *
9
+ * Once. Every payment has a {@link paymentKey}; the seen store records the ones this wallet
10
+ * took, and the inbox credit path (`internalizeIncoming` with `seen`) reads and writes the same
11
+ * store. So a payment that arrives live and again through the message box (the payer's link
12
+ * dropped before the ack, so it sent the same token there) is credited, and announced, once.
13
+ *
14
+ * Kept. A failure `classifyCreditError` calls environmental (offline, headers behind, a locked
15
+ * database) keeps the payment on this device and answers `received`: by then the payer may
16
+ * broadcast it, so it is better kept than refused. Anything else is refused (`rejected`), which
17
+ * is safe at that point because the payer still has the payment and sends it through the
18
+ * message box instead. A kept payment was acknowledged, so its payer will not send it again,
19
+ * and only this device has its derivation: it is never dropped until the wallet has it.
20
+ * {@link retryKeptDirectPayments} offers it again; one the wallet refuses outright (it does not
21
+ * pay this wallet, or its inputs were double spent), or still cannot take after
22
+ * {@link NEEDS_ATTENTION_ATTEMPTS} counted tries more than a day after it arrived, is flagged as
23
+ * needing attention, and only the user may dismiss it.
24
+ *
25
+ * Both lists live in the device store (`deviceKVStorage`), keyed by identity key and network,
26
+ * so they outlive the wallet's database. A kept list this version cannot read is never written
27
+ * over (no payment is kept while it is unreadable), and entries it does not recognise are
28
+ * written back as they were: either may hold the only copy of a payment.
29
+ */
30
+ import { Transaction, Utils } from '@bsv/sdk'
31
+ import type { KVStorage } from '../localpay/pending'
32
+ import type { CreditFailureKind } from '../pay/creditErrors'
33
+ import { creditDescription } from '../pay/rails/handle'
34
+ import { getDirectPayConfig } from '../toolboxConfig'
35
+ import { deviceKVStorage } from './deviceStore'
36
+ import { paymentKey } from './paymentKey'
37
+ import {
38
+ isWebRTPayError,
39
+ type DirectPaySeenStore,
40
+ type IncomingDirectPayment,
41
+ type WebRTPayModule,
42
+ type WebRTPayWallet
43
+ } from './webrtpay'
44
+
45
+ /** Payment keys remembered per wallet and network, newest kept. */
46
+ export const SEEN_LIMIT = 2000
47
+ /** Payments waiting for the wallet; a new one is refused while this many wait (those needing attention do not count). */
48
+ export const KEPT_LIMIT = 50
49
+ /** Characters of stored kept-list JSON (transactions are kept as base64). */
50
+ export const KEPT_BUDGET = 1_000_000
51
+ /**
52
+ * A kept payment the wallet still cannot take needs attention only after this many counted
53
+ * tries AND this long after it arrived, so a lagging chain tracker has time to catch up.
54
+ * Environmental failures do not count as tries.
55
+ */
56
+ export const NEEDS_ATTENTION_ATTEMPTS = 5
57
+ export const NEEDS_ATTENTION_AGE_MS = 24 * 60 * 60 * 1000
58
+
59
+ export const DIRECT_PAY_SEEN_PREFIX = 'direct_pay_seen_v1:'
60
+ export const KEPT_DIRECT_PAYMENTS_PREFIX = 'direct_pay_kept_v1:'
61
+
62
+ const seenStorageKey = (identity: string, chain: string) => `${DIRECT_PAY_SEEN_PREFIX}${identity}:${chain}`
63
+ const keptStorageKey = (identity: string, chain: string) => `${KEPT_DIRECT_PAYMENTS_PREFIX}${identity}:${chain}`
64
+
65
+ /** Reasons sent to the payer: fixed text, so nothing about this wallet's internals leaks. */
66
+ const NOT_ACCEPTED = 'The wallet could not verify or record this payment'
67
+ const CANNOT_KEEP = 'The wallet cannot take payments right now; try again later'
68
+
69
+ /** Where a wallet's direct-pay lists are kept, and which wallet and network they are for. */
70
+ export interface DirectPayStore {
71
+ storage: KVStorage
72
+ identity: string
73
+ chain: string
74
+ }
75
+
76
+ // ---- storage ------------------------------------------------------------------------------
77
+
78
+ // The live receive, the inbox credit pass and a retry pass can all change one list. Serialize
79
+ // each list's whole read-modify-write (as outbox.ts does), so one cannot write back a stale copy
80
+ // over a payment another just kept.
81
+ const tails = new WeakMap<KVStorage, Map<string, Promise<void>>>()
82
+
83
+ function locked<T>(storage: KVStorage, key: string, fn: () => Promise<T>): Promise<T> {
84
+ let byKey = tails.get(storage)
85
+ if (!byKey) tails.set(storage, (byKey = new Map()))
86
+ const run = (byKey.get(key) ?? Promise.resolve()).then(fn)
87
+ byKey.set(
88
+ key,
89
+ run.then(
90
+ () => undefined,
91
+ () => undefined
92
+ )
93
+ )
94
+ return run
95
+ }
96
+
97
+ /** The list stored under `key` (none stored reads as empty), or null when it cannot be read. */
98
+ async function readArray(storage: KVStorage, key: string): Promise<unknown[] | null> {
99
+ try {
100
+ const value: unknown = JSON.parse((await storage.getKeyValue(key)) ?? '[]')
101
+ return Array.isArray(value) ? value : null
102
+ } catch {
103
+ return null
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Which payments this wallet already took, by {@link paymentKey}, shared by the live receive
109
+ * and the inbox credit path. Unreadable counts as empty: a lost record only means a redelivery
110
+ * is offered to the wallet again, which keeps the output it already has. `add` never throws.
111
+ */
112
+ export function createDirectPaySeenStore({ storage, identity, chain }: DirectPayStore): DirectPaySeenStore {
113
+ const key = seenStorageKey(identity, chain)
114
+ const read = async () => ((await readArray(storage, key)) ?? []).filter((k): k is string => typeof k === 'string')
115
+ return {
116
+ has: async paymentKey => (await read()).includes(paymentKey),
117
+ add: paymentKey =>
118
+ locked(storage, key, async () => {
119
+ const keys = [...(await read()).filter(k => k !== paymentKey), paymentKey].slice(-SEEN_LIMIT)
120
+ try {
121
+ await storage.setKeyValue(key, JSON.stringify(keys))
122
+ } catch {
123
+ // The wallet has the payment by now; see above.
124
+ }
125
+ })
126
+ }
127
+ }
128
+
129
+ /**
130
+ * The seen store the inbox credit path passes to `internalizeIncoming`: this wallet's, in the
131
+ * device store. Undefined when this build does not offer direct payments (nothing arrives live,
132
+ * so there is nothing to credit twice) or the identity key is not known yet.
133
+ */
134
+ export function inboxSeenStore(identity: string | undefined, chain: string): DirectPaySeenStore | undefined {
135
+ if (!identity || getDirectPayConfig()?.enabled !== true) return undefined
136
+ return createDirectPaySeenStore({ storage: deviceKVStorage, identity, chain })
137
+ }
138
+
139
+ // ---- receiving ----------------------------------------------------------------------------
140
+
141
+ /** What became of a payment from a peer. */
142
+ export interface DirectReceipt {
143
+ /** The ack for the payer: in the wallet, or kept on this device until the wallet can take it. */
144
+ status: 'accepted' | 'received'
145
+ /**
146
+ * This wallet had already taken or kept this payment (the payer delivered it again after
147
+ * losing the ack, or it came through the inbox first). Announce a payment only when false.
148
+ */
149
+ repeat: boolean
150
+ /** The wallet took the payment just now, so its balance changed (a kept one on redelivery too). */
151
+ added: boolean
152
+ }
153
+
154
+ /**
155
+ * Takes a payment from an authenticated peer into the wallet (once; see
156
+ * {@link createDirectPaySeenStore}) and returns the ack. A failure `classify` calls
157
+ * environmental keeps it for {@link retryKeptDirectPayments} and answers `received`.
158
+ *
159
+ * @throws a `WebRTPayError` for the payer, which the client turns into a `rejected` ack:
160
+ * `invalid_payment` when it does not pay this wallet, `rejected` when the wallet refuses it or
161
+ * it cannot be kept. Nothing is stored then; the payer still has the payment.
162
+ */
163
+ export async function receiveDirectPayment(o: {
164
+ webrtpay: Pick<WebRTPayModule, 'acceptDirectPayment' | 'WebRTPayError'>
165
+ wallet: WebRTPayWallet
166
+ originator: string
167
+ store: DirectPayStore
168
+ payment: IncomingDirectPayment
169
+ /** The sender's note, from the link (`onPayment`'s `ctx.note`). */
170
+ note?: string
171
+ classify: (e: unknown) => CreditFailureKind
172
+ }): Promise<DirectReceipt> {
173
+ const { webrtpay, store } = o
174
+ let result: { txid: string; status: 'accepted' | 'duplicate' }
175
+ try {
176
+ result = await webrtpay.acceptDirectPayment(o.wallet, o.payment, {
177
+ originator: o.originator,
178
+ seen: createDirectPaySeenStore(store),
179
+ labels: ['peerpay'],
180
+ description: creditDescription(o.note, o.payment.sender)
181
+ })
182
+ } catch (error) {
183
+ if (isWebRTPayError(webrtpay, error)) throw error
184
+ if (o.classify(error) !== 'environmental') {
185
+ throw new webrtpay.WebRTPayError('rejected', NOT_ACCEPTED, { cause: error })
186
+ }
187
+ const kept = await keepForRetry(webrtpay, store, toEntry(o.payment, o.note, error))
188
+ return { status: 'received', repeat: !kept, added: false }
189
+ }
190
+ // A payment kept earlier was announced when it was kept.
191
+ const wasKept = await forget(store, keyOf(o.payment, result.txid))
192
+ return { status: 'accepted', repeat: result.status === 'duplicate' || wasKept, added: result.status === 'accepted' }
193
+ }
194
+
195
+ // ---- kept payments ------------------------------------------------------------------------
196
+
197
+ /**
198
+ * Thrown by a retry pass's `run` to end the pass early (its time is up); the payment it was
199
+ * about to offer, and every one after it, stays as it is for the next pass.
200
+ */
201
+ export class RetryStopped extends Error {
202
+ constructor(message = 'The retry pass stopped early') {
203
+ super(message)
204
+ this.name = 'RetryStopped'
205
+ }
206
+ }
207
+
208
+ /** Why the wallet could not add a kept payment after retrying, so the user should look at it. */
209
+ export interface NeedsAttention {
210
+ since: number
211
+ /**
212
+ * `refused`: it does not pay this wallet, or its inputs were double spent. `unverifiable`: the
213
+ * wallet still could not take it after {@link NEEDS_ATTENTION_ATTEMPTS} tries, more than a day
214
+ * after it arrived.
215
+ */
216
+ reason: 'refused' | 'unverifiable'
217
+ }
218
+
219
+ /** A kept payment as stored: everything needed to take it into the wallet. */
220
+ export interface KeptDirectPayment {
221
+ messageId: string
222
+ /** The payer's identity key. */
223
+ sender: string
224
+ note?: string
225
+ token: {
226
+ customInstructions: { derivationPrefix: string; derivationSuffix: string }
227
+ /** Atomic BEEF, base64. */
228
+ transaction: string
229
+ amount: number
230
+ outputIndex: number
231
+ }
232
+ }
233
+
234
+ /** A payment kept on this device, acknowledged as received, that the wallet has not taken yet. */
235
+ export interface KeptDirectPaymentInfo {
236
+ /** {@link paymentKey}: one entry per payment output. */
237
+ key: string
238
+ txid: string
239
+ sender: string
240
+ amount: number
241
+ receivedAt: number
242
+ /** Failed retries counted towards needing attention. */
243
+ attempts: number
244
+ /** The last failure (local text; never sent to the payer). */
245
+ error: string
246
+ /** Set once retrying stopped looking likely to work; the payment is still kept and retried. */
247
+ needsAttention?: NeedsAttention
248
+ payment: KeptDirectPayment
249
+ }
250
+
251
+ /**
252
+ * Offers kept payments to the wallet again. One the wallet takes (or already has) leaves the
253
+ * list; nothing else ever does. A failed retry is judged with `classify`: environmental is not
254
+ * counted; double spent, or `invalid_payment` from the package, flags it as needing attention at
255
+ * once; anything else counts a try, and needs attention after {@link NEEDS_ATTENTION_ATTEMPTS}
256
+ * tries more than {@link NEEDS_ATTENTION_AGE_MS} after it arrived.
257
+ *
258
+ * `onNeedsAttention` hears of each payment once, when it is first flagged. Payments that need
259
+ * attention are offered only with `includeNeedsAttention`. Each payment's wallet call goes
260
+ * through `run`, which may throw {@link RetryStopped} to end the pass there. Returns how many
261
+ * payments the wallet took. Run it single-flight per wallet.
262
+ */
263
+ export async function retryKeptDirectPayments(o: {
264
+ webrtpay: Pick<WebRTPayModule, 'acceptDirectPayment' | 'WebRTPayError'>
265
+ wallet: WebRTPayWallet
266
+ originator: string
267
+ store: DirectPayStore
268
+ classify: (e: unknown) => CreditFailureKind
269
+ includeNeedsAttention?: boolean
270
+ onNeedsAttention?: (kept: KeptDirectPaymentInfo) => void
271
+ run?: <T>(call: () => Promise<T>) => Promise<T>
272
+ }): Promise<number> {
273
+ const { webrtpay, store } = o
274
+ const seen = createDirectPaySeenStore(store)
275
+ const run = o.run ?? (<T>(call: () => Promise<T>) => call())
276
+ let accepted = 0
277
+ for (const entry of (await readKept(store))?.entries ?? []) {
278
+ if (entry.needsAttention && !o.includeNeedsAttention) continue
279
+ try {
280
+ const result = await run(() =>
281
+ webrtpay.acceptDirectPayment(o.wallet, toIncoming(entry), {
282
+ originator: o.originator,
283
+ seen,
284
+ labels: ['peerpay'],
285
+ description: creditDescription(entry.payment.note, entry.payment.sender)
286
+ })
287
+ )
288
+ if (result.status === 'accepted') accepted++
289
+ } catch (error) {
290
+ if (error instanceof RetryStopped) break
291
+ const verdict = retryVerdict(webrtpay, o.classify, error)
292
+ if (verdict === 'temporary') continue
293
+ const failed: KeptEntry = { ...entry, error: messageOf(error).slice(0, 500) }
294
+ if (!entry.needsAttention) {
295
+ if (verdict === 'unproven') failed.attempts = entry.attempts + 1
296
+ const tooLong =
297
+ failed.attempts >= NEEDS_ATTENTION_ATTEMPTS && Date.now() - entry.receivedAt > NEEDS_ATTENTION_AGE_MS
298
+ if (verdict === 'refused' || tooLong) {
299
+ failed.needsAttention = { since: Date.now(), reason: verdict === 'refused' ? 'refused' : 'unverifiable' }
300
+ }
301
+ }
302
+ // Kept either way. If this write fails, the try is just not counted (or flagged) yet.
303
+ if ((await rewrite(store, entry.key, () => failed)) === true && failed.needsAttention && !entry.needsAttention) {
304
+ try {
305
+ o.onNeedsAttention?.(infoOf(failed))
306
+ } catch {
307
+ // The flag is stored; the list shows it.
308
+ }
309
+ }
310
+ continue
311
+ }
312
+ await forget(store, entry.key)
313
+ }
314
+ return accepted
315
+ }
316
+
317
+ /** A wallet's kept-payment list as this device holds it. */
318
+ export interface KeptDirectPaymentsList {
319
+ /** The kept payments this version can read, oldest first. */
320
+ payments: KeptDirectPaymentInfo[]
321
+ /** The stored list cannot be read. It is left as it is, and no payment is kept until it can be. */
322
+ unreadable: boolean
323
+ /** Stored entries this version does not recognise; they are kept as they are. */
324
+ unknown: number
325
+ }
326
+
327
+ /** The open wallet's kept payments. */
328
+ export async function listKeptDirectPayments(store: DirectPayStore): Promise<KeptDirectPaymentsList> {
329
+ const stored = await readKept(store)
330
+ if (!stored) return { payments: [], unreadable: true, unknown: 0 }
331
+ return { payments: stored.entries.map(infoOf), unreadable: false, unknown: stored.unknown }
332
+ }
333
+
334
+ /**
335
+ * Removes a kept payment because the user dismissed it. Only one that needs attention can go
336
+ * (the others are still being retried), and the screen offers it only after its recovery
337
+ * details were copied. Returns false when it is no longer kept (the wallet took it meanwhile).
338
+ * Throws, removing nothing, when it does not need attention or the list cannot be written.
339
+ */
340
+ export async function dismissKeptDirectPayment(store: DirectPayStore, key: string): Promise<boolean> {
341
+ const stored = await readKept(store)
342
+ if (!stored) throw new Error('The direct payments kept on this device could not be read, so nothing was removed.')
343
+ const entry = stored.entries.find(e => e.key === key)
344
+ if (!entry) return false
345
+ if (!entry.needsAttention)
346
+ throw new Error('Only a payment that needs attention can be dismissed; this one is still being retried.')
347
+ const removed = await rewrite(store, key, () => undefined)
348
+ if (removed === undefined) return false
349
+ if (!removed) throw new Error('This payment could not be removed from this device. Try again.')
350
+ return true
351
+ }
352
+
353
+ /**
354
+ * Retry time: the payer no longer has the payment, so anything not known to be final keeps it.
355
+ * `refused` is final: it does not pay this wallet (`invalid_payment`), or its inputs were
356
+ * double spent. Environmental failures are `temporary` and not counted; the rest `unproven`.
357
+ */
358
+ function retryVerdict(
359
+ webrtpay: Pick<WebRTPayModule, 'WebRTPayError'>,
360
+ classify: (e: unknown) => CreditFailureKind,
361
+ error: unknown
362
+ ): 'refused' | 'temporary' | 'unproven' {
363
+ if (isWebRTPayError(webrtpay, error)) return error.code === 'invalid_payment' ? 'refused' : 'unproven'
364
+ switch (classify(error)) {
365
+ case 'environmental':
366
+ return 'temporary'
367
+ case 'double_spend':
368
+ return 'refused'
369
+ default:
370
+ return 'unproven'
371
+ }
372
+ }
373
+
374
+ /** A kept payment as stored. */
375
+ interface KeptEntry {
376
+ key: string
377
+ payment: KeptDirectPayment
378
+ error: string
379
+ receivedAt: number
380
+ attempts: number
381
+ needsAttention?: NeedsAttention
382
+ }
383
+
384
+ function infoOf(entry: KeptEntry): KeptDirectPaymentInfo {
385
+ const { key, payment, error, receivedAt, attempts, needsAttention } = entry
386
+ return {
387
+ key,
388
+ txid: key.split(':')[0],
389
+ sender: payment.sender,
390
+ amount: payment.token.amount,
391
+ receivedAt,
392
+ attempts,
393
+ error,
394
+ ...(needsAttention && { needsAttention }),
395
+ payment
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Adds the payment to the kept list, once; returns false when it was already there. Nothing
401
+ * kept is ever dropped to make room: a payment that cannot be kept is refused instead (the
402
+ * payer still has it), as is every payment while the stored list cannot be read.
403
+ */
404
+ function keepForRetry(
405
+ webrtpay: Pick<WebRTPayModule, 'WebRTPayError'>,
406
+ store: DirectPayStore,
407
+ entry: KeptEntry
408
+ ): Promise<boolean> {
409
+ const key = keptStorageKey(store.identity, store.chain)
410
+ return locked(store.storage, key, async () => {
411
+ try {
412
+ const stored = await readKept(store)
413
+ if (!stored) throw new Error('The kept payments on this device cannot be read.')
414
+ if (stored.entries.some(e => e.key === entry.key)) return false
415
+ if (stored.entries.filter(e => !e.needsAttention).length >= KEPT_LIMIT) {
416
+ throw new Error('Too many payments are waiting for the wallet.')
417
+ }
418
+ const text = JSON.stringify([...stored.items, entry])
419
+ if (text.length > KEPT_BUDGET) throw new Error('No room to keep this payment.')
420
+ await store.storage.setKeyValue(key, text)
421
+ return true
422
+ } catch (cause) {
423
+ throw new webrtpay.WebRTPayError('rejected', CANNOT_KEEP, { cause })
424
+ }
425
+ })
426
+ }
427
+
428
+ /** Removes a payment from the kept list and says whether it was there. A failed write leaves it. */
429
+ async function forget(store: DirectPayStore, key: string): Promise<boolean> {
430
+ return (await rewrite(store, key, () => undefined)) !== undefined
431
+ }
432
+
433
+ /**
434
+ * Replaces (`change` returns an entry) or removes (it returns undefined) the stored entry for
435
+ * `key`, from the list as stored now. Every other stored item, recognised or not, is written
436
+ * back exactly as it was read. Returns undefined when nothing was there to change (or the list
437
+ * cannot be read: it is never written over), else whether the write succeeded.
438
+ */
439
+ function rewrite(
440
+ store: DirectPayStore,
441
+ key: string,
442
+ change: (entry: KeptEntry) => KeptEntry | undefined
443
+ ): Promise<boolean | undefined> {
444
+ const storageKey = keptStorageKey(store.identity, store.chain)
445
+ return locked(store.storage, storageKey, async () => {
446
+ const stored = await readKept(store)
447
+ const index = stored?.items.findIndex(item => toKeptEntry(item)?.key === key) ?? -1
448
+ if (!stored || index < 0) return undefined
449
+ const replacement = change(toKeptEntry(stored.items[index])!)
450
+ const items = stored.items.flatMap((item, i) => (i !== index ? [item] : replacement ? [replacement] : []))
451
+ try {
452
+ await store.storage.setKeyValue(storageKey, JSON.stringify(items))
453
+ } catch {
454
+ return false // the stored list stays as it was
455
+ }
456
+ return true
457
+ })
458
+ }
459
+
460
+ /** Every stored item, and the recognised entries; null when the list itself cannot be read. */
461
+ async function readKept(
462
+ store: DirectPayStore
463
+ ): Promise<{ items: unknown[]; entries: KeptEntry[]; unknown: number } | null> {
464
+ const items = await readArray(store.storage, keptStorageKey(store.identity, store.chain))
465
+ if (!items) return null
466
+ const entries = items.map(toKeptEntry).filter((e): e is KeptEntry => e !== undefined)
467
+ return { items, entries, unknown: items.length - entries.length }
468
+ }
469
+
470
+ /** A stored item as a kept payment, or undefined when it is not one this version can retry. */
471
+ function toKeptEntry(e: unknown): KeptEntry | undefined {
472
+ const item = e as Partial<KeptEntry> | null
473
+ const payment = item?.payment
474
+ const token = payment?.token
475
+ const derivation = token?.customInstructions
476
+ const recognised =
477
+ typeof item?.key === 'string' &&
478
+ typeof payment?.messageId === 'string' &&
479
+ typeof payment.sender === 'string' &&
480
+ typeof token?.transaction === 'string' &&
481
+ Number.isSafeInteger(token.amount) &&
482
+ Number.isSafeInteger(token.outputIndex) &&
483
+ token.outputIndex >= 0 &&
484
+ typeof derivation?.derivationPrefix === 'string' &&
485
+ typeof derivation.derivationSuffix === 'string'
486
+ if (!recognised || !item) return undefined
487
+ const { needsAttention, ...rest } = item as KeptEntry
488
+ return {
489
+ ...rest,
490
+ error: typeof item.error === 'string' ? item.error : '',
491
+ attempts: Number.isSafeInteger(item.attempts) && item.attempts! > 0 ? item.attempts! : 0,
492
+ receivedAt: Number.isFinite(item.receivedAt) ? item.receivedAt! : Date.now(),
493
+ ...(isNeedsAttention(needsAttention) && { needsAttention })
494
+ }
495
+ }
496
+
497
+ function isNeedsAttention(x: unknown): x is NeedsAttention {
498
+ const n = x as Partial<NeedsAttention> | undefined
499
+ return Number.isFinite(n?.since) && (n?.reason === 'refused' || n?.reason === 'unverifiable')
500
+ }
501
+
502
+ /** Same output index rule as the package: the token's, else the payment's, else 0. */
503
+ const outputIndexOf = (p: IncomingDirectPayment) => p.token.outputIndex ?? p.outputIndex ?? 0
504
+
505
+ const keyOf = (p: IncomingDirectPayment, txid: string) =>
506
+ paymentKey(
507
+ txid,
508
+ outputIndexOf(p),
509
+ p.token.customInstructions.derivationPrefix,
510
+ p.token.customInstructions.derivationSuffix
511
+ )
512
+
513
+ function toEntry(p: IncomingDirectPayment, note: string | undefined, error: unknown): KeptEntry {
514
+ const {
515
+ transaction,
516
+ amount,
517
+ customInstructions: { derivationPrefix, derivationSuffix }
518
+ } = p.token
519
+ const outputIndex = outputIndexOf(p)
520
+ return {
521
+ key: keyOf(p, Transaction.fromAtomicBEEF(transaction).id('hex')),
522
+ payment: {
523
+ messageId: p.messageId,
524
+ sender: p.sender,
525
+ ...(note ? { note } : {}),
526
+ token: {
527
+ customInstructions: { derivationPrefix, derivationSuffix },
528
+ transaction: Utils.toBase64(transaction),
529
+ amount,
530
+ outputIndex
531
+ }
532
+ },
533
+ error: messageOf(error).slice(0, 500),
534
+ receivedAt: Date.now(),
535
+ attempts: 0
536
+ }
537
+ }
538
+
539
+ function toIncoming(entry: KeptEntry): IncomingDirectPayment {
540
+ const { messageId, sender, token } = entry.payment
541
+ return { messageId, sender, token: { ...token, transaction: Utils.toArray(token.transaction, 'base64') } }
542
+ }
543
+
544
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error))