@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
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The two stablecoins demo mode holds, plus the BSV opening balance.
3
+ *
4
+ * DEV-ONLY. Nothing here describes a real issuer, a real overlay or a real
5
+ * asset: the genesis outpoints are obviously-fake repeated bytes so that a
6
+ * figure from this file can never be mistaken for one from an overlay, and
7
+ * the overlay URLs point at `.invalid`, which by RFC 2606 can never resolve.
8
+ *
9
+ * Naming follows the stablecoin UX spec, which uses `USDX` / "Acme Dollar" /
10
+ * "Acme Bank" throughout; the CHF asset copies that shape rather than
11
+ * inventing a second convention.
12
+ */
13
+ import type { TokenAssetInfo } from '../mandala/runtime'
14
+
15
+ /** Demo overlay identity — 66 hex chars, the length a real one has. */
16
+ const DEMO_OVERLAY_KEY = '02' + 'de'.repeat(32)
17
+ const DEMO_OVERLAY_URL = 'https://overlay.demo.invalid'
18
+
19
+ export const DEMO_USD: TokenAssetInfo = {
20
+ assetId: 'd0'.repeat(32) + '.0',
21
+ label: 'Acme Dollar',
22
+ ticker: 'USDX',
23
+ decimals: 2,
24
+ issuerName: 'Acme Bank',
25
+ overlayUrl: DEMO_OVERLAY_URL,
26
+ overlayIdentityKey: DEMO_OVERLAY_KEY
27
+ }
28
+
29
+ export const DEMO_CHF: TokenAssetInfo = {
30
+ assetId: 'cf'.repeat(32) + '.0',
31
+ label: 'Helvetia Franc',
32
+ ticker: 'CHFX',
33
+ decimals: 2,
34
+ issuerName: 'Helvetia Bank',
35
+ overlayIdentityKey: DEMO_OVERLAY_KEY,
36
+ overlayUrl: DEMO_OVERLAY_URL
37
+ }
38
+
39
+ export const DEMO_ASSETS: TokenAssetInfo[] = [DEMO_USD, DEMO_CHF]
40
+
41
+ export function demoAssetById(assetId: string): TokenAssetInfo | undefined {
42
+ return DEMO_ASSETS.find(a => a.assetId === assetId)
43
+ }
44
+
45
+ /** Opening BSV balance, in satoshis. 0.25 BSV — enough to read as funded. */
46
+ export const DEMO_OPENING_SATS = 25_000_000
47
+
48
+ /** Opening token balances, in base units (2 dp): 1,240.00 USDX / 860.50 CHFX. */
49
+ export const DEMO_OPENING_TOKEN_BASE_UNITS: Record<string, number> = {
50
+ [DEMO_USD.assetId]: 124_000,
51
+ [DEMO_CHF.assetId]: 86_050
52
+ }
53
+
54
+ /** Counterparties the demo history is transacted against. */
55
+ export const DEMO_COUNTERPARTIES = [
56
+ { name: 'Sofia Berger', key: '02' + 'a1'.repeat(32) },
57
+ { name: 'Marco Ferrari', key: '02' + 'b2'.repeat(32) },
58
+ { name: 'Lena Vogt', key: '02' + 'c3'.repeat(32) },
59
+ { name: 'Corner Store', key: '02' + 'd4'.repeat(32) }
60
+ ]
@@ -0,0 +1,240 @@
1
+ /**
2
+ * The demo wallet's whole world: one mutable, in-memory ledger.
3
+ *
4
+ * DEV-ONLY. Holds a BSV balance with its action history and a base-unit
5
+ * balance per demo stablecoin with its settlement history, and mutates both
6
+ * when the UI "sends". Nothing here touches SQLite, the keychain, an overlay
7
+ * or the network, so a demo send can never become a real one — and everything
8
+ * is gone at reload, which is what makes the mode safe to hand to someone.
9
+ *
10
+ * Figures are integers throughout (satoshis, token base units) for the same
11
+ * reason `ui/tokenFormat.ts` is: a float balance prints money that is not
12
+ * owned.
13
+ */
14
+ import type { TokenActivityRow, TokenActivityStatus } from '../mandala/runtime'
15
+ import type { WalletAction } from '@bsv/sdk'
16
+ import {
17
+ DEMO_CHF,
18
+ DEMO_COUNTERPARTIES,
19
+ DEMO_OPENING_SATS,
20
+ DEMO_OPENING_TOKEN_BASE_UNITS,
21
+ DEMO_USD,
22
+ demoAssetById
23
+ } from './demoAssets'
24
+
25
+ /** `ActivityAction` without importing the UI layer from core. */
26
+ export type DemoAction = WalletAction & {
27
+ reference?: string
28
+ created_at?: string | number | Date
29
+ senderIdentityKey?: string
30
+ }
31
+
32
+ interface DemoState {
33
+ satoshis: number
34
+ actions: DemoAction[]
35
+ tokenBaseUnits: Record<string, number>
36
+ tokenActivity: TokenActivityRow[]
37
+ }
38
+
39
+ const listeners = new Set<() => void>()
40
+
41
+ /** Deterministic 64-hex txid, so a demo row looks like a row and never collides. */
42
+ let txidCounter = 0
43
+ function demoTxid(): string {
44
+ txidCounter += 1
45
+ return txidCounter.toString(16).padStart(8, '0').repeat(8)
46
+ }
47
+
48
+ function daysAgo(n: number, hour = 12): string {
49
+ const d = new Date()
50
+ d.setDate(d.getDate() - n)
51
+ d.setHours(hour, (n * 7) % 60, 0, 0)
52
+ return d.toISOString()
53
+ }
54
+
55
+ function bsvAction(over: Partial<DemoAction> & { satoshis: number; description: string }): DemoAction {
56
+ return {
57
+ txid: demoTxid(),
58
+ status: 'completed',
59
+ isOutgoing: over.satoshis < 0,
60
+ labels: [],
61
+ version: 1,
62
+ lockTime: 0,
63
+ ...over,
64
+ // `satoshis` on a WalletAction is the signed delta to the balance, which
65
+ // is what the row renders; keep the caller's sign.
66
+ satoshis: over.satoshis
67
+ }
68
+ }
69
+
70
+ function tokenRow(
71
+ assetId: string,
72
+ role: 'sent' | 'received',
73
+ baseUnits: number,
74
+ at: string,
75
+ counterpartyKey?: string,
76
+ status: TokenActivityStatus = 'settled'
77
+ ): TokenActivityRow {
78
+ const asset = demoAssetById(assetId)
79
+ if (!asset) throw new Error(`demo: unknown assetId ${assetId}`)
80
+ return { txid: demoTxid(), role, asset, baseUnits, counterpartyKey, status, at }
81
+ }
82
+
83
+ /**
84
+ * The opening history: money in and out, on all three rails, spread over the
85
+ * last three weeks so the home list has day headers to group under.
86
+ */
87
+ function seed(): DemoState {
88
+ const [sofia, marco, lena, store] = DEMO_COUNTERPARTIES
89
+ txidCounter = 0
90
+ return {
91
+ satoshis: DEMO_OPENING_SATS,
92
+ actions: [
93
+ bsvAction({ satoshis: 12_000_000, description: 'Salary — October', created_at: daysAgo(18, 9) }),
94
+ bsvAction({ satoshis: -2_400_000, description: `Paid ${store.name}`, created_at: daysAgo(14, 18) }),
95
+ bsvAction({ satoshis: 6_500_000, description: `From ${sofia.name}`, created_at: daysAgo(11, 10) }),
96
+ bsvAction({ satoshis: -850_000, description: 'Coffee', created_at: daysAgo(7, 8) }),
97
+ bsvAction({ satoshis: -3_250_000, description: `Paid ${marco.name}`, created_at: daysAgo(4, 16) }),
98
+ bsvAction({ satoshis: 15_000_000, description: `From ${lena.name}`, created_at: daysAgo(2, 13) }),
99
+ bsvAction({ satoshis: -1_000_000, description: 'Lunch', created_at: daysAgo(0, 12) })
100
+ ],
101
+ tokenBaseUnits: { ...DEMO_OPENING_TOKEN_BASE_UNITS },
102
+ tokenActivity: [
103
+ tokenRow(DEMO_USD.assetId, 'received', 50_000, daysAgo(16, 11), sofia.key),
104
+ tokenRow(DEMO_CHF.assetId, 'received', 40_000, daysAgo(13, 15), lena.key),
105
+ tokenRow(DEMO_USD.assetId, 'sent', 12_500, daysAgo(9, 19), store.key),
106
+ tokenRow(DEMO_CHF.assetId, 'sent', 7_450, daysAgo(6, 12), marco.key),
107
+ tokenRow(DEMO_USD.assetId, 'received', 86_500, daysAgo(3, 14), marco.key),
108
+ tokenRow(DEMO_CHF.assetId, 'received', 53_500, daysAgo(1, 17), sofia.key),
109
+ // One row mid-flight, so the "settling" copy has something to render.
110
+ tokenRow(DEMO_USD.assetId, 'sent', 2_000, daysAgo(0, 11), lena.key, 'settling')
111
+ ]
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Initialised here rather than beside `listeners` above: `seed()` assigns
117
+ * `txidCounter`, so calling it any earlier reads that binding inside its
118
+ * temporal dead zone and throws on import.
119
+ */
120
+ let state: DemoState = seed()
121
+
122
+ function notify(): void {
123
+ listeners.forEach(l => l())
124
+ }
125
+
126
+ export function subscribeDemoLedger(listener: () => void): () => void {
127
+ listeners.add(listener)
128
+ return () => {
129
+ listeners.delete(listener)
130
+ }
131
+ }
132
+
133
+ // ── reads ──────────────────────────────────────────────────────────────
134
+
135
+ export function demoSatoshis(): number {
136
+ return state.satoshis
137
+ }
138
+
139
+ /** Newest first — the order the activity list renders in. */
140
+ export function demoActions(limit?: number, offset = 0): DemoAction[] {
141
+ const sorted = [...state.actions].sort(
142
+ (a, b) => new Date(b.created_at ?? 0).getTime() - new Date(a.created_at ?? 0).getTime()
143
+ )
144
+ return limit == null ? sorted.slice(offset) : sorted.slice(offset, offset + limit)
145
+ }
146
+
147
+ export function demoTotalActions(): number {
148
+ return state.actions.length
149
+ }
150
+
151
+ export function demoTokenBaseUnits(assetId: string): number {
152
+ return state.tokenBaseUnits[assetId] ?? 0
153
+ }
154
+
155
+ export function demoTokenActivity(limit?: number): TokenActivityRow[] {
156
+ const sorted = [...state.tokenActivity].sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime())
157
+ return limit == null ? sorted : sorted.slice(0, limit)
158
+ }
159
+
160
+ /** Base units awaiting settlement — what the UI shows as not-yet-final. */
161
+ export function demoUnsettledBaseUnits(assetId: string): number {
162
+ return state.tokenActivity
163
+ .filter(r => r.asset.assetId === assetId && r.role === 'received' && r.status === 'settling')
164
+ .reduce((sum, r) => sum + r.baseUnits, 0)
165
+ }
166
+
167
+ // ── writes ─────────────────────────────────────────────────────────────
168
+
169
+ /** Spend BSV. Returns the new row, or null when the balance cannot cover it. */
170
+ export function demoSendBsv(satoshis: number, description: string): DemoAction | null {
171
+ if (!Number.isFinite(satoshis) || satoshis <= 0) return null
172
+ if (satoshis > state.satoshis) return null
173
+ const action = bsvAction({
174
+ satoshis: -Math.round(satoshis),
175
+ description: description || 'Demo payment',
176
+ created_at: new Date().toISOString()
177
+ })
178
+ state = { ...state, satoshis: state.satoshis - Math.round(satoshis), actions: [...state.actions, action] }
179
+ notify()
180
+ return action
181
+ }
182
+
183
+ /** Receive BSV — for demonstrating an incoming payment on cue. */
184
+ export function demoReceiveBsv(satoshis: number, description: string): DemoAction | null {
185
+ if (!Number.isFinite(satoshis) || satoshis <= 0) return null
186
+ const action = bsvAction({
187
+ satoshis: Math.round(satoshis),
188
+ description: description || 'Demo receipt',
189
+ created_at: new Date().toISOString()
190
+ })
191
+ state = { ...state, satoshis: state.satoshis + Math.round(satoshis), actions: [...state.actions, action] }
192
+ notify()
193
+ return action
194
+ }
195
+
196
+ /** Spend a token. Returns the new row, or null when the balance cannot cover it. */
197
+ export function demoSendToken(
198
+ assetId: string,
199
+ baseUnits: number,
200
+ counterpartyKey?: string
201
+ ): TokenActivityRow | null {
202
+ if (!demoAssetById(assetId)) return null
203
+ if (!Number.isFinite(baseUnits) || baseUnits <= 0) return null
204
+ const held = demoTokenBaseUnits(assetId)
205
+ const amount = Math.round(baseUnits)
206
+ if (amount > held) return null
207
+ const row = tokenRow(assetId, 'sent', amount, new Date().toISOString(), counterpartyKey, 'settled')
208
+ state = {
209
+ ...state,
210
+ tokenBaseUnits: { ...state.tokenBaseUnits, [assetId]: held - amount },
211
+ tokenActivity: [...state.tokenActivity, row]
212
+ }
213
+ notify()
214
+ return row
215
+ }
216
+
217
+ /** Receive a token — for demonstrating an incoming payment on cue. */
218
+ export function demoReceiveToken(
219
+ assetId: string,
220
+ baseUnits: number,
221
+ counterpartyKey?: string
222
+ ): TokenActivityRow | null {
223
+ if (!demoAssetById(assetId)) return null
224
+ if (!Number.isFinite(baseUnits) || baseUnits <= 0) return null
225
+ const amount = Math.round(baseUnits)
226
+ const row = tokenRow(assetId, 'received', amount, new Date().toISOString(), counterpartyKey, 'settled')
227
+ state = {
228
+ ...state,
229
+ tokenBaseUnits: { ...state.tokenBaseUnits, [assetId]: demoTokenBaseUnits(assetId) + amount },
230
+ tokenActivity: [...state.tokenActivity, row]
231
+ }
232
+ notify()
233
+ return row
234
+ }
235
+
236
+ /** Back to the opening position, without a reload. */
237
+ export function resetDemoLedger(): void {
238
+ state = seed()
239
+ notify()
240
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * A `MandalaRuntime` backed entirely by the demo ledger.
3
+ *
4
+ * DEV-ONLY. Implements the members the UI actually reads or calls; everything
5
+ * else on the interface is drain/settlement machinery that has nothing to
6
+ * drain here, so it answers "nothing happened" rather than throwing — a demo
7
+ * must never crash on a background tick.
8
+ *
9
+ * `endpoints` deliberately carries the `.invalid` demo overlay rather than the
10
+ * configured one: if any code path ever did try to settle one of these rows,
11
+ * it must fail to resolve rather than reach a real issuer.
12
+ */
13
+ import type { MandalaRuntime, TokenAssetInfo, TokenAssetStatus, TokenBalance } from '../mandala/runtime'
14
+ import { DEMO_ASSETS, DEMO_USD } from './demoAssets'
15
+ import {
16
+ demoSendToken,
17
+ demoTokenActivity,
18
+ demoTokenBaseUnits,
19
+ demoUnsettledBaseUnits,
20
+ subscribeDemoLedger
21
+ } from './demoLedger'
22
+
23
+ function statusFor(): TokenAssetStatus {
24
+ return {
25
+ paused: false,
26
+ frozenBaseUnits: 0,
27
+ selfAdmitted: true,
28
+ recipientAdmitted: async () => true,
29
+ metadataResolved: true,
30
+ messageBoxUrl: 'https://messagebox.demo.invalid'
31
+ }
32
+ }
33
+
34
+ function balanceFor(asset: TokenAssetInfo): TokenBalance {
35
+ return {
36
+ asset,
37
+ baseUnits: demoTokenBaseUnits(asset.assetId),
38
+ unsettledBaseUnits: demoUnsettledBaseUnits(asset.assetId)
39
+ }
40
+ }
41
+
42
+ export function createDemoMandalaRuntime(): MandalaRuntime {
43
+ const runtime = {
44
+ available: true,
45
+ endpoints: {
46
+ overlayUrl: DEMO_USD.overlayUrl,
47
+ overlayIdentityKey: DEMO_USD.overlayIdentityKey,
48
+ messageBoxUrl: 'https://messagebox.demo.invalid'
49
+ },
50
+ store: {} as MandalaRuntime['store'],
51
+
52
+ // ── what the UI reads ───────────────────────────────────────────
53
+ listAssets: async () => DEMO_ASSETS,
54
+ balances: async () => DEMO_ASSETS.map(balanceFor),
55
+ activity: async (limit?: number) => demoTokenActivity(limit),
56
+ stuck: async () => [],
57
+ assetStatus: async () => statusFor(),
58
+ refreshAssetStatus: async () => statusFor(),
59
+ recipientRefusal: () => null,
60
+ subscribe: subscribeDemoLedger,
61
+
62
+ // ── what the UI calls ───────────────────────────────────────────
63
+ sendToHandle: async (args: { assetId: string; recipientIdentityKey: string; baseUnits: number }) => {
64
+ const row = demoSendToken(args.assetId, args.baseUnits, args.recipientIdentityKey)
65
+ if (!row) {
66
+ return {
67
+ kind: 'refused' as const,
68
+ code: 'ERR_INSUFFICIENT_FUNDS',
69
+ message: 'Not enough balance in demo mode.'
70
+ }
71
+ }
72
+ return { kind: 'sent' as const, txid: row.txid, settled: true, notified: true }
73
+ },
74
+ receiveFromInbox: async () => ({ credited: 0, failed: 0 }),
75
+ settleNow: async () => 'broadcast' as const,
76
+ cover: async () => ({ ok: true, mustSubmit: [] }),
77
+
78
+ // ── machinery with nothing to do ────────────────────────────────
79
+ drainNow: async () => {},
80
+ settlePendingSends: async () => 0,
81
+ ensureAdmissionsForHoldings: async () => 0,
82
+ reconcileJournals: async () => {},
83
+ recoverStaleAdmissions: async () => 0,
84
+ repairAdmittedAborted: async () => 0,
85
+ pruneBlindingReservations: async () => 0,
86
+ reviewTokenHoldings: async () => ({ settled: 0, removed: 0, unattested: 0, unreachable: false }),
87
+ resendTransfer: async () => ({ kind: 'unavailable', message: 'Demo mode' })
88
+ }
89
+
90
+ // The remaining members are injection points for machinery demo mode never
91
+ // starts (the drain, the nearby build, the frame verifier, the pending
92
+ // queue). Casting rather than stubbing each one keeps this file honest about
93
+ // the fact that nothing here is a real settlement path — the same approach
94
+ // `__tests__/__mocks__/fakeMandalaRuntime.ts` takes.
95
+ return runtime as unknown as MandalaRuntime
96
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The demo-mode switch, and the only thing outside this folder that decides
3
+ * whether any of it is live.
4
+ *
5
+ * DEV-ONLY, enforced twice over: `setDemoModeEnabled` refuses to latch on in a
6
+ * release bundle even if a release caller reaches it directly, and every call
7
+ * site behind it is itself wrapped in `__DEV__` so this module is never
8
+ * required into a production bundle at all. Same belt-and-braces shape as
9
+ * `core/services/vault/devMock.ts`.
10
+ *
11
+ * Deliberately NOT persisted. Demo mode is something you switch on to show
12
+ * someone the app and switch off again; a flag that survived a restart is a
13
+ * flag that is eventually on when nobody meant it to be.
14
+ */
15
+ const listeners = new Set<() => void>()
16
+ let enabled = false
17
+
18
+ export function isDemoModeEnabled(): boolean {
19
+ return __DEV__ && enabled
20
+ }
21
+
22
+ export function setDemoModeEnabled(on: boolean): void {
23
+ // A release caller can never turn this on, whatever it passes.
24
+ if (!__DEV__) {
25
+ enabled = false
26
+ return
27
+ }
28
+ if (enabled === on) return
29
+ enabled = on
30
+ listeners.forEach(l => l())
31
+ }
32
+
33
+ export function subscribeDemoMode(listener: () => void): () => void {
34
+ listeners.add(listener)
35
+ return () => {
36
+ listeners.delete(listener)
37
+ }
38
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The BSV half of demo mode: the two reads `WalletHomeScreen` makes for the
3
+ * balance figure and the activity list, answered from the demo ledger.
4
+ *
5
+ * DEV-ONLY. These are not a `WalletInterface` and deliberately are not one —
6
+ * demo mode substitutes the two READS the home screen performs, not the wallet
7
+ * itself, so no signing, key or storage path can ever be reached through here.
8
+ */
9
+ import { demoActions, demoSatoshis, demoTotalActions, type DemoAction } from './demoLedger'
10
+
11
+ /** Shape of `permissionsManager.listActions`' result, for the home screen. */
12
+ export interface DemoListActionsResult {
13
+ totalActions: number
14
+ actions: DemoAction[]
15
+ }
16
+
17
+ export function demoListActions(args: { limit?: number; offset?: number } = {}): DemoListActionsResult {
18
+ const { limit, offset = 0 } = args
19
+ return { totalActions: demoTotalActions(), actions: demoActions(limit, offset) }
20
+ }
21
+
22
+ /** Spendable satoshis — what `readWalletBalance`/`listOutputs` would total. */
23
+ export function demoWalletBalance(): number {
24
+ return demoSatoshis()
25
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Demo mode — a wallet full of obviously-fake money, for showing the app.
3
+ *
4
+ * DEV-ONLY, and structured so that it is not merely inert in production but
5
+ * absent from it: every call site requires this barrel from inside a `__DEV__`
6
+ * branch, and `__DEV__` is inlined to `false` at release bundle time, so the
7
+ * whole folder folds out. Same pattern as `utils/AgentationGate.tsx`.
8
+ *
9
+ * Nothing in here touches SQLite, the keychain, an overlay or the network.
10
+ */
11
+ export { DEMO_ASSETS, DEMO_CHF, DEMO_COUNTERPARTIES, DEMO_USD, demoAssetById } from './demoAssets'
12
+ export {
13
+ demoReceiveBsv,
14
+ demoReceiveToken,
15
+ demoSendBsv,
16
+ demoSendToken,
17
+ demoTokenActivity,
18
+ demoTokenBaseUnits,
19
+ resetDemoLedger,
20
+ subscribeDemoLedger,
21
+ type DemoAction
22
+ } from './demoLedger'
23
+ export { isDemoModeEnabled, setDemoModeEnabled, subscribeDemoMode } from './demoMode'
24
+ export { createDemoMandalaRuntime } from './demoMandalaRuntime'
25
+ export { demoListActions, demoWalletBalance, type DemoListActionsResult } from './demoWallet'
26
+ export { useDemoLedgerVersion, useDemoMandalaRuntime, useDemoMode } from './useDemo'
@@ -0,0 +1,59 @@
1
+ /**
2
+ * React bindings for demo mode.
3
+ *
4
+ * DEV-ONLY. Kept apart from `demoMode.ts` so that module stays importable from
5
+ * plain (non-React) code, and so the only thing a screen has to reach for is a
6
+ * hook that already re-renders when either the switch or the ledger moves.
7
+ */
8
+ import { useSyncExternalStore } from 'react'
9
+ import { isDemoModeEnabled, subscribeDemoMode } from './demoMode'
10
+ import { subscribeDemoLedger } from './demoLedger'
11
+ import { createDemoMandalaRuntime } from './demoMandalaRuntime'
12
+ import type { MandalaRuntime } from '../mandala/runtime'
13
+
14
+ /** One runtime for the session: its data is read through the ledger anyway. */
15
+ let runtime: MandalaRuntime | null = null
16
+ function demoRuntime(): MandalaRuntime {
17
+ if (!runtime) runtime = createDemoMandalaRuntime()
18
+ return runtime
19
+ }
20
+
21
+ /** Re-renders on the switch only. */
22
+ export function useDemoMode(): boolean {
23
+ return useSyncExternalStore(subscribeDemoMode, isDemoModeEnabled, () => false)
24
+ }
25
+
26
+ /**
27
+ * Re-renders on the switch AND on every ledger write, so a screen reading
28
+ * figures straight out of the ledger repaints when a demo payment lands.
29
+ */
30
+ export function useDemoLedgerVersion(): number {
31
+ return useSyncExternalStore(
32
+ listener => {
33
+ const offMode = subscribeDemoMode(listener)
34
+ const offLedger = subscribeDemoLedger(listener)
35
+ return () => {
36
+ offMode()
37
+ offLedger()
38
+ }
39
+ },
40
+ () => version,
41
+ () => 0
42
+ )
43
+ }
44
+
45
+ // `useSyncExternalStore` compares snapshots by identity, so the ledger needs a
46
+ // changing primitive to report rather than a fresh object each call.
47
+ let version = 0
48
+ subscribeDemoLedger(() => {
49
+ version += 1
50
+ })
51
+ subscribeDemoMode(() => {
52
+ version += 1
53
+ })
54
+
55
+ /** The demo runtime when the switch is on, otherwise null. */
56
+ export function useDemoMandalaRuntime(): MandalaRuntime | null {
57
+ const on = useDemoMode()
58
+ return on ? demoRuntime() : null
59
+ }
@@ -14,7 +14,7 @@
14
14
  * whose ancestry we resolved once should verify offline forever after.
15
15
  */
16
16
  import { Utils } from '@bsv/sdk'
17
- import type { ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile/out/src/services/chaintracker/chaintracks/Api/ChaintracksClientApi'
17
+ import type { Chain, ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile'
18
18
  import type { HeaderStore } from './headerStore'
19
19
 
20
20
  /** A merkle root as display-order hex, whether the source gave us a hex string
@@ -26,6 +26,9 @@ function rootHex(v: unknown): string {
26
26
  return typeof v === 'string' ? v : Utils.toHex(Array.from(v as ArrayLike<number>))
27
27
  }
28
28
 
29
+ /** Handed out when the remote cannot subscribe; never reaches the remote. */
30
+ const INERT_SUBSCRIPTION_PREFIX = 'offline-first:inert:'
31
+
29
32
  export class OfflineFirstChaintracks implements ChaintracksClientApi {
30
33
  private store: HeaderStore | undefined
31
34
  /**
@@ -35,9 +38,16 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
35
38
  */
36
39
  lastMissHeight: number | undefined
37
40
 
41
+ private inertSubscriptions = 0
42
+
43
+ /**
44
+ * @param chain The chain the remote serves. When given, `getChain` answers
45
+ * from it instead of asking the network.
46
+ */
38
47
  constructor(
39
48
  private readonly remote: ChaintracksClientApi,
40
- private readonly online: () => Promise<boolean>
49
+ private readonly online: () => Promise<boolean>,
50
+ private readonly chain?: Chain
41
51
  ) {}
42
52
 
43
53
  /** Consume the most recent unresolved height, if any. Kept for tests; classifiers must peek. */
@@ -124,10 +134,47 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
124
134
  return this.store?.tipHeight ?? 0
125
135
  }
126
136
 
127
- // ── Everything below is pure delegation ───────────────────────────────────
128
- getChain() {
129
- return this.remote.getChain()
137
+ /**
138
+ * The remote's own answer. `false` (the HTTP ChaintracksServiceClient) tells
139
+ * the Monitor and other toolbox consumers not to subscribe at all.
140
+ */
141
+ get supportsReorgEvents(): boolean | undefined {
142
+ return this.remote.supportsReorgEvents
143
+ }
144
+
145
+ // The toolbox Monitor passes this object as `chaintracksWithEvents` and, unless
146
+ // `supportsReorgEvents` is false, calls `getChain` and both subscriptions from
147
+ // every `runOnce` (via `Monitor.ready`) until they succeed. A rejection there
148
+ // stopped the whole task loop in 2.13 and is retried, with a network
149
+ // `getChain`, on every tick since 2.14, so these three answer offline and
150
+ // never reject. TaskReviewProvenTxs remains the reorg audit without live events.
151
+ async getChain(): Promise<Chain> {
152
+ return this.chain ?? (await this.remote.getChain())
153
+ }
154
+ async subscribeHeaders(listener: Parameters<ChaintracksClientApi['subscribeHeaders']>[0]): Promise<string> {
155
+ try {
156
+ return await this.remote.subscribeHeaders(listener)
157
+ } catch (e: any) {
158
+ return this.inertSubscription('headers', e)
159
+ }
130
160
  }
161
+ async subscribeReorgs(listener: Parameters<ChaintracksClientApi['subscribeReorgs']>[0]): Promise<string> {
162
+ try {
163
+ return await this.remote.subscribeReorgs(listener)
164
+ } catch (e: any) {
165
+ return this.inertSubscription('reorgs', e)
166
+ }
167
+ }
168
+ async unsubscribe(subscriptionId: string): Promise<boolean> {
169
+ if (subscriptionId.startsWith(INERT_SUBSCRIPTION_PREFIX)) return true
170
+ return await this.remote.unsubscribe(subscriptionId)
171
+ }
172
+ private inertSubscription(kind: string, e: any): string {
173
+ console.warn(`[OfflineFirstChaintracks] ${kind} subscription unavailable, no live events: ${e?.message ?? e}`)
174
+ return `${INERT_SUBSCRIPTION_PREFIX}${kind}:${++this.inertSubscriptions}`
175
+ }
176
+
177
+ // ── Everything below is pure delegation ───────────────────────────────────
131
178
  getInfo() {
132
179
  return this.remote.getInfo()
133
180
  }
@@ -164,13 +211,4 @@ export class OfflineFirstChaintracks implements ChaintracksClientApi {
164
211
  isSynchronized() {
165
212
  return this.remote.isSynchronized()
166
213
  }
167
- subscribeHeaders(listener: Parameters<ChaintracksClientApi['subscribeHeaders']>[0]) {
168
- return this.remote.subscribeHeaders(listener)
169
- }
170
- subscribeReorgs(listener: Parameters<ChaintracksClientApi['subscribeReorgs']>[0]) {
171
- return this.remote.subscribeReorgs(listener)
172
- }
173
- unsubscribe(subscriptionId: string) {
174
- return this.remote.unsubscribe(subscriptionId)
175
- }
176
214
  }
@@ -20,14 +20,12 @@
20
20
  * helper checks linkage but not difficulty.
21
21
  */
22
22
  import { Utils } from '@bsv/sdk'
23
- import {
24
- blockHash,
25
- deserializeBaseBlockHeader,
26
- validateHeaderDifficulty
27
- } from '@bsv/wallet-toolbox-mobile/out/src/services/chaintracker/chaintracks/util/blockHeaderUtilities'
23
+ import { utils as chaintracksUtils } from '@bsv/wallet-toolbox-mobile'
28
24
  import type { HeaderCheckpoint } from './checkpoints'
29
25
  import type { HeaderFs } from './fs'
30
26
 
27
+ const { blockHash, deserializeBaseBlockHeader, validateHeaderProofOfWork } = chaintracksUtils
28
+
31
29
  const HEADER_BYTES = 80
32
30
  const ROOT_BYTES = 32
33
31
 
@@ -195,11 +193,10 @@ export class HeaderStore {
195
193
  }
196
194
  const hash = blockHash(header)
197
195
  // Throws on failure — a header that does not meet its own target is not a
198
- // header, and accepting it would let anyone mint merkle roots.
199
- // The upstream .d.ts types `hash` as Buffer, but the implementation only
200
- // ever does `asArray(hash)`, which accepts a display-order hex string
201
- // (what blockHash returns) identically to a Buffer — hence the cast.
202
- validateHeaderDifficulty(hash as unknown as Buffer, parsed.bits)
196
+ // header, and accepting it would let anyone mint merkle roots. Takes the
197
+ // display-order hex hash blockHash returns, validates the compact target
198
+ // encoding, and honours the toolbox's consensus proof-of-work exceptions.
199
+ validateHeaderProofOfWork({ ...parsed, height: firstHeight + i, hash })
203
200
  newRoots.set(new Uint8Array(Utils.toArray(parsed.merkleRoot, 'hex')), i * ROOT_BYTES)
204
201
  prev = hash
205
202
  }