@bsv/expo-wallet-toolbox 0.5.0 → 0.7.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 (90) hide show
  1. package/CHANGELOG.md +255 -0
  2. package/README.md +19 -0
  3. package/core/amountFormatHelpers.ts +238 -34
  4. package/core/backup/RemoteSyncReader.ts +2 -5
  5. package/core/backup/codec.ts +2 -2
  6. package/core/backup/push.ts +1 -1
  7. package/core/config.tsx +12 -5
  8. package/core/contacts/contactActivity.ts +153 -0
  9. package/core/contacts/contactCache.ts +41 -0
  10. package/core/contacts/contactsStore.ts +183 -0
  11. package/core/context/WalletContext.tsx +55 -10
  12. package/core/demo/demoAssets.ts +60 -0
  13. package/core/demo/demoLedger.ts +240 -0
  14. package/core/demo/demoMandalaRuntime.ts +96 -0
  15. package/core/demo/demoMode.ts +38 -0
  16. package/core/demo/demoWallet.ts +25 -0
  17. package/core/demo/index.ts +26 -0
  18. package/core/demo/useDemo.ts +59 -0
  19. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  20. package/core/headers/headerStore.ts +7 -10
  21. package/core/i18n/translations.tsx +1234 -74
  22. package/core/identity/contactLink.ts +36 -0
  23. package/core/identity/handleRegistry/client.ts +285 -0
  24. package/core/identity/handleRegistry/profileCert.ts +254 -0
  25. package/core/identity/handleRegistry/registration.ts +559 -0
  26. package/core/identity/handleRegistry/resolver.ts +247 -0
  27. package/core/identity/handleRegistry/rules.ts +104 -0
  28. package/core/index.ts +20 -2
  29. package/core/localpay/pendingAborts.ts +5 -1
  30. package/core/monitor/MonitorSupervisor.ts +121 -0
  31. package/core/monitor/TaskBackupPush.ts +1 -1
  32. package/core/monitor/TaskCreditInbox.ts +1 -1
  33. package/core/monitor/TaskDrainOutbox.ts +1 -1
  34. package/core/monitor/TaskSendOffline.ts +1 -1
  35. package/core/net/online.ts +49 -0
  36. package/core/numberFormat.ts +19 -0
  37. package/core/offline/plan.ts +1 -1
  38. package/core/pay/recordProof.ts +2 -6
  39. package/core/services/arcadeBroadcastProvider.ts +1 -4
  40. package/core/services/exchangeRate.ts +1 -1
  41. package/core/services/externalOrigin.ts +5 -2
  42. package/core/services/vault/transfers.ts +2 -2
  43. package/core/services/walletServiceConfig.ts +31 -20
  44. package/core/storage/StorageExpoSQLite.ts +41 -34
  45. package/core/storage/methods/findSql.ts +3 -0
  46. package/core/storage/methods/listActionsSql.ts +8 -5
  47. package/core/storage/methods/listOutputsSql.ts +2 -2
  48. package/core/storage/methods/processOfflineActions.ts +2 -3
  49. package/core/storage/methods/reviewStatusSql.ts +7 -2
  50. package/core/storage/schema/createTables.ts +29 -0
  51. package/core/toolboxConfig.ts +70 -0
  52. package/core/toolboxTypes.ts +40 -0
  53. package/core/userAvatar.ts +79 -0
  54. package/core/walletMonitor.ts +8 -3
  55. package/package.json +7 -7
  56. package/ui/activityFilter.ts +115 -0
  57. package/ui/components/pay/PaymentSuccessOverlay.tsx +46 -6
  58. package/ui/components/pay/RecipientField.tsx +84 -70
  59. package/ui/components/pay/StepBar.tsx +32 -0
  60. package/ui/components/pay/UniversalSend.tsx +677 -149
  61. package/ui/components/ui/PencilEditField.tsx +109 -0
  62. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  63. package/ui/components/wallet/ActivityRow.tsx +222 -120
  64. package/ui/components/wallet/AmountInput.tsx +18 -6
  65. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  66. package/ui/components/wallet/ContactSigil.tsx +49 -0
  67. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  68. package/ui/components/wallet/FitAmount.tsx +148 -0
  69. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  70. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  71. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  72. package/ui/components/wallet/ProfileButton.tsx +62 -0
  73. package/ui/components/wallet/UserAvatar.tsx +85 -0
  74. package/ui/components/wallet/avatarIcons.ts +122 -0
  75. package/ui/hooks/useContactsStore.ts +10 -0
  76. package/ui/hooks/useMandala.ts +18 -1
  77. package/ui/hooks/useOnline.ts +65 -20
  78. package/ui/index.ts +26 -1
  79. package/ui/screens/ContactScreen.tsx +289 -0
  80. package/ui/screens/ContactsScreen.tsx +373 -0
  81. package/ui/screens/IdentifierScreen.tsx +234 -0
  82. package/ui/screens/NewContactScreen.tsx +362 -0
  83. package/ui/screens/PayScreen.tsx +20 -7
  84. package/ui/screens/ProfileScreen.tsx +783 -0
  85. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  86. package/ui/screens/TrustScreen.tsx +1 -1
  87. package/ui/screens/WalletConfigScreen.tsx +42 -0
  88. package/ui/screens/WalletHomeScreen.tsx +528 -83
  89. package/ui/tokenStatus.ts +21 -0
  90. package/ui/txStatus.ts +43 -5
@@ -1,24 +1,88 @@
1
- // Safe locale detection for React Native
2
- const getLocaleDefault = (): string => {
3
- try {
4
- // Try to get locale using Intl API if available
5
- return Intl.NumberFormat().resolvedOptions().locale?.split('-u-')[0] || 'en-US'
6
- } catch {
7
- // Fallback to en-US if Intl is not fully supported
8
- return 'en-US'
9
- }
10
- }
1
+ import { getNumberLocale } from './numberFormat'
11
2
 
12
- const localeDefault = getLocaleDefault()
3
+ /**
4
+ * The locale every figure on this screen is printed through.
5
+ *
6
+ * A function, not a module constant: the separators are a user preference now
7
+ * (see `core/numberFormat.ts`), so a figure formatted at module-load time
8
+ * would be stuck with whatever the device implied at launch.
9
+ */
10
+ const locale = (): string => getNumberLocale()
13
11
 
14
12
  const SATS_PER_BSV = 100_000_000
15
13
  const CENT_THRESHOLD = 0.01
16
14
 
15
+ /**
16
+ * Above this many currency units, a fiat figure is abbreviated and its minor
17
+ * units are dropped. Below it the cents are kept exactly: those are the
18
+ * balances a holder reconciles against a bank app, and `$1,234.56` rounded to
19
+ * `$1.2k` is no longer the same number to them.
20
+ */
21
+ const FIAT_ABBREVIATE_ABOVE = 100_000
22
+
23
+ /**
24
+ * `1500 -> "1.5k"`, `1_000_000 -> "1M"`, `2_400_000_000 -> "2.4B"`.
25
+ *
26
+ * At most one decimal place and never a trailing `.0`, because the point of
27
+ * the short form is to be read at a glance. Values under 1000 are returned
28
+ * grouped and unabbreviated — there is nothing to save.
29
+ */
30
+ const ABBREVIATION_STEPS: { limit: number; divisor: number; suffix: string }[] = [
31
+ { limit: 1_000_000_000, divisor: 1_000_000_000, suffix: 'B' },
32
+ { limit: 1_000_000, divisor: 1_000_000, suffix: 'M' },
33
+ { limit: 1_000, divisor: 1_000, suffix: 'k' }
34
+ ]
35
+
36
+ /**
37
+ * The magnitude `value` should be shown at. `suffix` is `''` when the value is
38
+ * small enough to print in full. Shared by the satoshi and fiat paths so the
39
+ * two can never disagree about where a 'k' becomes an 'M'.
40
+ */
41
+ const scaleForAbbreviation = (value: number): { scaled: number; suffix: string } => {
42
+ const abs = Math.abs(value)
43
+ for (let i = 0; i < ABBREVIATION_STEPS.length; i++) {
44
+ const { limit, divisor, suffix } = ABBREVIATION_STEPS[i]
45
+ if (abs < limit) continue
46
+ // One decimal, trimmed: 1.0k reads as noise, 1.5k does not.
47
+ const scaled = Math.round((abs / divisor) * 10) / 10
48
+ // 999,950 rounds to 1000k; that is 1M.
49
+ const up = ABBREVIATION_STEPS[i - 1]
50
+ if (scaled >= 1000 && up) return { scaled: Math.round((abs / up.divisor) * 10) / 10, suffix: up.suffix }
51
+ return { scaled, suffix }
52
+ }
53
+ return { scaled: abs, suffix: '' }
54
+ }
55
+
56
+ const abbreviateNumber = (value: number): string => {
57
+ const { scaled, suffix } = scaleForAbbreviation(value)
58
+ if (!suffix) return formatSatoshisLocale(Math.abs(value))
59
+ return `${Number.isInteger(scaled) ? String(scaled) : formatDecimalLocale(scaled, 1)}${suffix}`
60
+ }
61
+
62
+ /** A number at fixed decimals in the active locale's separators. */
63
+ const formatDecimalLocale = (value: number, digits: number): string => {
64
+ try {
65
+ return new Intl.NumberFormat(locale(), {
66
+ minimumFractionDigits: digits,
67
+ maximumFractionDigits: digits,
68
+ useGrouping: true
69
+ }).format(value)
70
+ } catch {
71
+ return value.toFixed(digits)
72
+ }
73
+ }
74
+
17
75
  export type UsdToFiat = Record<string, number>
18
76
 
19
77
  export type AmountFormatOptions = {
20
78
  showPlus?: boolean
79
+ /** "sats" instead of "satoshis". Never changes the figure. */
21
80
  abbreviate?: boolean
81
+ /**
82
+ * Shorten large figures to k/M/B. Only for dense lists (activity rows): an
83
+ * approval, a balance or a transaction detail must show the exact amount.
84
+ */
85
+ compact?: boolean
22
86
  showFiatAsInteger?: boolean
23
87
  usdToFiat?: UsdToFiat
24
88
  }
@@ -29,11 +93,7 @@ export const isFiatCurrency = (currency: string): boolean => Boolean(currency) &
29
93
  * Satoshis per 1 unit of `currency`. USD is the WhatsOnChain rate; other fiat
30
94
  * is that rate divided by the USD→fiat cross (1 USD = `usdToFiat[code]` units).
31
95
  */
32
- export const satoshisPerFiatUnit = (
33
- currency: string,
34
- satoshisPerUSD: number,
35
- usdToFiat: UsdToFiat = {}
36
- ): number => {
96
+ export const satoshisPerFiatUnit = (currency: string, satoshisPerUSD: number, usdToFiat: UsdToFiat = {}): number => {
37
97
  if (currency === 'USD') return satoshisPerUSD
38
98
  const fx = usdToFiat[currency]
39
99
  if (!(satoshisPerUSD > 0) || !(fx > 0)) return 0
@@ -42,7 +102,7 @@ export const satoshisPerFiatUnit = (
42
102
 
43
103
  export const fiatFractionDigits = (currency: string): number => {
44
104
  try {
45
- const digits = new Intl.NumberFormat(localeDefault, {
105
+ const digits = new Intl.NumberFormat(locale(), {
46
106
  style: 'currency',
47
107
  currency
48
108
  }).resolvedOptions().maximumFractionDigits
@@ -52,6 +112,65 @@ export const fiatFractionDigits = (currency: string): number => {
52
112
  }
53
113
  }
54
114
 
115
+ /**
116
+ * The symbol this wallet prints for a currency, whatever the locale would.
117
+ *
118
+ * `currencyDisplay: 'narrowSymbol'` is not enough: a locale narrows only as
119
+ * far as it can still disambiguate, so an `en-NL` device renders USD as
120
+ * "US$" — which is a correct answer to a question nobody asked. The wallet
121
+ * shows one currency at a time and says which in Settings, so the short
122
+ * symbol is never ambiguous here.
123
+ *
124
+ * Currencies absent from this table keep whatever the locale produces, which
125
+ * for a code like CHF is already the code itself.
126
+ */
127
+ const PREFERRED_SYMBOL: Record<string, string> = {
128
+ USD: '$',
129
+ AUD: '$',
130
+ CAD: '$',
131
+ NZD: '$',
132
+ BRL: 'R$',
133
+ EUR: '€',
134
+ GBP: '£',
135
+ JPY: '¥',
136
+ CNY: '¥',
137
+ INR: '₹',
138
+ RUB: '₽',
139
+ PLN: 'zł',
140
+ IDR: 'Rp'
141
+ }
142
+
143
+ /**
144
+ * Format through Intl, then swap the currency token for our own symbol.
145
+ *
146
+ * Rebuilt from `formatToParts` rather than string-replaced so the locale keeps
147
+ * deciding WHERE the symbol sits and whether a space follows it — only the
148
+ * glyph is ours.
149
+ */
150
+ const formatCurrencyParts = (
151
+ value: number,
152
+ loc: string,
153
+ currency: string,
154
+ options: Intl.NumberFormatOptions
155
+ ): string => {
156
+ const preferred = PREFERRED_SYMBOL[currency]
157
+ const parts = new Intl.NumberFormat(loc, options).formatToParts(value)
158
+ return parts.map(p => (p.type === 'currency' && preferred ? preferred : p.value)).join('')
159
+ }
160
+
161
+ /** Digits only, in the locale's separators, for when currency formatting fails. */
162
+ const formatPlainDigits = (value: number, loc: string, minDigits: number, maxDigits: number): string => {
163
+ try {
164
+ return new Intl.NumberFormat(loc, {
165
+ minimumFractionDigits: minDigits,
166
+ maximumFractionDigits: maxDigits,
167
+ useGrouping: true
168
+ }).format(value)
169
+ } catch {
170
+ return value.toFixed(minDigits)
171
+ }
172
+ }
173
+
55
174
  // Format number as currency with fallback for platforms where Intl is not fully supported
56
175
  const formatCurrency = (
57
176
  value: number,
@@ -67,6 +186,12 @@ const formatCurrency = (
67
186
  const options: Intl.NumberFormatOptions = {
68
187
  currency,
69
188
  style: 'currency',
189
+ // The separator preference is expressed as a locale, and a locale also
190
+ // carries that language's NAME for the currency — fr-FR renders USD as
191
+ // "$US". The UI's language is chosen elsewhere, so pin the short symbol
192
+ // and let the locale govern only the digits, which is all the
193
+ // preference was ever about.
194
+ currencyDisplay: 'narrowSymbol',
70
195
  minimumFractionDigits: minDigits
71
196
  }
72
197
 
@@ -74,10 +199,14 @@ const formatCurrency = (
74
199
  options.maximumFractionDigits = maxDigits
75
200
  }
76
201
 
77
- const formatter = new Intl.NumberFormat(locale, options)
78
- formatted = formatter.format(abs)
202
+ formatted = formatCurrencyParts(abs, locale, currency, options)
79
203
  } catch {
80
- formatted = `${currency} ${abs.toFixed(minDigits)}`
204
+ // Hermes lacks `formatToParts` / `narrowSymbol` on some builds. Keep our
205
+ // symbol in front of plain locale digits rather than dropping to the ISO
206
+ // code ("USD 3.45"); only a currency with no symbol of ours shows its code.
207
+ const digits = formatPlainDigits(abs, locale, minDigits, maxDigits ?? minDigits)
208
+ const preferred = PREFERRED_SYMBOL[currency]
209
+ formatted = preferred ? `${preferred}${digits}` : `${currency} ${digits}`
81
210
  }
82
211
  // Same sign convention as the satoshi formatter, so a column of mixed
83
212
  // currencies reads one way: minus for money out, plus for money in when the
@@ -93,7 +222,7 @@ const fiatSign = (value: number, showPlus: boolean): string => (value < 0 ? '-'
93
222
  */
94
223
  const formatSatoshisLocale = (satoshis: number): string => {
95
224
  try {
96
- return new Intl.NumberFormat(localeDefault, {
225
+ return new Intl.NumberFormat(locale(), {
97
226
  maximumFractionDigits: 0,
98
227
  useGrouping: true
99
228
  }).format(satoshis)
@@ -108,7 +237,7 @@ const formatSatoshisLocale = (satoshis: number): string => {
108
237
  */
109
238
  const formatBsvLocale = (bsvValue: number): string => {
110
239
  try {
111
- return new Intl.NumberFormat(localeDefault, {
240
+ return new Intl.NumberFormat(locale(), {
112
241
  minimumFractionDigits: 0,
113
242
  maximumFractionDigits: 8,
114
243
  useGrouping: true
@@ -130,7 +259,8 @@ export const formatSatoshisAsFiat = (
130
259
  satoshisPerUnit: number,
131
260
  showFiatAsInteger = false,
132
261
  currency = 'USD',
133
- showPlus = false
262
+ showPlus = false,
263
+ compact = false
134
264
  ): string => {
135
265
  if (!Number.isInteger(Number(satoshis)) || !satoshisPerUnit || satoshisPerUnit <= 0) {
136
266
  return '...'
@@ -145,17 +275,32 @@ export const formatSatoshisAsFiat = (
145
275
  const threshold = digits === 0 ? 1 : 1 / factor
146
276
 
147
277
  if (v > 0 && v < threshold && !showFiatAsInteger) {
148
- const smallest = formatCurrency(threshold, localeDefault, currency, digits, digits)
278
+ const smallest = formatCurrency(threshold, locale(), currency, digits, digits)
149
279
  return `< ${fiatSign(raw, showPlus)}${smallest}`
150
280
  }
151
281
 
152
282
  const sign = raw < 0 ? -1 : 1
283
+
284
+ /**
285
+ * Only large figures shorten. A balance a holder reconciles against a bank
286
+ * app keeps its exact minor units, because `$1,234.56` shown as `$1.2k` is
287
+ * not the same number to the person reading it — it is a different number
288
+ * that happens to be close. Past `FIAT_ABBREVIATE_ABOVE` the cents have
289
+ * stopped being the point and the width has started to be.
290
+ */
291
+ if (compact && v >= FIAT_ABBREVIATE_ABOVE) {
292
+ const { scaled, suffix } = scaleForAbbreviation(v)
293
+ const shortDigits = Number.isInteger(scaled) ? 0 : 1
294
+ const body = formatCurrency(sign * scaled, locale(), currency, shortDigits, shortDigits, showPlus)
295
+ return `${body}${suffix}`
296
+ }
297
+
153
298
  const rounded = (sign * Math.ceil(Math.abs(raw) * factor)) / factor
154
299
 
155
300
  const minDigits = showFiatAsInteger ? 0 : digits
156
301
  const maxDigits = showFiatAsInteger ? 0 : digits
157
302
 
158
- return formatCurrency(rounded, localeDefault, currency, minDigits, maxDigits, showPlus)
303
+ return formatCurrency(rounded, locale(), currency, minDigits, maxDigits, showPlus)
159
304
  }
160
305
 
161
306
  /**
@@ -165,7 +310,23 @@ export const formatSatoshisAsFiat = (
165
310
  *
166
311
  * All formatting is locale-aware.
167
312
  */
168
- export const formatSatoshisAsBsv = (satoshis: number, showPlus = false, abbreviate = false): string => {
313
+ /**
314
+ * The exact satoshi count, never switched to BSV or shortened: `+1,234,567 sats`.
315
+ * For the one place a holder checks what the transaction actually moved.
316
+ */
317
+ export const formatSatoshisExact = (satoshis: number, showPlus = false): { value: string; unit: string } => {
318
+ const n = Number(satoshis)
319
+ if (!Number.isInteger(n)) return { value: '---', unit: 'sats' }
320
+ const sign = n < 0 ? '-' : showPlus && n > 0 ? '+' : ''
321
+ return { value: `${sign}${formatSatoshisLocale(Math.abs(n))}`, unit: 'sats' }
322
+ }
323
+
324
+ export const formatSatoshisAsBsv = (
325
+ satoshis: number,
326
+ showPlus = false,
327
+ abbreviate = false,
328
+ compact = false
329
+ ): string => {
169
330
  const numValue = Number(satoshis)
170
331
  if (!Number.isInteger(numValue)) return '---'
171
332
 
@@ -175,11 +336,15 @@ export const formatSatoshisAsBsv = (satoshis: number, showPlus = false, abbrevia
175
336
  if (absValue >= SATS_PER_BSV) {
176
337
  // Display as BSV
177
338
  const bsvValue = absValue / SATS_PER_BSV
178
- return `${sign}${formatBsvLocale(bsvValue)} BSV`
339
+ // A whole-BSV figure abbreviates on the same ladder once it passes 1000,
340
+ // so "1,000 BSV" reads "1k BSV" rather than growing a digit per decade.
341
+ const body = compact && bsvValue >= 1000 ? abbreviateNumber(bsvValue) : formatBsvLocale(bsvValue)
342
+ return `${sign}${body} BSV`
179
343
  } else {
180
- // Display as satoshis
344
+ // Display as satoshis. `abbreviate` shortens the label, `compact` the figure.
181
345
  const label = abbreviate ? 'sats' : 'satoshis'
182
- return `${sign}${formatSatoshisLocale(absValue)} ${label}`
346
+ const body = compact ? abbreviateNumber(absValue) : formatSatoshisLocale(absValue)
347
+ return `${sign}${body} ${label}`
183
348
  }
184
349
  }
185
350
 
@@ -194,14 +359,14 @@ export const formatAmount = (
194
359
  satoshisPerUSD: number = 0,
195
360
  options: AmountFormatOptions = {}
196
361
  ): string => {
197
- const { showPlus = false, abbreviate = false, showFiatAsInteger = false, usdToFiat = {} } = options
362
+ const { showPlus = false, abbreviate = false, compact = false, showFiatAsInteger = false, usdToFiat = {} } = options
198
363
 
199
364
  if (isFiatCurrency(currency)) {
200
365
  const per = satoshisPerFiatUnit(currency, satoshisPerUSD, usdToFiat)
201
- return formatSatoshisAsFiat(satoshis, per, showFiatAsInteger, currency, showPlus)
366
+ return formatSatoshisAsFiat(satoshis, per, showFiatAsInteger, currency, showPlus, compact)
202
367
  }
203
368
 
204
- return formatSatoshisAsBsv(satoshis, showPlus, abbreviate)
369
+ return formatSatoshisAsBsv(satoshis, showPlus, abbreviate, compact)
205
370
  }
206
371
 
207
372
  /**
@@ -252,7 +417,7 @@ export const formatAmountInInputUnit = (
252
417
  const amount = Math.abs(n) / per
253
418
  const digits = fiatFractionDigits(currency)
254
419
  try {
255
- return new Intl.NumberFormat(localeDefault, {
420
+ return new Intl.NumberFormat(locale(), {
256
421
  minimumFractionDigits: digits,
257
422
  maximumFractionDigits: digits
258
423
  }).format(amount)
@@ -295,7 +460,12 @@ export const parseDisplayToSatoshis = (
295
460
  * In BSV mode, the label depends on the amount (satoshis vs BSV).
296
461
  * If no satoshi value is provided, returns "satoshis" (the input label for BSV mode).
297
462
  */
298
- export const getUnitLabel = (currency: string, satoshis?: number, abbreviate = false, satoshisPerUSD?: number): string => {
463
+ export const getUnitLabel = (
464
+ currency: string,
465
+ satoshis?: number,
466
+ abbreviate = false,
467
+ satoshisPerUSD?: number
468
+ ): string => {
299
469
  if (isFiatCurrency(currency)) {
300
470
  if (currency === 'USD' && satoshis !== undefined && satoshisPerUSD && satoshisPerUSD > 0) {
301
471
  const usd = Math.abs(satoshis / satoshisPerUSD)
@@ -314,3 +484,37 @@ export const getUnitLabel = (currency: string, satoshis?: number, abbreviate = f
314
484
 
315
485
  // Keep legacy exports for backward compatibility during migration
316
486
  export const formatSatoshis = formatSatoshisAsBsv
487
+
488
+ /**
489
+ * Split a formatted figure so its minor units can be set smaller and raised,
490
+ * the way a price tag writes them.
491
+ *
492
+ * `head` is everything up to and including the decimal separator, `frac` the
493
+ * minor-unit digits, `tail` whatever trails them (a suffixed currency symbol
494
+ * in the locales that put it there).
495
+ *
496
+ * Returns `frac: ''` — meaning "draw this as one run" — when there is nothing
497
+ * to raise, and deliberately when the figure is ABBREVIATED: the `.5` of
498
+ * `1.5k` is a magnitude, not cents, and shrinking it would read as `1` with a
499
+ * superscript. Detected by a letter immediately after the digits, which is
500
+ * exactly what the k/M/B suffix is.
501
+ */
502
+ export const splitAmountFraction = (value: string): { head: string; frac: string; tail: string } => {
503
+ const whole = { head: value, frac: '', tail: '' }
504
+ if (!value) return whole
505
+ let sep: string
506
+ try {
507
+ sep = new Intl.NumberFormat(locale()).formatToParts(1.1).find(p => p.type === 'decimal')?.value ?? '.'
508
+ } catch {
509
+ sep = '.'
510
+ }
511
+ const at = value.lastIndexOf(sep)
512
+ if (at < 0) return whole
513
+ const rest = value.slice(at + sep.length)
514
+ const digits = /^\d+/.exec(rest)?.[0] ?? ''
515
+ if (!digits) return whole
516
+ const tail = rest.slice(digits.length)
517
+ // An abbreviation suffix (k/M/B) means those digits are magnitude, not cents.
518
+ if (/^\p{L}/u.test(tail)) return whole
519
+ return { head: value.slice(0, at + sep.length), frac: digits, tail }
520
+ }
@@ -7,14 +7,11 @@
7
7
  * drive a live remote storage provider.
8
8
  */
9
9
  import type { CompletedProtoWallet } from '@bsv/sdk'
10
- import type {
11
- RequestSyncChunkArgs,
12
- SyncChunk
13
- } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
14
- import type { TableSettings } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
10
+ import type { TableSettings } from '@bsv/wallet-toolbox-mobile'
15
11
  import type { BackupClient, LogEntry } from './client'
16
12
  import { decodeChunk, emptyChunk } from './codec'
17
13
  import type { BackupChain } from './constants'
14
+ import type { RequestSyncChunkArgs, SyncChunk } from '../toolboxTypes'
18
15
 
19
16
  export class BackupChainError extends Error {
20
17
  constructor (message: string) {
@@ -16,12 +16,12 @@
16
16
  */
17
17
  import type { CompletedProtoWallet } from '@bsv/sdk'
18
18
  import { Utils } from '@bsv/sdk'
19
- import type { SyncChunk } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
20
19
  import {
21
20
  parseJsonRpc,
22
21
  stringifyJsonRpc
23
- } from '@bsv/wallet-toolbox-mobile/out/src/storage/remoting/BinaryJson'
22
+ } from '@bsv/wallet-toolbox-mobile'
24
23
  import { BACKUP_PROTOCOL, backupKeyId, type BackupChain } from './constants'
24
+ import type { SyncChunk } from '../toolboxTypes'
25
25
 
26
26
  /**
27
27
  * Minimum length before a numeric array is worth packing as bytes.
@@ -16,7 +16,6 @@
16
16
  * pass.
17
17
  */
18
18
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
19
- import type { SyncChunk } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
20
19
  import { BackupClient, BackupHttpError, ERR_SEQ_CONFLICT } from './client'
21
20
  import { encodeChunk, estimateEncodedBytes, isEmptyChunk } from './codec'
22
21
  import { GENERATION_CHUNK_THRESHOLD, MAX_ITEMS, MAX_ROUGH_SIZE, type BackupChain } from './constants'
@@ -33,6 +32,7 @@ import {
33
32
  import { backupPseudonym, deriveBackupWallet } from './derive'
34
33
  import { getDeviceId } from './deviceId'
35
34
  import { isBackupPushEnabled } from './preference'
35
+ import type { SyncChunk } from '../toolboxTypes'
36
36
 
37
37
  export interface PushDeps {
38
38
  storage: StorageExpoSQLite
package/core/config.tsx CHANGED
@@ -42,9 +42,16 @@ export const DEFAULT_CHAIN: AppChain = 'main'
42
42
  /**
43
43
  * Internal authority label passed only by the wallet shell.
44
44
  *
45
- * Keep this deliberately outside the hostname namespace. The permissions
46
- * manager grants this originator administrative access, so using an ordinary
47
- * DNS name would let whoever controls that host acquire the same authority
48
- * through a paired connection.
45
+ * The permissions manager grants this originator administrative access, so it
46
+ * must be a name no external caller can present. It used to sit outside the
47
+ * hostname namespace altogether (`urn:bsv-wallet:internal-admin`), but
48
+ * @bsv/sdk 2.8 accepts only canonical hostnames as originators. It now lives
49
+ * in the RFC 6761 `.invalid` TLD, which never resolves, so no host can be
50
+ * served from it, and `parseExternalOrigin` refuses that whole TLD at the
51
+ * external trust boundary. An ordinary DNS name would let whoever controls
52
+ * that host acquire the same authority through a paired connection.
49
53
  */
50
- export const ADMIN_ORIGINATOR = 'urn:bsv-wallet:internal-admin'
54
+ export const ADMIN_ORIGINATOR = 'internal-admin.bsv-wallet.invalid'
55
+
56
+ /** The label before @bsv/sdk 2.8, still found in data persisted by older builds. */
57
+ export const LEGACY_ADMIN_ORIGINATOR = 'urn:bsv-wallet:internal-admin'
@@ -0,0 +1,153 @@
1
+ /**
2
+ * A contact's activity: every interaction with one counterparty, every asset,
3
+ * both directions (Deggen ruling, 2026-09-17 design review).
4
+ *
5
+ * Three sources, merged and sorted by time, newest first:
6
+ *
7
+ * 1. Outbound BSV/peer sends — EXACT, via the label the handle and nearby
8
+ * rails both write on a sent action (`labels: ['peerpay'|'localpay', recipientKey]`).
9
+ * 2. Everything else a plain label filter can't reach (inbound payments,
10
+ * which carry the sender only on the output's `senderIdentityKey`, never
11
+ * as a label) — read from the most recent `RECENT_WINDOW` actions and
12
+ * matched client-side with `counterpartyOf()`. This is a bounded recent
13
+ * window, not full history: an old inbound payment outside it will not
14
+ * surface here. Documented limitation (see the 2026-09-18 spec) rather
15
+ * than a silent one.
16
+ * 3. Token transfers — EXACT, via `token_settlements.counterpartyKey`
17
+ * (`idx_token_settlements_counterpartyKey`).
18
+ *
19
+ * The address rail is never attributable to a contact (no key in its label)
20
+ * and is excluded here the same way it is everywhere else in the app.
21
+ */
22
+ import { counterpartyOf } from '../pay/counterparty'
23
+
24
+ /** The recent-window size for source (2) above. */
25
+ export const RECENT_WINDOW = 200
26
+
27
+ /** The slice of a wallet action this module reads. Matches what
28
+ * `listActionsSql` actually builds (see storage/methods/listActionsSql.ts). */
29
+ export interface ContactBsvAction {
30
+ txid?: string
31
+ satoshis: number
32
+ status: string
33
+ isOutgoing?: boolean
34
+ description?: string
35
+ labels?: string[]
36
+ senderIdentityKey?: string
37
+ created_at?: string | number
38
+ }
39
+
40
+ export interface ContactActivityWallet {
41
+ listActions(
42
+ args: { labels?: string[]; labelQueryMode?: 'any' | 'all'; limit?: number; includeLabels?: boolean },
43
+ originator?: string
44
+ ): Promise<{ actions: ContactBsvAction[] }>
45
+ }
46
+
47
+ /** The slice of `token_settlements` this module reads. */
48
+ export interface ContactSettlementRow {
49
+ txid: string
50
+ role: 'sent' | 'received'
51
+ assetId: string
52
+ state: string
53
+ counterpartyKey?: string
54
+ amountBaseUnits?: number
55
+ createdAt: string
56
+ }
57
+
58
+ export interface ContactSettlementsDb {
59
+ getAllAsync(sql: string, params: (string | number | null)[]): Promise<unknown[]>
60
+ }
61
+
62
+ export type ContactActivityItem = ({ kind: 'bsv' } & ContactBsvAction) | ({ kind: 'token' } & ContactSettlementRow)
63
+
64
+ function timeOf(item: ContactActivityItem): number {
65
+ const raw = item.kind === 'bsv' ? item.created_at : item.createdAt
66
+ if (raw === undefined || raw === null) return 0
67
+ const ts = new Date(raw as string).getTime()
68
+ return Number.isNaN(ts) ? 0 : ts
69
+ }
70
+
71
+ /** Token transfers with this counterparty. Exported separately so it can be
72
+ * unit-tested against a real in-memory SQLite (see `mandala/settlementStore.ts`'s
73
+ * own test pattern) without a wallet in the loop. */
74
+ export async function listTokenSettlementsByCounterparty(
75
+ db: ContactSettlementsDb,
76
+ counterpartyKey: string
77
+ ): Promise<ContactSettlementRow[]> {
78
+ const rows = (await db.getAllAsync(
79
+ 'SELECT txid, role, assetId, state, counterpartyKey, amountBaseUnits, createdAt FROM token_settlements WHERE counterpartyKey = ? ORDER BY createdAt DESC',
80
+ [counterpartyKey]
81
+ )) as {
82
+ txid: string
83
+ role: string
84
+ assetId: string
85
+ state: string
86
+ counterpartyKey: string | null
87
+ amountBaseUnits: number | null
88
+ createdAt: string
89
+ }[]
90
+ return rows.map(r => ({
91
+ txid: r.txid,
92
+ role: r.role as 'sent' | 'received',
93
+ assetId: r.assetId,
94
+ state: r.state,
95
+ counterpartyKey: r.counterpartyKey ?? undefined,
96
+ amountBaseUnits: r.amountBaseUnits ?? undefined,
97
+ createdAt: r.createdAt
98
+ }))
99
+ }
100
+
101
+ /**
102
+ * Every activity item with `identityKey`, merged and sorted newest first.
103
+ *
104
+ * `wallet` and `settlementsDb` are both optional so a caller that only has
105
+ * one half built (e.g. a token-less wallet) still gets what it can — same
106
+ * fail-open posture as `resolveIdentity.ts`.
107
+ */
108
+ export async function getContactActivity(args: {
109
+ wallet?: ContactActivityWallet
110
+ adminOriginator?: string
111
+ settlementsDb?: ContactSettlementsDb
112
+ identityKey: string
113
+ }): Promise<ContactActivityItem[]> {
114
+ const { wallet, adminOriginator, settlementsDb, identityKey } = args
115
+ const items: ContactActivityItem[] = []
116
+
117
+ if (wallet) {
118
+ try {
119
+ const outbound = await wallet.listActions(
120
+ { labels: [identityKey], labelQueryMode: 'any', limit: 500, includeLabels: true },
121
+ adminOriginator
122
+ )
123
+ const recent = await wallet.listActions({ limit: RECENT_WINDOW, includeLabels: true }, adminOriginator)
124
+ const seen = new Set<string>()
125
+ for (const action of [...outbound.actions, ...recent.actions]) {
126
+ const cp = counterpartyOf({
127
+ labels: action.labels,
128
+ senderIdentityKey: action.senderIdentityKey,
129
+ txid: action.txid
130
+ })
131
+ if (!cp || cp.kind !== 'identityKey' || cp.value !== identityKey) continue
132
+ const key = action.txid ?? `${action.description ?? ''}:${action.created_at ?? ''}`
133
+ if (seen.has(key)) continue
134
+ seen.add(key)
135
+ items.push({ kind: 'bsv', ...action })
136
+ }
137
+ } catch {
138
+ // Best-effort, same posture as resolveIdentity: a read failure here
139
+ // must not blank a screen that also shows token activity below.
140
+ }
141
+ }
142
+
143
+ if (settlementsDb) {
144
+ try {
145
+ const settlements = await listTokenSettlementsByCounterparty(settlementsDb, identityKey)
146
+ for (const row of settlements) items.push({ kind: 'token', ...row })
147
+ } catch {
148
+ // Same posture as above.
149
+ }
150
+ }
151
+
152
+ return items.sort((a, b) => timeOf(b) - timeOf(a))
153
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What a background refresh should write to a contact's cache columns.
3
+ *
4
+ * `refreshContactCache` replaces all three in one UPDATE — that is what keeps
5
+ * it a single statement and keeps `name` untouchable — so a caller that names
6
+ * only the avatar silently blanks the handle stored beside it. This decides
7
+ * the COMPLETE row instead, from what the contact already had and what this
8
+ * pass actually learned.
9
+ *
10
+ * An absent learned value means "not looked up this time" and keeps what is
11
+ * there; an EMPTY one means "looked, and there is none" and clears it. That
12
+ * distinction is the whole reason this is a function and not a spread: a
13
+ * registry 404 has to be able to remove a handle the contact no longer holds.
14
+ */
15
+ export interface ContactCache {
16
+ cachedHandle?: string
17
+ cachedAvatarUrl?: string
18
+ cachedCertifier?: string
19
+ }
20
+
21
+ function pick(current: string | undefined, learned: string | undefined): string | undefined {
22
+ if (learned === undefined) return current
23
+ return learned === '' ? undefined : learned
24
+ }
25
+
26
+ /** The row to write, or null when this pass learned nothing new. */
27
+ export function mergeContactCache(
28
+ current: ContactCache,
29
+ learned: { cachedHandle?: string; cachedAvatarUrl?: string }
30
+ ): ContactCache | null {
31
+ const merged: ContactCache = {
32
+ cachedHandle: pick(current.cachedHandle, learned.cachedHandle),
33
+ cachedAvatarUrl: pick(current.cachedAvatarUrl, learned.cachedAvatarUrl),
34
+ cachedCertifier: current.cachedCertifier
35
+ }
36
+ const unchanged =
37
+ merged.cachedHandle === current.cachedHandle &&
38
+ merged.cachedAvatarUrl === current.cachedAvatarUrl &&
39
+ merged.cachedCertifier === current.cachedCertifier
40
+ return unchanged ? null : merged
41
+ }