@bsv/expo-wallet-toolbox 0.20.0 → 0.22.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.
- package/CHANGELOG.md +147 -0
- package/README.md +78 -13
- package/core/contacts/contactActivity.ts +48 -28
- package/core/contacts/contactsStore.ts +2 -2
- package/core/context/WalletContext.tsx +166 -219
- package/core/demo/demoAssets.ts +8 -10
- package/core/demo/demoLedger.ts +32 -38
- package/core/demo/demoMandalaRuntime.ts +67 -49
- package/core/demo/index.ts +1 -1
- package/core/directpay/DirectPayManager.ts +148 -29
- package/core/directpay/DirectPayProvider.tsx +11 -2
- package/core/directpay/payFlow.ts +10 -1
- package/core/directpay/settings.ts +56 -9
- package/core/directpay/types.ts +11 -2
- package/core/directpay/webrtpay.ts +4 -0
- package/core/i18n/translations.tsx +185 -84
- package/core/index.ts +55 -37
- package/core/localpay/build.ts +110 -569
- package/core/localpay/codec.ts +190 -93
- package/core/localpay/pending.ts +217 -202
- package/core/localpay/session.ts +99 -25
- package/core/localpay/types.ts +6 -5
- package/core/localpay/verify.ts +118 -173
- package/core/mandala/abortGuard.ts +97 -120
- package/core/mandala/accessPolicy.ts +133 -0
- package/core/mandala/assets.ts +370 -0
- package/core/mandala/colorGuard.ts +178 -0
- package/core/mandala/colorModule.ts +82 -0
- package/core/mandala/createRuntime.ts +483 -2392
- package/core/mandala/handle.ts +694 -0
- package/core/mandala/kvStore.ts +105 -0
- package/core/mandala/nearby.ts +185 -0
- package/core/mandala/receipt.ts +121 -0
- package/core/mandala/runtime.ts +166 -312
- package/core/mandala/settle.ts +540 -0
- package/core/mandala/transferJournal.ts +395 -0
- package/core/mandala/types.ts +61 -311
- package/core/networks.ts +5 -5
- package/core/offline/cancelParked.ts +80 -63
- package/core/offline/payerHold.ts +52 -118
- package/core/parsePeerPayURI.ts +25 -12
- package/core/pay/rails/direct.ts +6 -2
- package/core/pay/rails/handle.ts +15 -14
- package/core/pay/rails/index.ts +5 -3
- package/core/pay/rails/nearby.ts +25 -87
- package/core/profiles/assertProfileEmpty.ts +19 -10
- package/core/services/vault/guard.ts +5 -4
- package/core/storage/StorageExpoSQLite.ts +93 -229
- package/core/storage/methods/processOfflineActions.ts +86 -136
- package/core/storage/schema/createTables.ts +9 -184
- package/package.json +6 -5
- package/ui/components/pay/AssetPicker.tsx +2 -2
- package/ui/components/pay/HandleReceive.tsx +10 -4
- package/ui/components/pay/NearbyFlow.tsx +324 -239
- package/ui/components/pay/RequestHub.tsx +10 -0
- package/ui/components/pay/UniversalSend.tsx +31 -28
- package/ui/components/pay/useRecipientInput.ts +2 -2
- package/ui/components/ui/PermissionSheet.tsx +94 -160
- package/ui/components/ui/colorPrompt.ts +236 -0
- package/ui/components/wallet/AmountInput.tsx +9 -6
- package/ui/components/wallet/AssetAmount.tsx +6 -6
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ContactActivityList.tsx +10 -13
- package/ui/components/wallet/tokenEviction.ts +9 -9
- package/ui/hooks/useMandala.ts +6 -6
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/importDatabases.ts +1 -1
- package/ui/screens/PayScreen.tsx +14 -20
- package/ui/screens/SettingsScreen.tsx +3 -1
- package/ui/screens/WalletCheckScreen.tsx +7 -2
- package/ui/screens/WalletHomeScreen.tsx +40 -14
- package/ui/screens/tokenRowTitle.ts +28 -15
- package/ui/tokenFormat.ts +133 -69
- package/ui/tokenStatus.ts +5 -8
- package/core/localpay/settlementAck.ts +0 -155
- package/core/mandala/basketMigration.ts +0 -166
- package/core/mandala/bundle.ts +0 -244
- package/core/mandala/drain.ts +0 -754
- package/core/mandala/inboxPrehold.ts +0 -193
- package/core/mandala/permissionModule.ts +0 -931
- package/core/mandala/resendTransfer.ts +0 -178
- package/core/mandala/settlementStore.ts +0 -434
- package/core/mandala/token.ts +0 -45
- package/core/offline/tokenFrames.ts +0 -197
package/core/localpay/pending.ts
CHANGED
|
@@ -1,13 +1,8 @@
|
|
|
1
|
-
import { Beef } from '@bsv/sdk'
|
|
1
|
+
import { Beef, Transaction } from '@bsv/sdk'
|
|
2
|
+
import { decodeToken } from '@bsv/mandala'
|
|
2
3
|
import type { PaymentFrame, TokenPayment } from './codec'
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
// exports are both needed — bundle.ts's is the home-screen row label,
|
|
6
|
-
// permissionModule.ts's is the one that P-routes a listActions query to
|
|
7
|
-
// MandalaTokenModule's consent gate.
|
|
8
|
-
import { MANDALA_ACTION_LABEL as MANDALA_TOKEN_SPEND_LABEL } from '../mandala/permissionModule'
|
|
9
|
-
import type { AdmissionEntryWire } from '../mandala/types'
|
|
10
|
-
import { isRetriableInternalizeFailure } from '../mandala/drain'
|
|
4
|
+
import type { NearbyTokenDeps } from '../mandala/runtime'
|
|
5
|
+
import { isRetriableReceiptFailure, isTransportReceiptFailure, receiptFailureCode } from '../mandala/receipt'
|
|
11
6
|
import { failedPostReason } from '../pay/creditErrors'
|
|
12
7
|
|
|
13
8
|
export const PENDING_KEY = 'localpay_pending'
|
|
@@ -111,19 +106,15 @@ export function getPendingCorruptNotice(): boolean {
|
|
|
111
106
|
|
|
112
107
|
/**
|
|
113
108
|
* Every byte field of a frame travels as a `number[]`: `JSON.stringify` turns a
|
|
114
|
-
* `Uint8Array` into an index-keyed object, and a token frame's
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
* expo-sqlite on Android stringifies into a TEXT row, unreadable by every later
|
|
119
|
-
* send that walked the received coin's ancestry (2026-09-16).
|
|
109
|
+
* `Uint8Array` into an index-keyed object, and a token frame's byte fields
|
|
110
|
+
* came back that way for as long as only `transaction` was converted
|
|
111
|
+
* (2026-09-16). The v7 token block's only byte fields are `certificates`;
|
|
112
|
+
* its evidence members are JSON already and are stored as they are.
|
|
120
113
|
*/
|
|
121
114
|
type WireBytes = number[]
|
|
122
115
|
|
|
123
|
-
interface WireToken extends Omit<TokenPayment, 'certificates'
|
|
116
|
+
interface WireToken extends Omit<TokenPayment, 'certificates'> {
|
|
124
117
|
certificates: WireBytes[]
|
|
125
|
-
linkage: Array<{ txid: string; payload: WireBytes }>
|
|
126
|
-
admissions: Array<Omit<AdmissionEntryWire, 'signature'> & { signature: WireBytes }>
|
|
127
118
|
}
|
|
128
119
|
|
|
129
120
|
interface Serialised extends Omit<PendingPayment, 'frame'> {
|
|
@@ -135,8 +126,7 @@ interface Serialised extends Omit<PendingPayment, 'frame'> {
|
|
|
135
126
|
* index-keyed object JSON makes of a `Uint8Array` — entries like that are still
|
|
136
127
|
* sitting in queues on devices), or already revived. Never throws: `readAll`
|
|
137
128
|
* quarantines the WHOLE queue on a throw, and one unreadable byte field must not
|
|
138
|
-
* cost every other payment in it. An unreadable field comes back EMPTY
|
|
139
|
-
* every consumer treats as "nothing held" (`putLinkage` refuses to store it).
|
|
129
|
+
* cost every other payment in it. An unreadable field comes back EMPTY.
|
|
140
130
|
*/
|
|
141
131
|
function reviveBytes(value: unknown): Uint8Array {
|
|
142
132
|
if (value instanceof Uint8Array) return value
|
|
@@ -167,9 +157,7 @@ function toWire(p: PendingPayment): Serialised {
|
|
|
167
157
|
? {
|
|
168
158
|
token: {
|
|
169
159
|
...token,
|
|
170
|
-
certificates: token.certificates.map(c => Array.from(c))
|
|
171
|
-
linkage: token.linkage.map(l => ({ txid: l.txid, payload: Array.from(l.payload) })),
|
|
172
|
-
admissions: token.admissions.map(a => ({ ...a, signature: Array.from(a.signature) }))
|
|
160
|
+
certificates: token.certificates.map(c => Array.from(c))
|
|
173
161
|
}
|
|
174
162
|
}
|
|
175
163
|
: {})
|
|
@@ -188,9 +176,7 @@ function fromWire(s: Serialised): PendingPayment {
|
|
|
188
176
|
? {
|
|
189
177
|
token: {
|
|
190
178
|
...token,
|
|
191
|
-
certificates: (token.certificates
|
|
192
|
-
linkage: (token.linkage ?? []).map(l => ({ txid: l.txid, payload: reviveBytes(l.payload) })),
|
|
193
|
-
admissions: (token.admissions ?? []).map(a => ({ ...a, signature: reviveBytes(a.signature) }))
|
|
179
|
+
certificates: (Array.isArray(token.certificates) ? token.certificates : []).map(reviveBytes)
|
|
194
180
|
}
|
|
195
181
|
}
|
|
196
182
|
: {})
|
|
@@ -415,11 +401,63 @@ export function canInternalizePending(_online: boolean): boolean {
|
|
|
415
401
|
return true
|
|
416
402
|
}
|
|
417
403
|
|
|
404
|
+
/**
|
|
405
|
+
* Failures that must never be allowed to abandon a payment (FIX I).
|
|
406
|
+
*
|
|
407
|
+
* `MAX_PENDING_ATTEMPTS` burns an attempt on an `internalizeAction` failure,
|
|
408
|
+
* but a transient `Block header not found for height N` from a fresh-block
|
|
409
|
+
* BUMP this device has not caught up on yet is a header lag, not a bad frame:
|
|
410
|
+
* the money is real and the next tick will credit it. A structurally bad BEEF
|
|
411
|
+
* is the opposite, and is deliberately NOT matched here.
|
|
412
|
+
*
|
|
413
|
+
* Moved here from the deleted `mandala/drain.ts` (plan 07 Task 16) with its
|
|
414
|
+
* patterns unchanged, less the pre-internalize settlement-write one: that
|
|
415
|
+
* write no longer exists (a missing `color_transfers` row already holds, W1).
|
|
416
|
+
*/
|
|
417
|
+
const RETRIABLE_INTERNALIZE_PATTERNS: readonly RegExp[] = [
|
|
418
|
+
/header not found/i,
|
|
419
|
+
/no header/i,
|
|
420
|
+
/chain ?tracker/i,
|
|
421
|
+
/network request failed/i,
|
|
422
|
+
/timed? ?out/i,
|
|
423
|
+
/econnreset|econnrefused|enotfound|fetch failed/i,
|
|
424
|
+
// internalizeAction posts an unproven payment itself (wallet-toolbox-mobile
|
|
425
|
+
// 2.14.7+); when no broadcaster answered, `failedPostReason` says so.
|
|
426
|
+
/no broadcaster could be reached/i
|
|
427
|
+
]
|
|
428
|
+
|
|
429
|
+
export function isRetriableInternalizeFailure(reason: string | undefined): boolean {
|
|
430
|
+
if (!reason) return false
|
|
431
|
+
return RETRIABLE_INTERNALIZE_PATTERNS.some(p => p.test(reason))
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* How a failure moves the attempt counter.
|
|
436
|
+
*
|
|
437
|
+
* - `auto` (default): one attempt, unless the reason is environmental (FIX I).
|
|
438
|
+
* - `free`: no attempt (a retryable overlay verdict; the money is real and
|
|
439
|
+
* the overlay itself said "later").
|
|
440
|
+
* - `exhaust`: straight to the ceiling (a definitive receipt refusal: the
|
|
441
|
+
* same receipt can only be refused again).
|
|
442
|
+
*/
|
|
443
|
+
export type AttemptPolicy = 'auto' | 'free' | 'exhaust'
|
|
444
|
+
|
|
445
|
+
function nextAttempts(p: PendingPayment, status: PendingStatus, reason: string | undefined, policy: AttemptPolicy) {
|
|
446
|
+
// Counted on failure only: 'processing' is set on the way in to every
|
|
447
|
+
// attempt, so counting there would burn the ceiling without anything having
|
|
448
|
+
// gone wrong.
|
|
449
|
+
if (status !== 'failed') return p.attempts
|
|
450
|
+
if (policy === 'exhaust') return Math.max(p.attempts ?? 0, MAX_PENDING_ATTEMPTS)
|
|
451
|
+
if (policy === 'free') return p.attempts
|
|
452
|
+
return isRetriableInternalizeFailure(reason) ? p.attempts : (p.attempts ?? 0) + 1
|
|
453
|
+
}
|
|
454
|
+
|
|
418
455
|
export async function updateStatus(
|
|
419
456
|
storage: KVStorage,
|
|
420
457
|
id: string,
|
|
421
458
|
status: PendingStatus,
|
|
422
|
-
failureReason?: string
|
|
459
|
+
failureReason?: string,
|
|
460
|
+
attemptPolicy: AttemptPolicy = 'auto'
|
|
423
461
|
): Promise<void> {
|
|
424
462
|
return withQueueLock(async () => {
|
|
425
463
|
let all: PendingPayment[]
|
|
@@ -436,19 +474,7 @@ export async function updateStatus(
|
|
|
436
474
|
status,
|
|
437
475
|
failureReason,
|
|
438
476
|
lastAttemptAt: new Date().toISOString(),
|
|
439
|
-
|
|
440
|
-
// every attempt, so counting there would burn the ceiling without
|
|
441
|
-
// anything having gone wrong.
|
|
442
|
-
//
|
|
443
|
-
// FIX I. And not on EVERY failure either: a transient `Block header
|
|
444
|
-
// not found for height N` from a fresh-block BUMP this device has
|
|
445
|
-
// not caught up on is a header lag, not a bad frame — the money is
|
|
446
|
-
// real and the next tick credits it. Burning an attempt on it is
|
|
447
|
-
// how a good payment reached `MAX_PENDING_ATTEMPTS` and stopped
|
|
448
|
-
// being retried. A structurally bad BEEF is deliberately NOT
|
|
449
|
-
// matched by `isRetriableInternalizeFailure` and still counts.
|
|
450
|
-
attempts:
|
|
451
|
-
status === 'failed' && !isRetriableInternalizeFailure(failureReason) ? (p.attempts ?? 0) + 1 : p.attempts
|
|
477
|
+
attempts: nextAttempts(p, status, failureReason, attemptPolicy)
|
|
452
478
|
}
|
|
453
479
|
: p
|
|
454
480
|
)
|
|
@@ -472,62 +498,25 @@ interface InternalizingWallet {
|
|
|
472
498
|
type AttributePayment = (txid: string, info: { senderIdentityKey: string; receivedVia?: string }) => Promise<void>
|
|
473
499
|
|
|
474
500
|
/**
|
|
475
|
-
*
|
|
476
|
-
*
|
|
477
|
-
*
|
|
478
|
-
* This is the moment this device becomes responsible for submitting the chain
|
|
479
|
-
* (settlement rule 3), so it is where the `token_settlements` row and the
|
|
480
|
-
* evidence the frame carried — its admissions and linkage payloads — have to
|
|
481
|
-
* be persisted. Supplied by the caller rather than called directly from here,
|
|
482
|
-
* for the same reason `attribute` is: this module knows about the KV-backed
|
|
483
|
-
* queue and nothing else, and should stay that way.
|
|
484
|
-
*
|
|
485
|
-
* Optional, and its failure is never the payment's failure: the coin is
|
|
486
|
-
* already credited by the time it runs, and the drain re-reads its own tables
|
|
487
|
-
* on every online tick.
|
|
501
|
+
* The runtime's `nearby.accept`: runs the lib's recipient path on a TOKEN
|
|
502
|
+
* frame (B7: verify online or by COVER, record in the host ledger, then
|
|
503
|
+
* internalize the plain receipt). Throws what the lib throws.
|
|
488
504
|
*/
|
|
489
|
-
export type
|
|
505
|
+
export type TokenAcceptHook = NearbyTokenDeps['accept']
|
|
490
506
|
|
|
491
507
|
/**
|
|
492
|
-
* The
|
|
508
|
+
* The runtime's `nearby.onReceived`: told how a TOKEN frame's receipt
|
|
509
|
+
* settled, credited (`ok`) or failed (`final` = refused for good).
|
|
510
|
+
* The runtime journals `held`/`settled`/`refused` in `color_transfers`.
|
|
493
511
|
*
|
|
494
|
-
*
|
|
495
|
-
*
|
|
496
|
-
* is
|
|
512
|
+
* Supplied by the caller rather than called directly from here: this module
|
|
513
|
+
* knows about the KV-backed queue and nothing else. Optional, and its failure
|
|
514
|
+
* is never the payment's: a credit stays a credit.
|
|
497
515
|
*/
|
|
498
|
-
|
|
516
|
+
export type TokenReceiveHook = NearbyTokenDeps['onReceived']
|
|
499
517
|
|
|
500
|
-
/**
|
|
501
|
-
|
|
502
|
-
* triple `verify.ts` checked the output against — written into
|
|
503
|
-
* `customInstructions` because the basket-insertion path forces every
|
|
504
|
-
* derivation field to undefined, and this is the only slot that survives to
|
|
505
|
-
* the day the coin is spent.
|
|
506
|
-
*/
|
|
507
|
-
const FT_PROTOCOL_ID: [number, string] = [2, 'p mandala token']
|
|
508
|
-
|
|
509
|
-
/** What `internalizeAction` is told about one frame's output. */
|
|
510
|
-
function internalizeOutput(frame: PaymentFrame): Record<string, unknown> {
|
|
511
|
-
if (frame.kind === 'token' && frame.token) {
|
|
512
|
-
// The toolbox never inspects a token script, credits no satoshis, and writes
|
|
513
|
-
// the output `spendable: true, change: false` immediately — which is exactly
|
|
514
|
-
// what makes a received-offline coin re-spendable before anyone has
|
|
515
|
-
// submitted anything (spec §1.6's chained offline hops).
|
|
516
|
-
return {
|
|
517
|
-
outputIndex: frame.outputIndex,
|
|
518
|
-
protocol: 'basket insertion',
|
|
519
|
-
insertionRemittance: {
|
|
520
|
-
basket: MANDALA_BASKET,
|
|
521
|
-
customInstructions: JSON.stringify({
|
|
522
|
-
protocolID: FT_PROTOCOL_ID,
|
|
523
|
-
keyID: `${frame.derivationPrefix} ${frame.derivationSuffix}`,
|
|
524
|
-
counterparty: frame.senderIdentityKey,
|
|
525
|
-
direction: 'received'
|
|
526
|
-
}),
|
|
527
|
-
tags: ['mandala', 'received', frame.token.assetId]
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
}
|
|
518
|
+
/** What `internalizeAction` is told about a BSV frame's output. */
|
|
519
|
+
function walletPaymentOutput(frame: PaymentFrame): Record<string, unknown> {
|
|
531
520
|
return {
|
|
532
521
|
outputIndex: frame.outputIndex,
|
|
533
522
|
protocol: 'wallet payment',
|
|
@@ -539,136 +528,162 @@ function internalizeOutput(frame: PaymentFrame): Record<string, unknown> {
|
|
|
539
528
|
}
|
|
540
529
|
}
|
|
541
530
|
|
|
531
|
+
/**
|
|
532
|
+
* The facts the receive hook reports, read from the frame itself: the txid
|
|
533
|
+
* `internalizeAction` credits (the AtomicBEEF subject) and the exact units of
|
|
534
|
+
* the named output (never a frame field). Undefined when the bytes do not
|
|
535
|
+
* yield them; the module still decides the internalize, and a receipt nobody
|
|
536
|
+
* journals is held by the broadcast hold all the same (a missing row holds, W1).
|
|
537
|
+
*/
|
|
538
|
+
function tokenReceiptFacts(frame: PaymentFrame): Parameters<TokenReceiveHook>[0] | undefined {
|
|
539
|
+
if (frame.kind !== 'token' || frame.token === undefined) return undefined
|
|
540
|
+
try {
|
|
541
|
+
const tx = Transaction.fromAtomicBEEF(Array.from(frame.transaction))
|
|
542
|
+
const txid = tx.id('hex')
|
|
543
|
+
const output = tx.outputs[frame.outputIndex]
|
|
544
|
+
const decoded = output ? decodeToken(output.lockingScript, txid, frame.outputIndex) : null
|
|
545
|
+
if (decoded === null || decoded.role !== 'value' || decoded.assetId !== frame.token.assetId) return undefined
|
|
546
|
+
return {
|
|
547
|
+
txid,
|
|
548
|
+
assetId: frame.token.assetId,
|
|
549
|
+
units: decoded.amount,
|
|
550
|
+
counterpartyKey: frame.senderIdentityKey,
|
|
551
|
+
outputIndex: frame.outputIndex
|
|
552
|
+
}
|
|
553
|
+
} catch (e) {
|
|
554
|
+
console.warn('[localpay] could not read the token receipt’s own facts:', messageOf(e))
|
|
555
|
+
return undefined
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Runs the receive hook; its failure is logged, never the payment's. */
|
|
560
|
+
async function reportReceipt(
|
|
561
|
+
onTokenReceived: TokenReceiveHook | undefined,
|
|
562
|
+
facts: Parameters<TokenReceiveHook>[0] | undefined,
|
|
563
|
+
outcome: Parameters<TokenReceiveHook>[1]
|
|
564
|
+
): Promise<void> {
|
|
565
|
+
if (!onTokenReceived || !facts) return
|
|
566
|
+
try {
|
|
567
|
+
await onTokenReceived(facts, outcome)
|
|
568
|
+
} catch (e) {
|
|
569
|
+
console.warn('[localpay] the token receipt hook failed:', messageOf(e))
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
542
573
|
export async function processPending(
|
|
543
574
|
wallet: InternalizingWallet,
|
|
544
575
|
storage: KVStorage,
|
|
545
576
|
originator: string,
|
|
546
577
|
attribute?: AttributePayment,
|
|
547
|
-
onTokenCredited?: TokenCreditedHook,
|
|
548
578
|
/**
|
|
549
|
-
* TOKEN FRAMES ONLY
|
|
550
|
-
*
|
|
551
|
-
*
|
|
552
|
-
* `internalizeAction` forces a broadcast of its own through
|
|
553
|
-
* `shareReqsWithWorld` → `attemptToPostReqsToNetwork`, and the guard that
|
|
554
|
-
* stops an unadmitted token transaction going out there is a lookup of this
|
|
555
|
-
* txid in `token_settlements`. With the row written only afterwards — which
|
|
556
|
-
* is all `onTokenCredited` can do — the guard finds nothing on the FIRST
|
|
557
|
-
* internalize and falls straight through to a real, unmediated broadcast. The
|
|
558
|
-
* common shop case (payee has Wi-Fi, payer none) hits that path every time.
|
|
579
|
+
* TOKEN FRAMES ONLY: the runtime's `nearby.onReceived`, run once the
|
|
580
|
+
* receipt settles either way.
|
|
559
581
|
*
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
*
|
|
582
|
+
* There is deliberately no hook BEFORE the internalize. The toolbox forces
|
|
583
|
+
* a broadcast inside `internalizeAction`, and what holds an unsettled
|
|
584
|
+
* 1Color tx there is the broadcast hold: the lib records the receipt in the
|
|
585
|
+
* host ledger before it internalizes (B7), which marks the tx as this
|
|
586
|
+
* wallet's custody, and its `color_transfers` row is not `settled` (a
|
|
587
|
+
* MISSING row holds). So the journal row written after the credit can only
|
|
588
|
+
* release, never fail open.
|
|
589
|
+
*/
|
|
590
|
+
onTokenReceived?: TokenReceiveHook,
|
|
591
|
+
/**
|
|
592
|
+
* TOKEN FRAMES ONLY: the runtime's `nearby.accept`. Without it a token
|
|
593
|
+
* frame is never internalized here (no plain internalize can credit a
|
|
594
|
+
* Mandala receipt the host has not verified); it fails retriably.
|
|
564
595
|
*/
|
|
565
|
-
|
|
596
|
+
acceptToken?: TokenAcceptHook
|
|
566
597
|
): Promise<{ id: string; success: boolean; error?: string }[]> {
|
|
567
598
|
const results: { id: string; success: boolean; error?: string }[] = []
|
|
568
599
|
for (const p of await getRetryable(storage)) {
|
|
569
600
|
await updateStatus(storage, p.id, 'processing')
|
|
601
|
+
const isToken = p.frame.kind === 'token'
|
|
602
|
+
const facts = isToken ? tokenReceiptFacts(p.frame) : undefined
|
|
603
|
+
let offline = false
|
|
570
604
|
try {
|
|
571
|
-
if (
|
|
572
|
-
//
|
|
573
|
-
//
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
605
|
+
if (isToken) {
|
|
606
|
+
// The BRC-207 receipt path of the lib (B7): the v4 body rebuilt from
|
|
607
|
+
// the frame, verified online or by COVER, recorded in the host ledger,
|
|
608
|
+
// then the plain receipt internalized into `p color <assetTag>`.
|
|
609
|
+
if (!acceptToken) throw new Error('token receipts are not available on this network (ERR_UNAVAILABLE)')
|
|
610
|
+
offline = (await acceptToken(p.frame)).offline
|
|
611
|
+
} else {
|
|
612
|
+
await wallet.internalizeAction(
|
|
613
|
+
{
|
|
614
|
+
tx: Array.from(p.frame.transaction),
|
|
615
|
+
outputs: [walletPaymentOutput(p.frame)],
|
|
616
|
+
// The activity list uses the description as the row title, so it
|
|
617
|
+
// says what happened — never who: a nearby transfer is blinded, so
|
|
618
|
+
// the payer's key it used to carry told the user nothing. The
|
|
619
|
+
// counterparty face is recovered from outputs.senderIdentityKey,
|
|
620
|
+
// which is why the rail label carries no key. A sender's note on
|
|
621
|
+
// the frame overrides this fixed wording, same as the message-box
|
|
622
|
+
// rail's PeerPay note.
|
|
623
|
+
description: truncateUtf8Bytes(
|
|
624
|
+
(p.frame.note?.trim() || 'Received BSV').padEnd(5),
|
|
625
|
+
MAX_INTERNALIZE_DESCRIPTION_BYTES
|
|
626
|
+
),
|
|
627
|
+
labels: [PEERPAY_LABEL]
|
|
628
|
+
},
|
|
629
|
+
originator
|
|
630
|
+
)
|
|
590
631
|
}
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
// on the frame overrides this fixed wording, same as the message-box
|
|
604
|
-
// rail's PeerPay note.
|
|
605
|
-
description: truncateUtf8Bytes(
|
|
606
|
-
(p.frame.note?.trim() || (p.frame.kind === 'token' ? 'Received token' : 'Received BSV')).padEnd(5),
|
|
607
|
-
MAX_INTERNALIZE_DESCRIPTION_BYTES
|
|
608
|
-
),
|
|
609
|
-
labels:
|
|
610
|
-
p.frame.kind === 'token'
|
|
611
|
-
? [PEERPAY_LABEL, MANDALA_ACTION_LABEL, MANDALA_TOKEN_SPEND_LABEL]
|
|
612
|
-
: [PEERPAY_LABEL]
|
|
613
|
-
},
|
|
614
|
-
originator
|
|
615
|
-
)
|
|
616
|
-
await updateStatus(storage, p.id, 'completed')
|
|
617
|
-
results.push({ id: p.id, success: true })
|
|
618
|
-
|
|
619
|
-
// The SECOND settlement write, and an idempotent re-derivation of the
|
|
620
|
-
// first: `onTokenHeld` already wrote the row before the internalize, and
|
|
621
|
-
// `upsertSettlement` never moves `state` on conflict, so this re-runs the
|
|
622
|
-
// same population harmlessly and is what still covers a caller that
|
|
623
|
-
// supplies only this hook. Isolated from the try/catch above for the same
|
|
624
|
-
// reason `attribute` is: the coin is credited by this point, so a failing
|
|
625
|
-
// write must not retroactively mark the payment 'failed' and
|
|
626
|
-
// re-internalize it.
|
|
627
|
-
if (onTokenCredited && p.frame.kind === 'token') {
|
|
628
|
-
try {
|
|
629
|
-
const txid = Beef.fromBinary(p.frame.transaction).atomicTxid
|
|
630
|
-
if (txid) await onTokenCredited(p.frame, txid)
|
|
631
|
-
} catch (e) {
|
|
632
|
-
// The drain owns the `token_settlements` row independently and
|
|
633
|
-
// re-reads its own tables on every online tick, so a lost write here
|
|
634
|
-
// costs a later reconciliation pass, not the payment.
|
|
635
|
-
console.warn(
|
|
636
|
-
'[localpay] token credited but settlement write failed:',
|
|
637
|
-
e instanceof Error ? e.message : String(e)
|
|
638
|
-
)
|
|
639
|
-
}
|
|
632
|
+
} catch (e) {
|
|
633
|
+
const error = failedPostReason(e) ?? messageOf(e)
|
|
634
|
+
if (isToken) {
|
|
635
|
+
// A definitive refusal (the lib's receive classifier: a malformed or
|
|
636
|
+
// contradicting body, a refused hop, a final verdict) goes straight to
|
|
637
|
+
// the ceiling and is journaled `refused`. A transport failure never
|
|
638
|
+
// burns an attempt. Anything else follows the BSV rule (FIX I).
|
|
639
|
+
const final = !isRetriableReceiptFailure(e)
|
|
640
|
+
await updateStatus(storage, p.id, 'failed', error, final ? 'exhaust' : isTransportReceiptFailure(e) ? 'free' : 'auto')
|
|
641
|
+
await reportReceipt(onTokenReceived, facts, { ok: false, code: receiptFailureCode(e), final })
|
|
642
|
+
} else {
|
|
643
|
+
await updateStatus(storage, p.id, 'failed', error)
|
|
640
644
|
}
|
|
645
|
+
results.push({ id: p.id, success: false, error })
|
|
646
|
+
continue
|
|
647
|
+
}
|
|
641
648
|
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
|
|
649
|
+
// Credited. The receipt is reported BEFORE the entry is marked completed:
|
|
650
|
+
// a crash in between re-runs the (idempotent, 0207 A.83) internalize and
|
|
651
|
+
// the (INSERT OR IGNORE) journal write, where the other order would leave
|
|
652
|
+
// a credit nobody ever journals. Its failure never un-credits the coin.
|
|
653
|
+
if (isToken) await reportReceipt(onTokenReceived, facts, { ok: true, offline })
|
|
654
|
+
try {
|
|
655
|
+
await updateStatus(storage, p.id, 'completed')
|
|
656
|
+
} catch (e) {
|
|
657
|
+
// The coin is credited; a queue write fault leaves the entry to be
|
|
658
|
+
// replayed (idempotently) on the next pass, never marked failed.
|
|
659
|
+
console.warn('[localpay] credited, but the queue could not record it:', messageOf(e))
|
|
660
|
+
}
|
|
661
|
+
results.push({ id: p.id, success: true })
|
|
662
|
+
|
|
663
|
+
// Best-effort, and deliberately isolated: by this point the payment has
|
|
664
|
+
// already completed successfully, so a failure here — a bad frame, a
|
|
665
|
+
// locked db — must not retroactively turn it into a 'failed' entry, and
|
|
666
|
+
// must not stop the loop from reaching whatever else is queued behind it.
|
|
667
|
+
if (attribute) {
|
|
668
|
+
try {
|
|
669
|
+
// internalizeAction's own resolved value carries no txid (the SDK's
|
|
670
|
+
// InternalizeActionResult is just `{ accepted: true }`), so it has to
|
|
671
|
+
// be derived from the frame itself. `frame.transaction` is an
|
|
672
|
+
// AtomicBEEF (see codec.ts), and `atomicTxid` is exactly the subject
|
|
673
|
+
// txid `internalizeAction` used internally to build the request that
|
|
674
|
+
// `holdReqsOffline` may have queued — see Beef.d.ts / the toolbox's
|
|
675
|
+
// own `validateAtomicBeef`.
|
|
676
|
+
const txid = Beef.fromBinary(p.frame.transaction).atomicTxid
|
|
677
|
+
if (txid) {
|
|
678
|
+
await attribute(txid, {
|
|
679
|
+
senderIdentityKey: p.frame.senderIdentityKey,
|
|
680
|
+
receivedVia: p.receivedVia
|
|
681
|
+
})
|
|
666
682
|
}
|
|
683
|
+
} catch {
|
|
684
|
+
// Not a readable BEEF, or the attribution write itself failed.
|
|
685
|
+
// Either way this is silent: the payment already succeeded above.
|
|
667
686
|
}
|
|
668
|
-
} catch (e) {
|
|
669
|
-
const error = failedPostReason(e) ?? (e instanceof Error ? e.message : String(e))
|
|
670
|
-
await updateStatus(storage, p.id, 'failed', error)
|
|
671
|
-
results.push({ id: p.id, success: false, error })
|
|
672
687
|
}
|
|
673
688
|
}
|
|
674
689
|
return results
|