@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.
Files changed (85) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +78 -13
  3. package/core/contacts/contactActivity.ts +48 -28
  4. package/core/contacts/contactsStore.ts +2 -2
  5. package/core/context/WalletContext.tsx +166 -219
  6. package/core/demo/demoAssets.ts +8 -10
  7. package/core/demo/demoLedger.ts +32 -38
  8. package/core/demo/demoMandalaRuntime.ts +67 -49
  9. package/core/demo/index.ts +1 -1
  10. package/core/directpay/DirectPayManager.ts +148 -29
  11. package/core/directpay/DirectPayProvider.tsx +11 -2
  12. package/core/directpay/payFlow.ts +10 -1
  13. package/core/directpay/settings.ts +56 -9
  14. package/core/directpay/types.ts +11 -2
  15. package/core/directpay/webrtpay.ts +4 -0
  16. package/core/i18n/translations.tsx +185 -84
  17. package/core/index.ts +55 -37
  18. package/core/localpay/build.ts +110 -569
  19. package/core/localpay/codec.ts +190 -93
  20. package/core/localpay/pending.ts +217 -202
  21. package/core/localpay/session.ts +99 -25
  22. package/core/localpay/types.ts +6 -5
  23. package/core/localpay/verify.ts +118 -173
  24. package/core/mandala/abortGuard.ts +97 -120
  25. package/core/mandala/accessPolicy.ts +133 -0
  26. package/core/mandala/assets.ts +370 -0
  27. package/core/mandala/colorGuard.ts +178 -0
  28. package/core/mandala/colorModule.ts +82 -0
  29. package/core/mandala/createRuntime.ts +483 -2392
  30. package/core/mandala/handle.ts +694 -0
  31. package/core/mandala/kvStore.ts +105 -0
  32. package/core/mandala/nearby.ts +185 -0
  33. package/core/mandala/receipt.ts +121 -0
  34. package/core/mandala/runtime.ts +166 -312
  35. package/core/mandala/settle.ts +540 -0
  36. package/core/mandala/transferJournal.ts +395 -0
  37. package/core/mandala/types.ts +61 -311
  38. package/core/networks.ts +5 -5
  39. package/core/offline/cancelParked.ts +80 -63
  40. package/core/offline/payerHold.ts +52 -118
  41. package/core/parsePeerPayURI.ts +25 -12
  42. package/core/pay/rails/direct.ts +6 -2
  43. package/core/pay/rails/handle.ts +15 -14
  44. package/core/pay/rails/index.ts +5 -3
  45. package/core/pay/rails/nearby.ts +25 -87
  46. package/core/profiles/assertProfileEmpty.ts +19 -10
  47. package/core/services/vault/guard.ts +5 -4
  48. package/core/storage/StorageExpoSQLite.ts +93 -229
  49. package/core/storage/methods/processOfflineActions.ts +86 -136
  50. package/core/storage/schema/createTables.ts +9 -184
  51. package/package.json +6 -5
  52. package/ui/components/pay/AssetPicker.tsx +2 -2
  53. package/ui/components/pay/HandleReceive.tsx +10 -4
  54. package/ui/components/pay/NearbyFlow.tsx +324 -239
  55. package/ui/components/pay/RequestHub.tsx +10 -0
  56. package/ui/components/pay/UniversalSend.tsx +31 -28
  57. package/ui/components/pay/useRecipientInput.ts +2 -2
  58. package/ui/components/ui/PermissionSheet.tsx +94 -160
  59. package/ui/components/ui/colorPrompt.ts +236 -0
  60. package/ui/components/wallet/AmountInput.tsx +9 -6
  61. package/ui/components/wallet/AssetAmount.tsx +6 -6
  62. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  63. package/ui/components/wallet/Balance.tsx +3 -1
  64. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  65. package/ui/components/wallet/tokenEviction.ts +9 -9
  66. package/ui/hooks/useMandala.ts +6 -6
  67. package/ui/hooks/useSpendableBalance.ts +3 -1
  68. package/ui/importDatabases.ts +1 -1
  69. package/ui/screens/PayScreen.tsx +14 -20
  70. package/ui/screens/SettingsScreen.tsx +3 -1
  71. package/ui/screens/WalletCheckScreen.tsx +7 -2
  72. package/ui/screens/WalletHomeScreen.tsx +40 -14
  73. package/ui/screens/tokenRowTitle.ts +28 -15
  74. package/ui/tokenFormat.ts +133 -69
  75. package/ui/tokenStatus.ts +5 -8
  76. package/core/localpay/settlementAck.ts +0 -155
  77. package/core/mandala/basketMigration.ts +0 -166
  78. package/core/mandala/bundle.ts +0 -244
  79. package/core/mandala/drain.ts +0 -754
  80. package/core/mandala/inboxPrehold.ts +0 -193
  81. package/core/mandala/permissionModule.ts +0 -931
  82. package/core/mandala/resendTransfer.ts +0 -178
  83. package/core/mandala/settlementStore.ts +0 -434
  84. package/core/mandala/token.ts +0 -45
  85. package/core/offline/tokenFrames.ts +0 -197
@@ -15,6 +15,7 @@ import PayCellRow from './PayCellRow'
15
15
  import { ConsequenceNote, PayAmountField, PayField } from './PayForm'
16
16
  import { spacing } from '@bsv/expo-wallet-toolbox'
17
17
  import type { TokenAssetStatus, TokenBalance } from '../../../core/mandala/runtime'
18
+ import { tokenUnitsFromField } from '../../tokenFormat'
18
19
 
19
20
  export type RequestMethod = 'get-nearby' | 'get-handle' | 'get-address'
20
21
 
@@ -55,6 +56,15 @@ export function requestSatsFrom(text: string): number | undefined {
55
56
  return Number.isFinite(n) && n > 0 ? n : undefined
56
57
  }
57
58
 
59
+ /**
60
+ * Exact token units from the hub's raw field in token mode, or undefined for
61
+ * an open request. The field emits whole units as plain digits; anything else
62
+ * is not a figure, and nothing is rounded into one or passed through a number.
63
+ */
64
+ export function requestUnitsFrom(text: string): bigint | undefined {
65
+ return tokenUnitsFromField(text)
66
+ }
67
+
58
68
  export default function RequestHub({
59
69
  requestSats,
60
70
  onChangeRequestSats,
@@ -43,7 +43,7 @@ import { useAssetStatus, useMandala } from '../../hooks/useMandala'
43
43
  import { useSpendableBalance } from '../../hooks/useSpendableBalance'
44
44
  import { useContactsStore } from '../../hooks/useContactsStore'
45
45
  import ContactSigil from '../wallet/ContactSigil'
46
- import { formatTokenAmount, formatTokenAmountWithUnit, shortAssetId } from '../../tokenFormat'
46
+ import { formatTokenAmount, formatTokenAmountWithUnit, shortAssetId, tokenUnitsFromField } from '../../tokenFormat'
47
47
  import { abbreviateKey } from '../../../core/pay/counterparty'
48
48
  import type { ContactRow } from '../../../core/contacts/contactsStore'
49
49
  import { createHandleRegistryClient } from '../../../core/identity/handleRegistry/client'
@@ -240,13 +240,13 @@ export interface UniversalSendProps {
240
240
  /** Prefilled amount in satoshis from a peerpay link or `?sats=`. */
241
241
  initialSats?: number
242
242
  /**
243
- * Prefilled TOKEN amount from a peerpay link's `asset=`/`amount=`: base units
244
- * of that asset. Takes precedence over `initialSats` — a link names one money.
243
+ * Prefilled TOKEN amount from a peerpay link's `asset=`/`amount=`: exact
244
+ * token units of that asset. Takes precedence over `initialSats` — a link names one money.
245
245
  * The figure only ever shows while that asset is the one selected (see the
246
246
  * unit tag on the figure below), so a link for a token this wallet turns out
247
247
  * not to hold seeds nothing.
248
248
  */
249
- initialTokenAmount?: { assetId: string; baseUnits: number }
249
+ initialTokenAmount?: { assetId: string; units: bigint }
250
250
  /**
251
251
  * The asset this payment is denominated in. `null` is BSV — the default, and
252
252
  * what every existing flow assumes. Controlled by the Pay screen so the
@@ -275,9 +275,9 @@ interface Figure {
275
275
  unit: string | null
276
276
  }
277
277
 
278
- function seedFigure(sats?: number, token?: { assetId: string; baseUnits: number }): Figure {
279
- if (token && Number.isFinite(token.baseUnits) && token.baseUnits > 0) {
280
- return { text: String(Math.round(token.baseUnits)), unit: token.assetId }
278
+ function seedFigure(sats?: number, token?: { assetId: string; units: bigint }): Figure {
279
+ if (token && typeof token.units === 'bigint' && token.units > 0n) {
280
+ return { text: token.units.toString(), unit: token.assetId }
281
281
  }
282
282
  if (sats && sats > 0) return { text: String(sats), unit: null }
283
283
  return { text: '', unit: null }
@@ -782,17 +782,17 @@ function UniversalSendInner(
782
782
  // Keyed on the figure's parts, not the object: a host that rebuilds the
783
783
  // token-amount object every render must not reseed over what is being typed.
784
784
  const initialTokenAssetId = initialTokenAmount?.assetId
785
- const initialTokenBaseUnits = initialTokenAmount?.baseUnits
785
+ const initialTokenUnits = initialTokenAmount?.units
786
786
  useEffect(() => {
787
787
  setFigure(
788
788
  seedFigure(
789
789
  initialSats,
790
- initialTokenAssetId !== undefined && initialTokenBaseUnits !== undefined
791
- ? { assetId: initialTokenAssetId, baseUnits: initialTokenBaseUnits }
790
+ initialTokenAssetId !== undefined && initialTokenUnits !== undefined
791
+ ? { assetId: initialTokenAssetId, units: initialTokenUnits }
792
792
  : undefined
793
793
  )
794
794
  )
795
- }, [initialSats, initialTokenAssetId, initialTokenBaseUnits])
795
+ }, [initialSats, initialTokenAssetId, initialTokenUnits])
796
796
  useEffect(() => {
797
797
  setNotice(initialNotice ? { type: 'error', message: initialNotice } : null)
798
798
  }, [initialNotice])
@@ -976,7 +976,7 @@ function UniversalSendInner(
976
976
  * allowed to promise "nothing was sent".
977
977
  */
978
978
  const sendToken = useCallback(
979
- async (to: Extract<RecipientTarget, { kind: 'handle' }>, baseUnits: number): Promise<boolean> => {
979
+ async (to: Extract<RecipientTarget, { kind: 'handle' }>, units: bigint): Promise<boolean> => {
980
980
  const runtime = mandala.runtime
981
981
  if (!runtime || !asset) throw new Error(t('wallet_not_ready'))
982
982
  const ctx = {
@@ -988,7 +988,7 @@ function UniversalSendInner(
988
988
  const result = await runtime.sendToHandle({
989
989
  assetId: asset.assetId,
990
990
  recipientIdentityKey: to.identityKey,
991
- baseUnits,
991
+ units,
992
992
  ...(note.trim() ? { note: note.trim() } : {})
993
993
  })
994
994
  if (result.kind !== 'sent') {
@@ -1010,7 +1010,7 @@ function UniversalSendInner(
1010
1010
  // Never falls back to the satoshi renderer: a token figure it could not
1011
1011
  // format would print as satoshis, which is a wrong number rather than a
1012
1012
  // missing one.
1013
- amountText: formatTokenAmountWithUnit(baseUnits, asset) ?? t('token_row_amount_pending'),
1013
+ amountText: formatTokenAmountWithUnit(units, asset) ?? t('token_row_amount_pending'),
1014
1014
  // `notified === false` takes priority: the money moved either way, but
1015
1015
  // the recipient has not been TOLD it did (the lib's own notify retries
1016
1016
  // in the background — see `TokenSendResult.notified`), and that is the
@@ -1058,10 +1058,12 @@ function UniversalSendInner(
1058
1058
  flashResult({ type: 'error', message: t('wallet_not_ready') })
1059
1059
  return
1060
1060
  }
1061
- // The same integer either way — satoshis on the BSV rail, base units of the
1062
- // asset on the token rail. The field emits whole units in both modes.
1061
+ // Satoshis on the BSV rail; exact bigint token units on the token rail,
1062
+ // never through a number (a figure past 2^53 would round). The field
1063
+ // emits whole units as plain digits in both modes.
1063
1064
  const amount = Math.round(Number(sendAmount))
1064
- if (!Number.isFinite(amount) || amount <= 0) {
1065
+ const units = asset ? tokenUnitsFromField(sendAmount) : undefined
1066
+ if (asset ? units === undefined : !Number.isFinite(amount) || amount <= 0) {
1065
1067
  flashResult({ type: 'error', message: t('enter_valid_amount') })
1066
1068
  return
1067
1069
  }
@@ -1072,8 +1074,8 @@ function UniversalSendInner(
1072
1074
  if (asset) {
1073
1075
  // D4: a token has no address rail, and `canSend` has already refused
1074
1076
  // one. This is the second gate, because the first is a render.
1075
- if (target.kind !== 'handle') return
1076
- const sent = await sendToken(target, amount)
1077
+ if (target.kind !== 'handle' || units === undefined) return
1078
+ const sent = await sendToken(target, units)
1077
1079
  if (!sent) return
1078
1080
  } else if (target.kind === 'handle') await sendHandle(target, amount)
1079
1081
  else await sendAddress(target, amount)
@@ -1222,7 +1224,8 @@ function UniversalSendInner(
1222
1224
  [storage, wallet, adminOriginator, peerPayClient, handleRetry, loadOutbox, t]
1223
1225
  )
1224
1226
 
1225
- const amountOk = Number(sendAmount) > 0
1227
+ // Token mode: an exact bigint figure (a number would round past 2^53).
1228
+ const amountOk = asset ? tokenUnitsFromField(sendAmount) !== undefined : Number(sendAmount) > 0
1226
1229
  const isHandle = target?.kind === 'handle'
1227
1230
  const isAddress = target?.kind === 'address'
1228
1231
  /**
@@ -1246,8 +1249,8 @@ function UniversalSendInner(
1246
1249
  // Advisory, and it may only ever say "no". Nothing here promises a send will
1247
1250
  // work; `resolveAssetState` and the registry both fail open, so a pre-flight
1248
1251
  // that said "this will work" would be the one claim they cannot support.
1249
- const baseUnits = asset ? Math.round(Number(sendAmount)) || 0 : 0
1250
- const overBalance = !!holding && baseUnits > holding.baseUnits
1252
+ const tokenUnits = asset ? (tokenUnitsFromField(sendAmount) ?? 0n) : 0n
1253
+ const overBalance = !!holding && tokenUnits > holding.units
1251
1254
  /**
1252
1255
  * The runtime's plain reason this recipient cannot be paid in this asset —
1253
1256
  * an address (D4), an unregistered identity, a blocked one.
@@ -1271,7 +1274,7 @@ function UniversalSendInner(
1271
1274
  // Only asked once the recipient resolved to a handle — an address is already
1272
1275
  // refused by D4 above, and half-typed text is not a recipient yet.
1273
1276
  const recipientRegistryRefused = !!asset && target?.kind === 'handle' && recipientAdmitted === false
1274
- const frozenBaseUnits = assetStatus?.frozenBaseUnits ?? 0
1277
+ const frozenUnits = assetStatus?.frozenUnits ?? 0n
1275
1278
  const tokenFormValid =
1276
1279
  !!asset &&
1277
1280
  isHandle &&
@@ -1333,10 +1336,10 @@ function UniversalSendInner(
1333
1336
  }
1334
1337
  : overBalance
1335
1338
  ? { key: 'pay_asset_over_balance', values: { ticker: asset.ticker } }
1336
- : frozenBaseUnits > 0
1339
+ : frozenUnits > 0n
1337
1340
  ? {
1338
1341
  key: 'pay_asset_frozen_note',
1339
- values: { ticker: asset.ticker, amount: formatTokenAmount(frozenBaseUnits, asset.decimals) ?? '' }
1342
+ values: { ticker: asset.ticker, amount: formatTokenAmount(frozenUnits, asset.decimals) ?? '' }
1340
1343
  }
1341
1344
  : spendableSats === 0
1342
1345
  ? { key: 'pay_asset_needs_bsv', values: { ticker: asset.ticker }, action: 'get-bsv' }
@@ -1376,7 +1379,7 @@ function UniversalSendInner(
1376
1379
  // "12.00 USD" on a BSV send reads as a stablecoin.
1377
1380
  const sendSats = Math.round(Number(sendAmount)) || 0
1378
1381
  const reviewAmount = asset
1379
- ? { value: formatTokenAmount(baseUnits, asset.decimals) ?? '', unit: asset.ticker }
1382
+ ? { value: formatTokenAmount(tokenUnits, asset.decimals) ?? '', unit: asset.ticker }
1380
1383
  : { value: formatSatoshisAsBsvDecimal(sendSats), unit: 'BSV' }
1381
1384
  // XR-044: the last on-screen chance to catch a look-alike asset before Send
1382
1385
  // — issuerName is unverified, but assetId cannot collide, so the review
@@ -1525,9 +1528,9 @@ function UniversalSendInner(
1525
1528
  value={sendAmount}
1526
1529
  onChangeText={setSendAmount}
1527
1530
  asset={asset ? { ticker: asset.ticker, decimals: asset.decimals } : undefined}
1528
- maxValue={holding ? String(holding.baseUnits) : undefined}
1531
+ maxValue={holding ? holding.units.toString() : undefined}
1529
1532
  availableText={
1530
- holding ? (formatTokenAmount(holding.baseUnits, holding.asset.decimals) ?? undefined) : undefined
1533
+ holding ? (formatTokenAmount(holding.units, holding.asset.decimals) ?? undefined) : undefined
1531
1534
  }
1532
1535
  />
1533
1536
 
@@ -62,14 +62,14 @@ export interface UseRecipientInputOptions {
62
62
  * request that has to wait (holdings not known yet) is applied only if the
63
63
  * recipient is still the one the link named.
64
64
  */
65
- export type PeerPayRequest = { identityKey: string; sats?: number; asset?: string; amount?: number }
65
+ export type PeerPayRequest = { identityKey: string; sats?: number; asset?: string; amount?: bigint }
66
66
 
67
67
  /** The request a classified handle carries, or null when it named no money at all. */
68
68
  function requestOf(input: {
69
69
  identityKey: string
70
70
  sats?: number
71
71
  asset?: string
72
- amount?: number
72
+ amount?: bigint
73
73
  }): PeerPayRequest | null {
74
74
  if (input.sats === undefined && input.asset === undefined) return null
75
75
  return {
@@ -6,6 +6,7 @@ import PressableScale from './PressableScale'
6
6
  import { useTranslation } from 'react-i18next'
7
7
  import AmountDisplay from '../wallet/AmountDisplay'
8
8
  import { describeProtocolPrompt } from './protocolPrompt'
9
+ import { describeColorRequest, type ColorPromptType } from './colorPrompt'
9
10
  import {
10
11
  spacing,
11
12
  radii,
@@ -93,53 +94,32 @@ export interface ActivePermission {
93
94
  /** Group-specific sub-permissions. */
94
95
  groupPermissions?: GroupPermissions
95
96
  /**
96
- * XR-040: set when a `mandala_spend`/`mandala_credit` prompt's per-asset
97
- * `lines` could not be trusted to be the WHOLE request (absent, malformed,
98
- * empty, or past `MANDALA_MAX_PROMPT_LINES`) — every asset a single
99
- * approval would release has to be shown, and a request this sheet cannot
100
- * fully enumerate must never be approvable. `handleDeny` is unaffected;
101
- * only the Allow control reads this.
97
+ * XR-040 (carried to the color module): set when a token consent message
98
+ * could not be read in full (`describeColorRequest` returned null) — every
99
+ * asset a single approval would release has to be shown, and a request this
100
+ * sheet cannot fully enumerate must never be approvable. `handleDeny` is
101
+ * unaffected; only the Allow control reads this.
102
102
  */
103
103
  approvalBlocked?: boolean
104
104
  }
105
105
 
106
- /** One line of a `mandala_spend`/`mandala_credit` prompt's `lines[]` array,
107
- * as loosely as a JSON.parse of counterparty-adjacent data should be trusted. */
108
- interface MandalaPromptLine {
109
- assetId?: unknown
110
- sendAmount?: unknown
111
- changeAmount?: unknown
112
- creditAmount?: unknown
113
- tokenName?: unknown
114
- /** Pre-formatted, e.g. "25.00 USDX" — see `MandalaSpendLine`/`MandalaCreditLine`. */
115
- display?: unknown
106
+ /** Always-visible copy for each color consent type, completing "<app> …". */
107
+ const COLOR_DESCRIPTIONS: Record<ColorPromptType, string> = {
108
+ color_send: 'wants to send tokens from your wallet',
109
+ color_signature: 'wants to sign with one of your token keys. Only approve if you just asked this app to move tokens',
110
+ color_access: 'wants to see your token holdings',
111
+ color_relinquish: 'wants to remove a token holding from your wallet'
116
112
  }
117
113
 
118
- /**
119
- * A sane display ceiling for a multi-asset Mandala prompt. Every real prompt
120
- * this app's own `MandalaTokenModule` builds groups by assetId — a handful at
121
- * most — so a `lines` array past this is either a bug or a bad-faith caller,
122
- * either way not something to enumerate as if it were the whole request.
123
- */
124
- const MANDALA_MAX_PROMPT_LINES = 25
125
-
126
- /**
127
- * `promptData.lines`, validated into a bounded array of loosely-typed line
128
- * objects — or `null` for anything this sheet cannot enumerate in full
129
- * (absent, not an array, empty, oversized, or containing a non-object entry).
130
- * `null` is the caller's signal to block approval rather than silently fall
131
- * back to the primary-only view (XR-040).
132
- */
133
- function sanitizedMandalaLines(raw: unknown): MandalaPromptLine[] | null {
134
- if (!Array.isArray(raw) || raw.length === 0 || raw.length > MANDALA_MAX_PROMPT_LINES) return null
135
- const lines: MandalaPromptLine[] = []
136
- for (const entry of raw) {
137
- if (!entry || typeof entry !== 'object') return null
138
- lines.push(entry as MandalaPromptLine)
139
- }
140
- return lines
114
+ /** What the sheet needs to render color consent messages. */
115
+ export interface ColorPromptDeps {
116
+ t: (key: string, o?: object) => string
117
+ /** Host-resolved, untrusted display metadata; undefined ⇒ exact base units. */
118
+ assetInfo: (assetId: string) => { ticker: string; decimals: number } | undefined
141
119
  }
142
120
 
121
+ const NO_COLOR_DEPS: ColorPromptDeps = { t: key => key, assetInfo: () => undefined }
122
+
143
123
  // ---------------------------------------------------------------------------
144
124
  // Helpers
145
125
  // ---------------------------------------------------------------------------
@@ -164,7 +144,8 @@ export function deriveActive(
164
144
  certificateAccessModalOpen: boolean
165
145
  spendingAuthorizationModalOpen: boolean
166
146
  },
167
- formatSats: (satoshis: number) => { value: string; unit: string }
147
+ formatSats: (satoshis: number) => { value: string; unit: string },
148
+ color: ColorPromptDeps = NO_COLOR_DEPS
168
149
  ): ActivePermission | null {
169
150
  // Dev preview — override ctx with real captured data so the description
170
151
  // logic below is exercised exactly as it would be in production.
@@ -332,130 +313,34 @@ export function deriveActive(
332
313
  }
333
314
  }
334
315
 
335
- // mandala: same shape as btms above — driven purely by queue length, resolved via advanceMandalaQueue
316
+ // mandala: the BRC-207 color module's consent queue — driven purely by queue
317
+ // length, resolved via advanceMandalaQueue (same shape as btms above).
336
318
  if (ctx.mandalaRequests.length > 0) {
337
319
  const r = ctx.mandalaRequests[0]
338
- let promptData: {
339
- type?: string
340
- action?: string
341
- assetId?: string
342
- tokenName?: string
343
- sendAmount?: number
344
- changeAmount?: number
345
- creditAmount?: number
346
- lines?: unknown
347
- // XR-041: relinquishOutput's own resolved-target fields.
348
- amount?: number
349
- display?: string
350
- outpoint?: string
351
- } = {}
352
- try {
353
- promptData = JSON.parse(r.message)
354
- } catch {
355
- // message not valid JSON — ignore, use defaults
356
- }
357
-
358
- const isRelinquish = promptData.type === 'mandala_access' && promptData.action === 'relinquishOutput'
359
- // XR-041: `display` is pre-formatted ("25.00 USDX"); fall back to the raw
360
- // base-unit amount + token name when it is not a string, same convention
361
- // as the spend/credit lines below.
362
- const relinquishAmount =
363
- typeof promptData.display === 'string'
364
- ? promptData.display
365
- : promptData.amount != null
366
- ? `${promptData.amount} ${promptData.tokenName || 'Mandala tokens'}`
367
- : undefined
368
-
369
- let description: string
370
- if (promptData.type === 'mandala_spend' && promptData.sendAmount != null) {
371
- description = `wants to spend ${promptData.sendAmount} ${promptData.tokenName || 'Mandala tokens'}`
372
- } else if (promptData.type === 'mandala_credit' && promptData.creditAmount != null) {
373
- description = `wants to credit ${promptData.creditAmount} ${promptData.tokenName || 'Mandala tokens'} to your wallet`
374
- } else if (isRelinquish && relinquishAmount) {
375
- // Named, not generic (XR-041): which holding, not just that "a" holding
376
- // is being removed.
377
- description = `wants to remove ${relinquishAmount} from your wallet`
378
- } else if (isRelinquish) {
379
- description = 'wants to remove a Mandala token holding from your wallet'
380
- } else if (promptData.type === 'mandala_access') {
381
- description = 'wants to see your Mandala token balance'
382
- } else if (promptData.type === 'mandala_signature') {
383
- description = 'wants to sign with one of your token keys. Only approve if you just asked this app to move tokens'
384
- } else {
385
- description = 'wants to access Mandala tokens'
386
- }
387
-
388
- const details: { label: string; value: string }[] = []
389
- let approvalBlocked = false
390
-
391
- if (promptData.type === 'mandala_spend' || promptData.type === 'mandala_credit') {
392
- // XR-040: `lines` carries EVERY asset this request touches — rendering
393
- // only the primary (back-compat) fields below is how a single approval
394
- // silently released a second, unshown asset. Every sanitized line is
395
- // rendered; an unsanitizable `lines` blocks approval instead of falling
396
- // back to a primary-only view that looks complete but is not.
397
- const lines = sanitizedMandalaLines(promptData.lines)
398
- if (lines === null) {
399
- approvalBlocked = true
400
- details.push({
401
- label: 'Warning',
402
- value: 'Could not verify this is the full request — deny and try again.'
403
- })
404
- } else {
405
- const numbered = lines.length > 1
406
- lines.forEach((line, i) => {
407
- const suffix = numbered ? ` ${i + 1}` : ''
408
- if (typeof line.tokenName === 'string' && line.tokenName) {
409
- details.push({ label: `Token${suffix}`, value: line.tokenName })
410
- }
411
- if (typeof line.sendAmount === 'number') {
412
- details.push({
413
- label: `Send amount${suffix}`,
414
- value: typeof line.display === 'string' ? line.display : String(line.sendAmount)
415
- })
416
- }
417
- if (typeof line.changeAmount === 'number' && line.changeAmount !== 0) {
418
- details.push({ label: `Change${suffix}`, value: String(line.changeAmount) })
419
- }
420
- if (typeof line.creditAmount === 'number') {
421
- details.push({
422
- label: `Credit amount${suffix}`,
423
- value: typeof line.display === 'string' ? line.display : String(line.creditAmount)
424
- })
425
- }
426
- if (typeof line.assetId === 'string' && line.assetId) {
427
- details.push({ label: `Asset ID${suffix}`, value: truncate(line.assetId, 28) })
428
- }
429
- })
320
+ const view = typeof r.message === 'string' ? describeColorRequest(r.message, color.assetInfo, color.t) : null
321
+ if (view === null) {
322
+ // Not readable in full: deny-only, and said in the always-visible description.
323
+ return {
324
+ kind: 'mandala',
325
+ requestID: '',
326
+ originator: r.originator || 'Unknown app',
327
+ title: 'Token Request',
328
+ description: 'wants to use your tokens, but this request could not be read — deny it.',
329
+ details: [],
330
+ approvalBlocked: true
430
331
  }
431
- } else if (isRelinquish) {
432
- // XR-041: identify the target the same way mandala_spend/mandala_credit
433
- // already identify theirs — token, amount, and the exact outpoint.
434
- if (promptData.tokenName) details.push({ label: 'Token', value: promptData.tokenName })
435
- if (relinquishAmount) details.push({ label: 'Amount', value: relinquishAmount })
436
- if (promptData.assetId) details.push({ label: 'Asset ID', value: truncate(promptData.assetId, 28) })
437
- if (promptData.outpoint) details.push({ label: 'Outpoint', value: truncate(promptData.outpoint, 28) })
438
- } else {
439
- if (promptData.assetId) details.push({ label: 'Asset ID', value: truncate(promptData.assetId, 28) })
440
332
  }
441
-
442
- // Said in the ALWAYS-VISIBLE description, not only the collapsed Details
443
- // section — the whole point is that this cannot be missed on the way to
444
- // an (already-disabled) Allow button.
445
- if (approvalBlocked) {
446
- description =
447
- 'wants to spend or credit Mandala tokens, but the full request could not be verified — deny and try again.'
448
- }
449
-
333
+ const description =
334
+ view.warning === undefined ? COLOR_DESCRIPTIONS[view.type] : `${COLOR_DESCRIPTIONS[view.type]}. ${view.warning}`
450
335
  return {
451
336
  kind: 'mandala',
452
337
  // mandala requests are resolved via advanceMandalaQueue, not permissionsManager — use a sentinel requestID
453
338
  requestID: '',
454
339
  originator: r.originator || 'Unknown app',
455
- title: 'Token Spend Request',
340
+ title: view.title,
456
341
  description,
457
- details,
458
- approvalBlocked
342
+ details: view.lines,
343
+ approvalBlocked: false
459
344
  }
460
345
  }
461
346
 
@@ -494,7 +379,8 @@ const PermissionSheet: React.FC = () => {
494
379
  advanceBtmsQueue,
495
380
  advanceMandalaQueue,
496
381
  managers,
497
- settings
382
+ settings,
383
+ mandala
498
384
  } = useContext(WalletContext)
499
385
 
500
386
  const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
@@ -504,6 +390,39 @@ const PermissionSheet: React.FC = () => {
504
390
  [currency, satoshisPerUSD, usdToFiat]
505
391
  )
506
392
 
393
+ // Token display metadata for color consent prompts: host-resolved and
394
+ // untrusted (the full asset id is always shown beside it). Loaded when a
395
+ // token prompt is queued; a failed or slow load only means exact base units.
396
+ const [colorAssets, setColorAssets] = useState<ReadonlyMap<string, { ticker: string; decimals: number }>>(
397
+ () => new Map()
398
+ )
399
+ const hasMandalaRequest = mandalaRequests.length > 0
400
+ useEffect(() => {
401
+ if (!hasMandalaRequest || mandala === undefined) return
402
+ let cancelled = false
403
+ // Through Promise.resolve so a synchronous throw is caught too, never
404
+ // crashing the sheet while a token prompt waits.
405
+ Promise.resolve()
406
+ .then(() => mandala.listAssets())
407
+ .then(assets => {
408
+ if (cancelled) return
409
+ setColorAssets(new Map(assets.map(a => [a.assetId, { ticker: a.ticker, decimals: a.decimals }])))
410
+ })
411
+ .catch(() => {
412
+ // Metadata is optional: the prompt falls back to exact base units.
413
+ })
414
+ return () => {
415
+ cancelled = true
416
+ }
417
+ }, [hasMandalaRequest, mandala])
418
+ const colorDeps = useMemo(
419
+ () => ({
420
+ t: (key: string, o?: object) => String(t(key, o as never)),
421
+ assetInfo: (assetId: string) => colorAssets.get(assetId)
422
+ }),
423
+ [t, colorAssets]
424
+ )
425
+
507
426
  const {
508
427
  protocolAccessModalOpen,
509
428
  setProtocolAccessModalOpen,
@@ -553,7 +472,8 @@ const PermissionSheet: React.FC = () => {
553
472
  certificateAccessModalOpen,
554
473
  spendingAuthorizationModalOpen
555
474
  },
556
- formatSats
475
+ formatSats,
476
+ colorDeps
557
477
  ),
558
478
  [
559
479
  protocolRequests,
@@ -567,7 +487,8 @@ const PermissionSheet: React.FC = () => {
567
487
  basketAccessModalOpen,
568
488
  certificateAccessModalOpen,
569
489
  spendingAuthorizationModalOpen,
570
- formatSats
490
+ formatSats,
491
+ colorDeps
571
492
  ]
572
493
  )
573
494
 
@@ -740,8 +661,8 @@ const PermissionSheet: React.FC = () => {
740
661
 
741
662
  const handleGrant = useCallback(() => {
742
663
  // XR-040: belt-and-braces alongside the Allow button's own `disabled` —
743
- // a mandala_spend/mandala_credit prompt whose `lines` this sheet could
744
- // not fully enumerate must never be approvable, from any call path.
664
+ // a token consent message this sheet could not read in full must never
665
+ // be approvable, from any call path.
745
666
  if (!active || granted || active.approvalBlocked) return
746
667
  haptics.success()
747
668
  setGranted(true)
@@ -893,7 +814,17 @@ const PermissionSheet: React.FC = () => {
893
814
  {active.details.map((d, i) => (
894
815
  <View key={i} style={styles.detailRow}>
895
816
  <Text style={[styles.detailLabel, { color: colors.textSecondary }]}>{d.label}</Text>
896
- <Text style={[styles.detailValue, { color: colors.textPrimary }]} numberOfLines={1}>
817
+ {/* Token prompts wrap instead of truncating: the full asset id and
818
+ exact amounts are what the user approves (IC §2.5). */}
819
+ <Text
820
+ style={[
821
+ styles.detailValue,
822
+ { color: colors.textPrimary },
823
+ active.kind === 'mandala' ? styles.detailValueWrap : null
824
+ ]}
825
+ numberOfLines={active.kind === 'mandala' ? undefined : 1}
826
+ selectable={active.kind === 'mandala'}
827
+ >
897
828
  {d.value}
898
829
  {d.unit ? (
899
830
  <Text style={[styles.detailUnit, { color: colors.textSecondary }]}> {d.unit}</Text>
@@ -1084,6 +1015,9 @@ const styles = StyleSheet.create({
1084
1015
  textAlign: 'right',
1085
1016
  fontVariant: ['tabular-nums']
1086
1017
  },
1018
+ detailValueWrap: {
1019
+ flexShrink: 1
1020
+ },
1087
1021
  detailUnit: {
1088
1022
  fontSize: 11.5,
1089
1023
  fontWeight: '500'