@bsv/expo-wallet-toolbox 0.7.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -71,8 +71,14 @@ import { getPending, type KVStorage, type TokenCreditedHook } from '../localpay/
71
71
  import type { PaymentFrame } from '../localpay/codec'
72
72
  import type { VerifyAdmissionFn } from '../localpay/settlementAck'
73
73
  import type { LockToPayee, TokenBuildDeps } from '../localpay/build'
74
- import { frameTokenAmount, tokenFrameSourcesFromOfflineActions, tokenFrameSourcesFromPending } from '../offline/tokenFrames'
74
+ import { MAX_TOKEN_DECIMALS } from '../localpay/session'
75
+ import {
76
+ frameTokenAmount,
77
+ tokenFrameSourcesFromOfflineActions,
78
+ tokenFrameSourcesFromPending
79
+ } from '../offline/tokenFrames'
75
80
  import { resendTokenTransfer, type TokenResendAction, type TokenResendOutcome } from './resendTransfer'
81
+ import { preHoldInboxSettlements } from './inboxPrehold'
76
82
  import type { CoverBundle, CoverVerifier } from './bundle'
77
83
  import { assembleBundle } from './bundle'
78
84
  import {
@@ -272,6 +278,21 @@ export interface CreateMandalaRuntimeArgs {
272
278
  const TOKEN_LIST_PAGE = 1000
273
279
  const TOKEN_LIST_MAX_PAGES = 1000
274
280
 
281
+ /**
282
+ * `meta.decimals` comes from the overlay's own asset registry — an external,
283
+ * issuer-controlled source — and flows straight into `TokenAssetInfo
284
+ * .decimals`, from there into every `ui/tokenFormat.ts` formatter downstream
285
+ * (XR-043: an unbounded decimals figure is how a malicious registry entry
286
+ * crashes the balance/activity UI, not just a session QR). Out-of-range or
287
+ * unresolvable reads as "unknown" — 0, the same fallback the previous
288
+ * `Number(meta?.decimals) || 0` already used — never a value past what any
289
+ * `ui/tokenFormat.ts` formatter will accept.
290
+ */
291
+ function safeTokenDecimals(value: unknown): number {
292
+ const n = Number(value)
293
+ return Number.isInteger(n) && n >= 0 && n <= MAX_TOKEN_DECIMALS ? n : 0
294
+ }
295
+
275
296
  /**
276
297
  * Every lib call runs as the admin originator.
277
298
  *
@@ -371,11 +392,39 @@ function referenceOf(result: unknown): { reference?: string } {
371
392
  return typeof reference === 'string' && reference.length > 0 ? { reference } : {}
372
393
  }
373
394
 
395
+ /**
396
+ * XR-034/XR-035: the payee already holds the bytes by the time this runs, so a
397
+ * transient write fault here (a busy/locked SQLite, a brief disk hiccup) must
398
+ * not be the only thing standing between "journaled" and "no durable record
399
+ * exists at all" — the latter is what leaves `wrapAbortActionForSettlements`
400
+ * nothing to block on. Three attempts, a short fixed backoff: enough for an
401
+ * ordinary transient fault to clear, small enough not to make a payer wait on
402
+ * a send that has already gone out. `upsertSettlement` is a plain upsert keyed
403
+ * on `txid`, so retrying it after a failed attempt is safe — nothing partial
404
+ * can have been committed for the caller to retry over.
405
+ */
406
+ async function upsertSettlementDurably(
407
+ store: Pick<SettlementStore, 'upsertSettlement'>,
408
+ row: Parameters<SettlementStore['upsertSettlement']>[0]
409
+ ): Promise<void> {
410
+ const attempts = 3
411
+ for (let attempt = 1; attempt <= attempts; attempt++) {
412
+ try {
413
+ await store.upsertSettlement(row)
414
+ return
415
+ } catch (e) {
416
+ if (attempt === attempts) throw e
417
+ await new Promise(resolve => setTimeout(resolve, attempt * 100))
418
+ }
419
+ }
420
+ }
421
+
374
422
  /** A store for a runtime with no database: every read is empty, every write a no-op. */
375
423
  function nullStore(): SettlementStore {
376
424
  return {
377
425
  getSettlement: async () => undefined,
378
426
  getSettlementByReference: async () => undefined,
427
+ hasUnresolvedLegacyBlockedRows: async () => false,
379
428
  listSettlements: async () => [],
380
429
  upsertSettlement: async () => undefined,
381
430
  advanceSettlement: async () => false,
@@ -421,7 +470,11 @@ interface ListedTokenOutput {
421
470
  * ux copy means by "settled with {{issuer}}". The broadcast that follows is
422
471
  * this device's bookkeeping, not the payment's fate.
423
472
  */
424
- export function activityStatusOf(row: TokenSettlementRow, nowMs: number, olderThanMs = STUCK_AFTER_MS): TokenActivityStatus {
473
+ export function activityStatusOf(
474
+ row: TokenSettlementRow,
475
+ nowMs: number,
476
+ olderThanMs = STUCK_AFTER_MS
477
+ ): TokenActivityStatus {
425
478
  switch (row.state) {
426
479
  case 'broadcast':
427
480
  case 'admitted':
@@ -486,7 +539,9 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
486
539
 
487
540
  const metadataCache = new Map<string, { label?: string; ticker?: string; decimals?: number } | null>()
488
541
  const resolveMetadata = args.resolveMetadata ?? (async (assetId: string) => await resolveAssetMetadata(assetId))
489
- const metadataOf = async (assetId: string): Promise<{ label?: string; ticker?: string; decimals?: number } | null> => {
542
+ const metadataOf = async (
543
+ assetId: string
544
+ ): Promise<{ label?: string; ticker?: string; decimals?: number } | null> => {
490
545
  const cached = metadataCache.get(assetId)
491
546
  if (cached !== undefined) return cached
492
547
  let resolved: { label?: string; ticker?: string; decimals?: number } | null = null
@@ -508,7 +563,7 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
508
563
  assetId,
509
564
  label: meta?.label && meta.label !== '' ? meta.label : `${assetId.slice(0, 20)}…`,
510
565
  ticker: meta?.ticker ?? '',
511
- decimals: Number(meta?.decimals) || 0,
566
+ decimals: safeTokenDecimals(meta?.decimals),
512
567
  ...(typeof issuerName === 'string' && issuerName !== '' ? { issuerName } : {}),
513
568
  overlayUrl,
514
569
  overlayIdentityKey
@@ -538,7 +593,10 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
538
593
  const isAdmittedIn = (rows: OverlayRegistryRow[], key: string): boolean =>
539
594
  rows.some(r => r.identityKey.toLowerCase() === key.toLowerCase() && r.status === 'admitted')
540
595
 
541
- const loadAssetStatusSnapshot = async (assetId: string, opts: { force?: boolean } = {}): Promise<AssetStatusSnapshot> => {
596
+ const loadAssetStatusSnapshot = async (
597
+ assetId: string,
598
+ opts: { force?: boolean } = {}
599
+ ): Promise<AssetStatusSnapshot> => {
542
600
  const [state, registryRows, meta] = await Promise.all([
543
601
  (async () => {
544
602
  try {
@@ -997,7 +1055,9 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
997
1055
  signerKey
998
1056
  })
999
1057
  if (!trusted) {
1000
- devLog(`[mandala] /submit of ${txid}: admission signature does not verify under the configured key; not an admission`)
1058
+ devLog(
1059
+ `[mandala] /submit of ${txid}: admission signature does not verify under the configured key; not an admission`
1060
+ )
1001
1061
  return { kind: 'unavailable', code: 'ERR_BAD_ADMISSION', retryable: true }
1002
1062
  }
1003
1063
  return { kind: 'admitted', outputsToAdmit: admitted.outputsToAdmit, signatureHex, signerKey }
@@ -1038,7 +1098,9 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1038
1098
  const resolveEmptyAdmittedSet = async (txid: string): Promise<OverlayVerdict> => {
1039
1099
  const onRecord = await fetchAdmission(overlayUrl, txid)
1040
1100
  if (onRecord === undefined || onRecord.kind === 'unavailable') {
1041
- devLog(`[mandala] /submit of ${txid} admitted nothing and no admission is on record; the step is retried next pass`)
1101
+ devLog(
1102
+ `[mandala] /submit of ${txid} admitted nothing and no admission is on record; the step is retried next pass`
1103
+ )
1042
1104
  return { kind: 'unavailable', code: 'ERR_EMPTY_ADMISSION', retryable: true }
1043
1105
  }
1044
1106
  devLog(`[mandala] /submit of ${txid} admitted nothing; the overlay's record says '${onRecord.kind}'`)
@@ -1081,7 +1143,17 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1081
1143
  devLog(`[mandala] could not read the cached admission of ${txid}:`, e)
1082
1144
  continue
1083
1145
  }
1084
- if (cached && cached.signatureHex !== '' && cached.signerKey === overlayIdentityKey) continue
1146
+ // XR-038: a cached admission that does not cover every vout THIS device
1147
+ // currently holds of `txid` is not "good enough, skip" — it would hand a
1148
+ // future offline payee an entry that (rightly) never covers the coin
1149
+ // being spent, so the fetch below still runs and the row is refreshed.
1150
+ if (
1151
+ cached &&
1152
+ cached.signatureHex !== '' &&
1153
+ cached.signerKey === overlayIdentityKey &&
1154
+ vouts.every(v => cached.outputsToAdmit.includes(v))
1155
+ )
1156
+ continue
1085
1157
  const verdict = await fetchAdmission(overlayUrl, txid)
1086
1158
  if (verdict?.kind !== 'admitted') continue
1087
1159
  try {
@@ -1100,15 +1172,16 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1100
1172
  }
1101
1173
  const unadmitted = vouts.filter(v => !verdict.outputsToAdmit.includes(v))
1102
1174
  if (unadmitted.length > 0) {
1103
- console.warn(`[mandala] ${txid} is admitted but not for held output(s) ${unadmitted.join(',')}; those coins will not cover offline`)
1175
+ console.warn(
1176
+ `[mandala] ${txid} is admitted but not for held output(s) ${unadmitted.join(',')}; those coins will not cover offline`
1177
+ )
1104
1178
  }
1105
1179
  }
1106
1180
  return fetched
1107
1181
  }
1108
1182
 
1109
1183
  /** DerSignature (string | number[] | Uint8Array), as the hex string OverlayVerdict wants. */
1110
- const derSignatureHex = (sig: DerSignature): string =>
1111
- typeof sig === 'string' ? sig : Utils.toHex(Array.from(sig))
1184
+ const derSignatureHex = (sig: DerSignature): string => (typeof sig === 'string' ? sig : Utils.toHex(Array.from(sig)))
1112
1185
 
1113
1186
  /**
1114
1187
  * GET /admin/admission/:txid (wire contract v2 §3), mapped onto
@@ -1386,6 +1459,25 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1386
1459
  })
1387
1460
  continue
1388
1461
  }
1462
+ // XR-042: `entry.kind === 'refused'/'evicted'` above (in `fetchAdmission`)
1463
+ // is the raw, UNSIGNED overlay HTTP response — unlike the 'admitted'
1464
+ // branch a few lines up, nothing here is checked against `overlayIdentityKey`
1465
+ // at all. A row this device already holds a σ_I-VERIFIED admission for
1466
+ // (`row.admissionSignatureHex`/`admissionOutputs`, only ever written
1467
+ // after `verifyFetchedAdmission` succeeded — see `fetchAdmission` and
1468
+ // `receiveFromInbox` above) is therefore not something a later unsigned
1469
+ // negative may downgrade: that positive is cryptographic and this
1470
+ // negative is not, so the positive stands. Reported as unattested
1471
+ // rather than removed — the next pass asks again, exactly like an
1472
+ // unreachable overlay.
1473
+ if (row.admissionSignatureHex && row.admissionOutputs && row.admissionOutputs.length > 0) {
1474
+ devLog(
1475
+ `[mandala] token review: ${row.txid} already carries a verified admission; ` +
1476
+ `ignoring the unsigned ${verdict.kind} verdict`
1477
+ )
1478
+ review.unattested++
1479
+ continue
1480
+ }
1389
1481
  const to: TokenSettlementState = verdict.kind === 'evicted' ? 'orphaned' : 'refused'
1390
1482
  await store.advanceSettlement(row.txid, [...NON_TERMINAL_SETTLEMENT_STATES], to, {
1391
1483
  refusedCode: verdict.kind === 'refused' ? verdict.code : undefined,
@@ -1807,6 +1899,11 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1807
1899
  amountBaseUnits: frameTokenAmount(frame),
1808
1900
  overlayUrl,
1809
1901
  overlayIdentityKey,
1902
+ // XR-038: the payee's own output — read as 0 when the frame carries none,
1903
+ // same as `frameTokenAmount` already does — so a cached admission that
1904
+ // covers some OTHER output of this txid can never stand in for a real
1905
+ // `/submit` of the one THIS device is actually owed.
1906
+ relevantVout: frame.outputIndex ?? 0,
1810
1907
  createdAt: existing?.createdAt
1811
1908
  })
1812
1909
  emit()
@@ -1840,7 +1937,12 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1840
1937
  // branches on it, and `putLinkage` never overwrites a row already here.)
1841
1938
  await cacheFrameEvidence(frame, `a ${state} frame`, { linkageSource: 'minted' })
1842
1939
  const existing = await store.getSettlement(txid)
1843
- await store.upsertSettlement({
1940
+ // XR-036: retried, same reason as `sendToHandle`'s own journal write
1941
+ // (`upsertSettlementDurably`) — `payerHold.ts`'s `holdSentPaymentOffline`
1942
+ // keeps its queue row non-drainable until THIS write lands, so a transient
1943
+ // fault here should not be the difference between a guarded hold and one
1944
+ // stuck at 'parked' for a later manual reconciliation.
1945
+ await upsertSettlementDurably(store, {
1844
1946
  txid,
1845
1947
  role: 'sent',
1846
1948
  assetId: token.assetId,
@@ -1851,6 +1953,11 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1851
1953
  amountBaseUnits: frameTokenAmount(frame),
1852
1954
  overlayUrl,
1853
1955
  overlayIdentityKey,
1956
+ // XR-038: same convention as `onTokenHeld` — output 0 is the payee's
1957
+ // unless the frame says otherwise, and that is the one output a cached
1958
+ // admission has to cover before the drain may skip a real `/submit` of
1959
+ // this tip.
1960
+ relevantVout: frame.outputIndex ?? 0,
1854
1961
  // The nearby rail's half of the abort guard: the action that built this
1855
1962
  // tip is `noSend` and stays that way until the drain broadcasts it, so
1856
1963
  // the reference is recorded the same moment the row is. Absent for a
@@ -1940,9 +2047,7 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1940
2047
  overlayUrl,
1941
2048
  overlayIdentityKey,
1942
2049
  linkage:
1943
- bytes.offChainValues.length > 0
1944
- ? [{ txid: id, payload: Uint8Array.from(bytes.offChainValues) }]
1945
- : []
2050
+ bytes.offChainValues.length > 0 ? [{ txid: id, payload: Uint8Array.from(bytes.offChainValues) }] : []
1946
2051
  },
1947
2052
  transaction: Uint8Array.from(bytes.beef)
1948
2053
  },
@@ -1993,6 +2098,10 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
1993
2098
  amountBaseUnits: Number(transfer.amount) || undefined,
1994
2099
  overlayUrl,
1995
2100
  overlayIdentityKey,
2101
+ // XR-038: `outputIndex` is where the SENDER's (randomised) tx put our
2102
+ // output — 0 for legacy messages — the one output a cached admission
2103
+ // has to cover before the drain may skip a real `/submit` of this txid.
2104
+ relevantVout: transfer.outputIndex ?? 0,
1996
2105
  ...(verified && admission
1997
2106
  ? { admissionOutputs: [...admission.outputsToAdmit], admissionSignatureHex: admission.signature }
1998
2107
  : {}),
@@ -2004,17 +2113,19 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2004
2113
  * The payer-side build's deps, carrying the same FIX H anchor.
2005
2114
  *
2006
2115
  * `assembleBundle` forwards this device's cached admissions onward as its own
2007
- * claim about the chain, and `buildTokenPaymentFrame` reads the asset's
2008
- * `overlayIdentityKey` off the SESSION — i.e. off the payee's request. Handing
2009
- * the build the configured key and verifier here is what lets it anchor on
2010
- * configuration instead (§9.10). Narrowed from a value for the same reason
2011
- * `tokenDeps` is.
2116
+ * claim about the chain, and (until XR-104) `buildTokenPaymentFrame` read the
2117
+ * asset's `overlayIdentityKey` off the SESSION — i.e. off the payee's
2118
+ * request. Handing the build the configured key, URL and verifier here is
2119
+ * what lets it anchor on configuration instead (§9.10): `buildTokenPaymentFrame`
2120
+ * now refuses outright when `session.asset`'s overlay does not match these.
2121
+ * Narrowed from a value for the same reason `tokenDeps` is.
2012
2122
  */
2013
2123
  const tokenBuildDepsValue = {
2014
2124
  store,
2015
2125
  lockToPayee,
2016
2126
  commitBlinding: blindingCommit,
2017
2127
  overlayIdentityKey,
2128
+ overlayUrl,
2018
2129
  verifyAdmission
2019
2130
  }
2020
2131
  const tokenBuildDeps: TokenBuildDeps = tokenBuildDepsValue
@@ -2102,7 +2213,9 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2102
2213
  return await resendTokenTransfer(txid, {
2103
2214
  blindingRecord: async id => {
2104
2215
  const record = await blindingGet(id)
2105
- return record ? { recipient: record.recipient, senderBlinded: record.senderBlinded, keyID: record.keyID } : undefined
2216
+ return record
2217
+ ? { recipient: record.recipient, senderBlinded: record.senderBlinded, keyID: record.keyID }
2218
+ : undefined
2106
2219
  },
2107
2220
  // The `mandala`-labelled action with its outputs: both rails write the
2108
2221
  // label (the nearby rail since 2026-09-16) and the payee output's marker.
@@ -2126,7 +2239,11 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2126
2239
  const cached = await store.getAdmission(id)
2127
2240
  // An unsigned entry (see `submit`) is bookkeeping, not evidence to forward.
2128
2241
  if (!cached || cached.signatureHex === '' || cached.signerKey === '') return undefined
2129
- return { outputsToAdmit: cached.outputsToAdmit, signatureHex: cached.signatureHex, signerKey: cached.signerKey }
2242
+ return {
2243
+ outputsToAdmit: cached.outputsToAdmit,
2244
+ signatureHex: cached.signatureHex,
2245
+ signerKey: cached.signerKey
2246
+ }
2130
2247
  },
2131
2248
  journal: { put: notifyPut, remove: notifyRemove },
2132
2249
  sendMessage: args => box.sendMessage(args as never),
@@ -2263,7 +2380,13 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2263
2380
  devLog(`[mandala] sent ${result.txid} but could not cache its evidence:`, e)
2264
2381
  }
2265
2382
  try {
2266
- await store.upsertSettlement({
2383
+ // XR-034/XR-035: retried (see `upsertSettlementDurably`) because this
2384
+ // row is the ONLY durable evidence of the hand-over — there is no
2385
+ // queue row and no pre-hand-over marker (the reference below does not
2386
+ // exist until `transferTokens` has already returned it), so losing
2387
+ // this write to one transient fault leaves the abort guard nothing to
2388
+ // block on for a payment the payee may already hold or have submitted.
2389
+ await upsertSettlementDurably(store, {
2267
2390
  txid: result.txid,
2268
2391
  role: 'sent',
2269
2392
  assetId,
@@ -2289,9 +2412,10 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2289
2412
  ...referenceOf(result)
2290
2413
  })
2291
2414
  } catch (e) {
2292
- // The transfer is committed; a journal failure costs a later
2293
- // reconciliation pass, never the payment.
2294
- devLog(`[mandala] sent ${result.txid} but could not journal it:`, e)
2415
+ // Every retry was exhausted: the transfer is still committed (the
2416
+ // payee already has the bytes), and this is now genuinely a later
2417
+ // reconciliation pass's problem, not the payment's.
2418
+ devLog(`[mandala] sent ${result.txid} but could not journal it after retrying:`, e)
2295
2419
  }
2296
2420
  emit()
2297
2421
  // `notified === false` is "committed, but the payee has not been told
@@ -2362,12 +2486,62 @@ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRun
2362
2486
  devLog('[mandala] no MessageBox client for the inbox drain:', e)
2363
2487
  return { credited: 0, failed: 0 }
2364
2488
  }
2365
- const result = await receiveTokens({
2366
- wallet: bound,
2367
- messageBoxClient: box,
2368
- processed: processedMessages,
2369
- settle: settleThroughDrain
2370
- })
2489
+
2490
+ // P1-4: for every hand-over message this pass can decode, write its
2491
+ // settlement row through the SAME settleThroughDrain/onTokenHeld path
2492
+ // below BEFORE receiveTokens ever gets to call internalizeAction — see
2493
+ // inboxPrehold.ts's header for exactly why that ordering is the whole
2494
+ // fix. `cover` here is the real pure walk, crossing the app/lib
2495
+ // @bsv/sdk seam the same way `libCoverArgs` does everywhere else in
2496
+ // this file (never a reimplementation of its verdict).
2497
+ let excluded: Set<string>
2498
+ try {
2499
+ excluded = await preHoldInboxSettlements({
2500
+ messageBoxClient: box,
2501
+ cover: (tip, bundle) =>
2502
+ coverWalk(
2503
+ ...libCoverArgs(
2504
+ tip,
2505
+ {
2506
+ assetId: bundle.assetId,
2507
+ overlayIdentityKey,
2508
+ tip,
2509
+ beef: bundle.beef,
2510
+ linkage: bundle.linkage,
2511
+ admissions: bundle.admissions
2512
+ },
2513
+ overlayIdentityKey
2514
+ )
2515
+ ),
2516
+ settle: settleThroughDrain
2517
+ })
2518
+ } catch (e) {
2519
+ // The pass could not even see the inbox, so there is nothing to
2520
+ // filter with — skip the whole receive rather than let a hand-over
2521
+ // credit run against receiveTokens with no guard in front of it.
2522
+ devLog('[mandala] inbox pre-hold pass failed; skipping this receive pass:', e)
2523
+ return { credited: 0, failed: 0 }
2524
+ }
2525
+ // A message whose pre-hold write failed is kept out of THIS
2526
+ // receiveTokens call only (`processed` is the library's own message
2527
+ // filter — receiveTokens skips any id already in it) and put back
2528
+ // immediately after, so a transient failure here retries whole on the
2529
+ // next drain tick instead of being credited on a bare table.
2530
+ for (const id of excluded) processedMessages.add(id)
2531
+ let result: {
2532
+ accepted: ReceivedTransfer[]
2533
+ failed: { messageId: string; error: unknown; refusedCode?: string }[]
2534
+ }
2535
+ try {
2536
+ result = await receiveTokens({
2537
+ wallet: bound,
2538
+ messageBoxClient: box,
2539
+ processed: processedMessages,
2540
+ settle: settleThroughDrain
2541
+ })
2542
+ } finally {
2543
+ for (const id of excluded) processedMessages.delete(id)
2544
+ }
2371
2545
  for (const transfer of result.accepted) {
2372
2546
  try {
2373
2547
  await journalReceived(transfer)
@@ -2434,4 +2608,3 @@ function assetIdOfTx(tx: Transaction): string | undefined {
2434
2608
  }
2435
2609
  return undefined
2436
2610
  }
2437
-
@@ -360,12 +360,12 @@ export interface TokenStepDeps extends EvidenceTrustAnchor {
360
360
  /**
361
361
  * Whether a cached admission may stand in for a submit.
362
362
  *
363
- * **Both halves are required, and the cryptographic one is not optional.** The
364
- * structural half — a non-empty admitted set, signed by the wallet's CONFIGURED
365
- * overlay identity key — only says the entry is addressed to the right overlay.
366
- * It says nothing about whether that overlay actually signed it, and this entry
367
- * may have arrived on a frame a counterparty composed. Skipping a `/submit` on
368
- * a forged entry is how a transaction the overlay has never seen reaches a real
363
+ * **Three halves are required, and none is optional.** The structural half —
364
+ * a non-empty admitted set, signed by the wallet's CONFIGURED overlay identity
365
+ * key — only says the entry is addressed to the right overlay. It says nothing
366
+ * about whether that overlay actually signed it, and this entry may have
367
+ * arrived on a frame a counterparty composed. Skipping a `/submit` on a forged
368
+ * entry is how a transaction the overlay has never seen reaches a real
369
369
  * broadcast: the drain would mark the ancestor `admitted` from the lie, walk
370
370
  * past it, and put an unadmitted chain on chain.
371
371
  *
@@ -376,13 +376,25 @@ export interface TokenStepDeps extends EvidenceTrustAnchor {
376
376
  * that column is re-derived from counterparty frame bytes by
377
377
  * `reconcileSettlements`, so anchoring trust in it would let the frame name its
378
378
  * own signer (wire contract §9.10).
379
+ *
380
+ * **The third half (XR-038): `requiredVouts` scoping.** A genuine σ_I over
381
+ * `(txid, outputsToAdmit)` proves the overlay admitted THOSE outputs of
382
+ * `txid` — nothing says the output THIS walk actually needs (the tip's own
383
+ * held/payee vout, or an ancestor edge's `parentVout`) is one of them. A payer
384
+ * who obtains a real admission for one output of a multi-output token tx
385
+ * (their own change, say) must not get the WHOLE transaction — including an
386
+ * output the issuer never admitted — treated as admitted. `requiredVouts`
387
+ * empty means "not proven which vout matters", never "no vout matters", so it
388
+ * is refused exactly like an absent row.
379
389
  */
380
390
  async function admissionStandsIn(
381
391
  row: TokenAdmissionRow | undefined,
382
- anchor: EvidenceTrustAnchor
392
+ anchor: EvidenceTrustAnchor,
393
+ requiredVouts: readonly number[]
383
394
  ): Promise<boolean> {
384
395
  if (row === undefined) return false
385
396
  if (row.signatureHex.length === 0 || row.outputsToAdmit.length === 0) return false
397
+ if (requiredVouts.length === 0 || !requiredVouts.every(v => row.outputsToAdmit.includes(v))) return false
386
398
  return await entryIsTrustworthy(
387
399
  {
388
400
  txid: row.txid,
@@ -394,6 +406,32 @@ async function admissionStandsIn(
394
406
  )
395
407
  }
396
408
 
409
+ /**
410
+ * Which vout(s) of `parentTxid` THIS walk actually needs it admitted for —
411
+ * from every `token_admission_edges` row already recorded (FIX K: derived
412
+ * once from the beef itself, never from a counterparty's say-so) for a
413
+ * transaction still in `mustSubmit` that spends `parentTxid`.
414
+ *
415
+ * Empty means "not proven", not "nothing needed": no cached edge names
416
+ * `parentTxid` as a parent of anything still being walked — most likely
417
+ * because evidence population has not run or lost a race — so the caller
418
+ * (`admissionStandsIn`) must refuse to skip rather than guess.
419
+ */
420
+ async function requiredVoutsOfAncestor(
421
+ store: SettlementStore,
422
+ parentTxid: string,
423
+ mustSubmit: readonly string[]
424
+ ): Promise<number[]> {
425
+ const vouts = new Set<number>()
426
+ for (const childTxid of mustSubmit) {
427
+ if (childTxid === parentTxid) continue
428
+ for (const edge of await store.parentsOf(childTxid)) {
429
+ if (edge.parentTxid === parentTxid) vouts.add(edge.parentVout)
430
+ }
431
+ }
432
+ return [...vouts]
433
+ }
434
+
397
435
  /**
398
436
  * FIX H in one predicate: is this σ_I the configured overlay's own?
399
437
  *
@@ -444,6 +482,12 @@ export async function postTokenStep(
444
482
  const { store } = deps
445
483
  const now = deps.now ?? (() => new Date())
446
484
  const tip = step.txid
485
+ // The wallet-relevant output of the TIP itself — see `TokenSettlementRow
486
+ // .relevantVout`. Nothing locally spends the tip, so this is the one vout
487
+ // an admission for `tip` has to cover, on both the fast path just below and
488
+ // the ordinary walk's own pass over the tip (it is always `mustSubmit`'s
489
+ // last entry).
490
+ const tipRequiredVouts = [settlement.relevantVout ?? 0]
447
491
 
448
492
  // The overlay's own σ_I over the tip is its ruling on the tip's ENTIRE
449
493
  // ancestry — nothing in the local evidence can outrank it, so there is
@@ -452,7 +496,7 @@ export async function postTokenStep(
452
496
  // bytes this device does not hold) left an already-admitted tip at
453
497
  // `admitted` on every tick, never broadcast (2026-09-16).
454
498
  const tipAdmission = await store.getAdmission(tip)
455
- if (await admissionStandsIn(tipAdmission, deps)) {
499
+ if (await admissionStandsIn(tipAdmission, deps, tipRequiredVouts)) {
456
500
  await store.advanceSettlement(tip, PRE_ADMIT_STATES, 'admitted', {
457
501
  admissionOutputs: tipAdmission?.outputsToAdmit,
458
502
  admissionSignatureHex: tipAdmission?.signatureHex
@@ -494,7 +538,13 @@ export async function postTokenStep(
494
538
  }
495
539
 
496
540
  const cached = await store.getAdmission(ancestorTxid)
497
- if (await admissionStandsIn(cached, deps)) {
541
+ // The tip's own required vout(s) when the walk reaches it (mustSubmit's
542
+ // last entry) — nothing spends the tip locally, so an edge lookup would
543
+ // find nothing. Every other entry is a true ancestor, scoped to whichever
544
+ // vout(s) of it something still in this walk actually spends.
545
+ const requiredVouts =
546
+ ancestorTxid === tip ? tipRequiredVouts : await requiredVoutsOfAncestor(store, ancestorTxid, cover.mustSubmit)
547
+ if (await admissionStandsIn(cached, deps, requiredVouts)) {
498
548
  await store.advanceSettlement(ancestorTxid, PRE_ADMIT_STATES, 'admitted', {
499
549
  admissionOutputs: cached?.outputsToAdmit,
500
550
  admissionSignatureHex: cached?.signatureHex
@@ -514,11 +564,18 @@ export async function postTokenStep(
514
564
  if (
515
565
  deps.verifyAdmission !== undefined &&
516
566
  !(await entryIsTrustworthy(
517
- { txid: ancestorTxid, outputsToAdmit: verdict.outputsToAdmit, signature: hexToBytes(verdict.signatureHex), signerKey: verdict.signerKey },
567
+ {
568
+ txid: ancestorTxid,
569
+ outputsToAdmit: verdict.outputsToAdmit,
570
+ signature: hexToBytes(verdict.signatureHex),
571
+ signerKey: verdict.signerKey
572
+ },
518
573
  deps
519
574
  ))
520
575
  ) {
521
- devLog(`[mandala] /submit of ${ancestorTxid} answered admitted without a verifiable σ_I; treated as unavailable`)
576
+ devLog(
577
+ `[mandala] /submit of ${ancestorTxid} answered admitted without a verifiable σ_I; treated as unavailable`
578
+ )
522
579
  if (before && SUBMITTABLE_STATES.includes(before.state)) {
523
580
  await store.advanceSettlement(ancestorTxid, ['submitting'], before.state)
524
581
  }
@@ -550,6 +607,27 @@ export async function postTokenStep(
550
607
  return 'serviceError'
551
608
  }
552
609
 
610
+ // XR-042: `deps.submit`'s negative verdicts, unlike its 'admitted' branch
611
+ // (checked above against `deps.verifyAdmission`), carry no signature at
612
+ // all. A row this device already holds a σ_I-VERIFIED admission for —
613
+ // `admissionSignatureHex`/`admissionOutputs`, only ever written after a
614
+ // verified admission (`admissionStandsIn`'s own callers, and
615
+ // `fetchAdmission`/`receiveFromInbox` upstream) — must not be unwound by a
616
+ // LATER unsigned negative for the same txid: that positive is
617
+ // cryptographic and this negative is not, so the positive stands. Put the
618
+ // row back where it was and stall, exactly like an 'unavailable' verdict,
619
+ // rather than treat "the overlay said no, unsigned" as final.
620
+ if (before?.admissionSignatureHex && before.admissionOutputs && before.admissionOutputs.length > 0) {
621
+ devLog(
622
+ `[mandala] /submit of ${ancestorTxid} answered ${verdict.kind} without a signature, but this device ` +
623
+ 'already holds a verified admission for it; treated as unavailable'
624
+ )
625
+ if (SUBMITTABLE_STATES.includes(before.state)) {
626
+ await store.advanceSettlement(ancestorTxid, ['submitting'], before.state)
627
+ }
628
+ return 'serviceError'
629
+ }
630
+
553
631
  // A final verdict for THIS txid. Evicted means it was admitted and then
554
632
  // undone (inputs restored overlay-side); refused means it never was.
555
633
  const to: TokenSettlementState = verdict.kind === 'evicted' ? 'orphaned' : 'refused'