@bsv/expo-wallet-toolbox 0.1.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 (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Size limits for wallet-interface arguments.
3
+ *
4
+ * WHY THESE NUMBERS. Peak RSS on this stack is roughly 20x the payload size and
5
+ * up to 30x under planning assumptions — native intake, the retained JSON
6
+ * string, the number[] in Hermes, GC slack, the Uint8Array copy for SQLite, and
7
+ * SQLite's own copies. So a 4 MB call is ~120 MB of peak, and the 100 MB network
8
+ * ceiling would be 2-3 GB: above the jetsam limit of every iPhone with 4 GB or
9
+ * less. Exceeding the Hermes heap is an uncatchable `LLVM ERROR: OOM` abort, not
10
+ * an exception, so there is no degrade-and-warn design available — a cap set too
11
+ * high converts into a crash rather than an error, and every check here must
12
+ * refuse BEFORE anything allocates.
13
+ *
14
+ * 100 MB remains the NETWORK ceiling. It is not a memory cap and must never be
15
+ * used as one.
16
+ *
17
+ * The limits are deliberately far below what memory alone would allow, because
18
+ * the largest legitimate page payload in this app today is a 65,536-byte
19
+ * localpay AtomicBEEF and a ~25-byte P2PKH locking script. 4 MB is ~60x observed
20
+ * traffic; sizing to the memory budget instead would leave two orders of
21
+ * magnitude of headroom nobody uses.
22
+ *
23
+ * Nothing here serialises anything. Every size is summed from a length that is
24
+ * already materialised, so a check is O(#inputs + #outputs) integer reads.
25
+ *
26
+ * THE VAULT IS NOT SUBJECT TO THESE. Its K1 traffic is ordinary-sized today —
27
+ * a 25-byte P2PKH locking script and a ~107-byte unlocking script per input —
28
+ * comfortably inside every limit below. The exemption is structural rather
29
+ * than sized to fit current vault traffic: the vault calls the permissions
30
+ * manager directly and never passes through the wrapper in capWalletArgs.ts,
31
+ * so it stays insulated from any future tightening of these limits. It is
32
+ * paired with the vault's own input cap in services/vault/transfers.ts.
33
+ */
34
+ import type { DeviceTier } from '../deviceTier'
35
+
36
+ export interface WalletArgLimits {
37
+ /** Total bytes across every field of one call. */
38
+ aggregate: number
39
+ /** One output's locking script. */
40
+ outputScript: number
41
+ /** All output locking scripts summed. */
42
+ outputScriptTotal: number
43
+ /** Entries in `outputs` or `inputs`. */
44
+ arrayLength: number
45
+ /** One input's declared unlockingScriptLength. */
46
+ unlockingScriptLength: number
47
+ /** All declared unlockingScriptLengths summed. */
48
+ unlockingScriptLengthTotal: number
49
+ /** One supplied unlocking script (createAction input, or a signAction spend). */
50
+ unlockingScript: number
51
+ /** createAction inputBEEF. */
52
+ inputBEEF: number
53
+ /** internalizeAction tx (AtomicBEEF). */
54
+ internalizeTx: number
55
+ /** One output's customInstructions string. */
56
+ customInstructions: number
57
+ }
58
+
59
+ const MB = 1024 * 1024
60
+
61
+ const BASE: WalletArgLimits = {
62
+ aggregate: 4 * MB,
63
+ outputScript: 100_000,
64
+ outputScriptTotal: 500_000,
65
+ arrayLength: 1000,
66
+ unlockingScriptLength: 100_000,
67
+ unlockingScriptLengthTotal: 500_000,
68
+ unlockingScript: 100_000,
69
+ inputBEEF: 2 * MB,
70
+ internalizeTx: 1 * MB,
71
+ customInstructions: 4096
72
+ }
73
+
74
+ /**
75
+ * Limits for a device tier.
76
+ *
77
+ * `low` is under 3.5 GB of RAM (see core/deviceTier.ts), where the app has
78
+ * already been process-terminated for memory it considered normal — so the
79
+ * aggregate is halved. The per-field limits do not change: they are sized to
80
+ * observed traffic, not to the memory budget.
81
+ */
82
+ export function limitsForTier(tier: DeviceTier): WalletArgLimits {
83
+ return tier === 'low' ? { ...BASE, aggregate: BASE.aggregate / 2 } : { ...BASE }
84
+ }
85
+
86
+ export interface ArgRefusal {
87
+ field: string
88
+ limit: number
89
+ actual: number
90
+ message: string
91
+ }
92
+
93
+ /** Calls that can carry transaction bytes. Everything else passes untouched. */
94
+ const SIZED_CALLS = new Set(['createAction', 'signAction', 'internalizeAction'])
95
+
96
+ const refuse = (field: string, actual: number, limit: number, why?: string): ArgRefusal => ({
97
+ field,
98
+ limit,
99
+ actual,
100
+ message: why ?? `The ${field} parameter must be at most ${limit} bytes (got ${actual})`
101
+ })
102
+
103
+ /** Bytes represented by a hex string, or 0 for anything that is not one. */
104
+ const hexBytes = (v: unknown): number => (typeof v === 'string' ? Math.floor(v.length / 2) : 0)
105
+
106
+ const arrayBytes = (v: unknown): number => (Array.isArray(v) ? v.length : 0)
107
+
108
+ const asRecord = (v: unknown): Record<string, unknown> | null =>
109
+ v != null && typeof v === 'object' ? (v as Record<string, unknown>) : null
110
+
111
+ const asArray = (v: unknown): unknown[] => (Array.isArray(v) ? v : [])
112
+
113
+ /**
114
+ * A locking script beginning with 0xff is refused outright.
115
+ *
116
+ * OP_INVALIDOPCODE makes the output provably unspendable, so no legitimate
117
+ * caller wants one. Cheap to refuse, and nothing is lost.
118
+ */
119
+ const startsWithInvalidOpcode = (script: unknown): boolean =>
120
+ typeof script === 'string' && /^ff/i.test(script.trim())
121
+
122
+ /**
123
+ * Check one call's arguments against the limits.
124
+ *
125
+ * Returns the first violation, or null when the call is acceptable. Never
126
+ * throws: it runs on untrusted page input, and a thrown TypeError here would
127
+ * surface as an opaque wallet error instead of a size refusal.
128
+ */
129
+ export function checkWalletArgs(call: string, args: unknown, limits: WalletArgLimits): ArgRefusal | null {
130
+ if (!SIZED_CALLS.has(call)) return null
131
+ const a = asRecord(args)
132
+ if (!a) return null
133
+
134
+ try {
135
+ let total = 0
136
+
137
+ // ── internalizeAction ──
138
+ if (call === 'internalizeAction') {
139
+ const tx = arrayBytes(a.tx)
140
+ if (tx > limits.internalizeTx) return refuse('tx', tx, limits.internalizeTx)
141
+ total += tx
142
+ }
143
+
144
+ // ── signAction spends ──
145
+ if (call === 'signAction') {
146
+ const spends = asRecord(a.spends)
147
+ if (spends) {
148
+ for (const [index, spend] of Object.entries(spends)) {
149
+ const s = asRecord(spend)
150
+ const bytes = hexBytes(s?.unlockingScript)
151
+ if (bytes > limits.unlockingScript) {
152
+ return refuse(`spends[${index}].unlockingScript`, bytes, limits.unlockingScript)
153
+ }
154
+ total += bytes
155
+ }
156
+ }
157
+ }
158
+
159
+ // ── createAction ──
160
+ if (call === 'createAction') {
161
+ const beef = arrayBytes(a.inputBEEF)
162
+ if (beef > limits.inputBEEF) return refuse('inputBEEF', beef, limits.inputBEEF)
163
+ total += beef
164
+
165
+ const outputs = asArray(a.outputs)
166
+ if (outputs.length > limits.arrayLength) {
167
+ return refuse('outputs.length', outputs.length, limits.arrayLength)
168
+ }
169
+ let scriptTotal = 0
170
+ for (let i = 0; i < outputs.length; i++) {
171
+ const o = asRecord(outputs[i])
172
+ if (!o) continue
173
+ if (startsWithInvalidOpcode(o.lockingScript)) {
174
+ return refuse(
175
+ `outputs[${i}].lockingScript`,
176
+ hexBytes(o.lockingScript),
177
+ limits.outputScript,
178
+ `The outputs[${i}].lockingScript parameter must not begin with 0xff: OP_INVALIDOPCODE makes the ` +
179
+ 'output unspendable'
180
+ )
181
+ }
182
+ const bytes = hexBytes(o.lockingScript)
183
+ if (bytes > limits.outputScript) {
184
+ return refuse(`outputs[${i}].lockingScript`, bytes, limits.outputScript)
185
+ }
186
+ const ci = typeof o.customInstructions === 'string' ? o.customInstructions.length : 0
187
+ if (ci > limits.customInstructions) {
188
+ return refuse(`outputs[${i}].customInstructions`, ci, limits.customInstructions)
189
+ }
190
+ scriptTotal += bytes
191
+ total += bytes + ci
192
+ }
193
+ if (scriptTotal > limits.outputScriptTotal) {
194
+ return refuse('outputs.lockingScript', scriptTotal, limits.outputScriptTotal)
195
+ }
196
+
197
+ const inputs = asArray(a.inputs)
198
+ if (inputs.length > limits.arrayLength) {
199
+ return refuse('inputs.length', inputs.length, limits.arrayLength)
200
+ }
201
+ let declaredTotal = 0
202
+ for (let i = 0; i < inputs.length; i++) {
203
+ const inp = asRecord(inputs[i])
204
+ if (!inp) continue
205
+ // The declared length needs its own cap: the SDK only cross-checks it
206
+ // against a supplied unlockingScript and never bounds it, so a tiny
207
+ // payload can still make the wallet fund and build a ~1 MB-per-input
208
+ // transaction. This is the one limit a byte total cannot substitute for.
209
+ const declared = typeof inp.unlockingScriptLength === 'number' ? inp.unlockingScriptLength : 0
210
+ if (declared > limits.unlockingScriptLength) {
211
+ return refuse(`inputs[${i}].unlockingScriptLength`, declared, limits.unlockingScriptLength)
212
+ }
213
+ declaredTotal += declared
214
+
215
+ const supplied = hexBytes(inp.unlockingScript)
216
+ if (supplied > limits.unlockingScript) {
217
+ return refuse(`inputs[${i}].unlockingScript`, supplied, limits.unlockingScript)
218
+ }
219
+ total += supplied
220
+ }
221
+ if (declaredTotal > limits.unlockingScriptLengthTotal) {
222
+ return refuse('inputs.unlockingScriptLength', declaredTotal, limits.unlockingScriptLengthTotal)
223
+ }
224
+ }
225
+
226
+ if (total > limits.aggregate) return refuse('aggregate', total, limits.aggregate)
227
+ return null
228
+ } catch {
229
+ // Untrusted input must never turn a size check into a crash. Failing open
230
+ // is correct here: the per-field caps below the app layer still apply, and a
231
+ // shape this function cannot walk is not a shape that carries megabytes.
232
+ return null
233
+ }
234
+ }
@@ -0,0 +1,170 @@
1
+ import type { AppChain } from '../config'
2
+ import { toWalletChain } from '../config'
3
+ import {
4
+ ChaintracksServiceClient,
5
+ Services
6
+ } from '@bsv/wallet-toolbox-mobile'
7
+ import type {
8
+ BsvExchangeRate,
9
+ WalletServicesOptions
10
+ } from '@bsv/wallet-toolbox-mobile/out/src/sdk'
11
+ import type { ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile/out/src/services/chaintracker/chaintracks/Api/ChaintracksClientApi'
12
+ import type { ChainTracker } from '@bsv/sdk'
13
+
14
+ /**
15
+ * The chaintracks URL for a network — the one place this table is defined.
16
+ * `createServiceOptions` below and `WalletContext` (which needs the same URL
17
+ * to build the remote client it wraps in `OfflineFirstChaintracks`) both call
18
+ * this, rather than each keeping their own copy that could drift.
19
+ */
20
+ export function chaintracksUrlFor(network: AppChain): string {
21
+ if (network === 'main') {
22
+ return process.env?.EXPO_PUBLIC_CHAINTRACKS_URL ?? 'https://arcade-v2-us-1.bsvblockchain.tech/chaintracks/v1'
23
+ }
24
+ if (network === 'test') {
25
+ return (
26
+ process.env?.EXPO_PUBLIC_TEST_CHAINTRACKS_URL ??
27
+ 'https://arcade-v2-testnet-us-1.bsvblockchain.tech/chaintracks/v1'
28
+ )
29
+ }
30
+ return (
31
+ process.env?.EXPO_PUBLIC_TERATEST_CHAINTRACKS_URL ?? 'https://arcade-v2-ttn-us-1.bsvblockchain.tech/chaintracks/v1'
32
+ )
33
+ }
34
+
35
+ /**
36
+ * Points `services.getChainTracker()` at `tracker` directly, instead of the
37
+ * `ChaintracksChainTracker` that `Services.getChainTracker()` would otherwise
38
+ * construct around `options.chaintracks`
39
+ * (out/src/services/Services.js:149-154). That default's own
40
+ * `isValidRootForHeight` (out/src/services/chaintracker/ChaintracksChainTracker.js:21-56)
41
+ * does NOT call the chaintracks client's `isValidRootForHeight` — it calls
42
+ * `findHeaderForHeight` with its own 6x/250ms retry loop and throws on
43
+ * persistent failure. So passing an offline-first client as
44
+ * `options.chaintracks` alone (what `createServiceOptions`'s
45
+ * `chaintracksOverride` does) never reaches the client's store-first lookup:
46
+ * offline verification burns ~1.5s retrying then throws instead of consulting
47
+ * the local window. This is the seam that actually makes it live — `tracker`
48
+ * already implements `isValidRootForHeight` + `currentHeight`, which is
49
+ * everything the `ChainTracker` interface, and therefore `Beef.verify`, uses.
50
+ *
51
+ * Deliberately does NOT touch `findHeaderForHeight`: WalletContext's own
52
+ * merkle-path service consumes a real header object from it
53
+ * (`r.header = { ...header, height }`), so that must stay pure delegation to
54
+ * the remote client, not a root-only synthetic header.
55
+ */
56
+ export function installOfflineChainTracker(services: Services, tracker: ChainTracker): void {
57
+ services.getChainTracker = async () => tracker
58
+ }
59
+
60
+ /**
61
+ * Build the WalletServicesOptions for a given network.
62
+ * Pure function — no React dependencies.
63
+ */
64
+ export function createServiceOptions(
65
+ network: AppChain,
66
+ callbackToken: string,
67
+ bsvExchangeRate: BsvExchangeRate,
68
+ arcUrlOverride?: string,
69
+ arcApiKeyOverride?: string,
70
+ /**
71
+ * Substitute for the plain remote chaintracks client. WalletContext passes an
72
+ * OfflineFirstChaintracks wrapping the default, which is what makes BEEF
73
+ * verification work with no network.
74
+ */
75
+ chaintracksOverride?: ChaintracksClientApi
76
+ ): WalletServicesOptions {
77
+ const walletChain = toWalletChain(network)
78
+ const base = {
79
+ chain: walletChain,
80
+ bsvExchangeRate,
81
+ fiatExchangeRates: {
82
+ timestamp: new Date(),
83
+ base: 'USD' as const,
84
+ rates: { USD: 1 }
85
+ }
86
+ }
87
+
88
+ if (network === 'main') {
89
+ return {
90
+ ...base,
91
+ arcUrl: arcUrlOverride ?? process.env?.EXPO_PUBLIC_ARC_URL ?? 'https://arcade-v2-us-1.bsvblockchain.tech',
92
+ arcConfig: {
93
+ apiKey: arcApiKeyOverride ?? process.env?.EXPO_PUBLIC_ARC_API_KEY ?? '',
94
+ callbackToken
95
+ },
96
+ bsvUpdateMsecs: 60 * 60 * 1000,
97
+ fiatUpdateMsecs: 60 * 60 * 1000,
98
+ whatsOnChainApiKey: process.env?.EXPO_PUBLIC_WOC_API_KEY ?? '',
99
+ taalApiKey: process.env?.EXPO_PUBLIC_WOC_API_KEY ?? '',
100
+ chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
101
+ }
102
+ }
103
+
104
+ if (network === 'test') {
105
+ return {
106
+ ...base,
107
+ arcUrl: arcUrlOverride ?? process.env?.EXPO_PUBLIC_TEST_ARC_URL ?? 'https://arcade-v2-testnet-us-1.bsvblockchain.tech',
108
+ arcConfig: {
109
+ apiKey: arcApiKeyOverride ?? process.env?.EXPO_PUBLIC_TEST_ARC_API_KEY ?? '',
110
+ callbackToken
111
+ },
112
+ bsvUpdateMsecs: 60 * 60 * 1000000,
113
+ fiatUpdateMsecs: 60 * 60 * 1000000,
114
+ whatsOnChainApiKey: process.env?.EXPO_PUBLIC_TEST_WOC_API_KEY ?? '',
115
+ taalApiKey: process.env?.EXPO_PUBLIC_TEST_TAAL_API_KEY ?? '',
116
+ chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
117
+ }
118
+ }
119
+
120
+ // teratest
121
+ return {
122
+ ...base,
123
+ arcUrl: arcUrlOverride ?? process.env?.EXPO_PUBLIC_TERATEST_ARC_URL ?? 'https://arcade-v2-ttn-us-1.bsvblockchain.tech',
124
+ arcConfig: {
125
+ apiKey: arcApiKeyOverride ?? process.env?.EXPO_PUBLIC_TERATEST_ARC_API_KEY ?? '',
126
+ callbackToken
127
+ },
128
+ bsvUpdateMsecs: 60 * 60 * 1000000,
129
+ fiatUpdateMsecs: 60 * 60 * 1000000,
130
+ whatsOnChainApiKey: process.env?.EXPO_PUBLIC_TERATEST_WOC_API_KEY ?? '',
131
+ taalApiKey: process.env?.EXPO_PUBLIC_TERATEST_WOC_API_KEY ?? '',
132
+ chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Create a configured Services instance for the given network.
138
+ *
139
+ * A `chaintracksOverride` is installed as the chain tracker here, not left to
140
+ * the caller. The two halves — putting the offline-first client at
141
+ * `options.chaintracks` and making `getChainTracker()` return it — are useless
142
+ * apart: the injection alone leaves the store-first lookup unreachable behind
143
+ * `ChaintracksChainTracker`, which is the single most dangerous defect this
144
+ * feature has had, and it is invisible (verification simply refuses everything
145
+ * while offline). Doing both at the one place they are both known means no
146
+ * caller can supply one without the other.
147
+ */
148
+ export function createServices(
149
+ network: AppChain,
150
+ callbackToken: string,
151
+ bsvExchangeRate: BsvExchangeRate,
152
+ arcUrlOverride?: string,
153
+ arcApiKeyOverride?: string,
154
+ chaintracksOverride?: ChaintracksClientApi
155
+ ): { services: Services; serviceOptions: WalletServicesOptions } {
156
+ const serviceOptions = createServiceOptions(
157
+ network,
158
+ callbackToken,
159
+ bsvExchangeRate,
160
+ arcUrlOverride,
161
+ arcApiKeyOverride,
162
+ chaintracksOverride
163
+ )
164
+ const services = new Services(serviceOptions)
165
+ // `ChaintracksClientApi` declares `isValidRootForHeight` and `currentHeight`
166
+ // (ChaintracksClientApi.d.ts:137-138), which is the whole of `ChainTracker`, so
167
+ // an override is always usable as one directly.
168
+ if (chaintracksOverride) installOfflineChainTracker(services, chaintracksOverride)
169
+ return { services, serviceOptions }
170
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Adapter to make StorageExpoSQLite work with the wallet-toolbox ecosystem
3
+ *
4
+ * This is a temporary adapter that allows using local SQLite storage
5
+ * until StorageExpoSQLite fully implements the WalletStorageProvider interface
6
+ */
7
+
8
+ import { StorageProvider } from '@bsv/wallet-toolbox-mobile'
9
+ import { StorageExpoSQLite } from './StorageExpoSQLite'
10
+ import type { AppChain } from '../config'
11
+ import { toWalletChain } from '../config'
12
+
13
+ export interface LocalStorageConfig {
14
+ network: AppChain
15
+ identityKey: string
16
+ storageName?: string
17
+ }
18
+
19
+ /**
20
+ * Initialize local storage for the wallet
21
+ */
22
+ export async function initializeLocalStorage(config: LocalStorageConfig): Promise<StorageExpoSQLite> {
23
+ const { network, identityKey, storageName = 'bsv-wallet' } = config
24
+
25
+ // Create storage instance
26
+ const storage = new StorageExpoSQLite({
27
+ ...StorageProvider.createStorageBaseOptions(toWalletChain(network))
28
+ })
29
+
30
+ // Initialize database
31
+ await storage.migrate(storageName, identityKey)
32
+
33
+ // Verify it's ready
34
+ await storage.makeAvailable()
35
+
36
+ return storage
37
+ }
38
+
39
+ /**
40
+ * Check if a storage URL indicates local storage
41
+ */
42
+ export function isLocalStorage(storageUrl: string): boolean {
43
+ return storageUrl === 'local'
44
+ }
45
+
46
+ /**
47
+ * Get storage display name
48
+ */
49
+ export function getStorageDisplayName(storageUrl: string): string {
50
+ if (isLocalStorage(storageUrl)) {
51
+ return 'Local Storage (On Device)'
52
+ }
53
+ try {
54
+ return new URL(storageUrl).hostname
55
+ } catch {
56
+ return storageUrl
57
+ }
58
+ }