@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -101,7 +101,7 @@ import { announceEviction, evictionsFrom } from '../components/wallet/tokenEvict
101
101
  import { SEEN_EVICTIONS_KEY, useSeenSet } from '../tokenSeen'
102
102
  import { profileScopedKey, useActiveProfileIndex } from '../../core/profiles/profileStore'
103
103
  import { tokenRowStatusView } from '../tokenStatus'
104
- import { formatTokenAmount, tokenAmountParts } from '../tokenFormat'
104
+ import { formatTokenAmount, tokenAmountParts, tokenBalanceSplit } from '../tokenFormat'
105
105
  import AssetSwitcherDropdown, { BSV_LABEL } from '../components/wallet/AssetSwitcherDropdown'
106
106
  import { exportTransactionsAsCsv } from '../exportTransactions'
107
107
  import {
@@ -623,7 +623,9 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
623
623
  return
624
624
  }
625
625
  const { totalOutputs } = await pm.listOutputs({ basket: sdk.specOpWalletBalance }, adminOriginator)
626
- total = totalOutputs ?? 0
626
+ // sdk 4 types `totalOutputs` as number | DecimalString (BRC-112 module
627
+ // balances); the satoshi wallet balance is always a safe integer.
628
+ total = Number(totalOutputs ?? 0)
627
629
  }
628
630
  setBalance(total)
629
631
  await AsyncStorage.setItem(balanceCacheKey, String(total))
@@ -1112,15 +1114,19 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1112
1114
  const decryptMetadata = makeMetadataDecryptor(pm, adminOriginator)
1113
1115
  // Every resend goes over the message box, whatever rail the payment
1114
1116
  // first took. What differs is the body: a token row re-sends the
1115
- // Mandala transfer notification (the runtime rebuilds it from the
1116
- // blinding journal and the payee output's marker); a BSV row rebuilds
1117
+ // §7.2 hand-over (the runtime rebuilds it from its journal row, the
1118
+ // color module's evidence and this device's bytes); a BSV row rebuilds
1117
1119
  // its BRC-29 PeerPay token. Identification is by LABEL, like every
1118
1120
  // other token decision on this screen.
1119
1121
  const isToken = actions.find(a => a.txid === txid)?.labels?.includes('mandala') ?? false
1120
1122
  let outcome: Awaited<ReturnType<typeof resendPaymentDetails>>
1121
1123
  if (isToken) {
1122
1124
  if (!mandalaRuntime) throw new Error(t('unknown_error'))
1123
- outcome = await mandalaRuntime.resendTransfer(txid, { refetch, decryptMetadata })
1125
+ const resent = await mandalaRuntime.resendTransfer(txid)
1126
+ outcome =
1127
+ resent === 'resent'
1128
+ ? { ok: true }
1129
+ : { ok: false, reason: resent === 'not-found' ? 'no_record' : 'no_transaction' }
1124
1130
  } else {
1125
1131
  const url = await readMessageBoxUrl(selectedNetwork)
1126
1132
  if (!url) {
@@ -1150,11 +1156,17 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1150
1156
  // too, instead of leaving it looking like it never went anywhere.
1151
1157
  if (storage && offlineByTxid.get(txid)?.status === 'parked') {
1152
1158
  try {
1153
- // XR-036 review follow-up: `isToken` (derived above from the
1154
- // action's own 'mandala' label) is the only signal
1155
- // `releaseParkedPayment` has for whether this txid needs a
1156
- // durable token_settlements row before it may be promoted.
1157
- await releaseParkedPayment({ storage, txid, isTokenHold: isToken })
1159
+ // `isToken` (derived above from the action's own 'mandala'
1160
+ // label) tells `releaseParkedPayment` this park is released
1161
+ // through the journal: the runtime's hook confirms the row is
1162
+ // handed over (the resend above already moved it) before the
1163
+ // queue row is promoted.
1164
+ await releaseParkedPayment({
1165
+ storage,
1166
+ txid,
1167
+ isTokenHold: isToken,
1168
+ ...(isToken && mandalaRuntime ? { onHandedOver: mandalaRuntime.nearby.onHandedOver } : {})
1169
+ })
1158
1170
  } catch (e) {
1159
1171
  console.warn('[localpay] resent but could not release:', e instanceof Error ? e.message : e)
1160
1172
  }
@@ -1476,8 +1488,8 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1476
1488
  const actionByTxid = new Map(actions.filter(a => a.txid).map(a => [a.txid as string, a]))
1477
1489
  const map = new Map<string, NonNullable<React.ComponentProps<typeof ActivityRow>['token']>>()
1478
1490
  for (const [txid, row] of tokenByTxid) {
1479
- const signedBaseUnits = row.role === 'sent' ? -row.baseUnits : row.baseUnits
1480
- const figure = formatTokenAmount(signedBaseUnits, row.asset.decimals, {
1491
+ const signedUnits = row.role === 'sent' ? -row.units : row.units
1492
+ const figure = formatTokenAmount(signedUnits, row.asset.decimals, {
1481
1493
  showPlus: row.role === 'received'
1482
1494
  })
1483
1495
  const action = actionByTxid.get(txid)
@@ -1488,7 +1500,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1488
1500
  labels: action?.labels,
1489
1501
  description: action?.description,
1490
1502
  assetId: row.asset.assetId,
1491
- baseUnits: row.baseUnits,
1503
+ units: row.units,
1492
1504
  t
1493
1505
  }),
1494
1506
  amount: figure ? { value: figure, unit: row.asset.ticker } : undefined,
@@ -1703,8 +1715,15 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1703
1715
  * up. Everything below them still scrolls with the activity it describes.
1704
1716
  */
1705
1717
  /** The hero figure: the token on screen, or the BSV balance. `null` is UNKNOWN. */
1706
- const heroParts = heldAsset ? tokenAmountParts(heldAsset.baseUnits, heldAsset.asset) : balanceParts
1718
+ const heroParts = heldAsset ? tokenAmountParts(heldAsset.units, heldAsset.asset) : balanceParts
1707
1719
  const heroText = heroParts ? `${heroParts.value} ${heroParts.unit}`.trim() : undefined
1720
+ /**
1721
+ * W10: the hero figure is everything spendable, offline credits included.
1722
+ * When part of it is not yet settled with the issuer, the line under it says
1723
+ * how much is pending and how much is settled — never folded together, and
1724
+ * never summed (the pending part is already inside the figure).
1725
+ */
1726
+ const heroPending = useMemo(() => (heldAsset ? tokenBalanceSplit(heldAsset, t) : null), [heldAsset, t])
1708
1727
 
1709
1728
  const pinnedHeader = useMemo(
1710
1729
  () => (
@@ -1763,6 +1782,12 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1763
1782
  {heldAsset.asset.label || heldAsset.asset.issuerName || ''}
1764
1783
  </Text>
1765
1784
  ) : null}
1785
+ {heroPending ? (
1786
+ <>
1787
+ <Text style={[styles.balanceContext, { color: colors.textSecondary }]}>{heroPending.pending}</Text>
1788
+ <Text style={[styles.balanceContext, { color: colors.textSecondary }]}>{heroPending.settled}</Text>
1789
+ </>
1790
+ ) : null}
1766
1791
  </>
1767
1792
  )}
1768
1793
  </TouchableOpacity>
@@ -1825,6 +1850,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1825
1850
  hasVaultMeta,
1826
1851
  hasTokens,
1827
1852
  heldAsset,
1853
+ heroPending,
1828
1854
  payDestination,
1829
1855
  destinationPress,
1830
1856
  MaterialCommunityIcons
@@ -9,29 +9,42 @@ const NEARBY_FIXED: Record<'sent' | 'received', string> = {
9
9
  * The message-box rail's own fixed wording (`@bsv/mandala`'s `transfer.ts`
10
10
  * `Send ${amount} of ${assetId}` / `receive.ts` `Receive ${amount} of
11
11
  * ${assetId}`), reconstructed from the row's own fields so it can be told
12
- * apart from a real note. Requires `assetId`/`baseUnits` — without them
12
+ * apart from a real note. Requires `assetId`/`units` — without them
13
13
  * there is nothing to reconstruct against, so the caller below treats the
14
14
  * rail as unrecognised rather than guess.
15
15
  */
16
- function messageBoxFixed(role: 'sent' | 'received', assetId?: string, baseUnits?: number): string | undefined {
17
- if (assetId === undefined || baseUnits === undefined) return undefined
18
- return `${role === 'sent' ? 'Send' : 'Receive'} ${baseUnits} of ${assetId}`
16
+ function messageBoxFixed(role: 'sent' | 'received', assetId?: string, units?: bigint): string | undefined {
17
+ if (assetId === undefined || typeof units !== 'bigint') return undefined
18
+ // A bigint's own decimal string: exact past 2^53, as the lib wrote it.
19
+ return `${role === 'sent' ? 'Send' : 'Receive'} ${units.toString()} of ${assetId}`
20
+ }
21
+
22
+ /** `@bsv/mandala` 0.5.0's own default descriptions (`sendHandover`, `acceptHandover`). */
23
+ const LIB_FIXED: Record<'sent' | 'received', string> = {
24
+ sent: 'Send Mandala tokens',
25
+ received: 'Receive Mandala tokens'
19
26
  }
20
27
 
21
28
  /**
22
- * The fixed wording for whichever rail authored this action, or `undefined`
29
+ * The fixed wordings for whichever rail authored this action, or `undefined`
23
30
  * when the action carries neither rail's marker label — in which case the
24
31
  * description is never trusted as a note (see `tokenRowTitle`'s doc).
25
32
  */
26
- function fixedDescriptionFor(
33
+ function fixedDescriptionsFor(
27
34
  role: 'sent' | 'received',
28
35
  labels: string[] | undefined,
29
36
  assetId: string | undefined,
30
- baseUnits: number | undefined
31
- ): string | undefined {
37
+ units: bigint | undefined
38
+ ): string[] | undefined {
32
39
  const set = new Set(labels ?? [])
33
- if (set.has(PEERPAY_LABEL)) return NEARBY_FIXED[role]
34
- if (set.has('transfer') || set.has('receive')) return messageBoxFixed(role, assetId, baseUnits)
40
+ if (set.has(PEERPAY_LABEL)) return [NEARBY_FIXED[role]]
41
+ if (set.has('transfer') || set.has('receive')) {
42
+ // Every token hand-over is lib-built since B7, on both rails. Without the
43
+ // row's own asset and units the older wording cannot be ruled out, so the
44
+ // description is not trusted as a note at all.
45
+ const older = messageBoxFixed(role, assetId, units)
46
+ return older === undefined ? undefined : [LIB_FIXED[role], older]
47
+ }
35
48
  return undefined
36
49
  }
37
50
 
@@ -44,7 +57,7 @@ function fixedDescriptionFor(
44
57
  * (label `'localpay'`, fixed wording "Sent/Received token") and the
45
58
  * message-box rail (label `'transfer'`/`'receive'`, `@bsv/mandala`'s own
46
59
  * fixed wording "Send/Receive N of assetId"). An action from neither rail —
47
- * or a message-box action missing the `assetId`/`baseUnits` needed to
60
+ * or a message-box action missing the `assetId`/`units` needed to
48
61
  * reconstruct its fixed wording — never has its description shown: it may be
49
62
  * an opaque developer string the lib wrote for some other purpose, not
50
63
  * anything a user typed (the reason this override existed in the first
@@ -57,12 +70,12 @@ export function tokenRowTitle(args: {
57
70
  description?: string
58
71
  /** The row's own asset id — needed to recognise the message-box rail's fixed wording. */
59
72
  assetId?: string
60
- /** The row's own amount, in base units — same reason as `assetId`. */
61
- baseUnits?: number
73
+ /** The row's own exact token units — same reason as `assetId`. */
74
+ units?: bigint
62
75
  t: (key: string, values?: Record<string, unknown>) => string
63
76
  }): string {
64
- const fixed = fixedDescriptionFor(args.role, args.labels, args.assetId, args.baseUnits)
65
- const hasNote = fixed !== undefined && !!args.description && args.description !== fixed
77
+ const fixed = fixedDescriptionsFor(args.role, args.labels, args.assetId, args.units)
78
+ const hasNote = fixed !== undefined && !!args.description && !fixed.includes(args.description)
66
79
  if (hasNote) return args.description as string
67
80
  return args.t(args.role === 'sent' ? 'token_row_sent' : 'token_row_received', { ticker: args.ticker })
68
81
  }
package/ui/tokenFormat.ts CHANGED
@@ -2,108 +2,173 @@
2
2
  * Token money, formatted so the wallet never prints a number it cannot stand
3
3
  * behind (ux §1 principle 4).
4
4
  *
5
- * Two rules the BSV helpers do not enforce and cannot be bent to:
5
+ * Amounts are exact `bigint` token units on every hop (IC §0, 0162:143): a
6
+ * per-output amount reaches 2^64-1 and a balance is an unbounded sum, both far
7
+ * past 2^53, where a JS number silently rounds. Nothing in this file turns a
8
+ * token amount into a number — not for the digits, not for the grouping.
9
+ *
10
+ * Two rules the lib's helpers do not enforce and cannot be bent to:
6
11
  *
7
12
  * 1. FIXED decimals, never trimmed. `1,240.00 USDX` is money; `1,240 USDX` is
8
13
  * a quantity, and the difference is what a holder reads as "cents exist
9
14
  * here". The lib's own `formatAmount` right-trims, so every figure in the
10
- * design is unreachable through it.
11
- * 2. Integer arithmetic only. A balance is base units; dividing by 10^decimals
12
- * in floating point and then rounding is how a wallet prints 1,239.99 for
13
- * 124000 at 2 dp. The split below is string surgery on the integer, so the
14
- * printed digits are exactly the digits that are owned.
15
+ * design is unreachable through it; the split below pads instead.
16
+ * 2. Integer arithmetic only. The split is string surgery on the integer's
17
+ * decimal digits, so the printed digits are exactly the digits that are
18
+ * owned.
19
+ *
20
+ * Parsing is the lib's `parseAmount` (the uint64 bound, the decimals bound and
21
+ * the display grammar live there once), wrapped so a bad keystroke is `null`
22
+ * rather than a throw.
15
23
  *
16
24
  * There is deliberately no fiat path and no currency symbol: the wallet has no
17
25
  * price for a token and a `$` beside a USD-ticker balance would be the wallet
18
26
  * vouching for someone else's peg (ux §6.1).
19
27
  */
28
+ import { parseAmount } from '@bsv/mandala'
20
29
 
21
30
  /**
22
31
  * XR-043: mirrored at every other boundary that ever reads a token's
23
- * decimals — `core/localpay/session.ts`'s session codec and
24
- * `core/mandala/createRuntime.ts`'s asset-metadata resolution enforce the
25
- * same bound at THEIR boundaries; this is the last line of defense inside
26
- * the formatters themselves, since a decimals value can reach here from a
27
- * path neither of those touches (a stale cached asset, a test double, a
28
- * future caller). Nothing token-shaped this wallet knows of uses more than a
29
- * handful; an unbounded decimals value is how `String(...).padStart` (and
30
- * an unbounded regex quantifier below) blows up the confirmation UI.
32
+ * decimals — `core/localpay/session.ts`'s session codec and the runtime's
33
+ * asset-metadata resolution enforce the same bound at THEIR boundaries; this
34
+ * is the last line of defense inside the formatters themselves, since a
35
+ * decimals value can reach here from a path neither of those touches (a stale
36
+ * cached asset, a test double, a future caller). It is also BRC-162's own
37
+ * `dec` bound (0..18), the one the lib's `parseAmount` enforces.
31
38
  */
32
39
  const MAX_TOKEN_DECIMALS = 18
33
40
 
34
- /** Grouping separators for the integer part, in the device's own locale. */
41
+ function decimalsOk(decimals: number): boolean {
42
+ return Number.isInteger(decimals) && decimals >= 0 && decimals <= MAX_TOKEN_DECIMALS
43
+ }
44
+
45
+ /**
46
+ * The device locale's grouping separator, read off a formatted sample number
47
+ * (the device's default locale, as the wallet always grouped token figures).
48
+ * Only the separator comes from the locale; a token amount's digits never
49
+ * pass through a number. Falls back to `,` when the platform's Intl cannot
50
+ * answer, and to none for a locale that does not group.
51
+ */
52
+ function groupSeparator(): string {
53
+ try {
54
+ const part = new Intl.NumberFormat(undefined, { useGrouping: true })
55
+ .formatToParts(1000000)
56
+ .find(p => p.type === 'group')
57
+ return part ? part.value : ''
58
+ } catch {
59
+ return ','
60
+ }
61
+ }
62
+
63
+ /** `'1240'` → `'1,240'`, in threes from the right, on the digit string itself. */
35
64
  function groupInteger(digits: string): string {
36
- const n = Number(digits)
37
- if (!Number.isFinite(n)) return digits
38
- // Safe: the integer part of a base-unit figure is always smaller than the
39
- // figure itself, and anything past 2^53 is already unrepresentable upstream.
40
- return n.toLocaleString(undefined, { useGrouping: true, maximumFractionDigits: 0 })
65
+ const sep = groupSeparator()
66
+ if (!sep || digits.length <= 3) return digits
67
+ let out = ''
68
+ for (let i = digits.length; i > 0; i -= 3) {
69
+ const chunk = digits.slice(Math.max(0, i - 3), i)
70
+ out = out ? `${chunk}${sep}${out}` : chunk
71
+ }
72
+ return out
41
73
  }
42
74
 
43
75
  /**
44
- * `1240000` at 2 dp → `"1,240.00"`. Negative inputs keep their sign; a
45
- * non-finite input is refused with `null` rather than rendered as `NaN`, so a
76
+ * `124000n` at 2 dp → `"1,240.00"`. Negative inputs keep their sign (a sent
77
+ * row); anything that is not a `bigint`, or a decimals value outside 0..18, is
78
+ * refused with `null` rather than rendered as a rounded or `NaN` figure, so a
46
79
  * caller that forgot to guard prints nothing instead of nonsense.
47
80
  */
48
- export function formatTokenAmount(
49
- baseUnits: number,
50
- decimals: number,
51
- opts: { showPlus?: boolean } = {}
52
- ): string | null {
53
- if (!Number.isFinite(baseUnits) || !Number.isInteger(decimals) || decimals < 0 || decimals > MAX_TOKEN_DECIMALS)
54
- return null
55
- const d = Math.floor(decimals)
56
- const rounded = Math.round(Math.abs(baseUnits))
57
- const digits = String(rounded).padStart(d + 1, '0')
58
- const intPart = d === 0 ? digits : digits.slice(0, digits.length - d)
59
- const fracPart = d === 0 ? '' : digits.slice(digits.length - d)
60
- const body = d === 0 ? groupInteger(intPart) : `${groupInteger(intPart)}.${fracPart}`
61
- const sign = baseUnits < 0 ? '−' : opts.showPlus ? '+' : ''
81
+ export function formatTokenAmount(units: bigint, decimals: number, opts: { showPlus?: boolean } = {}): string | null {
82
+ if (typeof units !== 'bigint' || !decimalsOk(decimals)) return null
83
+ const negative = units < 0n
84
+ const digits = (negative ? -units : units).toString().padStart(decimals + 1, '0')
85
+ const intPart = digits.slice(0, digits.length - decimals)
86
+ const fracPart = digits.slice(digits.length - decimals)
87
+ const body = decimals === 0 ? groupInteger(intPart) : `${groupInteger(intPart)}.${fracPart}`
88
+ const sign = negative ? '−' : opts.showPlus ? '+' : ''
62
89
  return `${sign}${body}`
63
90
  }
64
91
 
65
92
  /** `"1,240.00"` + `"USDX"` — the two halves a money figure is drawn from. */
66
93
  export function tokenAmountParts(
67
- baseUnits: number,
94
+ units: bigint,
68
95
  asset: { decimals: number; ticker: string },
69
96
  opts: { showPlus?: boolean } = {}
70
97
  ): { value: string; unit: string } | null {
71
- const value = formatTokenAmount(baseUnits, asset.decimals, opts)
98
+ const value = formatTokenAmount(units, asset.decimals, opts)
72
99
  if (value === null) return null
73
100
  return { value, unit: asset.ticker }
74
101
  }
75
102
 
76
103
  /** `"1,240.00 USDX"` — the one string VoiceOver reads for a token figure. */
77
104
  export function formatTokenAmountWithUnit(
78
- baseUnits: number,
105
+ units: bigint,
79
106
  asset: { decimals: number; ticker: string },
80
107
  opts: { showPlus?: boolean } = {}
81
108
  ): string | null {
82
- const parts = tokenAmountParts(baseUnits, asset, opts)
109
+ const parts = tokenAmountParts(units, asset, opts)
83
110
  return parts && `${parts.value} ${parts.unit}`
84
111
  }
85
112
 
86
113
  /**
87
- * A typed display figure back to base units, for the amount field.
114
+ * W10: what part of a held balance is pending and what part is settled, as
115
+ * the two lines a balance row adds under its figure — or `null` when nothing
116
+ * is pending (the figure alone is the whole story) or a figure cannot be
117
+ * formatted.
88
118
  *
89
- * Returns `null` for anything that is not a whole number of base units — blank,
90
- * junk, or more decimal places than the asset has. The field never emits a
91
- * fraction: the wire takes integers, and a rounded one would silently pay a
92
- * different amount than the one on screen.
119
+ * `units` is everything spendable (the `p color balance` view, offline credits
120
+ * included) and `offlineUnits` the part tagged `color_offline`; the settled
121
+ * part is the difference, never a sum. The runtime already clamps
122
+ * `offlineUnits` to `units`; it is clamped again here so a stale or mocked
123
+ * figure can never print a negative settled amount.
124
+ */
125
+ export function tokenBalanceSplit(
126
+ balance: { asset: { decimals: number; ticker: string }; units: bigint; offlineUnits: bigint },
127
+ t: (key: string, values?: Record<string, unknown>) => string
128
+ ): { pending: string; settled: string } | null {
129
+ const { asset, units, offlineUnits } = balance
130
+ if (typeof units !== 'bigint' || typeof offlineUnits !== 'bigint' || offlineUnits <= 0n) return null
131
+ const pendingUnits = offlineUnits > units ? units : offlineUnits
132
+ const pending = formatTokenAmountWithUnit(pendingUnits, asset)
133
+ const settled = formatTokenAmountWithUnit(units - pendingUnits, asset)
134
+ if (pending === null || settled === null) return null
135
+ return {
136
+ pending: t('token_balance_pending', { amount: pending }),
137
+ settled: t('token_balance_settled', { amount: settled })
138
+ }
139
+ }
140
+
141
+ /**
142
+ * A typed display figure back to token units, for the amount field.
143
+ *
144
+ * Returns `null` for anything that is not a payable per-output amount: blank,
145
+ * junk, a sign, more decimal places than the asset has, zero, or more than
146
+ * `MAX_UINT64` (0162:143). The field never emits a fraction or a rounded
147
+ * figure: the wire takes exact integers, and a rounded one would silently pay
148
+ * a different amount than the one on screen.
149
+ */
150
+ export function parseTokenAmount(text: string, decimals: number): bigint | null {
151
+ if (typeof text !== 'string' || !decimalsOk(decimals)) return null
152
+ let units: bigint
153
+ try {
154
+ units = parseAmount(text, decimals)
155
+ } catch {
156
+ return null
157
+ }
158
+ return units > 0n ? units : null
159
+ }
160
+
161
+ /**
162
+ * Exact token units from an amount field's emitted value — the plain digit
163
+ * string `AmountInput` writes in token mode — or `undefined` when it is not a
164
+ * positive figure (blank, junk, a fraction, a sign, zero). Never through a
165
+ * number, and never rounded into a figure.
93
166
  */
94
- export function parseTokenAmount(text: string, decimals: number): number | null {
95
- if (!Number.isInteger(decimals) || decimals < 0 || decimals > MAX_TOKEN_DECIMALS) return null
96
- const trimmed = text.trim()
97
- if (!trimmed) return null
98
- const d = Math.floor(decimals)
99
- const match = new RegExp(`^(\\d*)(?:\\.(\\d{0,${d}}))?$`).exec(trimmed)
100
- if (!match) return null
101
- const intPart = match[1] ?? ''
102
- const fracPart = (match[2] ?? '').padEnd(d, '0')
103
- if (!intPart && !match[2]) return null
104
- const combined = `${intPart || '0'}${fracPart}`
105
- const value = Number(combined)
106
- return Number.isSafeInteger(value) ? value : null
167
+ export function tokenUnitsFromField(text: string): bigint | undefined {
168
+ const trimmed = typeof text === 'string' ? text.trim() : ''
169
+ if (!/^[0-9]+$/.test(trimmed)) return undefined
170
+ const units = BigInt(trimmed)
171
+ return units > 0n ? units : undefined
107
172
  }
108
173
 
109
174
  /**
@@ -120,21 +185,20 @@ export function tokenAmountMask(decimals: number): RegExp {
120
185
  return d === 0 ? /^\d*$/ : new RegExp(`^\\d*\\.?\\d{0,${d}}$`)
121
186
  }
122
187
 
123
- /** Base units → the exact display string the amount field should hold. */
124
- export function tokenAmountInputText(baseUnits: number, decimals: number): string {
125
- const formatted = formatTokenAmount(baseUnits, decimals)
188
+ /** Token units → the exact display string the amount field should hold. */
189
+ export function tokenAmountInputText(units: bigint, decimals: number): string {
190
+ const formatted = formatTokenAmount(units, decimals)
126
191
  if (formatted === null) return ''
127
- // The field is typed, not read: no grouping separators, which a decimal-pad
128
- // cannot produce and `parseTokenAmount` would refuse on the next keystroke.
129
- return formatted.replace(/[^\d.]/g, '')
192
+ // The field is typed, not read: no grouping separators or sign, which a
193
+ // decimal-pad cannot produce and `parseTokenAmount` would refuse on the next
194
+ // keystroke.
195
+ return formatted.replace(/[^0-9.]/g, '')
130
196
  }
131
197
 
132
198
  /**
133
- * A short, human-scannable form of a long `'<64-hex>.<vout>'` assetId —
134
- * `"a1b2c3d4…ef01.0"`. Same truncation `core/mandala/permissionModule.ts`'s
135
- * own (unexported) `shortAssetId` uses for prompt copy, kept as a small
136
- * separate copy here rather than an import so the UI layer does not reach
137
- * into `core/mandala` for a pure string helper.
199
+ * A short, human-scannable form of a long `'<64-hex>_<vout>'` assetId —
200
+ * `"a1b2c3d4…ef01_0"`. A pure string helper kept here so the UI layer does
201
+ * not reach into `core/mandala` for it.
138
202
  *
139
203
  * XR-044: an issuer-chosen ticker/label is not unique — a look-alike asset
140
204
  * from a different issuer can share both. `assetId` is the one thing that
package/ui/tokenStatus.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * What a token row's settlement state is called, and in what colour.
3
3
  *
4
- * Five states reach the UI (`TokenActivityStatus`), and the mapping is here
4
+ * Four states reach the UI (`TokenActivityStatus`), and the mapping is here
5
5
  * rather than inside a component so the same word appears in the activity list,
6
6
  * the Asset sheet and the home badge without three chances to disagree.
7
7
  *
@@ -19,7 +19,6 @@ const KEYS: Record<TokenActivityStatus, string> = {
19
19
  settling: 'token_status_settling',
20
20
  settled: 'token_status_settled',
21
21
  refused: 'token_status_refused',
22
- reversed: 'token_status_reversed',
23
22
  stuck: 'token_status_stuck'
24
23
  }
25
24
 
@@ -27,7 +26,6 @@ const TONES: Record<TokenActivityStatus, TokenStatusTone> = {
27
26
  settling: 'neutral',
28
27
  settled: 'positive',
29
28
  refused: 'error',
30
- reversed: 'error',
31
29
  stuck: 'warning'
32
30
  }
33
31
 
@@ -46,8 +44,7 @@ export function tokenRowStatusView(status: TokenActivityStatus, incoming: boolea
46
44
  case 'settled':
47
45
  return { key: incoming ? 'tx_status_received' : 'tx_status_sent', tone: 'settled' }
48
46
  case 'refused':
49
- case 'reversed':
50
- return { key: KEYS[status], tone: 'failed' }
47
+ return { key: KEYS.refused, tone: 'failed' }
51
48
  case 'stuck':
52
49
  return { key: KEYS.stuck, tone: 'attention' }
53
50
  default:
@@ -61,8 +58,9 @@ export function tokenStatusTone(status: TokenActivityStatus): TokenStatusTone {
61
58
 
62
59
  /**
63
60
  * The sentence a finished-but-unhappy row explains itself with, or `null` when
64
- * the status word is the whole story. Refusal and reversal are the two states a
65
- * holder is owed an explanation for, because money moved back.
61
+ * the status word is the whole story. A refusal is the state a holder is owed
62
+ * an explanation for, because money moved back (a received refusal is a
63
+ * credit the color module withdrew).
66
64
  *
67
65
  * `refusedCode` narrows a `stuck` or `received`-`refused` row to a more exact
68
66
  * reason, the same way `tokenSendCopy.ts` narrows a live send failure — by
@@ -95,6 +93,5 @@ export function tokenStatusDetailKey(
95
93
  if (has('shape', 'conservation', 'satoshi')) return 'token_frame_unreadable'
96
94
  return 'token_recv_reversed'
97
95
  }
98
- if (status === 'reversed') return 'token_settle_evicted'
99
96
  return null
100
97
  }