@bsv/expo-wallet-toolbox 0.3.1 → 0.5.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 (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -7,13 +7,16 @@
7
7
  * code is handed up to the Pay screen, which swaps this form for NearbyFlow.
8
8
  * Nothing here is chosen by the user except the recipient and the amount.
9
9
  *
10
- * The form recomposes by what the field resolved to: a note field exists
11
- * only for handles (an address has nowhere to carry one), and the "they are
12
- * not notified" consequence is shown only for addresses, where it is
13
- * load-bearing — a user who pastes an address expecting messaging-style
14
- * delivery has effectively posted cash.
10
+ * The form recomposes by what the field resolved to: a note field is shown
11
+ * for both handles and addresses (in BSV mode — a token has no address rail
12
+ * at all, D4). For a handle the note is sent to the counterparty and becomes
13
+ * their action's description; for an address there is no counterparty
14
+ * channel to carry it over, so it is purely the sender's own record for
15
+ * their own outbound description. The "they are not notified" consequence is
16
+ * shown only for addresses, where it is load-bearing — a user who pastes an
17
+ * address expecting messaging-style delivery has effectively posted cash.
15
18
  */
16
- import React, { memo, useCallback, useEffect, useMemo, useState } from 'react'
19
+ import React, { memo, useCallback, useEffect, useMemo, useState, useRef } from 'react'
17
20
  import { ActivityIndicator, Modal, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'
18
21
  import { useTranslation } from 'react-i18next'
19
22
 
@@ -30,7 +33,11 @@ import PaymentSuccessOverlay from './PaymentSuccessOverlay'
30
33
  import ResultBanner from './ResultBanner'
31
34
  import RecipientField from './RecipientField'
32
35
  import { useMessageBoxConfig } from './MessageBoxConfig'
33
- import { useRecipientInput, type RecipientTarget } from './useRecipientInput'
36
+ import { useRecipientInput, type RecipientTarget, type PeerPayRequest } from './useRecipientInput'
37
+ import { tokenSendCopy, tokenThrowCopy, type TokenSendCopy } from './tokenSendCopy'
38
+ import { useAssetStatus, useMandala } from '../../hooks/useMandala'
39
+ import { useSpendableBalance } from '../../hooks/useSpendableBalance'
40
+ import { formatTokenAmount, formatTokenAmountWithUnit } from '../../tokenFormat'
34
41
  import {
35
42
  useTheme,
36
43
  spacing,
@@ -38,6 +45,7 @@ import {
38
45
  radii,
39
46
  hitTargets,
40
47
  useWalletManagers,
48
+ useWalletStatus,
41
49
  CONSEQUENCE_KEYS,
42
50
  NO_MESSAGE_BOX,
43
51
  cancelOutboxPayment,
@@ -183,6 +191,21 @@ export interface UniversalSendProps {
183
191
  initialTarget?: Extract<RecipientTarget, { kind: 'handle' }>
184
192
  /** Prefilled amount in satoshis from a peerpay link or `?sats=`. */
185
193
  initialSats?: number
194
+ /**
195
+ * Prefilled TOKEN amount from a peerpay link's `asset=`/`amount=`: base units
196
+ * of that asset. Takes precedence over `initialSats` — a link names one money.
197
+ * The figure only ever shows while that asset is the one selected (see the
198
+ * unit tag on the figure below), so a link for a token this wallet turns out
199
+ * not to hold seeds nothing.
200
+ */
201
+ initialTokenAmount?: { assetId: string; baseUnits: number }
202
+ /**
203
+ * The asset this payment is denominated in. `null` is BSV — the default, and
204
+ * what every existing flow assumes. Controlled by the Pay screen so the
205
+ * choice survives a hop into Get paid and back.
206
+ */
207
+ selectedAssetId?: string | null
208
+ onSelectAsset?: (assetId: string | null) => void
186
209
  /** Error text from a malformed peerpay link, shown as a banner. */
187
210
  initialNotice?: string | null
188
211
  /** Open the scanner as soon as the form mounts (deep link `cell=pay-nearby`). */
@@ -193,54 +216,250 @@ export interface UniversalSendProps {
193
216
  dismissTo?: DismissTarget
194
217
  }
195
218
 
219
+ /**
220
+ * The typed (or link-supplied) figure, tagged with the unit it was entered in:
221
+ * `null` for satoshis, an assetId for that token's base units.
222
+ */
223
+ interface Figure {
224
+ text: string
225
+ unit: string | null
226
+ }
227
+
228
+ function seedFigure(sats?: number, token?: { assetId: string; baseUnits: number }): Figure {
229
+ if (token && Number.isFinite(token.baseUnits) && token.baseUnits > 0) {
230
+ return { text: String(Math.round(token.baseUnits)), unit: token.assetId }
231
+ }
232
+ if (sats && sats > 0) return { text: String(sats), unit: null }
233
+ return { text: '', unit: null }
234
+ }
235
+
196
236
  function UniversalSend({
197
237
  initialTarget,
198
238
  initialSats,
239
+ initialTokenAmount,
199
240
  initialNotice,
200
241
  openScannerOnMount = false,
201
242
  onNearbySession,
243
+ selectedAssetId,
244
+ onSelectAsset,
202
245
  dismissTo = '/'
203
246
  }: UniversalSendProps) {
204
247
  const { t } = useTranslation()
205
248
  const { colors } = useTheme()
206
249
  const StatusBar = loadStatusBar()
207
250
  const { managers, adminOriginator, storage } = useWalletManagers()
251
+ const { walletBuilt } = useWalletStatus()
208
252
  const wallet = managers?.permissionsManager || null
209
253
 
254
+ // ── the asset axis ──────────────────────────────────────────────────
255
+ // Every line below is gated on `asset`: with no token held, `balances` is
256
+ // empty, `asset` is null, the picker renders nothing and this form is
257
+ // byte-for-byte the form it was.
258
+ const mandala = useMandala()
259
+ const spendableSats = useSpendableBalance()
260
+ const [localAssetId, setLocalAssetId] = useState<string | null>(null)
261
+ const assetId = selectedAssetId !== undefined ? selectedAssetId : localAssetId
262
+ const setAssetId = onSelectAsset ?? setLocalAssetId
263
+ const balances = mandala.balances ?? []
264
+ const holding = balances.find(b => b.asset.assetId === assetId) ?? null
265
+ const asset = holding?.asset ?? null
266
+ const issuer = asset?.issuerName || t('token_issuer_fallback')
267
+ /**
268
+ * Regulatory/registry facts for the selected asset (paused, frozen, this
269
+ * wallet's own registration, whether the metadata even resolved), from the
270
+ * runtime's ~10s cache. `null` (unknown/loading) blocks nothing — ux §4.2
271
+ * rule 3: pre-flight may only ever say "no", never invent a "yes" and never
272
+ * gate on an answer it does not have yet.
273
+ */
274
+ const assetStatus = useAssetStatus(asset?.assetId ?? null).status
275
+
210
276
  // Read-only here: the server is configured in Settings › Advanced.
211
277
  const { messageBoxUrl } = useMessageBoxConfig(t)
212
278
  const isConfigured = !!messageBoxUrl && messageBoxUrl !== NO_MESSAGE_BOX
213
279
 
214
- const [sendAmount, setSendAmount] = useState(initialSats && initialSats > 0 ? String(initialSats) : '')
280
+ /**
281
+ * The figure, tagged with the unit it was entered in. The field shows it and
282
+ * a send reads it ONLY while that unit is the one in force — an asset counts
283
+ * only once this wallet is known to hold it — so any change of money (the
284
+ * picker, a link naming a different one, the screen dropping an asset that
285
+ * turns out not to be held) blanks the figure instead of letting "2500" be
286
+ * read as 25.00 USDX one moment and 2,500 satoshis the next.
287
+ */
288
+ const [figure, setFigure] = useState<Figure>(() => seedFigure(initialSats, initialTokenAmount))
289
+ const unit = asset?.assetId ?? null
290
+ const sendAmount = figure.unit === unit ? figure.text : ''
291
+ const setSendAmount = (text: string) => setFigure({ text, unit })
215
292
  const [note, setNote] = useState('')
216
293
  const [notice, setNotice] = useState<{ type: 'error'; message: string } | null>(
217
294
  initialNotice ? { type: 'error', message: initialNotice } : null
218
295
  )
219
296
  const [isSending, setIsSending] = useState(false)
220
297
  const [sendResult, setSendResult] = useState<{ type: 'success' | 'error'; message: string } | null>(null)
298
+ /**
299
+ * The failed-token-send note, kept apart from `sendResult` because it carries
300
+ * an action ("Check again") that a plain banner has nowhere to put.
301
+ */
302
+ const [tokenFailure, setTokenFailure] = useState<TokenSendCopy | null>(null)
221
303
  /** The success moment, held until acknowledged — same screen as every rail. */
222
- const [sent, setSent] = useState<{ amount: number; recipient?: string } | null>(null)
304
+ const [sent, setSent] = useState<{
305
+ amount: number
306
+ recipient?: string
307
+ /** Token mode: the figure in the asset's own units. */
308
+ amountText?: string
309
+ /** Whether the issuer has confirmed it yet — never claimed, only reported. */
310
+ statusNote?: string
311
+ } | null>(null)
223
312
  const [outbox, setOutbox] = useState<OutboxEntry[]>([])
224
313
  const [retryingId, setRetryingId] = useState<string | null>(null)
225
314
 
226
- const onPeerPayAmount = useCallback((sats: number) => setSendAmount(String(sats)), [])
315
+ /**
316
+ * A token request, decided against a KNOWN set of holdings: the form
317
+ * switches to that token when this wallet holds it and takes `amount` in
318
+ * its base units (or leaves the figure to the user for an open request). A
319
+ * token this wallet does not hold cannot be paid from here, so the
320
+ * recipient is kept, the figure is not — a figure typed for the previous
321
+ * money must never stay armed at the new payee — and the banner says why;
322
+ * paying that person in BSV is still one tap away.
323
+ */
324
+ const applyTokenRequest = (
325
+ request: PeerPayRequest,
326
+ balances: { asset: { assetId: string } }[],
327
+ opts: { deferred: boolean }
328
+ ) => {
329
+ const held = balances.some(b => b.asset.assetId === request.asset)
330
+ if (!held) {
331
+ // Back to BSV, as the banner says; the figure typed for the old money
332
+ // must never stay armed at the new payee.
333
+ setAssetId(null)
334
+ setFigure(current => ({ ...current, text: '' }))
335
+ setNotice({ type: 'error', message: t('pay_asset_link_not_held') })
336
+ return
337
+ }
338
+ setAssetId(request.asset as string)
339
+ // A request applied LATER never writes over a figure the user has typed
340
+ // since; the link's own figure is taken only at the moment the link arrives.
341
+ if (!opts.deferred || figure.text === '') {
342
+ setFigure({ text: request.amount ? String(request.amount) : '', unit: request.asset as string })
343
+ }
344
+ setNotice(null)
345
+ setTokenFailure(null)
346
+ }
347
+ /**
348
+ * Whether this wallet can EVER hold a token here. The runtime is published at
349
+ * wallet build, and only on a chain with Mandala endpoints — so no runtime on
350
+ * a built wallet is a settled fact (holds nothing, ever), while no runtime on
351
+ * a wallet still building is merely unknown.
352
+ */
353
+ const tokensNever = walletBuilt && !mandala.available
354
+ /**
355
+ * A token link that arrived before the first balance read landed. `null`
356
+ * balances mean UNKNOWN, never "holds nothing" (useMandala's contract), and a
357
+ * pre-flight may only ever say "no" to a fact it has — so the request waits,
358
+ * and the effect below decides it the moment the holdings are known.
359
+ */
360
+ const pendingTokenRequestRef = useRef<PeerPayRequest | null>(null)
361
+ /**
362
+ * A pasted or scanned link named a money, and maybe a figure. `sats` is a
363
+ * BSV request: the form switches to BSV and takes the figure. `asset` is a
364
+ * token request, decided now if the holdings are known (or can never be
365
+ * held), otherwise parked until they are — see the effect below `recipient`.
366
+ */
367
+ const onPeerPayRequest = (request: PeerPayRequest) => {
368
+ if (request.asset !== undefined) {
369
+ if (tokensNever) {
370
+ applyTokenRequest(request, [], { deferred: false })
371
+ } else if (mandala.balances === null) {
372
+ pendingTokenRequestRef.current = request
373
+ } else {
374
+ applyTokenRequest(request, mandala.balances, { deferred: false })
375
+ }
376
+ return
377
+ }
378
+ if (request.sats !== undefined) {
379
+ pendingTokenRequestRef.current = null
380
+ setAssetId(null)
381
+ setFigure({ text: String(request.sats), unit: null })
382
+ setNotice(null)
383
+ setTokenFailure(null)
384
+ }
385
+ }
227
386
  const onPeerPayError = useCallback((message: string) => setNotice({ type: 'error', message }), [])
228
387
  const recipient = useRecipientInput({
229
388
  wallet,
230
389
  adminOriginator,
231
390
  initialTarget,
232
- onPeerPayAmount,
391
+ onPeerPayRequest,
233
392
  onPeerPayError,
234
393
  onNearbySession
235
394
  })
236
395
  const target = recipient.target
396
+ /**
397
+ * A token link that arrived before the holdings were known. `null` balances
398
+ * mean UNKNOWN, never "holds nothing" (useMandala's contract), and a
399
+ * pre-flight may only ever say "no" to a fact it has — so the request waits
400
+ * here and is decided the moment the holdings land (or the wallet finishes
401
+ * building with no token runtime). Applied only if the recipient is still
402
+ * the payee the link named: the user may have retargeted while it waited,
403
+ * and a figure in a money nobody at the new payee asked for must never arm.
404
+ */
405
+ const balancesKnown = mandala.balances !== null
406
+ useEffect(() => {
407
+ const pending = pendingTokenRequestRef.current
408
+ if (!pending) return
409
+ if (!tokensNever && mandala.balances === null) return
410
+ pendingTokenRequestRef.current = null
411
+ if (target?.kind !== 'handle' || target.identityKey !== pending.identityKey) return
412
+ applyTokenRequest(pending, tokensNever ? [] : (mandala.balances ?? []), { deferred: true })
413
+ // Keyed on the two events that can settle a parked request; everything
414
+ // else it reads is a plain closure over this render.
415
+ // eslint-disable-next-line react-hooks/exhaustive-deps
416
+ }, [balancesKnown, mandala.balances, tokensNever])
417
+
418
+ /**
419
+ * Whether the issuer's registry admits the typed recipient, for the ONE
420
+ * asset selected — the counterpart to `recipientRefusal`'s synchronous D4
421
+ * (address-shape) check, which never touches the registry at all. Asked
422
+ * only once the field has RESOLVED to an identity key: half-typed text is
423
+ * not a recipient, and `undefined` (unknown/still asking) never disables
424
+ * the CTA — only a proven `false` does (ux §4.2 rule 3).
425
+ */
426
+ const [recipientAdmitted, setRecipientAdmitted] = useState<boolean | undefined>(undefined)
427
+ useEffect(() => {
428
+ setRecipientAdmitted(undefined)
429
+ if (!asset || target?.kind !== 'handle' || !assetStatus) return
430
+ let live = true
431
+ void assetStatus
432
+ .recipientAdmitted(target.identityKey)
433
+ .then(admitted => {
434
+ if (live) setRecipientAdmitted(admitted)
435
+ })
436
+ .catch(() => {
437
+ // Fails open, same as every other pre-flight read: an unreachable
438
+ // registry is UNKNOWN, never a proven refusal.
439
+ if (live) setRecipientAdmitted(undefined)
440
+ })
441
+ return () => {
442
+ live = false
443
+ }
444
+ }, [asset, target, assetStatus])
237
445
 
238
446
  // A second deep link while mounted re-adopts the recipient (useRecipientInput);
239
447
  // the amount and the notice it carried must follow, or Pay sends the OLD
240
448
  // figure to the NEW person.
449
+ // Keyed on the figure's parts, not the object: a host that rebuilds the
450
+ // token-amount object every render must not reseed over what is being typed.
451
+ const initialTokenAssetId = initialTokenAmount?.assetId
452
+ const initialTokenBaseUnits = initialTokenAmount?.baseUnits
241
453
  useEffect(() => {
242
- setSendAmount(initialSats && initialSats > 0 ? String(initialSats) : '')
243
- }, [initialSats])
454
+ setFigure(
455
+ seedFigure(
456
+ initialSats,
457
+ initialTokenAssetId !== undefined && initialTokenBaseUnits !== undefined
458
+ ? { assetId: initialTokenAssetId, baseUnits: initialTokenBaseUnits }
459
+ : undefined
460
+ )
461
+ )
462
+ }, [initialSats, initialTokenAssetId, initialTokenBaseUnits])
244
463
  useEffect(() => {
245
464
  setNotice(initialNotice ? { type: 'error', message: initialNotice } : null)
246
465
  }, [initialNotice])
@@ -316,7 +535,15 @@ function UniversalSend({
316
535
  // The overlay stages its own haptic (inside Celebration) and tone; firing
317
536
  // haptics.success() here would double the beat. Only a human-readable
318
537
  // name goes on the success screen — a raw identity key is noise there.
319
- setSent({ amount: paidSats, recipient: recipient.selectedIdentity?.name })
538
+ setSent({
539
+ amount: paidSats,
540
+ recipient: recipient.selectedIdentity?.name,
541
+ // The handle rail always drops the payment in the recipient's message
542
+ // box rather than handing it over in person — worth saying explicitly
543
+ // here, since it is the one thing an in-person (Nearby) payer never
544
+ // has to wonder about (ux §4.2/§8 "Success / arrival").
545
+ statusNote: t('pay_sent_handed_to_wallet')
546
+ })
320
547
  },
321
548
  [peerPayClient, storage, wallet, adminOriginator, messageBoxUrl, note, recipient.selectedIdentity, loadOutbox, t]
322
549
  )
@@ -328,36 +555,126 @@ function UniversalSend({
328
555
  wallet: wallet as any,
329
556
  adminOriginator,
330
557
  address: to.address,
331
- satoshis: sats
558
+ satoshis: sats,
559
+ note
332
560
  })
333
561
  setSent({ amount: paidSatoshis, recipient: to.address })
334
562
  },
335
- [wallet, adminOriginator, t]
563
+ [wallet, adminOriginator, note, t]
564
+ )
565
+
566
+ /**
567
+ * The token send. One call, because the runtime owns the whole pipeline —
568
+ * coin selection, the blinded lock, the noSend build, the overlay submit, the
569
+ * journal and the abort on refusal. What this screen owns is the sentence the
570
+ * holder reads afterwards, and the rule that a refusal is the only outcome
571
+ * allowed to promise "nothing was sent".
572
+ */
573
+ const sendToken = useCallback(
574
+ async (to: Extract<RecipientTarget, { kind: 'handle' }>, baseUnits: number) => {
575
+ const runtime = mandala.runtime
576
+ if (!runtime || !asset) throw new Error(t('wallet_not_ready'))
577
+ const ctx = {
578
+ ticker: asset.ticker,
579
+ issuer: asset.issuerName,
580
+ issuerFallback: t('token_issuer_fallback'),
581
+ reasonFallback: t('token_err_reason_unknown')
582
+ }
583
+ const result = await runtime.sendToHandle({
584
+ assetId: asset.assetId,
585
+ recipientIdentityKey: to.identityKey,
586
+ baseUnits,
587
+ ...(note.trim() ? { note: note.trim() } : {})
588
+ })
589
+ if (result.kind !== 'sent') {
590
+ // The banner narrows the reason to one sentence; the console keeps the
591
+ // whole of it. On a rail that contacts nothing at send time, the raw
592
+ // message IS the diagnosis (a MessageBox that would not open, a wallet
593
+ // that could not sign) and is the only place it survives.
594
+ console.warn('[pay] token send failed:', result.kind, result.message ?? (result as { code?: string }).code)
595
+ setTokenFailure(tokenSendCopy(result, ctx))
596
+ return
597
+ }
598
+ setSent({
599
+ amount: 0,
600
+ recipient: recipient.selectedIdentity?.name,
601
+ // Never falls back to the satoshi renderer: a token figure it could not
602
+ // format would print as satoshis, which is a wrong number rather than a
603
+ // missing one.
604
+ amountText: formatTokenAmountWithUnit(baseUnits, asset) ?? t('token_row_amount_pending'),
605
+ // `notified === false` takes priority: the money moved either way, but
606
+ // the recipient has not been TOLD it did (the lib's own notify retries
607
+ // in the background — see `TokenSendResult.notified`), and that is the
608
+ // more useful thing to tell the payer, whether or not the coin is
609
+ // settled yet.
610
+ //
611
+ // Otherwise the handle rail now says SETTLING, not "not broadcast": a
612
+ // hand-over send never asked the overlay anything (§4.5 / wire §9.13),
613
+ // so the honest sentence is that the payment is made and is on its way
614
+ // to the issuer — which is exactly what the nearby rail has always
615
+ // said, and the same pair of keys says it. `settled` is kept ahead of
616
+ // it because it remains the runtime's own word for σ_I in hand, and a
617
+ // rail that one day hands one back must not be told to under-claim.
618
+ statusNote: !result.notified
619
+ ? t('pay_sent_not_notified')
620
+ : result.settled
621
+ ? t('token_sent_settled', { issuer })
622
+ : recipient.selectedIdentity?.name
623
+ ? t('token_sent_settling', { issuer, payee: recipient.selectedIdentity.name })
624
+ : t('token_sent_settling_unnamed', { issuer })
625
+ })
626
+ mandala.refresh()
627
+ },
628
+ [mandala, asset, issuer, recipient.selectedIdentity, note, t]
336
629
  )
337
630
 
338
631
  const handleSend = useCallback(async () => {
339
632
  if (!target) return
340
633
  // Guard before any side effect: a wallet that is not ready must leave the
341
634
  // form exactly as typed, with a banner, not a cleared field and silence.
342
- if (!wallet || !storage) {
635
+ // On the token path the runtime IS the wallet — it holds its own manager,
636
+ // storage and journal — so that is what has to be ready.
637
+ if (asset ? !mandala.runtime : !wallet || !storage) {
343
638
  flashResult({ type: 'error', message: t('wallet_not_ready') })
344
639
  return
345
640
  }
346
- const sats = Math.round(Number(sendAmount))
347
- if (!Number.isFinite(sats) || sats <= 0) {
641
+ // The same integer either way — satoshis on the BSV rail, base units of the
642
+ // asset on the token rail. The field emits whole units in both modes.
643
+ const amount = Math.round(Number(sendAmount))
644
+ if (!Number.isFinite(amount) || amount <= 0) {
348
645
  flashResult({ type: 'error', message: t('enter_valid_amount') })
349
646
  return
350
647
  }
351
648
  haptics.confirm()
352
649
  setIsSending(true)
650
+ setTokenFailure(null)
353
651
  try {
354
- if (target.kind === 'handle') await sendHandle(target, sats)
355
- else await sendAddress(target, sats)
356
- setSendAmount('')
652
+ if (asset) {
653
+ // D4: a token has no address rail, and `canSend` has already refused
654
+ // one. This is the second gate, because the first is a render.
655
+ if (target.kind !== 'handle') return
656
+ await sendToken(target, amount)
657
+ } else if (target.kind === 'handle') await sendHandle(target, amount)
658
+ else await sendAddress(target, amount)
659
+ setFigure(current => ({ ...current, text: '' }))
357
660
  setNote('')
358
661
  recipient.clearRecipient()
359
662
  } catch (error: any) {
360
663
  if (await handleWalletCheck(error)) return
664
+ if (asset) {
665
+ console.warn('[mandala] token send threw:', error)
666
+ // A throw out of the token path is NOT a refusal: the overlay may have
667
+ // admitted the transaction and lost the response, so the copy claims
668
+ // nothing and offers a balance check rather than a retry.
669
+ setTokenFailure(
670
+ tokenThrowCopy(error, {
671
+ ticker: asset.ticker,
672
+ issuer: asset.issuerName,
673
+ issuerFallback: t('token_issuer_fallback')
674
+ })
675
+ )
676
+ return
677
+ }
361
678
  const message =
362
679
  error instanceof RangeError
363
680
  ? t('enter_valid_amount')
@@ -373,12 +690,15 @@ function UniversalSend({
373
690
  }, [
374
691
  target,
375
692
  sendAmount,
693
+ asset,
694
+ sendToken,
376
695
  sendHandle,
377
696
  sendAddress,
378
697
  recipient,
379
698
  handleWalletCheck,
380
699
  flashResult,
381
700
  loadOutbox,
701
+ mandala.runtime,
382
702
  t,
383
703
  wallet,
384
704
  storage
@@ -480,7 +800,115 @@ function UniversalSend({
480
800
  // Address sends never touch the box, so they are not held hostage by it.
481
801
  const handleBlockedByOutbox = isHandle && outbox.length > 0
482
802
  const handleFormValid = isHandle && amountOk && !isSending && isConfigured
483
- const canSend = isAddress ? amountOk && !isSending : handleFormValid && !handleBlockedByOutbox
803
+
804
+ // ── token pre-flight ────────────────────────────────────────────────
805
+ // Advisory, and it may only ever say "no". Nothing here promises a send will
806
+ // work; `resolveAssetState` and the registry both fail open, so a pre-flight
807
+ // that said "this will work" would be the one claim they cannot support.
808
+ const baseUnits = asset ? Math.round(Number(sendAmount)) || 0 : 0
809
+ const overBalance = !!holding && baseUnits > holding.baseUnits
810
+ /**
811
+ * The runtime's plain reason this recipient cannot be paid in this asset —
812
+ * an address (D4), an unregistered identity, a blocked one.
813
+ *
814
+ * Asked only once the field has RESOLVED to something. Half-typed text is not
815
+ * a recipient, and answering "no" to it would put a refusal on screen for a
816
+ * name the user is still in the middle of writing.
817
+ */
818
+ const recipientRefusal =
819
+ asset && mandala.runtime && target
820
+ ? mandala.runtime.recipientRefusal(target.kind === 'handle' ? target.identityKey : target.address)
821
+ : null
822
+ const tokenAddressRefused = !!asset && isAddress
823
+ // Every one of these is a KNOWN-false fact, never an unknown one: `assetStatus`
824
+ // is `null` until the first read lands and fails open on every later read, so
825
+ // `=== true`/`=== false` (never a bare truthiness check) is what keeps a cold
826
+ // read or an unreachable overlay from disabling the button on a guess.
827
+ const paused = assetStatus?.paused === true
828
+ const unidentified = assetStatus?.metadataResolved === false
829
+ const selfUnregistered = assetStatus?.selfAdmitted === false
830
+ // Only asked once the recipient resolved to a handle — an address is already
831
+ // refused by D4 above, and half-typed text is not a recipient yet.
832
+ const recipientRegistryRefused = !!asset && target?.kind === 'handle' && recipientAdmitted === false
833
+ const frozenBaseUnits = assetStatus?.frozenBaseUnits ?? 0
834
+ const tokenFormValid =
835
+ !!asset &&
836
+ isHandle &&
837
+ amountOk &&
838
+ !isSending &&
839
+ !overBalance &&
840
+ !recipientRefusal &&
841
+ !tokenAddressRefused &&
842
+ !paused &&
843
+ !unidentified &&
844
+ !selfUnregistered &&
845
+ !recipientRegistryRefused
846
+
847
+ const canSend = asset
848
+ ? tokenFormValid
849
+ : isAddress
850
+ ? amountOk && !isSending
851
+ : handleFormValid && !handleBlockedByOutbox
852
+
853
+ /**
854
+ * At most one note, in this order — the same order as ux design §4.2's
855
+ * pre-flight table: the reasons that block the CTA first (most specific
856
+ * first), then the two that are advisory only (frozen, needs-BSV) and never
857
+ * disable it. The BSV-fee note stays last and — this is the part that
858
+ * matters — it NEVER disables the button: `useSpendableBalance()` returns
859
+ * `null` on a cold open, `null < n` is `true` in JavaScript, and the
860
+ * authoritative answer is the toolbox's own funding throw, which comes back
861
+ * as the same sentence.
862
+ */
863
+ const tokenNote: {
864
+ key: string
865
+ values?: Record<string, string>
866
+ /** The runtime's own sentence, which wins over the key when it has one. */
867
+ text?: string
868
+ action?: 'get-bsv'
869
+ } | null = asset
870
+ ? tokenAddressRefused
871
+ ? // D4, stated plainly. The runtime's own reason wins when it has one:
872
+ // it knows which of the several reasons an address cannot be paid
873
+ // applies, and a specific true sentence beats a general true sentence.
874
+ { key: 'pay_asset_no_address', values: { ticker: asset.ticker }, text: recipientRefusal ?? undefined }
875
+ : paused
876
+ ? { key: 'pay_asset_paused', values: { issuer, ticker: asset.ticker } }
877
+ : unidentified
878
+ ? { key: 'pay_asset_unidentified' }
879
+ : selfUnregistered
880
+ ? { key: 'pay_asset_self_unregistered', values: { issuer, ticker: asset.ticker } }
881
+ : recipientRegistryRefused
882
+ ? // The runtime's registry only answers a yes/no boolean, not WHY —
883
+ // `accessMode` says which gate refused: a denylist hit is a block,
884
+ // anything else (an allowlist gate, or none reported) reads as
885
+ // "not registered yet", which is the truer default of the two.
886
+ {
887
+ key:
888
+ assetStatus?.accessMode === 'denylist'
889
+ ? 'pay_asset_recipient_blocked'
890
+ : 'pay_asset_recipient_unregistered',
891
+ values: { issuer, ticker: asset.ticker }
892
+ }
893
+ : overBalance
894
+ ? { key: 'pay_asset_over_balance', values: { ticker: asset.ticker } }
895
+ : frozenBaseUnits > 0
896
+ ? {
897
+ key: 'pay_asset_frozen_note',
898
+ values: { ticker: asset.ticker, amount: formatTokenAmount(frozenBaseUnits, asset.decimals) ?? '' }
899
+ }
900
+ : spendableSats === 0
901
+ ? { key: 'pay_asset_needs_bsv', values: { ticker: asset.ticker }, action: 'get-bsv' }
902
+ : null
903
+ : null
904
+
905
+ const ctaLabel =
906
+ asset && amountOk
907
+ ? t('pay_asset_cta', {
908
+ amount: formatTokenAmount(baseUnits, asset.decimals) ?? '',
909
+ ticker: asset.ticker
910
+ })
911
+ : undefined
484
912
 
485
913
  return (
486
914
  <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
@@ -507,12 +935,40 @@ function UniversalSend({
507
935
  onSelectIdentity={recipient.selectIdentity}
508
936
  onClear={recipient.clearRecipient}
509
937
  onOpenScanner={recipient.openScanner}
938
+ assetTicker={asset?.ticker}
939
+ statusOverride={
940
+ recipientRefusal && !tokenAddressRefused
941
+ ? { text: recipientRefusal, tone: 'warning' }
942
+ : recipientRegistryRefused
943
+ ? {
944
+ text: t(
945
+ assetStatus?.accessMode === 'denylist' ? 'pay_asset_recipient_blocked' : 'pay_asset_recipient_unregistered',
946
+ { issuer, ticker: asset?.ticker }
947
+ ),
948
+ tone: 'warning'
949
+ }
950
+ : undefined
951
+ }
510
952
  />
511
953
  </PayField>
512
954
 
513
- <PayAmountField value={sendAmount} onChangeText={setSendAmount} />
955
+ {/* No "Paying with" picker here (design 1b, 2026-09-15): the coin is
956
+ chosen once, on Home's switcher, and arrives as `selectedAssetId`.
957
+ It still decides the unit of the figure, the available balance under
958
+ it, and which recipient shapes are legal for a token (D4, above) —
959
+ and a peerpay link naming an asset still moves it. */}
960
+
961
+ <PayAmountField
962
+ value={sendAmount}
963
+ onChangeText={setSendAmount}
964
+ asset={asset ? { ticker: asset.ticker, decimals: asset.decimals } : undefined}
965
+ maxValue={holding ? String(holding.baseUnits) : undefined}
966
+ availableText={
967
+ holding ? (formatTokenAmount(holding.baseUnits, holding.asset.decimals) ?? undefined) : undefined
968
+ }
969
+ />
514
970
 
515
- {isHandle && (
971
+ {(isHandle || (isAddress && !asset)) && (
516
972
  <PayField labelKey="note">
517
973
  <TextInput
518
974
  value={note}
@@ -528,17 +984,63 @@ function UniversalSend({
528
984
  </PayField>
529
985
  )}
530
986
 
531
- {/* Load-bearing for an address: this rail cannot notify the payee. Nothing for a handle. */}
532
- {isAddress && <ConsequenceNote textKey={CONSEQUENCE_KEYS.address} />}
987
+ {/* Load-bearing for an address: this rail cannot notify the payee. Nothing
988
+ for a handle, and nothing at all in token mode, where an address is
989
+ refused rather than warned about. */}
990
+ {isAddress && !asset && <ConsequenceNote textKey={CONSEQUENCE_KEYS.address} />}
991
+
992
+ {tokenNote && (
993
+ <ConsequenceNote
994
+ textKey={tokenNote.key}
995
+ values={tokenNote.values}
996
+ text={tokenNote.text}
997
+ action={
998
+ tokenNote.action === 'get-bsv'
999
+ ? {
1000
+ label: t('pay_asset_get_bsv'),
1001
+ onPress: () => loadExpoRouter().router.push('/pay?direction=get' as never)
1002
+ }
1003
+ : undefined
1004
+ }
1005
+ />
1006
+ )}
533
1007
 
534
- {isHandle && !isConfigured && (
1008
+ {isHandle && !isConfigured && !asset && (
535
1009
  <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('message_box_off_hint')}</Text>
536
1010
  )}
537
- {handleFormValid && handleBlockedByOutbox && (
1011
+ {handleFormValid && handleBlockedByOutbox && !asset && (
538
1012
  <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('finish_or_cancel_outgoing')}</Text>
539
1013
  )}
540
1014
 
541
- <PayCta onPress={handleSend} disabled={!canSend} busy={isSending} />
1015
+ <PayCta onPress={handleSend} disabled={!canSend} busy={isSending} label={ctaLabel} />
1016
+
1017
+ {/* A failed token send, in the app's own failure channel: error tone,
1018
+ dismissible, and carrying at most one affordance. "Check again"
1019
+ refreshes the balance rather than re-sending, because a retry after a
1020
+ lost response builds a second spend of the same coins. */}
1021
+ {tokenFailure && (
1022
+ <ResultBanner
1023
+ result={{ type: 'error', message: t(tokenFailure.key, tokenFailure.values) }}
1024
+ onDismiss={() => setTokenFailure(null)}
1025
+ colors={colors}
1026
+ action={
1027
+ tokenFailure.action === 'check-again'
1028
+ ? {
1029
+ label: t('token_err_check_again'),
1030
+ onPress: () => {
1031
+ mandala.refresh()
1032
+ setTokenFailure(null)
1033
+ }
1034
+ }
1035
+ : tokenFailure.action === 'get-bsv'
1036
+ ? {
1037
+ label: t('pay_asset_get_bsv'),
1038
+ onPress: () => loadExpoRouter().router.push('/pay?direction=get' as never)
1039
+ }
1040
+ : undefined
1041
+ }
1042
+ />
1043
+ )}
542
1044
 
543
1045
  {sendResult && <ResultBanner result={sendResult} onDismiss={() => setSendResult(null)} colors={colors} />}
544
1046
 
@@ -572,6 +1074,8 @@ function UniversalSend({
572
1074
  <PaymentSuccessOverlay
573
1075
  direction="sent"
574
1076
  amount={sent.amount}
1077
+ amountText={sent.amountText}
1078
+ statusNote={sent.statusNote}
575
1079
  recipientName={sent.recipient}
576
1080
  onDismiss={() => setSent(null)}
577
1081
  dismissTo={dismissTo}