@bsv/expo-wallet-toolbox 0.18.0 → 0.20.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 (135) hide show
  1. package/CHANGELOG.md +139 -30
  2. package/README.md +79 -79
  3. package/core/backup/RemoteSyncReader.ts +26 -24
  4. package/core/backup/appData.ts +9 -8
  5. package/core/backup/codec.ts +21 -18
  6. package/core/backup/constants.ts +5 -5
  7. package/core/backup/contactsBackup.ts +8 -8
  8. package/core/backup/cursor.ts +12 -7
  9. package/core/backup/derive.ts +3 -3
  10. package/core/backup/deviceId.ts +2 -2
  11. package/core/backup/erase.ts +2 -2
  12. package/core/backup/preference.ts +2 -2
  13. package/core/backup/push.ts +10 -12
  14. package/core/backup/restore.ts +22 -14
  15. package/core/backup/restoreOnImport.ts +3 -2
  16. package/core/config.tsx +17 -13
  17. package/core/constants.ts +34 -11
  18. package/core/contacts/contactsStore.ts +4 -3
  19. package/core/context/WalletConnectionContext.tsx +294 -212
  20. package/core/context/WalletContext.tsx +132 -97
  21. package/core/context/defaultWalletSettings.ts +4 -2
  22. package/core/demo/demoLedger.ts +1 -5
  23. package/core/directpay/DirectPayProvider.tsx +15 -24
  24. package/core/directpay/receive.ts +2 -1
  25. package/core/headers/checkpoints.ts +10 -1
  26. package/core/headers/headerStore.ts +13 -2
  27. package/core/hooks/useConfirmationSound.ts +3 -3
  28. package/core/hooks/useHaptics.ts +23 -6
  29. package/core/i18n/translations.tsx +303 -123
  30. package/core/index.ts +2 -0
  31. package/core/localpay/codec.ts +12 -6
  32. package/core/localpay/deviceCaps.ts +4 -14
  33. package/core/localpay/pending.ts +2 -1
  34. package/core/localpay/qr.ts +1 -1
  35. package/core/localpay/settlementAck.ts +1 -4
  36. package/core/localpay/transport/ble.ts +2 -2
  37. package/core/localpay/transport/socket.ts +1 -1
  38. package/core/mandala/abortGuard.ts +1 -1
  39. package/core/mandala/drain.ts +3 -0
  40. package/core/mandala/permissionModule.ts +3 -2
  41. package/core/mandala/resendTransfer.ts +4 -1
  42. package/core/mandala/runtime.ts +4 -4
  43. package/core/monitor/TaskBackupPush.ts +10 -13
  44. package/core/net/chainMatch.ts +8 -5
  45. package/core/networks.ts +145 -0
  46. package/core/parsePeerPayURI.ts +4 -1
  47. package/core/pay/beefRepair.ts +6 -3
  48. package/core/pay/creditErrors.ts +37 -1
  49. package/core/pay/rails/address.ts +10 -6
  50. package/core/pay/rails/handle.ts +84 -11
  51. package/core/pay/rails/index.ts +18 -2
  52. package/core/pay/receiveHistory.ts +8 -8
  53. package/core/peerpay/handleResendRequests.ts +11 -18
  54. package/core/peerpay/inboxAttempts.ts +1 -4
  55. package/core/peerpay/rebuildToken.ts +12 -9
  56. package/core/profiles/profileStore.ts +2 -1
  57. package/core/profiles/removalProblems.ts +3 -1
  58. package/core/services/arcTokenStorage.ts +2 -1
  59. package/core/services/arcadeBroadcastProvider.ts +7 -17
  60. package/core/services/secrets/envelope.ts +1 -6
  61. package/core/services/secrets/hkdf.ts +1 -6
  62. package/core/services/secrets/index.ts +3 -22
  63. package/core/services/usdFxRates.ts +1 -4
  64. package/core/services/vault/VaultKeyService.ts +2 -1
  65. package/core/services/vault/chainRecovery.ts +48 -21
  66. package/core/services/vault/metaAuthority.ts +4 -1
  67. package/core/services/vault/r1comb.ts +113 -51
  68. package/core/services/vault/session.ts +5 -1
  69. package/core/services/vault/transfers.ts +699 -576
  70. package/core/services/vault/vaultStore.ts +12 -10
  71. package/core/services/walletArgLimits.ts +1 -2
  72. package/core/services/walletConnectionValidation.ts +44 -28
  73. package/core/services/walletServiceConfig.ts +9 -40
  74. package/core/storage/StorageExpoSQLite.ts +7 -21
  75. package/core/storage/methods/listActionsSql.ts +81 -67
  76. package/core/storage/methods/listOutputsSql.ts +21 -16
  77. package/core/storage/methods/reviewStatusSql.ts +1 -4
  78. package/core/stores/ConnectionStore.ts +1 -1
  79. package/core/theme/ThemeContext.tsx +12 -16
  80. package/core/theme/motion.ts +3 -3
  81. package/core/theme/tokens.ts +6 -6
  82. package/core/toolboxConfig.ts +23 -0
  83. package/core/walletDbRegistry.ts +7 -5
  84. package/core/walletRepair/runWalletCheck.ts +1 -4
  85. package/package.json +2 -2
  86. package/ui/components/pay/AddressReceive.tsx +3 -3
  87. package/ui/components/pay/HandleReceive.tsx +58 -15
  88. package/ui/components/pay/MessageBoxConfig.tsx +46 -20
  89. package/ui/components/pay/NearbyFlow.tsx +575 -507
  90. package/ui/components/pay/OfflineNotice.tsx +1 -3
  91. package/ui/components/pay/PayCellRow.tsx +1 -4
  92. package/ui/components/pay/PayForm.tsx +1 -3
  93. package/ui/components/pay/RequestHub.tsx +14 -6
  94. package/ui/components/pay/UniversalSend.tsx +137 -40
  95. package/ui/components/pay/tokenSendCopy.ts +1 -2
  96. package/ui/components/pay/useRecipientInput.ts +2 -2
  97. package/ui/components/security/WalletLockNotice.tsx +1 -3
  98. package/ui/components/ui/AlertCard.tsx +44 -45
  99. package/ui/components/ui/BlurChrome.tsx +4 -15
  100. package/ui/components/ui/Celebration.tsx +3 -3
  101. package/ui/components/ui/ChoiceSheet.ts +1 -3
  102. package/ui/components/ui/ErrorBoundary.tsx +2 -6
  103. package/ui/components/ui/GroupedList.tsx +13 -31
  104. package/ui/components/ui/IconButton.tsx +6 -9
  105. package/ui/components/ui/ListRow.tsx +19 -25
  106. package/ui/components/ui/PresenceRow.tsx +4 -4
  107. package/ui/components/ui/PressableScale.tsx +24 -20
  108. package/ui/components/ui/Toast.tsx +23 -16
  109. package/ui/components/vault/KeyChooser.tsx +9 -6
  110. package/ui/components/vault/VaultBackdrop.tsx +1 -8
  111. package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
  112. package/ui/components/wallet/ActivityRow.tsx +3 -2
  113. package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
  114. package/ui/components/wallet/Balance.tsx +4 -1
  115. package/ui/components/wallet/ContactActivityList.tsx +7 -7
  116. package/ui/components/wallet/IconPickerSheet.tsx +1 -5
  117. package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
  118. package/ui/components/wallet/tokenEviction.ts +4 -1
  119. package/ui/hooks/useMandala.ts +1 -7
  120. package/ui/hooks/useOfflineNoticeActions.ts +21 -27
  121. package/ui/hooks/useSpendableBalance.ts +2 -2
  122. package/ui/hooks/useVaultCoverage.ts +7 -1
  123. package/ui/index.ts +9 -1
  124. package/ui/resolveIdentity.ts +20 -8
  125. package/ui/screens/ConnectionsScreen.tsx +44 -18
  126. package/ui/screens/LogsScreen.tsx +24 -22
  127. package/ui/screens/PairScreen.tsx +85 -54
  128. package/ui/screens/PayScreen.tsx +5 -1
  129. package/ui/screens/ProfileScreen.tsx +0 -3
  130. package/ui/screens/TrustScreen.tsx +125 -80
  131. package/ui/screens/VaultScreen.tsx +19 -7
  132. package/ui/screens/VaultTransferScreen.tsx +5 -1
  133. package/ui/screens/WalletCheckScreen.tsx +14 -17
  134. package/ui/screens/WalletConfigScreen.tsx +414 -376
  135. package/ui/screens/WalletHomeScreen.tsx +47 -42
@@ -10,6 +10,7 @@
10
10
  import * as SecureStore from 'expo-secure-store'
11
11
  import { p256 } from '@noble/curves/nist.js'
12
12
  import { VaultError } from './types'
13
+ import { APP_CHAINS, isAppChain, type AppChain } from '../../networks'
13
14
 
14
15
  const META_KEY_PREFIX = 'vault_meta_v6'
15
16
  const ENROLLMENT_DRAFT_KEY_PREFIX = 'vault_enrollment_draft_v1'
@@ -34,12 +35,12 @@ const MAX_KEYS = 5
34
35
  const MAX_ACTIVE_KEYS = MAX_KEYS + 1
35
36
  const VAULT_SLOT = 0x82
36
37
 
37
- export type VaultScopeChain = 'main' | 'test' | 'teratest'
38
+ export type VaultScopeChain = AppChain
38
39
 
39
40
  /** Every chain a vault can be namespaced under. One YubiKey is one physical
40
41
  * object, so a destructive maintenance operation has to look at all of them —
41
42
  * see `enrolledSerialsAcrossChains`. */
42
- const SCOPE_CHAINS: readonly VaultScopeChain[] = ['main', 'test', 'teratest']
43
+ const SCOPE_CHAINS: readonly VaultScopeChain[] = APP_CHAINS
43
44
 
44
45
  export interface VaultStoreScope {
45
46
  /** Compressed secp256k1 wallet identity key, lowercase hex. */
@@ -174,7 +175,7 @@ function normalizeScope(scope: VaultStoreScope): VaultStoreScope {
174
175
  if (!validIdentityKey(scope.identityKey)) {
175
176
  throw new VaultError('template-invalid', 'Vault scope requires a canonical wallet identity key')
176
177
  }
177
- if (scope.chain !== 'main' && scope.chain !== 'test' && scope.chain !== 'teratest') {
178
+ if (!isAppChain(scope.chain)) {
178
179
  throw new VaultError('template-invalid', 'Vault scope requires a supported chain')
179
180
  }
180
181
  const profileIndex = scope.profileIndex ?? 0
@@ -190,7 +191,7 @@ function scopedKey(scope = activeScope): string | null {
190
191
  }
191
192
 
192
193
  /** The shape of a captured meta storage key: `<prefix>_<chain>_<identityKey>`. */
193
- const SCOPE_KEY_PATTERN = /^vault_meta_v6_(main|test|teratest)_(0[23][0-9a-f]{64})$/
194
+ const SCOPE_KEY_PATTERN = /^vault_meta_v6_(main|test|teratest|scaletest)_(0[23][0-9a-f]{64})$/
194
195
 
195
196
  function enrollmentDraftKey(token: VaultScopeToken): string {
196
197
  const match = SCOPE_KEY_PATTERN.exec(token.storageKey)
@@ -255,11 +256,7 @@ async function clearMetaTag(token: VaultScopeToken): Promise<void> {
255
256
  * atomically within the caller's enqueueMutation critical section. The tag
256
257
  * is computed BEFORE writeMeta so a tagger failure (a rejected wallet call)
257
258
  * leaves storage completely untouched rather than updated-but-untagged. */
258
- async function writeMetaAndTag(
259
- token: VaultScopeToken,
260
- meta: VaultMeta,
261
- tagger?: VaultMetaTagger
262
- ): Promise<void> {
259
+ async function writeMetaAndTag(token: VaultScopeToken, meta: VaultMeta, tagger?: VaultMetaTagger): Promise<void> {
263
260
  const tag = tagger ? await tagger(meta) : undefined
264
261
  await writeMeta(token, meta)
265
262
  if (tag !== undefined) await writeMetaTag(token, tag)
@@ -305,7 +302,12 @@ function captureScope(required: boolean): VaultScopeToken | null {
305
302
  if (required) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
306
303
  return null
307
304
  }
308
- return { generation: scopeGeneration, storageKey, chain: activeScope!.chain, profileIndex: activeScope!.profileIndex ?? 0 }
305
+ return {
306
+ generation: scopeGeneration,
307
+ storageKey,
308
+ chain: activeScope!.chain,
309
+ profileIndex: activeScope!.profileIndex ?? 0
310
+ }
309
311
  }
310
312
 
311
313
  function assertScope(token: VaultScopeToken): void {
@@ -145,8 +145,7 @@ const asArray = (v: unknown): unknown[] => (Array.isArray(v) ? v : [])
145
145
  * OP_INVALIDOPCODE makes the output provably unspendable, so no legitimate
146
146
  * caller wants one. Cheap to refuse, and nothing is lost.
147
147
  */
148
- const startsWithInvalidOpcode = (script: unknown): boolean =>
149
- typeof script === 'string' && /^ff/i.test(script.trim())
148
+ const startsWithInvalidOpcode = (script: unknown): boolean => typeof script === 'string' && /^ff/i.test(script.trim())
150
149
 
151
150
  /**
152
151
  * Check one call's arguments against the limits.
@@ -23,7 +23,7 @@ export const MAX_RPC_PLAINTEXT_BYTES = 5 * MB
23
23
  // @bsv/sdk authenticated encryption adds 48 bytes today. Keep a small explicit
24
24
  // allowance so a future compatible envelope does not fail at the boundary.
25
25
  export const MAX_RPC_CIPHERTEXT_BYTES = MAX_RPC_PLAINTEXT_BYTES + 256
26
- export const MAX_RPC_CIPHERTEXT_CHARS = Math.ceil(MAX_RPC_CIPHERTEXT_BYTES * 4 / 3)
26
+ export const MAX_RPC_CIPHERTEXT_CHARS = Math.ceil((MAX_RPC_CIPHERTEXT_BYTES * 4) / 3)
27
27
  export const MAX_RPC_WIRE_CHARS = MAX_RPC_CIPHERTEXT_CHARS + 1024
28
28
  export const MAX_IN_FLIGHT_RPC = 4
29
29
  /**
@@ -96,12 +96,7 @@ export function buildConnectionAuthorityMessage(tuple: ConnectionAuthorityTuple)
96
96
  export function buildPairingSignatureMessage(
97
97
  params: Pick<Required<ConnectParams>, 'topic' | 'backendIdentityKey' | 'origin' | 'expiry'>
98
98
  ): string {
99
- return [
100
- params.topic,
101
- params.backendIdentityKey,
102
- params.origin,
103
- params.expiry
104
- ].join('|')
99
+ return [params.topic, params.backendIdentityKey, params.origin, params.expiry].join('|')
105
100
  }
106
101
 
107
102
  function requireBoundedString(value: unknown, name: string, maxBytes: number, minBytes = 1): string {
@@ -122,13 +117,25 @@ export function parseWalletProtocol(raw: unknown): { raw: string; value: WalletP
122
117
  } catch {
123
118
  throw new Error('protocolID is not valid JSON')
124
119
  }
125
- if (!Array.isArray(parsed) || parsed.length !== 2 || !Number.isInteger(parsed[0]) ||
126
- parsed[0] < 0 || parsed[0] > 2 || typeof parsed[1] !== 'string') {
120
+ if (
121
+ !Array.isArray(parsed) ||
122
+ parsed.length !== 2 ||
123
+ !Number.isInteger(parsed[0]) ||
124
+ parsed[0] < 0 ||
125
+ parsed[0] > 2 ||
126
+ typeof parsed[1] !== 'string'
127
+ ) {
127
128
  throw new Error('protocolID must be a valid [security level, protocol name] tuple')
128
129
  }
129
130
  const name = parsed[1]
130
- if (name.length < 5 || name.length > 400 || name !== name.trim().toLowerCase() ||
131
- !/^[a-z0-9 ]+$/.test(name) || name.includes(' ') || name.endsWith(' protocol')) {
131
+ if (
132
+ name.length < 5 ||
133
+ name.length > 400 ||
134
+ name !== name.trim().toLowerCase() ||
135
+ !/^[a-z0-9 ]+$/.test(name) ||
136
+ name.includes(' ') ||
137
+ name.endsWith(' protocol')
138
+ ) {
132
139
  throw new Error('protocolID contains an invalid protocol name')
133
140
  }
134
141
  const value = [parsed[0], name] as WalletProtocol
@@ -179,7 +186,7 @@ function validateSignature(raw: unknown): string {
179
186
  }
180
187
  // A DER ECDSA signature is normally 70-72 bytes. These wider bounds reject
181
188
  // empty/truncated and oversized values before the SDK's base64 decoder.
182
- const decodedBytes = Math.floor(sig.length * 3 / 4)
189
+ const decodedBytes = Math.floor((sig.length * 3) / 4)
183
190
  if (decodedBytes < 8 || decodedBytes > 80) throw new Error('Pairing signature has an invalid length')
184
191
  return sig
185
192
  }
@@ -235,7 +242,14 @@ export function validateStoredConnectionFields(raw: {
235
242
  const mobileIdentityKey = validateMobileIdentityKey(raw.mobileIdentityKey)
236
243
  const protocol = parseWalletProtocol(raw.protocolID)
237
244
  const external = validateCanonicalExternalOrigin(raw.origin)
238
- return { topic, backendIdentityKey, mobileIdentityKey, protocolIDRaw: protocol.raw, protocolID: protocol.value, external }
245
+ return {
246
+ topic,
247
+ backendIdentityKey,
248
+ mobileIdentityKey,
249
+ protocolIDRaw: protocol.raw,
250
+ protocolID: protocol.value,
251
+ external
252
+ }
239
253
  }
240
254
 
241
255
  /** XR-027: a stored connection's authority tag is untrusted AsyncStorage data
@@ -246,11 +260,7 @@ export function validateStoredConnectionFields(raw: {
246
260
  * than handed to verifyHmac. */
247
261
  export function validateStoredConnectionAuthorityTag(raw: unknown): string | undefined {
248
262
  if (raw === undefined || raw === null) return undefined
249
- if (
250
- typeof raw !== 'string' ||
251
- raw.length !== CONNECTION_AUTHORITY_TAG_CHARS ||
252
- !/^[A-Za-z0-9_-]+$/.test(raw)
253
- ) {
263
+ if (typeof raw !== 'string' || raw.length !== CONNECTION_AUTHORITY_TAG_CHARS || !/^[A-Za-z0-9_-]+$/.test(raw)) {
254
264
  throw new Error('Stored connection authority tag is invalid')
255
265
  }
256
266
  return raw
@@ -302,8 +312,12 @@ export function parseRelayResponse(raw: unknown): string {
302
312
  } catch {
303
313
  throw new Error('Origin server returned invalid relay JSON')
304
314
  }
305
- if (data === null || typeof data !== 'object' || Array.isArray(data) ||
306
- typeof (data as { relay?: unknown }).relay !== 'string') {
315
+ if (
316
+ data === null ||
317
+ typeof data !== 'object' ||
318
+ Array.isArray(data) ||
319
+ typeof (data as { relay?: unknown }).relay !== 'string'
320
+ ) {
307
321
  throw new Error('Origin server did not return a relay URL')
308
322
  }
309
323
  return validateRelayUrl((data as { relay: string }).relay)
@@ -342,16 +356,18 @@ export function parseBoundedWireEnvelope(raw: unknown, expectedTopic: string): B
342
356
  }
343
357
  }
344
358
  if (envelope.topic !== expectedTopic) throw new Error('Wallet relay message has the wrong topic')
345
- if (typeof envelope.ciphertext !== 'string' || envelope.ciphertext.length === 0 ||
346
- envelope.ciphertext.length > MAX_RPC_CIPHERTEXT_CHARS ||
347
- envelope.ciphertext.length % 4 === 1 ||
348
- Math.floor(envelope.ciphertext.length * 3 / 4) > MAX_RPC_CIPHERTEXT_BYTES ||
349
- !/^[A-Za-z0-9_-]+$/.test(envelope.ciphertext)) {
359
+ if (
360
+ typeof envelope.ciphertext !== 'string' ||
361
+ envelope.ciphertext.length === 0 ||
362
+ envelope.ciphertext.length > MAX_RPC_CIPHERTEXT_CHARS ||
363
+ envelope.ciphertext.length % 4 === 1 ||
364
+ Math.floor((envelope.ciphertext.length * 3) / 4) > MAX_RPC_CIPHERTEXT_BYTES ||
365
+ !/^[A-Za-z0-9_-]+$/.test(envelope.ciphertext)
366
+ ) {
350
367
  throw new Error('Wallet relay ciphertext is invalid or too large')
351
368
  }
352
- const mobileIdentityKey = envelope.mobileIdentityKey === undefined
353
- ? undefined
354
- : validateMobileIdentityKey(envelope.mobileIdentityKey)
369
+ const mobileIdentityKey =
370
+ envelope.mobileIdentityKey === undefined ? undefined : validateMobileIdentityKey(envelope.mobileIdentityKey)
355
371
  return { topic: expectedTopic, ciphertext: envelope.ciphertext, mobileIdentityKey }
356
372
  }
357
373
 
@@ -1,6 +1,7 @@
1
1
  import type { AppChain } from '../config'
2
2
  import { toWalletChain } from '../config'
3
3
  import { getServiceConfig } from '../toolboxConfig'
4
+ import { NETWORKS } from '../networks'
4
5
  import { ChaintracksServiceClient, Services } from '@bsv/wallet-toolbox-mobile'
5
6
  import type { ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile'
6
7
  import type { ChainTracker } from '@bsv/sdk'
@@ -15,9 +16,7 @@ import type { BsvExchangeRate, WalletServicesOptions } from '../toolboxTypes'
15
16
  export function chaintracksUrlFor(network: AppChain): string {
16
17
  const configured = getServiceConfig(network).chaintracksUrl
17
18
  if (configured != null && configured !== '') return configured
18
- if (network === 'main') return 'https://arcade-v2-us-1.bsvblockchain.tech/chaintracks/v1'
19
- if (network === 'test') return 'https://arcade-v2-testnet-us-1.bsvblockchain.tech/chaintracks/v1'
20
- return 'https://arcade-v2-ttn-us-1.bsvblockchain.tech/chaintracks/v1'
19
+ return `${NETWORKS[network].arcadeUrl}/chaintracks/v1`
21
20
  }
22
21
 
23
22
  /**
@@ -84,14 +83,7 @@ export function createServiceOptions(
84
83
  // monitor logged "no arcadeUrl configured; SSE disabled" on every start —
85
84
  // a nosend received while online sat unrecognised for 12 h on 2026-09-18
86
85
  // while the explorer showed it with 6 confirmations.
87
- const arcadeUrl =
88
- arcUrlOverride ??
89
- svc.arcUrl ??
90
- (network === 'main'
91
- ? 'https://arcade-v2-us-1.bsvblockchain.tech'
92
- : network === 'test'
93
- ? 'https://arcade-v2-testnet-us-1.bsvblockchain.tech'
94
- : 'https://arcade-v2-ttn-us-1.bsvblockchain.tech')
86
+ const arcadeUrl = arcUrlOverride ?? svc.arcUrl ?? NETWORKS[network].arcadeUrl
95
87
  const arcConfig = {
96
88
  apiKey: arcApiKeyOverride ?? svc.arcApiKey ?? '',
97
89
  // Must equal the Monitor's callbackToken so Arcade routes this wallet's
@@ -105,38 +97,15 @@ export function createServiceOptions(
105
97
  // this key as a Bearer token to arc.taal.com et al. on every ordinary
106
98
  // broadcast) — a host that scoped a key to WhatsOnChain must not have it
107
99
  // silently disclosed to TAAL just because it left taalApiKey unset.
108
- if (network === 'main') {
109
- return {
110
- ...base,
111
- ...arcade,
112
- bsvUpdateMsecs: 60 * 60 * 1000,
113
- fiatUpdateMsecs: 60 * 60 * 1000,
114
- whatsOnChainApiKey: svc.whatsOnChainApiKey ?? '',
115
- taalApiKey: svc.taalApiKey ?? '',
116
- chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
117
- }
118
- }
119
-
120
- if (network === 'test') {
121
- return {
122
- ...base,
123
- ...arcade,
124
- bsvUpdateMsecs: 60 * 60 * 1000000,
125
- fiatUpdateMsecs: 60 * 60 * 1000000,
126
- whatsOnChainApiKey: svc.whatsOnChainApiKey ?? '',
127
- taalApiKey: svc.taalApiKey ?? '',
128
- chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
129
- }
130
- }
131
-
132
- // teratest
100
+ const updateMsecs = network === 'main' ? 60 * 60 * 1000 : 60 * 60 * 1000000
133
101
  return {
134
102
  ...base,
135
103
  ...arcade,
136
- bsvUpdateMsecs: 60 * 60 * 1000000,
137
- fiatUpdateMsecs: 60 * 60 * 1000000,
138
- whatsOnChainApiKey: svc.whatsOnChainApiKey ?? '',
139
- taalApiKey: svc.taalApiKey ?? '',
104
+ bsvUpdateMsecs: updateMsecs,
105
+ fiatUpdateMsecs: updateMsecs,
106
+ // A network with no WhatsOnChain gets no key: there is no host to send it to.
107
+ whatsOnChainApiKey: NETWORKS[network].woc ? (svc.whatsOnChainApiKey ?? '') : '',
108
+ taalApiKey: NETWORKS[network].taalArcUrl ? (svc.taalApiKey ?? '') : '',
140
109
  chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
141
110
  }
142
111
  }
@@ -687,12 +687,7 @@ export class StorageExpoSQLite extends StorageProvider {
687
687
  return names
688
688
  }
689
689
 
690
- private async sqlInsert(
691
- table: string,
692
- entity: Record<string, any>,
693
- pkCol: string,
694
- trx?: TrxToken
695
- ): Promise<number> {
690
+ private async sqlInsert(table: string, entity: Record<string, any>, pkCol: string, trx?: TrxToken): Promise<number> {
696
691
  const db = this.getDB(trx)
697
692
  const cols: string[] = []
698
693
  const placeholders: string[] = []
@@ -1112,9 +1107,7 @@ export class StorageExpoSQLite extends StorageProvider {
1112
1107
  // fetch it at all: `SELECT *` would copy every matching output's
1113
1108
  // lockingScript out of SQLite and across the bridge into JS — on the JS
1114
1109
  // thread — only to be discarded below, which adds up across a page of them.
1115
- const columns = args.noScript
1116
- ? (await this.tableColumns('outputs')).filter(c => c !== 'lockingScript')
1117
- : undefined
1110
+ const columns = args.noScript ? (await this.tableColumns('outputs')).filter(c => c !== 'lockingScript') : undefined
1118
1111
 
1119
1112
  const rows = await this.sqlFind<any>(
1120
1113
  'outputs',
@@ -1152,12 +1145,7 @@ export class StorageExpoSQLite extends StorageProvider {
1152
1145
  tagIds?: number[],
1153
1146
  isQueryModeAll?: boolean
1154
1147
  ): Promise<{ count: number; total: number }> {
1155
- return await this.sqlSum(
1156
- 'outputs',
1157
- 'satoshis',
1158
- args as any,
1159
- this.outputExtraClauses(args, tagIds, isQueryModeAll)
1160
- )
1148
+ return await this.sqlSum('outputs', 'satoshis', args as any, this.outputExtraClauses(args, tagIds, isQueryModeAll))
1161
1149
  }
1162
1150
 
1163
1151
  async findOutputTags(args: FindOutputTagsArgs): Promise<TableOutputTag[]> {
@@ -1688,11 +1676,7 @@ export class StorageExpoSQLite extends StorageProvider {
1688
1676
  */
1689
1677
  async reclaimInputBeef(tipHeight: number, cutoff: string): Promise<{ rows: number }> {
1690
1678
  if (!this.isAvailable()) await this.makeAvailable()
1691
- const result = await this.getDB().runAsync(RECLAIM_INPUT_BEEF_SQL, [
1692
- new Date().toISOString(),
1693
- tipHeight,
1694
- cutoff
1695
- ])
1679
+ const result = await this.getDB().runAsync(RECLAIM_INPUT_BEEF_SQL, [new Date().toISOString(), tipHeight, cutoff])
1696
1680
  return { rows: result.changes ?? 0 }
1697
1681
  }
1698
1682
 
@@ -2155,7 +2139,9 @@ export class StorageExpoSQLite extends StorageProvider {
2155
2139
  const tokenTxids = await this.tokenSettlementTxids(reqApis.map(r => r.txid))
2156
2140
  if (tokenTxids.size === 0) return tokenTxids
2157
2141
  const reqs = reqApis.filter(r => tokenTxids.has(r.txid)).map(r => new EntityProvenTxReq(r))
2158
- devLog(`[StorageExpoSQLite] holding ${reqs.length} token req(s) from the monitor's retry for the settlement drain`)
2142
+ devLog(
2143
+ `[StorageExpoSQLite] holding ${reqs.length} token req(s) from the monitor's retry for the settlement drain`
2144
+ )
2159
2145
  await this.holdTokenReqs(reqs)
2160
2146
  return tokenTxids
2161
2147
  } catch (e) {
@@ -25,8 +25,12 @@ export async function listActionsSql(
25
25
  const r: ListActionsResult = { totalActions: 0, actions: [] }
26
26
 
27
27
  // Parse BRC-114 time labels
28
- const { from: actionTimeFrom, to: actionTimeTo, timeFilterRequested, remainingLabels: ordinaryLabelsPreSpecOp } =
29
- parseBrc114ActionTimeLabels(vargs.labels)
28
+ const {
29
+ from: actionTimeFrom,
30
+ to: actionTimeTo,
31
+ timeFilterRequested,
32
+ remainingLabels: ordinaryLabelsPreSpecOp
33
+ } = parseBrc114ActionTimeLabels(vargs.labels)
30
34
  const createdAtFrom = actionTimeFrom !== undefined ? new Date(actionTimeFrom) : undefined
31
35
  const createdAtTo = actionTimeTo !== undefined ? new Date(actionTimeTo) : undefined
32
36
 
@@ -143,81 +147,91 @@ export async function listActionsSql(
143
147
 
144
148
  // Include labels, inputs, outputs if requested
145
149
  if (vargs.includeLabels || vargs.includeInputs || vargs.includeOutputs) {
146
- await Promise.all(txs.map(async (tx, i) => {
147
- const action = r.actions[i] as any
148
-
149
- if (vargs.includeLabels) {
150
- action.labels = (await storage.getLabelsForTransactionId(tx.transactionId)).map(l => l.label)
151
- if (timeFilterRequested) {
152
- const ts = tx.created_at ? new Date(tx.created_at as any).getTime() : NaN
153
- if (!Number.isNaN(ts)) {
154
- const timeLabel = makeBrc114ActionTimeLabel(ts)
155
- if (!action.labels.includes(timeLabel)) action.labels.push(timeLabel)
150
+ await Promise.all(
151
+ txs.map(async (tx, i) => {
152
+ const action = r.actions[i] as any
153
+
154
+ if (vargs.includeLabels) {
155
+ action.labels = (await storage.getLabelsForTransactionId(tx.transactionId)).map(l => l.label)
156
+ if (timeFilterRequested) {
157
+ const ts = tx.created_at ? new Date(tx.created_at as any).getTime() : NaN
158
+ if (!Number.isNaN(ts)) {
159
+ const timeLabel = makeBrc114ActionTimeLabel(ts)
160
+ if (!action.labels.includes(timeLabel)) action.labels.push(timeLabel)
161
+ }
156
162
  }
157
163
  }
158
- }
159
164
 
160
- if (vargs.includeOutputs) {
161
- const outputs = await storage.findOutputs({
162
- partial: { transactionId: tx.transactionId },
163
- noScript: !vargs.includeOutputLockingScripts
164
- })
165
- action.outputs = []
166
- for (const o of outputs) {
167
- const ox = await storage.extendOutput(o, true, true) as any
168
- const wo: any = {
169
- satoshis: o.satoshis || 0,
170
- spendable: !!o.spendable,
171
- tags: (ox.tags?.map((t: any) => t.tag)) || [],
172
- outputIndex: Number(o.vout),
173
- outputDescription: (o as any).outputDescription || '',
174
- basket: ox.basket?.name || ''
175
- }
176
- if (o.customInstructions) wo.customInstructions = o.customInstructions
177
- if (vargs.includeOutputLockingScripts && o.lockingScript) {
178
- wo.lockingScript = typeof o.lockingScript === 'string'
179
- ? o.lockingScript
180
- : Array.from(o.lockingScript as any).map((b: any) => b.toString(16).padStart(2, '0')).join('')
165
+ if (vargs.includeOutputs) {
166
+ const outputs = await storage.findOutputs({
167
+ partial: { transactionId: tx.transactionId },
168
+ noScript: !vargs.includeOutputLockingScripts
169
+ })
170
+ action.outputs = []
171
+ for (const o of outputs) {
172
+ const ox = (await storage.extendOutput(o, true, true)) as any
173
+ const wo: any = {
174
+ satoshis: o.satoshis || 0,
175
+ spendable: !!o.spendable,
176
+ tags: ox.tags?.map((t: any) => t.tag) || [],
177
+ outputIndex: Number(o.vout),
178
+ outputDescription: (o as any).outputDescription || '',
179
+ basket: ox.basket?.name || ''
180
+ }
181
+ if (o.customInstructions) wo.customInstructions = o.customInstructions
182
+ if (vargs.includeOutputLockingScripts && o.lockingScript) {
183
+ wo.lockingScript =
184
+ typeof o.lockingScript === 'string'
185
+ ? o.lockingScript
186
+ : Array.from(o.lockingScript as any)
187
+ .map((b: any) => b.toString(16).padStart(2, '0'))
188
+ .join('')
189
+ }
190
+ action.outputs.push(wo)
181
191
  }
182
- action.outputs.push(wo)
183
192
  }
184
- }
185
193
 
186
- if (vargs.includeInputs) {
187
- const inputs = await storage.findOutputs({
188
- partial: { spentBy: tx.transactionId } as any,
189
- noScript: !vargs.includeInputSourceLockingScripts
190
- })
191
- action.inputs = []
192
- if (inputs.length > 0) {
193
- const rawTx = await storage.getRawTxOfKnownValidTransaction(tx.txid)
194
- let bsvTx: any = undefined
195
- if (rawTx) {
196
- const { Transaction } = await import('@bsv/sdk')
197
- bsvTx = Transaction.fromBinary(rawTx)
198
- }
199
- for (const o of inputs) {
200
- await storage.extendOutput(o, true, true)
201
- const input = bsvTx?.inputs.find((v: any) => v.sourceTXID === (o as any).txid && v.sourceOutputIndex === o.vout)
202
- const wo: any = {
203
- sourceOutpoint: `${(o as any).txid}.${o.vout}`,
204
- sourceSatoshis: o.satoshis || 0,
205
- inputDescription: (o as any).outputDescription || '',
206
- sequenceNumber: input?.sequence || 0
194
+ if (vargs.includeInputs) {
195
+ const inputs = await storage.findOutputs({
196
+ partial: { spentBy: tx.transactionId } as any,
197
+ noScript: !vargs.includeInputSourceLockingScripts
198
+ })
199
+ action.inputs = []
200
+ if (inputs.length > 0) {
201
+ const rawTx = await storage.getRawTxOfKnownValidTransaction(tx.txid)
202
+ let bsvTx: any = undefined
203
+ if (rawTx) {
204
+ const { Transaction } = await import('@bsv/sdk')
205
+ bsvTx = Transaction.fromBinary(rawTx)
207
206
  }
208
- action.inputs.push(wo)
209
- if (vargs.includeInputSourceLockingScripts) {
210
- wo.sourceLockingScript = typeof o.lockingScript === 'string'
211
- ? o.lockingScript
212
- : Array.from(o.lockingScript as any || []).map((b: any) => b.toString(16).padStart(2, '0')).join('')
213
- }
214
- if (vargs.includeInputUnlockingScripts) {
215
- wo.unlockingScript = input?.unlockingScript?.toHex()
207
+ for (const o of inputs) {
208
+ await storage.extendOutput(o, true, true)
209
+ const input = bsvTx?.inputs.find(
210
+ (v: any) => v.sourceTXID === (o as any).txid && v.sourceOutputIndex === o.vout
211
+ )
212
+ const wo: any = {
213
+ sourceOutpoint: `${(o as any).txid}.${o.vout}`,
214
+ sourceSatoshis: o.satoshis || 0,
215
+ inputDescription: (o as any).outputDescription || '',
216
+ sequenceNumber: input?.sequence || 0
217
+ }
218
+ action.inputs.push(wo)
219
+ if (vargs.includeInputSourceLockingScripts) {
220
+ wo.sourceLockingScript =
221
+ typeof o.lockingScript === 'string'
222
+ ? o.lockingScript
223
+ : Array.from((o.lockingScript as any) || [])
224
+ .map((b: any) => b.toString(16).padStart(2, '0'))
225
+ .join('')
226
+ }
227
+ if (vargs.includeInputUnlockingScripts) {
228
+ wo.unlockingScript = input?.unlockingScript?.toHex()
229
+ }
216
230
  }
217
231
  }
218
232
  }
219
- }
220
- }))
233
+ })
234
+ )
221
235
  }
222
236
 
223
237
  return r
@@ -34,7 +34,9 @@ export async function listOutputsSql(
34
34
  let basketId: number | undefined
35
35
  if (basket) {
36
36
  const baskets = await storage.findOutputBaskets({ partial: { userId, name: basket } })
37
- devLog(`[listOutputsSql] basket="${basket}" found ${baskets.length} matches${baskets.length > 0 ? ` (id=${baskets[0].basketId})` : ''}`)
37
+ devLog(
38
+ `[listOutputsSql] basket="${basket}" found ${baskets.length} matches${baskets.length > 0 ? ` (id=${baskets[0].basketId})` : ''}`
39
+ )
38
40
  if (baskets.length !== 1) return r
39
41
  basketId = baskets[0].basketId
40
42
  }
@@ -98,19 +100,11 @@ export async function listOutputsSql(
98
100
  // thread, to produce a single integer. Same filter, same answer; the row path
99
101
  // below still serves every other specOp.
100
102
  if (specOp?.totalOutputsIsSumOfSatoshis && !specOp.filterOutputs) {
101
- const { total } = await storage.sumOutputSatoshis(
102
- findArgs,
103
- tagIds.length > 0 ? tagIds : undefined,
104
- isQueryModeAll
105
- )
103
+ const { total } = await storage.sumOutputSatoshis(findArgs, tagIds.length > 0 ? tagIds : undefined, isQueryModeAll)
106
104
  return { totalOutputs: total, outputs: [] }
107
105
  }
108
106
 
109
- let outputs = await storage.findOutputs(
110
- findArgs,
111
- tagIds.length > 0 ? tagIds : undefined,
112
- isQueryModeAll
113
- )
107
+ let outputs = await storage.findOutputs(findArgs, tagIds.length > 0 ? tagIds : undefined, isQueryModeAll)
114
108
  if (outputs.length === 0 && basketId !== undefined && isLoggingEnabled()) {
115
109
  // Debug aid for an empty basket: what IS in there, before the filters. The
116
110
  // query is gated with the log — running it unconditionally cost a second
@@ -124,7 +118,12 @@ export async function listOutputsSql(
124
118
  )
125
119
  devLog(`[listOutputsSql] DEBUG basket=${basketId} raw outputs:`, JSON.stringify(raw))
126
120
  }
127
- devLog(`[listOutputsSql] basket="${basket}" specOp=${specOp?.name || 'none'} found ${outputs.length} outputs, satoshis: [${outputs.slice(0, 5).map(o => o.satoshis).join(',')}]`)
121
+ devLog(
122
+ `[listOutputsSql] basket="${basket}" specOp=${specOp?.name || 'none'} found ${outputs.length} outputs, satoshis: [${outputs
123
+ .slice(0, 5)
124
+ .map(o => o.satoshis)
125
+ .join(',')}]`
126
+ )
128
127
 
129
128
  // Count total
130
129
  if (outputs.length === limit) {
@@ -168,7 +167,10 @@ export async function listOutputsSql(
168
167
  if (includeLabels && (o as any).txid) {
169
168
  if (!labelsByTxId.has(o.transactionId)) {
170
169
  const txLabels = await storage.getLabelsForTransactionId(o.transactionId)
171
- labelsByTxId.set(o.transactionId, txLabels.map(l => l.label))
170
+ labelsByTxId.set(
171
+ o.transactionId,
172
+ txLabels.map(l => l.label)
173
+ )
172
174
  }
173
175
  wo.labels = labelsByTxId.get(o.transactionId)
174
176
  }
@@ -181,9 +183,12 @@ export async function listOutputsSql(
181
183
  if (includeLockingScripts) {
182
184
  await storage.validateOutputScript(o)
183
185
  if (o.lockingScript) {
184
- wo.lockingScript = typeof o.lockingScript === 'string'
185
- ? o.lockingScript
186
- : Array.from(o.lockingScript as any).map((b: any) => b.toString(16).padStart(2, '0')).join('')
186
+ wo.lockingScript =
187
+ typeof o.lockingScript === 'string'
188
+ ? o.lockingScript
189
+ : Array.from(o.lockingScript as any)
190
+ .map((b: any) => b.toString(16).padStart(2, '0'))
191
+ .join('')
187
192
  }
188
193
  }
189
194
 
@@ -75,10 +75,7 @@ export async function failInvalidReqTxs(args: {
75
75
  failed++
76
76
  } catch (e) {
77
77
  skipped++
78
- devLog(
79
- `[reviewStatus] could not fail transaction ${row.transactionId}:`,
80
- e instanceof Error ? e.message : e
81
- )
78
+ devLog(`[reviewStatus] could not fail transaction ${row.transactionId}:`, e instanceof Error ? e.message : e)
82
79
  }
83
80
  }
84
81
  return { failed, skipped }
@@ -8,7 +8,7 @@ export interface Connection {
8
8
  relay: string
9
9
  backendIdentityKey: string
10
10
  mobileIdentityKey: string
11
- protocolID: string // JSON-stringified WalletProtocol
11
+ protocolID: string // JSON-stringified WalletProtocol
12
12
  connectedAt: number
13
13
  status: 'active' | 'disconnected'
14
14
  /** XR-027: HMAC over (origin, sessionId, protocolID, backendIdentityKey),