@bsv/expo-wallet-toolbox 0.4.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,4 +1,4 @@
1
- export type HomeBadgeKind = 'attention' | 'unsent' | 'offline'
1
+ export type HomeBadgeKind = 'attention' | 'unsent' | 'token_attention' | 'offline'
2
2
 
3
3
  export type HomeBadge = { kind: HomeBadgeKind; count: number }
4
4
 
@@ -8,10 +8,18 @@ export function homeBadges(input: {
8
8
  unsent: number
9
9
  offlineQueued: number
10
10
  offlineRejected: number
11
+ /**
12
+ * Token payments that have been waiting to settle past the stuck bound
13
+ * (FIX M). They are not failures — the money is credited and spendable — but
14
+ * "they said they sent it and it never confirmed" must have a surface, or the
15
+ * only way to notice is to not notice.
16
+ */
17
+ tokenAttention?: number
11
18
  }): HomeBadge[] {
12
19
  const badges: HomeBadge[] = []
13
20
  if (input.attention > 0) badges.push({ kind: 'attention', count: input.attention })
14
21
  if (input.unsent > 0) badges.push({ kind: 'unsent', count: input.unsent })
22
+ if ((input.tokenAttention ?? 0) > 0) badges.push({ kind: 'token_attention', count: input.tokenAttention as number })
15
23
  const offline = input.offlineQueued + input.offlineRejected
16
24
  if (offline > 0) badges.push({ kind: 'offline', count: offline })
17
25
  return badges
@@ -0,0 +1,68 @@
1
+ import { PEERPAY_LABEL } from '../../core/localpay/pending'
2
+
3
+ const NEARBY_FIXED: Record<'sent' | 'received', string> = {
4
+ sent: 'Sent token',
5
+ received: 'Received token'
6
+ }
7
+
8
+ /**
9
+ * The message-box rail's own fixed wording (`@bsv/mandala`'s `transfer.ts`
10
+ * `Send ${amount} of ${assetId}` / `receive.ts` `Receive ${amount} of
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
13
+ * there is nothing to reconstruct against, so the caller below treats the
14
+ * rail as unrecognised rather than guess.
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}`
19
+ }
20
+
21
+ /**
22
+ * The fixed wording for whichever rail authored this action, or `undefined`
23
+ * when the action carries neither rail's marker label — in which case the
24
+ * description is never trusted as a note (see `tokenRowTitle`'s doc).
25
+ */
26
+ function fixedDescriptionFor(
27
+ role: 'sent' | 'received',
28
+ labels: string[] | undefined,
29
+ assetId: string | undefined,
30
+ baseUnits: number | undefined
31
+ ): string | undefined {
32
+ 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)
35
+ return undefined
36
+ }
37
+
38
+ /**
39
+ * A token activity row's title. Normally the fixed "Sent/Received <ticker>"
40
+ * template (`token_row_sent`/`token_row_received`) — but a sender's own note
41
+ * overrides it, same as a BSV row's description already does.
42
+ *
43
+ * Two rails write a real note into `description` today: the nearby rail
44
+ * (label `'localpay'`, fixed wording "Sent/Received token") and the
45
+ * message-box rail (label `'transfer'`/`'receive'`, `@bsv/mandala`'s own
46
+ * fixed wording "Send/Receive N of assetId"). An action from neither rail —
47
+ * or a message-box action missing the `assetId`/`baseUnits` needed to
48
+ * reconstruct its fixed wording — never has its description shown: it may be
49
+ * an opaque developer string the lib wrote for some other purpose, not
50
+ * anything a user typed (the reason this override existed in the first
51
+ * place).
52
+ */
53
+ export function tokenRowTitle(args: {
54
+ role: 'sent' | 'received'
55
+ ticker: string
56
+ labels?: string[]
57
+ description?: string
58
+ /** The row's own asset id — needed to recognise the message-box rail's fixed wording. */
59
+ assetId?: string
60
+ /** The row's own amount, in base units — same reason as `assetId`. */
61
+ baseUnits?: number
62
+ t: (key: string, values?: Record<string, unknown>) => string
63
+ }): string {
64
+ const fixed = fixedDescriptionFor(args.role, args.labels, args.assetId, args.baseUnits)
65
+ const hasNote = fixed !== undefined && !!args.description && args.description !== fixed
66
+ if (hasNote) return args.description as string
67
+ return args.t(args.role === 'sent' ? 'token_row_sent' : 'token_row_received', { ticker: args.ticker })
68
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Token money, formatted so the wallet never prints a number it cannot stand
3
+ * behind (ux §1 principle 4).
4
+ *
5
+ * Two rules the BSV helpers do not enforce and cannot be bent to:
6
+ *
7
+ * 1. FIXED decimals, never trimmed. `1,240.00 USDX` is money; `1,240 USDX` is
8
+ * a quantity, and the difference is what a holder reads as "cents exist
9
+ * 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
+ *
16
+ * There is deliberately no fiat path and no currency symbol: the wallet has no
17
+ * price for a token and a `$` beside a USD-ticker balance would be the wallet
18
+ * vouching for someone else's peg (ux §6.1).
19
+ */
20
+
21
+ /** Grouping separators for the integer part, in the device's own locale. */
22
+ function groupInteger(digits: string): string {
23
+ const n = Number(digits)
24
+ if (!Number.isFinite(n)) return digits
25
+ // Safe: the integer part of a base-unit figure is always smaller than the
26
+ // figure itself, and anything past 2^53 is already unrepresentable upstream.
27
+ return n.toLocaleString(undefined, { useGrouping: true, maximumFractionDigits: 0 })
28
+ }
29
+
30
+ /**
31
+ * `1240000` at 2 dp → `"1,240.00"`. Negative inputs keep their sign; a
32
+ * non-finite input is refused with `null` rather than rendered as `NaN`, so a
33
+ * caller that forgot to guard prints nothing instead of nonsense.
34
+ */
35
+ export function formatTokenAmount(
36
+ baseUnits: number,
37
+ decimals: number,
38
+ opts: { showPlus?: boolean } = {}
39
+ ): string | null {
40
+ if (!Number.isFinite(baseUnits) || !Number.isFinite(decimals) || decimals < 0) return null
41
+ const d = Math.floor(decimals)
42
+ const rounded = Math.round(Math.abs(baseUnits))
43
+ const digits = String(rounded).padStart(d + 1, '0')
44
+ const intPart = d === 0 ? digits : digits.slice(0, digits.length - d)
45
+ const fracPart = d === 0 ? '' : digits.slice(digits.length - d)
46
+ const body = d === 0 ? groupInteger(intPart) : `${groupInteger(intPart)}.${fracPart}`
47
+ const sign = baseUnits < 0 ? '−' : opts.showPlus ? '+' : ''
48
+ return `${sign}${body}`
49
+ }
50
+
51
+ /** `"1,240.00"` + `"USDX"` — the two halves a money figure is drawn from. */
52
+ export function tokenAmountParts(
53
+ baseUnits: number,
54
+ asset: { decimals: number; ticker: string },
55
+ opts: { showPlus?: boolean } = {}
56
+ ): { value: string; unit: string } | null {
57
+ const value = formatTokenAmount(baseUnits, asset.decimals, opts)
58
+ if (value === null) return null
59
+ return { value, unit: asset.ticker }
60
+ }
61
+
62
+ /** `"1,240.00 USDX"` — the one string VoiceOver reads for a token figure. */
63
+ export function formatTokenAmountWithUnit(
64
+ baseUnits: number,
65
+ asset: { decimals: number; ticker: string },
66
+ opts: { showPlus?: boolean } = {}
67
+ ): string | null {
68
+ const parts = tokenAmountParts(baseUnits, asset, opts)
69
+ return parts && `${parts.value} ${parts.unit}`
70
+ }
71
+
72
+ /**
73
+ * A typed display figure back to base units, for the amount field.
74
+ *
75
+ * Returns `null` for anything that is not a whole number of base units — blank,
76
+ * junk, or more decimal places than the asset has. The field never emits a
77
+ * fraction: the wire takes integers, and a rounded one would silently pay a
78
+ * different amount than the one on screen.
79
+ */
80
+ export function parseTokenAmount(text: string, decimals: number): number | null {
81
+ if (!Number.isFinite(decimals) || decimals < 0) return null
82
+ const trimmed = text.trim()
83
+ if (!trimmed) return null
84
+ const d = Math.floor(decimals)
85
+ const match = new RegExp(`^(\\d*)(?:\\.(\\d{0,${d}}))?$`).exec(trimmed)
86
+ if (!match) return null
87
+ const intPart = match[1] ?? ''
88
+ const fracPart = (match[2] ?? '').padEnd(d, '0')
89
+ if (!intPart && !match[2]) return null
90
+ const combined = `${intPart || '0'}${fracPart}`
91
+ const value = Number(combined)
92
+ return Number.isSafeInteger(value) ? value : null
93
+ }
94
+
95
+ /** The input mask for an asset's decimals: digits, one point, at most N places. */
96
+ export function tokenAmountMask(decimals: number): RegExp {
97
+ const d = Math.max(0, Math.floor(decimals))
98
+ return d === 0 ? /^\d*$/ : new RegExp(`^\\d*\\.?\\d{0,${d}}$`)
99
+ }
100
+
101
+ /** Base units → the exact display string the amount field should hold. */
102
+ export function tokenAmountInputText(baseUnits: number, decimals: number): string {
103
+ const formatted = formatTokenAmount(baseUnits, decimals)
104
+ if (formatted === null) return ''
105
+ // The field is typed, not read: no grouping separators, which a decimal-pad
106
+ // cannot produce and `parseTokenAmount` would refuse on the next keystroke.
107
+ return formatted.replace(/[^\d.]/g, '')
108
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * "Has the user already been told?" — two small persisted sets.
3
+ *
4
+ * · `mandala_seen_assets` clears an asset row's "New — tap to see who issues
5
+ * it" subtitle once the sheet has actually been opened. Disclosure that
6
+ * re-announces itself after it has been read is noise.
7
+ * · `mandala_seen_evictions` makes the withdrawal alert fire exactly once per
8
+ * transaction. An alert about money leaving is the most interruptive thing
9
+ * this feature does; raising it again on every foreground would train the
10
+ * user to dismiss it unread.
11
+ *
12
+ * AsyncStorage rather than the wallet database on purpose: this is a fact about
13
+ * what a person has seen on this device, not a fact about money, and it must
14
+ * never be able to block, delay or fail a payment path. Every read fails to the
15
+ * empty set, which errs toward telling the user again.
16
+ */
17
+ import { useCallback, useEffect, useState } from 'react'
18
+ import AsyncStorage from '@react-native-async-storage/async-storage'
19
+
20
+ export const SEEN_ASSETS_KEY = 'mandala_seen_assets'
21
+ export const SEEN_EVICTIONS_KEY = 'mandala_seen_evictions'
22
+
23
+ export async function readSeen(key: string): Promise<string[]> {
24
+ try {
25
+ const raw = await AsyncStorage.getItem(key)
26
+ if (!raw) return []
27
+ const parsed: unknown = JSON.parse(raw)
28
+ return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : []
29
+ } catch {
30
+ return []
31
+ }
32
+ }
33
+
34
+ export async function markSeen(key: string, id: string): Promise<void> {
35
+ try {
36
+ const current = await readSeen(key)
37
+ if (current.includes(id)) return
38
+ await AsyncStorage.setItem(key, JSON.stringify([...current, id]))
39
+ } catch {
40
+ // Cosmetic state. A write failure means one repeated subtitle or one
41
+ // repeated alert, never a wrong balance.
42
+ }
43
+ }
44
+
45
+ export interface SeenSet {
46
+ seen: string[]
47
+ isSeen: (id: string) => boolean
48
+ see: (id: string) => void
49
+ }
50
+
51
+ export function useSeenSet(key: string): SeenSet {
52
+ const [seen, setSeen] = useState<string[]>([])
53
+
54
+ useEffect(() => {
55
+ let live = true
56
+ void readSeen(key).then(ids => {
57
+ if (live) setSeen(ids)
58
+ })
59
+ return () => {
60
+ live = false
61
+ }
62
+ }, [key])
63
+
64
+ const see = useCallback(
65
+ (id: string) => {
66
+ setSeen(prev => (prev.includes(id) ? prev : [...prev, id]))
67
+ void markSeen(key, id)
68
+ },
69
+ [key]
70
+ )
71
+
72
+ const isSeen = useCallback((id: string) => seen.includes(id), [seen])
73
+
74
+ return { seen, isSeen, see }
75
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * What a token row's settlement state is called, and in what colour.
3
+ *
4
+ * Five states reach the UI (`TokenActivityStatus`), and the mapping is here
5
+ * rather than inside a component so the same word appears in the activity list,
6
+ * the Asset sheet and the home badge without three chances to disagree.
7
+ *
8
+ * Colour follows the app's one chroma rule: green means confirmed money and
9
+ * nothing else, so only `settled` earns it. `settling` is not a warning — it is
10
+ * the ordinary state of an offline payment that has not yet reached the issuer,
11
+ * and painting it amber would make the normal case look like a fault.
12
+ */
13
+ import type { TokenActivityStatus } from '../core/mandala/runtime'
14
+ import type { TxStatusView } from './txStatus'
15
+
16
+ export type TokenStatusTone = 'neutral' | 'positive' | 'warning' | 'error'
17
+
18
+ const KEYS: Record<TokenActivityStatus, string> = {
19
+ settling: 'token_status_settling',
20
+ settled: 'token_status_settled',
21
+ refused: 'token_status_refused',
22
+ reversed: 'token_status_reversed',
23
+ stuck: 'token_status_stuck'
24
+ }
25
+
26
+ const TONES: Record<TokenActivityStatus, TokenStatusTone> = {
27
+ settling: 'neutral',
28
+ settled: 'positive',
29
+ refused: 'error',
30
+ reversed: 'error',
31
+ stuck: 'warning'
32
+ }
33
+
34
+ export function tokenStatusKey(status: TokenActivityStatus): string {
35
+ return KEYS[status] ?? KEYS.settling
36
+ }
37
+
38
+ /**
39
+ * A token row's status in an activity list, in the same words and tones a BSV
40
+ * row uses: a finished transfer says what it did (Sent / Received), one still
41
+ * on its way to the issuer is plain "Pending", and only the states the holder
42
+ * may have to act on keep their own word and get colour.
43
+ */
44
+ export function tokenRowStatusView(status: TokenActivityStatus, incoming: boolean): TxStatusView {
45
+ switch (status) {
46
+ case 'settled':
47
+ return { key: incoming ? 'tx_status_received' : 'tx_status_sent', tone: 'settled' }
48
+ case 'refused':
49
+ case 'reversed':
50
+ return { key: KEYS[status], tone: 'failed' }
51
+ case 'stuck':
52
+ return { key: KEYS.stuck, tone: 'attention' }
53
+ default:
54
+ return { key: 'tx_status_pending', tone: 'settled' }
55
+ }
56
+ }
57
+
58
+ export function tokenStatusTone(status: TokenActivityStatus): TokenStatusTone {
59
+ return TONES[status] ?? 'neutral'
60
+ }
61
+
62
+ /**
63
+ * 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.
66
+ *
67
+ * `refusedCode` narrows a `stuck` or `received`-`refused` row to a more exact
68
+ * reason, the same way `tokenSendCopy.ts` narrows a live send failure — by
69
+ * substring match against the wire's `ERR_*` vocabulary
70
+ * (`docs/.../mandala-wire-contract-v2.md`), because the code space spans two
71
+ * overlay engines and the manager's own free-text reject reasons. Unmatched
72
+ * or absent falls back to the plain status sentence, which is true for every
73
+ * one of them.
74
+ */
75
+ export function tokenStatusDetailKey(
76
+ status: TokenActivityStatus,
77
+ role: 'sent' | 'received',
78
+ refusedCode?: string
79
+ ): string | null {
80
+ const code = (refusedCode ?? '').toLowerCase()
81
+ const has = (...needles: string[]) => needles.some(n => code.includes(n))
82
+
83
+ if (status === 'stuck') {
84
+ if (has('pause')) return 'token_settle_paused_retry'
85
+ return 'token_settle_unreachable_retry'
86
+ }
87
+ if (status === 'refused') {
88
+ if (role === 'sent') return 'token_err_refused'
89
+ // Received side: a chain-linkage reason means an ancestor in the transfer
90
+ // was the one refused, not this frame's own content; anything else that
91
+ // is a content-shape reason reads as an unreadable frame rather than a
92
+ // generic reversal. Both are narrower, truer sentences than the plain
93
+ // "could not be confirmed" fallback.
94
+ if (has('linkage')) return 'token_chain_reversed'
95
+ if (has('shape', 'conservation', 'satoshi')) return 'token_frame_unreadable'
96
+ return 'token_recv_reversed'
97
+ }
98
+ if (status === 'reversed') return 'token_settle_evicted'
99
+ return null
100
+ }
package/ui/txStatus.ts CHANGED
@@ -22,11 +22,44 @@ export interface TxStatusView {
22
22
  * Map a raw action status (and any live offline-queue state) to a tone.
23
23
  *
24
24
  * The offline queue row outranks the raw status: a held transaction sits at
25
- * 'unproven' (which would read as a settled "Accepted") or at 'nosend' when
25
+ * 'unproven' (which would read as a quiet "Pending") or at 'nosend' when
26
26
  * payer-side promotion failed, so without this the user would see a confirmed
27
27
  * payment that has not actually gone anywhere.
28
28
  */
29
- export function txStatusView(status: string, offlineStatus?: string): TxStatusView {
29
+ /**
30
+ * Labels the Pay / Get paid rails write on their actions: handle and nearby
31
+ * payments, address payments, and stablecoin transfers. An outgoing action
32
+ * without one was made by a connected app or the wallet itself (an identity
33
+ * certificate, say), so it reads "Spent", not "Sent".
34
+ */
35
+ const PAYMENT_LABELS = new Set(['peerpay', 'localpay', 'legacy', 'mandala'])
36
+
37
+ export function isPaymentAction(labels?: readonly string[]): boolean {
38
+ return Boolean(labels?.some(l => PAYMENT_LABELS.has(l)))
39
+ }
40
+
41
+ /** What a row says it did once it settles. Its i18n key is `tx_status_<kind>`. */
42
+ export type ActivityKind = 'sent' | 'received' | 'spent' | 'transferred'
43
+
44
+ /**
45
+ * The one place a row's word is decided, so the status line and the activity
46
+ * filter can never disagree about which word a row says.
47
+ */
48
+ export function activityKind(incoming: boolean | undefined, labels?: readonly string[]): ActivityKind {
49
+ // A vault move stays the holder's money whichever way it goes.
50
+ if (labels?.includes('vault')) return 'transferred'
51
+ if (incoming) return 'received'
52
+ return isPaymentAction(labels) ? 'sent' : 'spent'
53
+ }
54
+
55
+ export function txStatusView(
56
+ status: string,
57
+ offlineStatus?: string,
58
+ incoming?: boolean,
59
+ labels?: readonly string[]
60
+ ): TxStatusView {
61
+ const done = `tx_status_${activityKind(incoming, labels)}`
62
+
30
63
  switch (offlineStatus) {
31
64
  case 'queued':
32
65
  return { key: 'tx_status_offline_queued', tone: 'inflight' }
@@ -42,12 +75,17 @@ export function txStatusView(status: string, offlineStatus?: string): TxStatusVi
42
75
  }
43
76
 
44
77
  switch (status) {
78
+ // The chain words ("Confirmed", "Accepted") answered a question about the
79
+ // ledger; the user's question is what happened to their money. A settled
80
+ // row therefore says what it DID — Received or Sent — from the moment it is
81
+ // handed to the network: the block proof that follows changes nothing the
82
+ // holder can act on. The states below that DO need action keep their own words.
45
83
  case 'completed':
46
- return { key: 'tx_status_confirmed', tone: 'settled' }
47
84
  case 'unproven':
48
- return { key: 'tx_status_accepted', tone: 'settled' }
85
+ return { key: done, tone: 'settled' }
86
+ // Already handed to the network: say what it does, Sent or Received.
49
87
  case 'sending':
50
- return { key: 'tx_status_broadcasting', tone: 'inflight' }
88
+ return { key: done, tone: 'inflight' }
51
89
  case 'nosend':
52
90
  return { key: 'tx_status_not_sent', tone: 'attention' }
53
91
  case 'unsigned':
Binary file
Binary file
@@ -1,75 +0,0 @@
1
- /**
2
- * The K1 vault script: byte-length constants, the customInstructions codec,
3
- * and locking-script construction.
4
- *
5
- * Every K1 detail lives here so no other module needs to know the template's
6
- * shape. A K1 vault output is a plain P2PKH output — no R1/YubiKey leg, no
7
- * template contract — locked to a BIP32 child key derived per
8
- * services/vault/vaultDerivation.ts.
9
- *
10
- * SECURITY: nothing secret passes through this module — only public keys,
11
- * hashes, and script bytes.
12
- */
13
- import { LockingScript, P2PKH } from '@bsv/sdk'
14
-
15
- /** Exact: a P2PKH locking script is always
16
- * OP_DUP OP_HASH160 push(20) OP_EQUALVERIFY OP_CHECKSIG = 1+1+1+20+1+1 = 25 bytes. */
17
- export const K1_LOCK_LEN = 25
18
-
19
- /** Conservative estimate, not exact: a real P2PKH unlock measures ~107 bytes
20
- * (push(≤72-byte DER sig) + push(33-byte compressed pubkey)), matching the
21
- * staging-unlock shape the legacy reclaim still builds (see transfers.ts's
22
- * reclaimStagingOutputs). DER signatures
23
- * vary between 70 and 72 bytes, so this pins the ceiling rather than the
24
- * exact length. */
25
- export const K1_UNLOCK_LEN = 108
26
-
27
- /**
28
- * What a K1 vault output records about itself.
29
- *
30
- * `v` is the customInstructions format version and is a hard fork from the
31
- * old template-based line: v2 records carry a different type discriminator
32
- * entirely and must never decode as v3 — see decodeVaultInstructions.
33
- */
34
- export interface VaultInstructions {
35
- v: 3
36
- type: 'K1'
37
- /** BIP32 child key ID, e.g. 'bip32/7'. See vaultDerivation.ts's
38
- * BIP32_KEYID_PREFIX / bip32KeyID. */
39
- keyID: string
40
- }
41
-
42
- export function encodeVaultInstructions(i: VaultInstructions): string {
43
- return JSON.stringify(i)
44
- }
45
-
46
- /**
47
- * Parse an output's customInstructions, or null if it is not a well-formed
48
- * K1 v3 record.
49
- *
50
- * Fails closed on anything unrecognised — including old v2 R1-K1 records —
51
- * because a malformed record means an output we cannot construct a valid
52
- * spend for, and silently dropping it from the spendable set beats building
53
- * a transaction that cannot be signed.
54
- */
55
- export function decodeVaultInstructions(ci?: string): VaultInstructions | null {
56
- if (!ci) return null
57
- let parsed: unknown
58
- try {
59
- parsed = JSON.parse(ci)
60
- } catch {
61
- return null
62
- }
63
- if (!parsed || typeof parsed !== 'object') return null
64
- const p = parsed as Partial<VaultInstructions>
65
- if (p.v !== 3 || p.type !== 'K1') return null
66
- if (typeof p.keyID !== 'string' || !p.keyID.startsWith('bip32/')) return null
67
- return { v: 3, type: 'K1', keyID: p.keyID }
68
- }
69
-
70
- /** Build a K1 vault locking script: a plain P2PKH lock to the given public
71
- * key hash. Synchronous — there is no template to await; callers may still
72
- * `await` this without effect. */
73
- export function buildVaultLockingScript(a: { k1PublicKeyHash: number[] }): LockingScript {
74
- return new P2PKH().lock(a.k1PublicKeyHash)
75
- }
@@ -1,84 +0,0 @@
1
- /**
2
- * Vault sealing crypto — pure functions, no I/O, no logging.
3
- *
4
- * Scheme (`bsvb-vault-seal-v1`, the age-plugin-yubikey / systemd-cryptenroll
5
- * PKCS#11 pattern):
6
- *
7
- * seal : ephemeral P-256 keypair e/E; S = ECDH(e, yubiPub);
8
- * KEK = HKDF-SHA256(S, salt, info); C = AES-256-GCM(KEK, V)
9
- * unseal : S = on-token ECDH(slot, E) ← the touch-gated step;
10
- * KEK = HKDF(S, salt, info); V = AES-GCM-decrypt(KEK, C)
11
- *
12
- * The token returns the 32-byte x-coordinate of the shared point (PIV
13
- * KeyAgreement semantics); softwareEcdh mirrors that exactly so both sides
14
- * derive the same KEK.
15
- *
16
- * SECURITY: never log inputs or outputs of these functions.
17
- */
18
- import { p256 } from '@noble/curves/nist.js'
19
- import { Hash, SymmetricKey, Utils } from '@bsv/sdk'
20
- import { SealedBlob, VaultError } from './types'
21
- import { randomBytes } from './random'
22
- import { hkdfSha256 } from '../secrets/hkdf'
23
-
24
- export const SEAL_INFO = 'bsvb-vault-seal-v1'
25
-
26
- /** ECDH over P-256 returning the hex x-coordinate (32 bytes) — the same value
27
- * a YubiKey's PIV KeyAgreement operation produces. */
28
- export function softwareEcdh(privHex: string, pubHex: string): string {
29
- const priv = Uint8Array.from(Utils.toArray(privHex, 'hex'))
30
- const pub = Uint8Array.from(Utils.toArray(pubHex, 'hex'))
31
- const shared = p256.getSharedSecret(priv, pub, false) // 65B uncompressed point
32
- return Utils.toHex(Array.from(shared.slice(1, 33)))
33
- }
34
-
35
- /** Generate a fresh ephemeral P-256 scalar from our own entropy source
36
- * (avoids depending on a WebCrypto global under React Native). */
37
- function ephemeralKeypair(): { privHex: string; pubHex: string } {
38
- // Rejection-sample until the scalar is valid for the curve (overwhelmingly
39
- // first-try; the loop is belt-and-braces).
40
- for (;;) {
41
- const candidate = Uint8Array.from(randomBytes(32))
42
- try {
43
- const pub = p256.getPublicKey(candidate, false)
44
- return { privHex: Utils.toHex(Array.from(candidate)), pubHex: Utils.toHex(Array.from(pub)) }
45
- } catch {
46
- // invalid scalar (zero or >= order) — draw again
47
- }
48
- }
49
- }
50
-
51
- /** Seal the vault key V to a YubiKey's PIV public key. Software-only —
52
- * requires no token present, so re-sealing and enrollment never need touch. */
53
- export function sealVaultKey(
54
- v: number[],
55
- yubiPubHex: string,
56
- meta: { slot: number; serial: string }
57
- ): SealedBlob {
58
- const { privHex: ePriv, pubHex: ePub } = ephemeralKeypair()
59
- const salt = randomBytes(32)
60
- const shared = softwareEcdh(ePriv, yubiPubHex)
61
- const kek = hkdfSha256(Utils.toArray(shared, 'hex'), salt, SEAL_INFO)
62
- const c = new SymmetricKey(kek).encrypt(v) as number[]
63
- return {
64
- v: 1,
65
- slot: meta.slot,
66
- ePub,
67
- salt: Utils.toHex(salt),
68
- c: Utils.toHex(c),
69
- yubiSerial: meta.serial,
70
- yubiPubSha256: Utils.toHex(Hash.sha256(Utils.toArray(yubiPubHex, 'hex')))
71
- }
72
- }
73
-
74
- /** Recover V from a seal given the token-computed shared secret (hex
75
- * x-coordinate from the ceremony's ECDH). Throws `seal-corrupt` on any
76
- * mismatch — wrong secret, tampered ciphertext, malformed blob. */
77
- export function unsealVaultKey(blob: SealedBlob, sharedSecretHex: string): number[] {
78
- try {
79
- const kek = hkdfSha256(Utils.toArray(sharedSecretHex, 'hex'), Utils.toArray(blob.salt, 'hex'), SEAL_INFO)
80
- return new SymmetricKey(kek).decrypt(Utils.toArray(blob.c, 'hex')) as number[]
81
- } catch {
82
- throw new VaultError('seal-corrupt', 'Vault seal could not be opened')
83
- }
84
- }