@bsv/expo-wallet-toolbox 0.21.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 (78) hide show
  1. package/CHANGELOG.md +114 -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/i18n/translations.tsx +72 -0
  11. package/core/index.ts +55 -37
  12. package/core/localpay/build.ts +110 -569
  13. package/core/localpay/codec.ts +190 -93
  14. package/core/localpay/pending.ts +217 -202
  15. package/core/localpay/session.ts +99 -25
  16. package/core/localpay/types.ts +6 -5
  17. package/core/localpay/verify.ts +118 -173
  18. package/core/mandala/abortGuard.ts +97 -120
  19. package/core/mandala/accessPolicy.ts +133 -0
  20. package/core/mandala/assets.ts +370 -0
  21. package/core/mandala/colorGuard.ts +178 -0
  22. package/core/mandala/colorModule.ts +82 -0
  23. package/core/mandala/createRuntime.ts +483 -2392
  24. package/core/mandala/handle.ts +694 -0
  25. package/core/mandala/kvStore.ts +105 -0
  26. package/core/mandala/nearby.ts +185 -0
  27. package/core/mandala/receipt.ts +121 -0
  28. package/core/mandala/runtime.ts +166 -312
  29. package/core/mandala/settle.ts +540 -0
  30. package/core/mandala/transferJournal.ts +395 -0
  31. package/core/mandala/types.ts +61 -311
  32. package/core/networks.ts +5 -5
  33. package/core/offline/cancelParked.ts +80 -63
  34. package/core/offline/payerHold.ts +52 -118
  35. package/core/parsePeerPayURI.ts +25 -12
  36. package/core/pay/rails/handle.ts +15 -14
  37. package/core/pay/rails/index.ts +5 -3
  38. package/core/pay/rails/nearby.ts +25 -87
  39. package/core/profiles/assertProfileEmpty.ts +19 -10
  40. package/core/services/vault/guard.ts +5 -4
  41. package/core/storage/StorageExpoSQLite.ts +93 -229
  42. package/core/storage/methods/processOfflineActions.ts +86 -136
  43. package/core/storage/schema/createTables.ts +9 -184
  44. package/package.json +6 -5
  45. package/ui/components/pay/AssetPicker.tsx +2 -2
  46. package/ui/components/pay/HandleReceive.tsx +4 -4
  47. package/ui/components/pay/NearbyFlow.tsx +324 -239
  48. package/ui/components/pay/RequestHub.tsx +10 -0
  49. package/ui/components/pay/UniversalSend.tsx +31 -28
  50. package/ui/components/pay/useRecipientInput.ts +2 -2
  51. package/ui/components/ui/PermissionSheet.tsx +94 -160
  52. package/ui/components/ui/colorPrompt.ts +236 -0
  53. package/ui/components/wallet/AmountInput.tsx +9 -6
  54. package/ui/components/wallet/AssetAmount.tsx +6 -6
  55. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  56. package/ui/components/wallet/Balance.tsx +3 -1
  57. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  58. package/ui/components/wallet/tokenEviction.ts +9 -9
  59. package/ui/hooks/useMandala.ts +6 -6
  60. package/ui/hooks/useSpendableBalance.ts +3 -1
  61. package/ui/importDatabases.ts +1 -1
  62. package/ui/screens/PayScreen.tsx +14 -20
  63. package/ui/screens/SettingsScreen.tsx +3 -1
  64. package/ui/screens/WalletCheckScreen.tsx +7 -2
  65. package/ui/screens/WalletHomeScreen.tsx +40 -14
  66. package/ui/screens/tokenRowTitle.ts +28 -15
  67. package/ui/tokenFormat.ts +133 -69
  68. package/ui/tokenStatus.ts +5 -8
  69. package/core/localpay/settlementAck.ts +0 -155
  70. package/core/mandala/basketMigration.ts +0 -166
  71. package/core/mandala/bundle.ts +0 -244
  72. package/core/mandala/drain.ts +0 -754
  73. package/core/mandala/inboxPrehold.ts +0 -193
  74. package/core/mandala/permissionModule.ts +0 -931
  75. package/core/mandala/resendTransfer.ts +0 -178
  76. package/core/mandala/settlementStore.ts +0 -434
  77. package/core/mandala/token.ts +0 -45
  78. package/core/offline/tokenFrames.ts +0 -197
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Consent copy for the BRC-207 color module's `requestTokenAccess` messages
3
+ * (IC §2.5). Field names are the module 0.2.0's own (`actionConsent` /
4
+ * `transactionConsent` for `color_send` / `color_signature`). Every amount on
5
+ * the wire is a canonical decimal string (IC §0) and is shown exactly, never
6
+ * through a JS number. Asset metadata (ticker, decimals) is host-resolved and
7
+ * untrusted, so the full asset id is always shown beside it.
8
+ *
9
+ * Anything this file cannot read in full returns `null`: the sheet then shows
10
+ * a deny-only prompt, because a request it cannot enumerate must never be
11
+ * approvable (XR-040 carried forward).
12
+ */
13
+ import { formatAmount, parseDecimalAmount } from '@bsv/mandala'
14
+ import { COLOR_PROMPT_TYPES, type ColorPromptType } from '../../../core/mandala/accessPolicy'
15
+
16
+ export type { ColorPromptType } from '../../../core/mandala/accessPolicy'
17
+
18
+ export interface ColorPromptView {
19
+ type: ColorPromptType
20
+ title: string
21
+ lines: { label: string; value: string }[]
22
+ warning?: string
23
+ }
24
+
25
+ type AssetInfo = (assetId: string) => { ticker: string; decimals: number } | undefined
26
+ type Translate = (key: string, o?: object) => string
27
+
28
+ /** A display ceiling: real requests carry a handful of legs; past this the request is not enumerated. */
29
+ const MAX_ASSETS = 25
30
+ const MAX_DESTINATIONS = 100
31
+ const MAX_OUTPUTS = 1000
32
+ const MAX_SIGNERS = 100
33
+ const MAX_SIGNATURES = 1000
34
+
35
+ const ASSET_ID = /^[0-9a-f]{64}_(0|[1-9][0-9]*)$/
36
+ const OUTPOINT = /^[0-9a-f]{64}\.(0|[1-9][0-9]*)$/
37
+ const ISSUE = 'ISSUE'
38
+
39
+ const TITLE_KEYS: Record<ColorPromptType, string> = {
40
+ color_send: 'color_prompt_send_title',
41
+ color_signature: 'color_prompt_signature_title',
42
+ color_access: 'color_prompt_access_title',
43
+ color_relinquish: 'color_prompt_relinquish_title'
44
+ }
45
+
46
+ /** Thrown inside this file only: the message is not fully readable. */
47
+ class Unreadable extends Error {}
48
+
49
+ function fail(): never {
50
+ throw new Unreadable()
51
+ }
52
+
53
+ function isRecord(v: unknown): v is Record<string, unknown> {
54
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
55
+ }
56
+
57
+ function amountOf(v: unknown): bigint {
58
+ const units = parseDecimalAmount(v)
59
+ return units === null ? fail() : units
60
+ }
61
+
62
+ function countOf(v: unknown): number {
63
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : fail()
64
+ }
65
+
66
+ function assetIdOf(v: unknown, allowIssue = false): string {
67
+ if (typeof v !== 'string') fail()
68
+ if (allowIssue && v === ISSUE) return v
69
+ return ASSET_ID.test(v) ? v : fail()
70
+ }
71
+
72
+ function listOf(v: unknown, max: number, allowEmpty = false): unknown[] {
73
+ if (!Array.isArray(v) || v.length > max || (!allowEmpty && v.length === 0)) fail()
74
+ return v
75
+ }
76
+
77
+ function stringsOf(v: unknown, max: number): string[] {
78
+ const list = listOf(v, max, true)
79
+ return list.every(s => typeof s === 'string') ? (list as string[]) : fail()
80
+ }
81
+
82
+ /** `units` of `assetId` for a person: `<decimal> <ticker>` when the asset's
83
+ * metadata is usable, otherwise the exact base units. */
84
+ function unitsText(units: bigint, assetId: string, assetInfo: AssetInfo): string {
85
+ let meta: { ticker: string; decimals: number } | undefined
86
+ try {
87
+ meta = assetId === ISSUE ? undefined : assetInfo(assetId)
88
+ } catch {
89
+ meta = undefined
90
+ }
91
+ const ticker = typeof meta?.ticker === 'string' ? meta.ticker.trim() : ''
92
+ if (meta !== undefined && ticker.length > 0) {
93
+ try {
94
+ return `${formatAmount(units, meta.decimals)} ${ticker}`
95
+ } catch {
96
+ // decimals outside 0..18: fall through to exact base units
97
+ }
98
+ }
99
+ return `${units.toString()} units`
100
+ }
101
+
102
+ function describeTransaction(
103
+ m: Record<string, unknown>,
104
+ type: 'color_send' | 'color_signature',
105
+ assetInfo: AssetInfo
106
+ ): ColorPromptView['lines'] {
107
+ const lines: ColorPromptView['lines'] = []
108
+ const push = (label: string, value: string): void => {
109
+ lines.push({ label, value })
110
+ }
111
+ const assets = listOf(m.assets, MAX_ASSETS, true)
112
+ const destinations = listOf(m.destinations, MAX_DESTINATIONS, true)
113
+ const satoshis = isRecord(m.satoshis) ? m.satoshis : fail()
114
+ const fee = satoshis.fee
115
+ if (typeof fee !== 'number' || !Number.isSafeInteger(fee)) fail()
116
+ const lockTime = countOf(m.lockTime)
117
+ listOf(m.signatures, MAX_SIGNATURES, true)
118
+ if (assets.length === 0 && m.deploy === undefined) fail()
119
+
120
+ if (type === 'color_signature') push('Signs input', String(countOf(m.inputIndex)))
121
+ if (type === 'color_send' && m.handoff === true) push('Delivery', 'Recipient completes it (hand-over)')
122
+
123
+ if (m.deploy !== undefined) {
124
+ const deploy = isRecord(m.deploy) ? m.deploy : fail()
125
+ push('Issues new asset', `${amountOf(deploy.amount).toString()} units`)
126
+ }
127
+
128
+ for (const raw of assets) {
129
+ const a = isRecord(raw) ? raw : fail()
130
+ const assetId = assetIdOf(a.assetId)
131
+ const show = (units: bigint): string => unitsText(units, assetId, assetInfo)
132
+ const outgoing = amountOf(a.outgoingAmount)
133
+ const kept = amountOf(a.keptAmount)
134
+ const input = amountOf(a.inputAmount)
135
+ const foreign = amountOf(a.foreignAmount)
136
+ const burned = amountOf(a.burned)
137
+ const minted = amountOf(a.minted)
138
+ amountOf(a.transferred)
139
+ const outgoingAuthorities = countOf(a.outgoingAuthorities)
140
+ const keptAuthorities = countOf(a.keptAuthorities)
141
+ const authorityInputs = countOf(a.authorityInputs)
142
+ countOf(a.foreignAuthorityInputs)
143
+ if (a.operations !== undefined) stringsOf(a.operations, 16)
144
+
145
+ push('Asset ID', assetId)
146
+ push('Sending', show(outgoing))
147
+ if (kept !== 0n) push('Kept as change', show(kept))
148
+ if (input !== 0n) push('Spent from this wallet', show(input))
149
+ if (foreign !== 0n) push('From another wallet', show(foreign))
150
+ if (burned !== 0n) push('Burned', show(burned))
151
+ if (minted !== 0n) push('Minted', show(minted))
152
+ if (authorityInputs > 0) push('Authorities spent', String(authorityInputs))
153
+ if (outgoingAuthorities > 0) push('Authorities sent', String(outgoingAuthorities))
154
+ if (keptAuthorities > 0) push('Authorities kept', String(keptAuthorities))
155
+ }
156
+
157
+ for (const raw of destinations) {
158
+ const d = isRecord(raw) ? raw : fail()
159
+ const index = countOf(d.outputIndex)
160
+ if (d.assetId !== undefined) {
161
+ const assetId = assetIdOf(d.assetId, true)
162
+ const units = amountOf(d.amount)
163
+ const what = d.role === 'authority' ? 'authority' : unitsText(units, assetId, assetInfo)
164
+ push(`Output ${index}`, what)
165
+ } else {
166
+ push(`Output ${index}`, `${countOf(d.satoshis)} sats`)
167
+ }
168
+ }
169
+
170
+ push('Network fee', `${fee} sats`)
171
+ if (lockTime !== 0) push('Lock time', String(lockTime))
172
+ return lines
173
+ }
174
+
175
+ function describeAccess(m: Record<string, unknown>): ColorPromptView['lines'] {
176
+ const lines: ColorPromptView['lines'] = []
177
+ if (typeof m.basket === 'string') lines.push({ label: 'Reads', value: m.basket })
178
+ else if (m.labels !== undefined) {
179
+ const labels = stringsOf(m.labels, 100)
180
+ lines.push({ label: 'Reads', value: labels.length > 0 ? labels.join(', ') : 'token activity' })
181
+ } else fail()
182
+ if (m.assetId !== undefined) lines.push({ label: 'Asset ID', value: assetIdOf(m.assetId) })
183
+ if (m.role !== undefined) {
184
+ if (m.role !== 'value' && m.role !== 'authority') fail()
185
+ lines.push({ label: 'Holding', value: m.role })
186
+ }
187
+ return lines
188
+ }
189
+
190
+ function describeRelinquish(m: Record<string, unknown>): ColorPromptView['lines'] {
191
+ const assetId = assetIdOf(m.assetId)
192
+ if (m.role !== 'value' && m.role !== 'authority') fail()
193
+ const outpoint = typeof m.outpoint === 'string' && OUTPOINT.test(m.outpoint) ? m.outpoint : fail()
194
+ return [
195
+ { label: 'Asset ID', value: assetId },
196
+ { label: 'Holding', value: m.role as string },
197
+ { label: 'Outpoint', value: outpoint }
198
+ ]
199
+ }
200
+
201
+ /**
202
+ * What a color consent message asks, for the permission sheet. `null` when the
203
+ * message is not fully readable (bad JSON, an unknown type, a missing member, a
204
+ * JSON-number or non-canonical amount, an oversized list): the sheet then shows
205
+ * a generic deny-only prompt.
206
+ */
207
+ export function describeColorRequest(message: string, assetInfo: AssetInfo, t: Translate): ColorPromptView | null {
208
+ let m: unknown
209
+ try {
210
+ m = JSON.parse(message)
211
+ } catch {
212
+ return null
213
+ }
214
+ if (!isRecord(m) || typeof m.type !== 'string') return null
215
+ if (!(COLOR_PROMPT_TYPES as readonly string[]).includes(m.type)) return null
216
+ const type = m.type as ColorPromptType
217
+ try {
218
+ let lines: ColorPromptView['lines']
219
+ switch (type) {
220
+ case 'color_send':
221
+ case 'color_signature':
222
+ lines = describeTransaction(m, type, assetInfo)
223
+ break
224
+ case 'color_access':
225
+ lines = describeAccess(m)
226
+ break
227
+ case 'color_relinquish':
228
+ lines = describeRelinquish(m)
229
+ break
230
+ }
231
+ return { type, title: t(TITLE_KEYS[type]), lines }
232
+ } catch {
233
+ // Unreadable, or any other failure while building the view: fail closed to the deny-only prompt.
234
+ return null
235
+ }
236
+ }
@@ -17,7 +17,7 @@ import {
17
17
  satoshisPerFiatUnit,
18
18
  decimalSeparator
19
19
  } from '@bsv/expo-wallet-toolbox'
20
- import { parseTokenAmount, tokenAmountInputText, tokenAmountMask } from '../../tokenFormat'
20
+ import { parseTokenAmount, tokenAmountInputText, tokenAmountMask, tokenUnitsFromField } from '../../tokenFormat'
21
21
 
22
22
  /**
23
23
  * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
@@ -146,7 +146,9 @@ export const AmountInput: React.FC<AmountInputProps> = ({
146
146
  useEffect(() => {
147
147
  if (!asset) return
148
148
  if (value === lastEmitted.current) return
149
- setDisplayText(!value || value === '0' ? '' : tokenAmountInputText(Number(value), asset.decimals))
149
+ // `value` is exact token units as plain digits; never through a number.
150
+ const units = tokenUnitsFromField(value)
151
+ setDisplayText(units === undefined ? '' : tokenAmountInputText(units, asset.decimals))
150
152
  lastEmitted.current = value
151
153
  // `asset` is a fresh object literal on every render of most callers
152
154
  // (e.g. `asset={{ ticker, decimals }}`), so depending on it directly
@@ -164,10 +166,11 @@ export const AmountInput: React.FC<AmountInputProps> = ({
164
166
  if (asset) {
165
167
  if (text && !tokenAmountMask(asset.decimals).test(text)) return
166
168
  setDisplayText(text)
167
- const baseUnits = parseTokenAmount(text, asset.decimals)
168
- // The field never emits a fraction: the wire takes whole base units, and
169
- // a rounded figure would pay an amount other than the one on screen.
170
- const next = baseUnits === null ? '' : String(baseUnits)
169
+ const units = parseTokenAmount(text, asset.decimals)
170
+ // The field never emits a fraction, a zero or a figure above uint64: the
171
+ // wire takes exact whole units, and a rounded figure would pay an amount
172
+ // other than the one on screen. Emitted as the bigint's own digits.
173
+ const next = units === null ? '' : units.toString()
171
174
  lastEmitted.current = next
172
175
  onChangeText(next)
173
176
  return
@@ -24,8 +24,8 @@ import { spacing, typography, useTheme } from '@bsv/expo-wallet-toolbox'
24
24
  import { formatTokenAmountWithUnit, tokenAmountParts } from '../../tokenFormat'
25
25
 
26
26
  export interface AssetAmountProps {
27
- /** Base units. `null` means UNKNOWN and renders a spinner, never a zero. */
28
- baseUnits: number | null
27
+ /** Exact token units. `null` means UNKNOWN and renders a spinner, never a zero. */
28
+ units: bigint | null
29
29
  asset: { decimals: number; ticker: string }
30
30
  /** `row` is the balances/activity figure; `sheet` is the Asset sheet's headline. */
31
31
  size?: 'row' | 'sheet'
@@ -35,7 +35,7 @@ export interface AssetAmountProps {
35
35
  }
36
36
 
37
37
  export default function AssetAmount({
38
- baseUnits,
38
+ units,
39
39
  asset,
40
40
  size = 'row',
41
41
  showPlus = false,
@@ -43,13 +43,13 @@ export default function AssetAmount({
43
43
  }: AssetAmountProps) {
44
44
  const { colors } = useTheme()
45
45
 
46
- if (baseUnits === null) {
46
+ if (units === null) {
47
47
  return <ActivityIndicator size="small" color={colors.textTertiary} accessibilityRole="progressbar" />
48
48
  }
49
49
 
50
- const parts = tokenAmountParts(baseUnits, asset, { showPlus })
50
+ const parts = tokenAmountParts(units, asset, { showPlus })
51
51
  if (!parts) return null
52
- const label = formatTokenAmountWithUnit(baseUnits, asset, { showPlus }) ?? ''
52
+ const label = formatTokenAmountWithUnit(units, asset, { showPlus }) ?? ''
53
53
 
54
54
  const color =
55
55
  tone === 'incoming' ? colors.successAmount : tone === 'secondary' ? colors.textSecondary : colors.textPrimary
@@ -22,7 +22,8 @@ import { Pressable, StyleSheet, Text, TouchableOpacity, View } from 'react-nativ
22
22
  import Animated, { runOnJS, useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated'
23
23
  import { hitTargets, radii, spacing, typography, useTheme } from '@bsv/expo-wallet-toolbox'
24
24
  import type { TokenBalance } from '../../../core/mandala/runtime'
25
- import { shortAssetId, tokenAmountParts } from '../../tokenFormat'
25
+ import { useTranslation } from 'react-i18next'
26
+ import { shortAssetId, tokenAmountParts, tokenBalanceSplit } from '../../tokenFormat'
26
27
 
27
28
  /**
28
29
  * @expo/vector-icons' index barrel re-exports every icon set, one of which
@@ -70,6 +71,7 @@ export default function AssetSwitcherDropdown({
70
71
  bsv
71
72
  }: AssetSwitcherDropdownProps) {
72
73
  const { colors } = useTheme()
74
+ const { t } = useTranslation()
73
75
 
74
76
  // Fade + scale in place, no gesture — this is a dropdown, not a draggable
75
77
  // drawer. Mirrors Sheet's rendered/visible split so content unmounts only
@@ -149,7 +151,8 @@ export default function AssetSwitcherDropdown({
149
151
  fullName={b.asset.label}
150
152
  issuerName={b.asset.issuerName}
151
153
  fingerprint={shortAssetId(b.asset.assetId)}
152
- figure={tokenAmountParts(b.baseUnits, b.asset)}
154
+ figure={tokenAmountParts(b.units, b.asset)}
155
+ pending={tokenBalanceSplit(b, t)?.pending}
153
156
  selected={selected === b.asset.assetId}
154
157
  onPress={() => choose(b.asset.assetId)}
155
158
  />
@@ -166,6 +169,7 @@ function CoinRow({
166
169
  issuerName,
167
170
  fingerprint,
168
171
  figure,
172
+ pending,
169
173
  selected,
170
174
  onPress
171
175
  }: {
@@ -176,6 +180,8 @@ function CoinRow({
176
180
  /** XR-044: `shortAssetId(assetId)` — the one thing a look-alike asset cannot share. Absent for BSV. */
177
181
  fingerprint?: string
178
182
  figure: { value: string; unit: string } | null
183
+ /** W10: the part of `figure` not yet settled with the issuer, as its own line. Absent when none is. */
184
+ pending?: string
179
185
  selected: boolean
180
186
  onPress: () => void
181
187
  }) {
@@ -194,7 +200,7 @@ function CoinRow({
194
200
  accessibilityRole="button"
195
201
  // The checkmark is not the only signal: state travels with the element.
196
202
  accessibilityState={{ selected }}
197
- accessibilityLabel={[ticker, fullName, identityLine, figureText].filter(Boolean).join(', ')}
203
+ accessibilityLabel={[ticker, fullName, identityLine, figureText, pending].filter(Boolean).join(', ')}
198
204
  >
199
205
  <View style={styles.body}>
200
206
  <Text style={[styles.name, { color: colors.textPrimary }]} numberOfLines={1}>
@@ -212,10 +218,21 @@ function CoinRow({
212
218
  )}
213
219
  </View>
214
220
  {figure && (
215
- <Text style={[styles.figure, { color: colors.textPrimary }]} numberOfLines={1} accessibilityLabel={figureText}>
216
- {figure.value}
217
- {figure.unit ? <Text style={[styles.unit, { color: colors.textSecondary }]}> {figure.unit}</Text> : null}
218
- </Text>
221
+ <View style={styles.figureColumn}>
222
+ <Text
223
+ style={[styles.figure, { color: colors.textPrimary }]}
224
+ numberOfLines={1}
225
+ accessibilityLabel={figureText}
226
+ >
227
+ {figure.value}
228
+ {figure.unit ? <Text style={[styles.unit, { color: colors.textSecondary }]}> {figure.unit}</Text> : null}
229
+ </Text>
230
+ {!!pending && (
231
+ <Text style={[styles.pending, { color: colors.textSecondary }]} numberOfLines={1}>
232
+ {pending}
233
+ </Text>
234
+ )}
235
+ </View>
219
236
  )}
220
237
  <View style={styles.check}>{selected && <Ionicons name="checkmark" size={20} color={colors.accent} />}</View>
221
238
  </TouchableOpacity>
@@ -277,5 +294,7 @@ const styles = StyleSheet.create({
277
294
  identity: { ...typography.caption2, marginTop: 1, fontVariant: ['tabular-nums'] },
278
295
  figure: { ...typography.body, fontWeight: '600', fontVariant: ['tabular-nums'] },
279
296
  unit: { ...typography.footnote },
297
+ figureColumn: { alignItems: 'flex-end' },
298
+ pending: { ...typography.caption2, marginTop: 1, fontVariant: ['tabular-nums'] },
280
299
  check: { width: 20, alignItems: 'center' }
281
300
  })
@@ -52,7 +52,9 @@ export default function Balance() {
52
52
  adminOriginator
53
53
  )
54
54
 
55
- const total = totalOutputs ?? 0
55
+ // sdk 4 types `totalOutputs` as number | DecimalString (BRC-112 module
56
+ // balances); the satoshi wallet balance is always a safe integer.
57
+ const total = Number(totalOutputs ?? 0)
56
58
  setAccountBalance({ key: cacheKey, value: total })
57
59
 
58
60
  // Cache the new balance
@@ -4,8 +4,8 @@
4
4
  * figure in the display currency with the other denomination beneath), so a
5
5
  * payment looks identical whether you find it on Home or on the person.
6
6
  *
7
- * A token settlement has no wallet action of its own here — `getContactActivity`
8
- * reads it straight off `token_settlements` — so this builds the minimal
7
+ * A token transfer has no wallet action of its own here — `getContactActivity`
8
+ * reads it straight off the `color_transfers` journal — so this builds the minimal
9
9
  * action `ActivityRow` needs around it and hands the token facts through the
10
10
  * row's own `token` prop, exactly as Home does for a `'mandala'`-labelled row.
11
11
  */
@@ -20,21 +20,18 @@ import { useMandala } from '../../hooks/useMandala'
20
20
  import { formatTokenAmount } from '../../tokenFormat'
21
21
  import { tokenRowStatusView } from '../../tokenStatus'
22
22
  import type { TokenActivityStatus } from '../../../core/mandala/runtime'
23
- import type { ContactActivityItem, ContactSettlementRow } from '../../../core/contacts/contactActivity'
23
+ import type { ContactActivityItem, ContactTransferRow } from '../../../core/contacts/contactActivity'
24
24
 
25
- /** Same reading of a settlement's `state` as the runtime's `activityStatusOf`,
26
- * minus the "stuck after N hours" clock — a contact page is a record, not a
25
+ /** Same reading of a journal row's `state` as the runtime's `activityStatusOf`,
26
+ * minus the "stuck after N days" clock — a contact page is a record, not a
27
27
  * queue, so an old unsettled row reads as "settling" rather than as a fault
28
- * to act on (the acting happens on Home). */
29
- function statusOf(row: ContactSettlementRow): TokenActivityStatus {
28
+ * to act on (the acting happens on Home). Cancelled sends never get here. */
29
+ function statusOf(row: ContactTransferRow): TokenActivityStatus {
30
30
  switch (row.state) {
31
- case 'broadcast':
32
- case 'admitted':
31
+ case 'settled':
33
32
  return 'settled'
34
33
  case 'refused':
35
34
  return 'refused'
36
- case 'orphaned':
37
- return 'reversed'
38
35
  default:
39
36
  return 'settling'
40
37
  }
@@ -80,8 +77,8 @@ export default function ContactActivityList({
80
77
  const ticker = holding?.asset.ticker ?? item.assetId.slice(0, 8)
81
78
  const incoming = item.role === 'received'
82
79
  const figure =
83
- holding && item.amountBaseUnits !== undefined
84
- ? formatTokenAmount(incoming ? item.amountBaseUnits : -item.amountBaseUnits, holding.asset.decimals, {
80
+ holding && item.units !== undefined
81
+ ? formatTokenAmount(incoming ? item.units : -item.units, holding.asset.decimals, {
85
82
  showPlus: incoming
86
83
  })
87
84
  : undefined
@@ -22,18 +22,18 @@ export interface EvictionNotice {
22
22
  txid: string
23
23
  ticker: string
24
24
  issuer?: string
25
- /** Base units the holder lost. */
26
- baseUnits: number
25
+ /** Exact token units the holder lost. */
26
+ units: bigint
27
27
  decimals: number
28
28
  }
29
29
 
30
30
  /**
31
31
  * Money that was credited to this wallet and is no longer there.
32
32
  *
33
- * A `reversed` row is exactly that and nothing else: a `refused` SENT payment
34
- * never left, so the holder's balance is unchanged and there is nothing to
35
- * announce; a `refused` RECEIVED payment is the settlement spec's row 1
36
- * (reversed credit) and belongs here too.
33
+ * A `refused` RECEIVED row is exactly that: the color module credited it
34
+ * (spendable, `color_offline`) and withdrew it when the issuer's overlay
35
+ * refused it. A `refused` SENT payment never left, so the holder's balance is
36
+ * unchanged and there is nothing to announce.
37
37
  */
38
38
  export function evictionsFrom(
39
39
  rows: readonly TokenActivityRow[] | null,
@@ -41,13 +41,13 @@ export function evictionsFrom(
41
41
  ): EvictionNotice[] {
42
42
  if (!rows) return []
43
43
  return rows
44
- .filter(r => r.role === 'received' && (r.status === 'reversed' || r.status === 'refused'))
44
+ .filter(r => r.role === 'received' && r.status === 'refused')
45
45
  .filter(r => !alreadySeen.includes(r.txid))
46
46
  .map(r => ({
47
47
  txid: r.txid,
48
48
  ticker: r.asset.ticker,
49
49
  issuer: r.asset.issuerName,
50
- baseUnits: r.baseUnits,
50
+ units: r.units,
51
51
  decimals: r.asset.decimals
52
52
  }))
53
53
  }
@@ -55,7 +55,7 @@ export function evictionsFrom(
55
55
  /** Raises the alert and resolves once it has been acknowledged. */
56
56
  export async function announceEviction(t: Translate, notice: EvictionNotice): Promise<void> {
57
57
  const issuer = notice.issuer || t('token_issuer_fallback')
58
- const amount = formatTokenAmount(notice.baseUnits, notice.decimals)
58
+ const amount = formatTokenAmount(notice.units, notice.decimals)
59
59
  await showAlert({
60
60
  title: t('token_evicted_title', { ticker: notice.ticker }),
61
61
  // Without a figure the sentence would be "some money left" — true, useless,
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Everything token-shaped on a screen (a balance row, a picker option, an
5
5
  * activity status, a refusal sentence) comes from `MandalaRuntime` and nothing
6
- * else: the UI never talks to the overlay, the lib or the settlement tables
6
+ * else: the UI never talks to the overlay, the lib or the transfer journal
7
7
  * directly, so failure copy, journalling and state stay in one place
8
8
  * (core/mandala/runtime.ts's own design rule).
9
9
  *
@@ -35,7 +35,7 @@ import type {
35
35
  TokenAssetStatus,
36
36
  TokenBalance
37
37
  } from '../../core/mandala/runtime'
38
- import type { TokenSettlementRow } from '../../core/mandala/types'
38
+ import type { ColorTransferRow } from '../../core/mandala/types'
39
39
 
40
40
  /**
41
41
  * expo-router is required lazily rather than imported at module scope: this
@@ -103,20 +103,20 @@ export interface MandalaState {
103
103
  balances: TokenBalance[] | null
104
104
  /** Just the assets, for a picker. `[]` when nothing is held. */
105
105
  assets: TokenAssetInfo[]
106
- /** Non-terminal settlement rows past the stuck bound (FIX M) — the home badge. */
107
- stuck: TokenSettlementRow[]
106
+ /** Non-terminal `color_transfers` rows past the stuck bound (FIX M) — the home badge. */
107
+ stuck: ColorTransferRow[]
108
108
  /** True only while the FIRST read is outstanding; a refresh keeps the figures. */
109
109
  loading: boolean
110
110
  refresh: () => void
111
111
  }
112
112
 
113
113
  const EMPTY_ASSETS: TokenAssetInfo[] = []
114
- const EMPTY_STUCK: TokenSettlementRow[] = []
114
+ const EMPTY_STUCK: ColorTransferRow[] = []
115
115
 
116
116
  export function useMandala(): MandalaState {
117
117
  const runtime = useMandalaRuntime()
118
118
  const [balances, setBalances] = useState<TokenBalance[] | null>(null)
119
- const [stuck, setStuck] = useState<TokenSettlementRow[]>(EMPTY_STUCK)
119
+ const [stuck, setStuck] = useState<ColorTransferRow[]>(EMPTY_STUCK)
120
120
  const [loading, setLoading] = useState(false)
121
121
  const [nonce, setNonce] = useState(0)
122
122
  const runtimeRef = useRef<MandalaRuntime | null>(runtime)
@@ -51,7 +51,9 @@ export function useSpendableBalance(): number | null {
51
51
  const pm = managers?.permissionsManager
52
52
  if (!pm) return
53
53
  const { totalOutputs } = await pm.listOutputs({ basket: sdk.specOpWalletBalance }, adminOriginator)
54
- total = totalOutputs ?? 0
54
+ // sdk 4 types `totalOutputs` as number | DecimalString (BRC-112 module
55
+ // balances); the satoshi wallet balance is always a safe integer.
56
+ total = Number(totalOutputs ?? 0)
55
57
  }
56
58
  if (cancelled) return
57
59
  setBalance(prev => (prev?.key === cacheKey && prev.value === total ? prev : { key: cacheKey, value: total }))
@@ -437,7 +437,7 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
437
437
  // backupDatabaseAsync just copied key_value_store verbatim, including
438
438
  // any localpay_pending queue the source had — a record placed there by
439
439
  // whoever wrote that file, never re-verified by processPending before
440
- // it is drained into internalizeAction/onTokenHeld. Quarantine at this
440
+ // it is drained into internalizeAction. Quarantine at this
441
441
  // boundary, before the copy is ever registered or read: an imported
442
442
  // backup must never be able to seed the live queue (XR-081).
443
443
  await destDb.runAsync('DELETE FROM key_value_store WHERE key IN (?, ?)', [PENDING_KEY, PENDING_SUMMARY_KEY])
@@ -21,7 +21,7 @@ import { partitionQueueByGrace } from '../../core/offline/queueGrace'
21
21
  import PaymentQrDisplay from '../components/pay/PaymentQrDisplay'
22
22
  import UniversalSend, { type UniversalSendHandle } from '../components/pay/UniversalSend'
23
23
  import type { PayStep } from '../components/pay/StepBar'
24
- import RequestHub, { requestSatsFrom, type RequestMethod } from '../components/pay/RequestHub'
24
+ import RequestHub, { requestSatsFrom, requestUnitsFrom, type RequestMethod } from '../components/pay/RequestHub'
25
25
  import NearbyFlow from '../components/pay/NearbyFlow'
26
26
  import HandleReceive from '../components/pay/HandleReceive'
27
27
  import AddressReceive from '../components/pay/AddressReceive'
@@ -164,7 +164,7 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
164
164
  const satsParam = linkSats ?? Number(firstParam(params.sats))
165
165
  const initialSats = Number.isFinite(satsParam) && satsParam > 0 ? Number(satsParam) : undefined
166
166
  const initialTokenAmount = useMemo(
167
- () => (linkAsset && linkAmount ? { assetId: linkAsset, baseUnits: linkAmount } : undefined),
167
+ () => (linkAsset && linkAmount ? { assetId: linkAsset, units: linkAmount } : undefined),
168
168
  [linkAsset, linkAmount]
169
169
  )
170
170
  // Memoized: useRecipientInput re-adopts initialTarget whenever its identity changes.
@@ -259,25 +259,19 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
259
259
  * on the payee's own screen and binding the payer to that figure. The
260
260
  * discriminated shape makes the unit impossible to lose.
261
261
  */
262
- const request: { kind: 'bsv'; sats?: number } | { kind: 'token'; baseUnits?: number; assetId: string } = asset
263
- ? { kind: 'token', baseUnits: requestSatsFrom(requestSats), assetId: asset.assetId }
262
+ const request: { kind: 'bsv'; sats?: number } | { kind: 'token'; units?: bigint; assetId: string } = asset
263
+ ? { kind: 'token', units: requestUnitsFrom(requestSats), assetId: asset.assetId }
264
264
  : { kind: 'bsv', sats: requestSatsFrom(requestSats) }
265
265
  const initialNearbyRequest = useMemo(
266
- () => ({
267
- sats: requestSatsFrom(requestSats),
268
- ...(asset
266
+ () =>
267
+ asset
269
268
  ? {
270
- asset: {
271
- id: asset.assetId,
272
- label: asset.label,
273
- ticker: asset.ticker,
274
- decimals: asset.decimals,
275
- overlayUrl: asset.overlayUrl,
276
- overlayIdentityKey: asset.overlayIdentityKey
277
- }
269
+ // Exact token units (session v2 carries `a` as a decimal string);
270
+ // the session names no overlay, the payer uses its own (W6).
271
+ units: requestUnitsFrom(requestSats),
272
+ asset: { id: asset.assetId, label: asset.label, ticker: asset.ticker, decimals: asset.decimals }
278
273
  }
279
- : {})
280
- }),
274
+ : { sats: requestSatsFrom(requestSats) },
281
275
  [requestSats, asset]
282
276
  )
283
277
  // One camera raise per deep link; a cancelled advisory must not re-open it.
@@ -527,8 +521,8 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
527
521
  // base units, and every satoshi-shaped prop below must not see them.
528
522
  const sats = request.kind === 'bsv' ? request.sats : undefined
529
523
  const requestedAmountText =
530
- asset && request.kind === 'token' && request.baseUnits !== undefined
531
- ? (formatTokenAmountWithUnit(request.baseUnits, asset) ?? undefined)
524
+ asset && request.kind === 'token' && request.units !== undefined
525
+ ? (formatTokenAmountWithUnit(request.units, asset) ?? undefined)
532
526
  : undefined
533
527
  switch (method) {
534
528
  case 'get-nearby':
@@ -540,7 +534,7 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
540
534
  <HandleReceive
541
535
  initialSats={sats}
542
536
  asset={asset ? { assetId: asset.assetId, ticker: asset.ticker, issuerName: asset.issuerName } : null}
543
- requestedBaseUnits={request.kind === 'token' ? request.baseUnits : undefined}
537
+ requestedUnits={request.kind === 'token' ? request.units : undefined}
544
538
  requestedAmountText={requestedAmountText}
545
539
  assetMessageBoxUrl={selectedAssetStatus?.messageBoxUrl ?? null}
546
540
  onBsvInstead={() => setSelectedAssetId(null)}
@@ -65,7 +65,9 @@ export function SettingsScreen() {
65
65
  { basket: sdk.specOpWalletBalance },
66
66
  adminOriginator
67
67
  )
68
- const total = totalOutputs ?? 0
68
+ // sdk 4 types `totalOutputs` as number | DecimalString (BRC-112 module
69
+ // balances); the satoshi wallet balance is always a safe integer.
70
+ const total = Number(totalOutputs ?? 0)
69
71
  setAccountBalance(total)
70
72
  setBalanceLoading(false)
71
73
  await Promise.all([