@bsv/expo-wallet-toolbox 0.19.0 → 0.21.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 (141) hide show
  1. package/CHANGELOG.md +154 -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/DirectPayManager.ts +148 -29
  24. package/core/directpay/DirectPayProvider.tsx +26 -26
  25. package/core/directpay/payFlow.ts +10 -1
  26. package/core/directpay/receive.ts +2 -1
  27. package/core/directpay/settings.ts +56 -9
  28. package/core/directpay/types.ts +11 -2
  29. package/core/directpay/webrtpay.ts +4 -0
  30. package/core/headers/checkpoints.ts +10 -1
  31. package/core/headers/headerStore.ts +13 -2
  32. package/core/hooks/useConfirmationSound.ts +3 -3
  33. package/core/hooks/useHaptics.ts +23 -6
  34. package/core/i18n/translations.tsx +382 -209
  35. package/core/index.ts +2 -0
  36. package/core/localpay/codec.ts +12 -6
  37. package/core/localpay/deviceCaps.ts +4 -14
  38. package/core/localpay/pending.ts +2 -1
  39. package/core/localpay/qr.ts +1 -1
  40. package/core/localpay/settlementAck.ts +1 -4
  41. package/core/localpay/transport/ble.ts +2 -2
  42. package/core/localpay/transport/socket.ts +1 -1
  43. package/core/mandala/abortGuard.ts +1 -1
  44. package/core/mandala/drain.ts +3 -0
  45. package/core/mandala/permissionModule.ts +3 -2
  46. package/core/mandala/resendTransfer.ts +4 -1
  47. package/core/mandala/runtime.ts +4 -4
  48. package/core/monitor/TaskBackupPush.ts +10 -13
  49. package/core/net/chainMatch.ts +8 -5
  50. package/core/networks.ts +145 -0
  51. package/core/parsePeerPayURI.ts +4 -1
  52. package/core/pay/beefRepair.ts +6 -3
  53. package/core/pay/creditErrors.ts +37 -1
  54. package/core/pay/rails/address.ts +10 -6
  55. package/core/pay/rails/direct.ts +6 -2
  56. package/core/pay/rails/handle.ts +84 -11
  57. package/core/pay/rails/index.ts +18 -2
  58. package/core/pay/receiveHistory.ts +8 -8
  59. package/core/peerpay/handleResendRequests.ts +11 -18
  60. package/core/peerpay/inboxAttempts.ts +1 -4
  61. package/core/peerpay/rebuildToken.ts +12 -9
  62. package/core/profiles/profileStore.ts +2 -1
  63. package/core/profiles/removalProblems.ts +3 -1
  64. package/core/services/arcTokenStorage.ts +2 -1
  65. package/core/services/arcadeBroadcastProvider.ts +7 -17
  66. package/core/services/secrets/envelope.ts +1 -6
  67. package/core/services/secrets/hkdf.ts +1 -6
  68. package/core/services/secrets/index.ts +3 -22
  69. package/core/services/usdFxRates.ts +1 -4
  70. package/core/services/vault/VaultKeyService.ts +2 -1
  71. package/core/services/vault/chainRecovery.ts +48 -21
  72. package/core/services/vault/metaAuthority.ts +4 -1
  73. package/core/services/vault/r1comb.ts +113 -51
  74. package/core/services/vault/session.ts +5 -1
  75. package/core/services/vault/transfers.ts +699 -576
  76. package/core/services/vault/vaultStore.ts +12 -10
  77. package/core/services/walletArgLimits.ts +1 -2
  78. package/core/services/walletConnectionValidation.ts +44 -28
  79. package/core/services/walletServiceConfig.ts +9 -40
  80. package/core/storage/StorageExpoSQLite.ts +7 -21
  81. package/core/storage/methods/listActionsSql.ts +81 -67
  82. package/core/storage/methods/listOutputsSql.ts +21 -16
  83. package/core/storage/methods/reviewStatusSql.ts +1 -4
  84. package/core/stores/ConnectionStore.ts +1 -1
  85. package/core/theme/ThemeContext.tsx +12 -16
  86. package/core/theme/motion.ts +3 -3
  87. package/core/theme/tokens.ts +6 -6
  88. package/core/toolboxConfig.ts +23 -0
  89. package/core/walletDbRegistry.ts +7 -5
  90. package/core/walletRepair/runWalletCheck.ts +1 -4
  91. package/package.json +2 -2
  92. package/ui/components/pay/AddressReceive.tsx +3 -3
  93. package/ui/components/pay/HandleReceive.tsx +21 -15
  94. package/ui/components/pay/MessageBoxConfig.tsx +46 -20
  95. package/ui/components/pay/NearbyFlow.tsx +575 -507
  96. package/ui/components/pay/OfflineNotice.tsx +1 -3
  97. package/ui/components/pay/PayCellRow.tsx +1 -4
  98. package/ui/components/pay/PayForm.tsx +1 -3
  99. package/ui/components/pay/RequestHub.tsx +14 -6
  100. package/ui/components/pay/UniversalSend.tsx +79 -27
  101. package/ui/components/pay/tokenSendCopy.ts +1 -2
  102. package/ui/components/pay/useRecipientInput.ts +2 -2
  103. package/ui/components/security/WalletLockNotice.tsx +1 -3
  104. package/ui/components/ui/AlertCard.tsx +44 -45
  105. package/ui/components/ui/BlurChrome.tsx +4 -15
  106. package/ui/components/ui/Celebration.tsx +3 -3
  107. package/ui/components/ui/ChoiceSheet.ts +1 -3
  108. package/ui/components/ui/ErrorBoundary.tsx +2 -6
  109. package/ui/components/ui/GroupedList.tsx +13 -31
  110. package/ui/components/ui/IconButton.tsx +6 -9
  111. package/ui/components/ui/ListRow.tsx +19 -25
  112. package/ui/components/ui/PresenceRow.tsx +4 -4
  113. package/ui/components/ui/PressableScale.tsx +24 -20
  114. package/ui/components/ui/Toast.tsx +23 -16
  115. package/ui/components/vault/KeyChooser.tsx +9 -6
  116. package/ui/components/vault/VaultBackdrop.tsx +1 -8
  117. package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
  118. package/ui/components/wallet/ActivityRow.tsx +3 -2
  119. package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
  120. package/ui/components/wallet/Balance.tsx +4 -1
  121. package/ui/components/wallet/ContactActivityList.tsx +7 -7
  122. package/ui/components/wallet/IconPickerSheet.tsx +1 -5
  123. package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
  124. package/ui/components/wallet/tokenEviction.ts +4 -1
  125. package/ui/hooks/useMandala.ts +1 -7
  126. package/ui/hooks/useOfflineNoticeActions.ts +21 -27
  127. package/ui/hooks/useSpendableBalance.ts +2 -2
  128. package/ui/hooks/useVaultCoverage.ts +7 -1
  129. package/ui/index.ts +9 -1
  130. package/ui/resolveIdentity.ts +20 -8
  131. package/ui/screens/ConnectionsScreen.tsx +44 -18
  132. package/ui/screens/LogsScreen.tsx +24 -22
  133. package/ui/screens/PairScreen.tsx +85 -54
  134. package/ui/screens/PayScreen.tsx +5 -1
  135. package/ui/screens/ProfileScreen.tsx +0 -3
  136. package/ui/screens/TrustScreen.tsx +125 -80
  137. package/ui/screens/VaultScreen.tsx +19 -7
  138. package/ui/screens/VaultTransferScreen.tsx +5 -1
  139. package/ui/screens/WalletCheckScreen.tsx +14 -17
  140. package/ui/screens/WalletConfigScreen.tsx +414 -376
  141. package/ui/screens/WalletHomeScreen.tsx +47 -42
@@ -9,7 +9,8 @@
9
9
  * makes a crash recoverable.
10
10
  */
11
11
  import { PeerPayClient, type IncomingPayment } from '@bsv/message-box-client'
12
- import { Beef, P2PKH, PublicKey, Random, Transaction, Utils, type AtomicBEEF } from '@bsv/sdk'
12
+ import AsyncStorage from '@react-native-async-storage/async-storage'
13
+ import { Beef, LookupResolver, P2PKH, PublicKey, Random, Transaction, Utils, type AtomicBEEF } from '@bsv/sdk'
13
14
  import { BRC29_PROTOCOL_ID } from './address'
14
15
  import {
15
16
  getOutboxEntries,
@@ -27,15 +28,83 @@ import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
27
28
  import type { MandalaRuntime, TokenSendResult } from '../../mandala/runtime'
28
29
  import { trimTrailingSlashes } from '../../net/trimTrailingSlashes'
29
30
  import { paymentKey } from '../../directpay/paymentKey'
31
+ import type { AppChain } from '../../config'
32
+ import { APP_CHAINS, NETWORKS, type OverlayPreset } from '../../networks'
33
+ import { profileScopedKey } from '../../profiles/profileStore'
34
+ import { getMessageBoxUrlOverride } from '../../toolboxConfig'
30
35
 
31
36
  export const MESSAGE_BOX_URL_KEY = 'message_box_url'
32
- export const DEFAULT_MESSAGE_BOX_URL = 'https://messagebox.bsvblockchain.tech'
37
+ /** Mainnet's default. Every network has its own: see `defaultMessageBoxUrlFor`. */
38
+ export const DEFAULT_MESSAGE_BOX_URL = NETWORKS.main.messageBoxUrl
33
39
  /** The previous default. A saved preference equal to it is treated as "use the
34
40
  * default", so existing installs follow the default forward. */
35
41
  export const LEGACY_MESSAGE_BOX_URL = 'https://messagebox.babbage.systems'
36
42
  /** The sentinel the config panel writes when the user opts out of a server. */
37
43
  export const NO_MESSAGE_BOX = 'noMessageBox'
38
44
 
45
+ /** The MessageBox server a network uses unless the user chose another. */
46
+ export function defaultMessageBoxUrlFor(network: AppChain): string {
47
+ return getMessageBoxUrlOverride(network) ?? NETWORKS[network].messageBoxUrl
48
+ }
49
+
50
+ /**
51
+ * The MessageBox host to use, from the profile's saved preference.
52
+ *
53
+ * `undefined` means the user turned MessageBox off. Anything that is not a
54
+ * deliberate choice of a server follows the network's default: nothing saved,
55
+ * the retired default, or a default of ANY network — until each network had a
56
+ * server of its own every network used mainnet's, so a testnet profile's saved
57
+ * mainnet default is the old default, not a preference for mainnet's server.
58
+ */
59
+ export function resolveMessageBoxUrl(saved: string | null | undefined, network: AppChain): string | undefined {
60
+ if (saved === NO_MESSAGE_BOX) return undefined
61
+ if (!saved || saved === LEGACY_MESSAGE_BOX_URL || isAnyNetworkDefault(saved)) {
62
+ return defaultMessageBoxUrlFor(network)
63
+ }
64
+ return saved
65
+ }
66
+
67
+ function isAnyNetworkDefault(url: string): boolean {
68
+ return APP_CHAINS.some(chain => NETWORKS[chain].messageBoxUrl === url || defaultMessageBoxUrlFor(chain) === url)
69
+ }
70
+
71
+ /** Read the active (or named) profile's MessageBox host for `network`. */
72
+ export async function readMessageBoxUrl(network: AppChain, profileIndex?: number): Promise<string | undefined> {
73
+ return resolveMessageBoxUrl(await AsyncStorage.getItem(profileScopedKey(MESSAGE_BOX_URL_KEY, profileIndex)), network)
74
+ }
75
+
76
+ /**
77
+ * Point a MessageBox (or PeerPay) client's overlay lookups at `network`.
78
+ *
79
+ * The client resolves a recipient's host by asking the overlay for their
80
+ * advertisement, and falls back to its own configured host when there is none.
81
+ * Left alone it asks MAINNET's overlay on every network — PeerPayClient does not
82
+ * pass a `networkPreset` through to MessageBoxClient at all — so a test-chain
83
+ * payment could be routed to a host someone advertised on mainnet.
84
+ *
85
+ * On a network with no overlay (`'local'`) there is nothing to ask: the lookup
86
+ * answers "no advertisements", and every message goes to the configured host.
87
+ * `local` would otherwise mean `http://localhost:8080`, which on a phone is
88
+ * nothing at all.
89
+ *
90
+ * Sets `networkPreset` and `lookupResolver`, the two fields MessageBoxClient
91
+ * 2.5.3 reads for routing (`queryAdvertisements`, `anointHost`). A test pins
92
+ * those names, so an upgrade that renames them fails loudly rather than
93
+ * quietly routing through mainnet again.
94
+ */
95
+ export function bindMessageBoxNetwork<T extends object>(client: T, network: AppChain): T {
96
+ const preset = NETWORKS[network].overlayPreset
97
+ const target = client as unknown as { networkPreset: OverlayPreset; lookupResolver: unknown }
98
+ target.networkPreset = preset
99
+ target.lookupResolver = preset === 'local' ? NO_OVERLAY_RESOLVER : new LookupResolver({ networkPreset: preset })
100
+ return client
101
+ }
102
+
103
+ /** The lookup for a network with no overlay: never any advertisements. */
104
+ const NO_OVERLAY_RESOLVER = {
105
+ query: async () => ({ type: 'output-list' as const, outputs: [] })
106
+ }
107
+
39
108
  /** The message box outbound payments are delivered into. */
40
109
  const PAYMENT_INBOX = 'payment_inbox'
41
110
 
@@ -43,16 +112,20 @@ const PAYMENT_INBOX = 'payment_inbox'
43
112
  export function makePeerPayClient(args: {
44
113
  wallet: ConstructorParameters<typeof PeerPayClient>[0]['walletClient'] | null | undefined
45
114
  messageBoxUrl: string | null | undefined
115
+ network: AppChain
46
116
  originator?: string
47
117
  }): PeerPayClient | null {
48
- const { wallet, messageBoxUrl, originator } = args
118
+ const { wallet, messageBoxUrl, network, originator } = args
49
119
  if (!wallet || !messageBoxUrl || messageBoxUrl === NO_MESSAGE_BOX) return null
50
120
  try {
51
- return new PeerPayClient({
52
- messageBoxHost: messageBoxUrl,
53
- walletClient: wallet,
54
- originator
55
- })
121
+ return bindMessageBoxNetwork(
122
+ new PeerPayClient({
123
+ messageBoxHost: messageBoxUrl,
124
+ walletClient: wallet,
125
+ originator
126
+ }),
127
+ network
128
+ )
56
129
  } catch {
57
130
  return null
58
131
  }
@@ -744,10 +817,10 @@ export async function cancelOutboxPayment(args: {
744
817
  * recipient may already hold a signed, deliverable token. A missing row must be treated
745
818
  * exactly like a row that IS delivered/delivering: refuse, rather than assume "never sent".
746
819
  */
747
- export function isAbortSafe (
748
- action: { labels?: string[], txid?: string },
820
+ export function isAbortSafe(
821
+ action: { labels?: string[]; txid?: string },
749
822
  outboxEntries: Array<Pick<OutboxEntry, 'txid' | 'delivered' | 'delivering'>>
750
- ): { aborted: boolean, needsAbandon?: boolean } {
823
+ ): { aborted: boolean; needsAbandon?: boolean } {
751
824
  if (!action.labels?.includes('peerpay')) return { aborted: true }
752
825
  const stored = action.txid != null ? outboxEntries.find(e => e.txid === action.txid) : undefined
753
826
  if (stored == null || stored.delivered === true || stored.delivering === true) {
@@ -30,7 +30,15 @@ export type RailId = 'nearby' | 'handle' | 'address'
30
30
  */
31
31
  export type PayTarget =
32
32
  | { kind: 'nearby'; session: Session }
33
- | { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string; note?: string }
33
+ | {
34
+ kind: 'handle'
35
+ identityKey: string
36
+ sats?: number
37
+ asset?: string
38
+ amount?: number
39
+ messageBoxUrl?: string
40
+ note?: string
41
+ }
34
42
  | { kind: 'address'; address: string; sats?: number; network?: 'main' | 'test' }
35
43
 
36
44
  /** Six cell names. Since the universal input, `pay-*` are deep-link aliases that all open the send form; `get-*` open one receive method directly. */
@@ -131,7 +139,15 @@ export type RecipientInput =
131
139
  | { kind: 'empty' }
132
140
  | { kind: 'address'; address: string; network?: 'main' | 'test' }
133
141
  | { kind: 'invalid_address' }
134
- | { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string; note?: string }
142
+ | {
143
+ kind: 'handle'
144
+ identityKey: string
145
+ sats?: number
146
+ asset?: string
147
+ amount?: number
148
+ messageBoxUrl?: string
149
+ note?: string
150
+ }
135
151
  | { kind: 'invalid_link'; message: string }
136
152
  | { kind: 'search'; query: string }
137
153
 
@@ -32,8 +32,8 @@ export const RECEIVE_HISTORY_KEY = 'pay_receive_issued_dates'
32
32
  export const MAX_RECEIVE_HISTORY = 3650
33
33
 
34
34
  export interface KVStorage {
35
- getKeyValue (k: string): Promise<string | undefined>
36
- setKeyValue (k: string, v: string): Promise<void>
35
+ getKeyValue(k: string): Promise<string | undefined>
36
+ setKeyValue(k: string, v: string): Promise<void>
37
37
  }
38
38
 
39
39
  // Same discipline as localpay/pending.ts and pay/watchlist.ts: every read-modify-write on
@@ -41,13 +41,13 @@ export interface KVStorage {
41
41
  // silently drops an entry.
42
42
  let queueLock: Promise<unknown> = Promise.resolve()
43
43
 
44
- function withQueueLock<T> (fn: () => Promise<T>): Promise<T> {
44
+ function withQueueLock<T>(fn: () => Promise<T>): Promise<T> {
45
45
  const run = queueLock.then(fn, fn)
46
46
  queueLock = run.catch(() => undefined)
47
47
  return run
48
48
  }
49
49
 
50
- async function readAll (storage: KVStorage): Promise<string[]> {
50
+ async function readAll(storage: KVStorage): Promise<string[]> {
51
51
  const raw = await storage.getKeyValue(RECEIVE_HISTORY_KEY)
52
52
  if (!raw) return []
53
53
  try {
@@ -58,7 +58,7 @@ async function readAll (storage: KVStorage): Promise<string[]> {
58
58
  }
59
59
  }
60
60
 
61
- function normalise (dates: Iterable<string>): string[] {
61
+ function normalise(dates: Iterable<string>): string[] {
62
62
  return [...new Set(dates)].sort().slice(-MAX_RECEIVE_HISTORY)
63
63
  }
64
64
 
@@ -68,7 +68,7 @@ function normalise (dates: Iterable<string>): string[] {
68
68
  * remembered here too, independent of whether that address also survives the watchlist's
69
69
  * own 7-day prune.
70
70
  */
71
- export async function recordIssuedDate (storage: KVStorage, date: string): Promise<void> {
71
+ export async function recordIssuedDate(storage: KVStorage, date: string): Promise<void> {
72
72
  return withQueueLock(async () => {
73
73
  const all = await readAll(storage)
74
74
  if (all.includes(date)) return
@@ -77,7 +77,7 @@ export async function recordIssuedDate (storage: KVStorage, date: string): Promi
77
77
  }
78
78
 
79
79
  /** Every recorded date, deduplicated and sorted ascending. */
80
- export async function getIssuedDates (storage: KVStorage): Promise<string[]> {
80
+ export async function getIssuedDates(storage: KVStorage): Promise<string[]> {
81
81
  return normalise(await readAll(storage))
82
82
  }
83
83
 
@@ -86,7 +86,7 @@ export async function getIssuedDates (storage: KVStorage): Promise<string[]> {
86
86
  * already merged every device's own history into one deduplicated, capped list and wants a
87
87
  * single write rather than N individual `recordIssuedDate` inserts.
88
88
  */
89
- export async function setIssuedDates (storage: KVStorage, dates: string[]): Promise<void> {
89
+ export async function setIssuedDates(storage: KVStorage, dates: string[]): Promise<void> {
90
90
  return withQueueLock(async () => {
91
91
  await storage.setKeyValue(RECEIVE_HISTORY_KEY, JSON.stringify(normalise(dates)))
92
92
  })
@@ -1,11 +1,6 @@
1
1
  import { Beef } from '@bsv/sdk'
2
2
  import { PUBKEY_LABEL } from '../pay/counterparty'
3
- import {
4
- ackControlMessages,
5
- isDuplicateMessageError,
6
- listControlMessages,
7
- parseControlMessage
8
- } from './control'
3
+ import { ackControlMessages, isDuplicateMessageError, listControlMessages, parseControlMessage } from './control'
9
4
  import { getOutboxEntries, type OutboxEntry } from './outbox'
10
5
  import { instructionsFromOutput, rebuildPeerPayToken } from './rebuildToken'
11
6
 
@@ -28,14 +23,13 @@ interface StorageLike {
28
23
  setKeyValue: (key: string, value: string) => Promise<void>
29
24
  /** Optional, and only used to recover derivation data listActions did not
30
25
  * hand back — see `outputsFromStorage`. */
31
- findTransactions?: (args: {
32
- partial: { txid: string }
33
- noRawTx?: boolean
34
- }) => Promise<{ transactionId?: number }[]>
26
+ findTransactions?: (args: { partial: { txid: string }; noRawTx?: boolean }) => Promise<{ transactionId?: number }[]>
35
27
  findOutputs?: (args: {
36
28
  partial: { transactionId: number }
37
29
  noScript?: boolean
38
- }) => Promise<{ vout?: number; satoshis?: number | null; customInstructions?: string | null; basketId?: number | null }[]>
30
+ }) => Promise<
31
+ { vout?: number; satoshis?: number | null; customInstructions?: string | null; basketId?: number | null }[]
32
+ >
39
33
  }
40
34
 
41
35
  /**
@@ -126,9 +120,11 @@ export type PeerPayActionLike = {
126
120
  export type PendingResend = { txid: string; sender: string }
127
121
 
128
122
  type ListAckClient = {
129
- listMessages(args: { messageBox: string; host?: string; acceptPayments?: boolean }): Promise<
130
- { messageId: string; sender: string; body: unknown }[]
131
- >
123
+ listMessages(args: {
124
+ messageBox: string
125
+ host?: string
126
+ acceptPayments?: boolean
127
+ }): Promise<{ messageId: string; sender: string; body: unknown }[]>
132
128
  acknowledgeMessage(args: { messageIds: string[] }): Promise<unknown>
133
129
  }
134
130
 
@@ -237,10 +233,7 @@ function actionFromOutbox(entry: OutboxEntry, txid: string): PeerPayActionLike {
237
233
  export function makeListPeerPayAction(
238
234
  wallet:
239
235
  | {
240
- listActions(
241
- args: unknown,
242
- originator?: string
243
- ): Promise<{ actions: PeerPayActionLike[] }>
236
+ listActions(args: unknown, originator?: string): Promise<{ actions: PeerPayActionLike[] }>
244
237
  }
245
238
  | null
246
239
  | undefined,
@@ -25,9 +25,6 @@ export async function loadInboxAttempts(storage: StorageLike): Promise<Record<st
25
25
  }
26
26
  }
27
27
 
28
- export async function saveInboxAttempts(
29
- storage: StorageLike,
30
- map: Record<string, InboxAttempt>
31
- ): Promise<void> {
28
+ export async function saveInboxAttempts(storage: StorageLike, map: Record<string, InboxAttempt>): Promise<void> {
32
29
  await storage.setKeyValue(INBOX_ATTEMPTS_KEY, JSON.stringify(map))
33
30
  }
@@ -1,9 +1,11 @@
1
1
  import type { OutboxEntry } from './outbox'
2
2
 
3
- export function instructionsFromOutput(customInstructions: unknown): {
4
- derivationPrefix: string
5
- derivationSuffix: string
6
- } | undefined {
3
+ export function instructionsFromOutput(customInstructions: unknown):
4
+ | {
5
+ derivationPrefix: string
6
+ derivationSuffix: string
7
+ }
8
+ | undefined {
7
9
  let parsed: unknown = customInstructions
8
10
  if (typeof customInstructions === 'string') {
9
11
  try {
@@ -35,13 +37,14 @@ type RebuildOutput = {
35
37
  * is the one to take. If nothing is marked either way, fall back to the first
36
38
  * output that carries derivation data — the previous behaviour.
37
39
  */
38
- function paymentOutput(outputs: RebuildOutput[]):
39
- | { instructions: { derivationPrefix: string; derivationSuffix: string }; out: RebuildOutput }
40
- | undefined {
40
+ function paymentOutput(
41
+ outputs: RebuildOutput[]
42
+ ): { instructions: { derivationPrefix: string; derivationSuffix: string }; out: RebuildOutput } | undefined {
41
43
  const parsed = outputs
42
44
  .map(out => ({ out, instructions: instructionsFromOutput(out.customInstructions) }))
43
- .filter((x): x is { out: RebuildOutput; instructions: { derivationPrefix: string; derivationSuffix: string } } =>
44
- x.instructions !== undefined
45
+ .filter(
46
+ (x): x is { out: RebuildOutput; instructions: { derivationPrefix: string; derivationSuffix: string } } =>
47
+ x.instructions !== undefined
45
48
  )
46
49
  if (parsed.length === 0) return undefined
47
50
  return parsed.find(x => !x.out.basket) ?? parsed[0]
@@ -24,6 +24,7 @@
24
24
  import { useSyncExternalStore } from 'react'
25
25
  import AsyncStorage from '@react-native-async-storage/async-storage'
26
26
  import { DEFAULT_CHAIN, type AppChain } from '../config'
27
+ import { APP_CHAINS } from '../networks'
27
28
 
28
29
  export const PROFILES_STORAGE_KEY = 'wallet_profiles_v1'
29
30
 
@@ -67,7 +68,7 @@ export interface ProfilesState {
67
68
  profiles: ProfileRecord[]
68
69
  }
69
70
 
70
- const CHAINS: readonly AppChain[] = ['main', 'test', 'teratest']
71
+ const CHAINS: readonly AppChain[] = APP_CHAINS
71
72
 
72
73
  /** Known networks only, once each, in CHAINS order; undefined when none is left. */
73
74
  export function normalizeRestorePending(raw: unknown): AppChain[] | undefined {
@@ -18,7 +18,9 @@ const PENDING_BLOCKERS: RemovalBlocker[] = [
18
18
  'inbox-pending'
19
19
  ]
20
20
 
21
- export type RemovalProblem = Exclude<ProfileRemovalCheck, { kind: 'ok' }> | Exclude<RemoveProfileResult, { kind: 'removed' }>
21
+ export type RemovalProblem =
22
+ | Exclude<ProfileRemovalCheck, { kind: 'ok' }>
23
+ | Exclude<RemoveProfileResult, { kind: 'removed' }>
22
24
 
23
25
  /** The i18n keys that explain a refusal or failure, one paragraph per kind of reason. */
24
26
  export function removalProblemKeys(problem: RemovalProblem): string[] {
@@ -2,6 +2,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
2
2
  import * as SecureStore from 'expo-secure-store'
3
3
  import { arcApiTokenStorageKey } from '../constants'
4
4
  import { profileScopedKey } from '../profiles/profileStore'
5
+ import { APP_CHAINS } from '../networks'
5
6
 
6
7
  /**
7
8
  * XR-106: the custom ARC API token a holder can configure in
@@ -55,7 +56,7 @@ export async function setArcApiToken(network: string, token: string | null): Pro
55
56
 
56
57
  /** Delete Wallet: drop one profile's token on every network, whichever profile is active. */
57
58
  export async function clearArcApiTokensForProfile(index: number): Promise<void> {
58
- for (const network of ['main', 'test', 'teratest']) {
59
+ for (const network of APP_CHAINS) {
59
60
  const key = profileScopedKey(arcApiTokenStorageKey(network), index)
60
61
  try {
61
62
  await AsyncStorage.removeItem(key)
@@ -1,4 +1,5 @@
1
1
  import { Beef, Transaction, Utils } from '@bsv/sdk'
2
+ import type { WocEndpoints } from '../networks'
2
3
  import type { PostBeefResult, PostTxResultForTxid } from '../toolboxTypes'
3
4
 
4
5
  const BROADCAST_TIMEOUT_MS = 30_000
@@ -315,23 +316,12 @@ export function createGorillaPoolBroadcastService(arcUrl: string) {
315
316
  /**
316
317
  * WhatsOnChain broadcast service — raw tx hex.
317
318
  */
318
- export function createWocBroadcastService(chain: string, apiKey?: string) {
319
- // XQ-011: `chain` here is WalletContext.tsx's un-normalized `walletChain`,
320
- // which a corrupted/garbage persisted finalConfig.network value passes
321
- // through unchanged (toWalletChain only special-cases the literal
322
- // 'teratest'). Every sibling consumer of that same raw value —
323
- // chaintracksUrlFor, the backupChain ternary that actually buckets which
324
- // local DB is opened, walletDbRegistry's registry key — fails safe by
325
- // collapsing any unrecognized string to a teratest/testnet bucket. This
326
- // switch used to do the opposite, defaulting an unrecognized value to the
327
- // live mainnet broadcast endpoint: the most privileged branch, not the
328
- // least. Fail safe the same direction as every other consumer instead.
329
- const baseUrl =
330
- chain === 'main'
331
- ? 'https://api.whatsonchain.com/v1/bsv/main'
332
- : chain === 'test'
333
- ? 'https://api.whatsonchain.com/v1/bsv/test'
334
- : 'https://api.woc-ttn.bsvblockchain.tech/v1/bsv/test'
319
+ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
320
+ // XQ-011: this used to take the raw chain string and pick a host with a
321
+ // ternary, so a corrupted value needed a fail-safe branch. It now takes the
322
+ // network's own WhatsOnChain entry from NETWORKS: a network with no
323
+ // WhatsOnChain has no entry, and the caller does not register this service.
324
+ const baseUrl = `${woc.apiBase}/v1/bsv/${woc.segment}`
335
325
  const name = 'WhatsOnChain'
336
326
 
337
327
  return {
@@ -40,12 +40,7 @@ export function generateKekId(): string {
40
40
  return Utils.toHex(Random(8))
41
41
  }
42
42
 
43
- export function sealSecret(
44
- kek: number[],
45
- kekId: string,
46
- name: SecretName,
47
- plaintext: string
48
- ): EnvelopeBlob {
43
+ export function sealSecret(kek: number[], kekId: string, name: SecretName, plaintext: string): EnvelopeBlob {
49
44
  const salt = Random(SALT_LEN)
50
45
  const dek = deriveDek(kek, salt, name)
51
46
  const c = new SymmetricKey(dek).encrypt(Utils.toArray(plaintext, 'utf8')) as number[]
@@ -14,12 +14,7 @@ import { Hash, Utils } from '@bsv/sdk'
14
14
  const HASH_LEN = 32
15
15
 
16
16
  /** RFC 5869 HKDF with SHA-256. `info` accepts bytes or a UTF-8 string. */
17
- export function hkdfSha256(
18
- ikm: number[],
19
- salt: number[],
20
- info: number[] | string,
21
- length: number = 32
22
- ): number[] {
17
+ export function hkdfSha256(ikm: number[], salt: number[], info: number[] | string, length: number = 32): number[] {
23
18
  if (length > 255 * HASH_LEN) throw new Error('hkdf: length too large')
24
19
  const infoBytes: number[] = typeof info === 'string' ? Utils.toArray(info, 'utf8') : info
25
20
  // Extract: PRK = HMAC(salt, IKM); zero-length salt means a hash-length zero block
@@ -14,24 +14,12 @@
14
14
  *
15
15
  * peekKek is intentionally not re-exported.
16
16
  */
17
- export type {
18
- EnvelopeBlob,
19
- KekPolicy,
20
- KekSentinel,
21
- SecretName,
22
- UnavailableReason,
23
- UnlockState
24
- } from './types'
17
+ export type { EnvelopeBlob, KekPolicy, KekSentinel, SecretName, UnavailableReason, UnlockState } from './types'
25
18
  export { EnvelopeError, SECRET_NAMES } from './types'
26
19
 
27
20
  export { openSecret, sealSecret } from './envelope'
28
21
 
29
- export {
30
- biometricKind,
31
- hasStrongBiometrics,
32
- resolveProvisioningPolicy,
33
- type ResolvedPolicy
34
- } from './policy'
22
+ export { biometricKind, hasStrongBiometrics, resolveProvisioningPolicy, type ResolvedPolicy } from './policy'
35
23
 
36
24
  export {
37
25
  autoUnlockKek,
@@ -44,14 +32,7 @@ export {
44
32
  unlockKek
45
33
  } from './kek'
46
34
 
47
- export {
48
- deleteAllSecrets,
49
- deleteSecret,
50
- getSecret,
51
- hasAnySecret,
52
- hasSecret,
53
- putSecret
54
- } from './store'
35
+ export { deleteAllSecrets, deleteSecret, getSecret, hasAnySecret, hasSecret, putSecret } from './store'
55
36
 
56
37
  export {
57
38
  hasLegacySecrets,
@@ -87,10 +87,7 @@ export async function loadUsdFxRates(
87
87
  const parsed = parseFrankfurterResponse(await res.json())
88
88
  if (!parsed) return rates
89
89
  const next = { ...rates, ...parsed, USD: 1 }
90
- await storage.setItem(
91
- FX_CACHE_KEY,
92
- JSON.stringify({ rates: parsed, timestamp: new Date(now).toISOString() })
93
- )
90
+ await storage.setItem(FX_CACHE_KEY, JSON.stringify({ rates: parsed, timestamp: new Date(now).toISOString() }))
94
91
  return next
95
92
  } catch (error) {
96
93
  console.error('Error fetching USD FX rates from Frankfurter:', error)
@@ -787,7 +787,8 @@ export async function resumeEnrollmentDraft(args: {
787
787
  const scope = vaultStore.getScope()
788
788
  const tag = scope ? await vaultStore.getEnrollmentDraftTag(stored.record.serial, scopeToken) : null
789
789
  const authentic =
790
- scope !== null && (await verifyVaultDraftAuthorityTag(args.wallet, args.adminOriginator, stored.record, scope, tag))
790
+ scope !== null &&
791
+ (await verifyVaultDraftAuthorityTag(args.wallet, args.adminOriginator, stored.record, scope, tag))
791
792
  if (authentic) {
792
793
  args.onPhase('done')
793
794
  return { ...stored.record }
@@ -229,7 +229,12 @@ async function recoverOneCandidate(
229
229
 
230
230
  let salt: string
231
231
  try {
232
- salt = await deriveVaultSalt(w, adminOriginator, ci.saltKeyId, ci.keys.map(key => key.serial))
232
+ salt = await deriveVaultSalt(
233
+ w,
234
+ adminOriginator,
235
+ ci.saltKeyId,
236
+ ci.keys.map(key => key.serial)
237
+ )
233
238
  } catch {
234
239
  return { kind: 'problem', reason: 'could not derive the salt for this record' }
235
240
  }
@@ -263,20 +268,25 @@ async function internalizeCandidate(
263
268
  candidate: RecoverableCandidate
264
269
  ): Promise<string | undefined> {
265
270
  try {
266
- await w.internalizeAction({
267
- tx: candidate.beef,
268
- outputs: [{
269
- outputIndex: candidate.vaultOutputIndex,
270
- protocol: 'basket insertion',
271
- insertionRemittance: {
272
- basket: VAULT_BASKET,
273
- customInstructions: encodeVaultInstructionsV7(candidate.ci),
274
- tags: ['vault']
275
- }
276
- }],
277
- description: 'Recovered vault deposit',
278
- seekPermission: false
279
- }, adminOriginator)
271
+ await w.internalizeAction(
272
+ {
273
+ tx: candidate.beef,
274
+ outputs: [
275
+ {
276
+ outputIndex: candidate.vaultOutputIndex,
277
+ protocol: 'basket insertion',
278
+ insertionRemittance: {
279
+ basket: VAULT_BASKET,
280
+ customInstructions: encodeVaultInstructionsV7(candidate.ci),
281
+ tags: ['vault']
282
+ }
283
+ }
284
+ ],
285
+ description: 'Recovered vault deposit',
286
+ seekPermission: false
287
+ },
288
+ adminOriginator
289
+ )
280
290
  } catch (e) {
281
291
  return `could not internalize the recovered output: ${(e as Error)?.message ?? 'unknown error'}`
282
292
  }
@@ -454,9 +464,13 @@ async function scanVaultChain(
454
464
  }
455
465
  inspected++
456
466
  const outcome = await recoverOneCandidate(w, adminOriginator, lookup, chain, k, markerScriptHex, txid)
457
- if (outcome.kind === 'ready') { ready.push(outcome); break }
458
- else if (outcome.kind === 'pending') { pending.push(outcome.ci); break }
459
- else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason })
467
+ if (outcome.kind === 'ready') {
468
+ ready.push(outcome)
469
+ break
470
+ } else if (outcome.kind === 'pending') {
471
+ pending.push(outcome.ci)
472
+ break
473
+ } else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason })
460
474
  // 'spent': a superseded output (already withdrawn or re-locked) —
461
475
  // entirely normal, silently skipped; keep inspecting other candidates
462
476
  // at this index.
@@ -480,7 +494,10 @@ async function restoreScannedDeposits(
480
494
  let pendingConfirmation = 0
481
495
  let unreachable = 0
482
496
  for (const candidate of ready) {
483
- if (!opensWithAny(candidate.ci, live)) { unreachable++; continue }
497
+ if (!opensWithAny(candidate.ci, live)) {
498
+ unreachable++
499
+ continue
500
+ }
484
501
  const failure = await internalizeCandidate(w, adminOriginator, candidate)
485
502
  if (failure) problems.push({ index: candidate.index, reason: failure })
486
503
  else found++
@@ -507,7 +524,10 @@ async function restoreScannedDeposits(
507
524
  * which returns one row per outpoint (see outputStatus).
508
525
  */
509
526
  export function wocChainLookup(chain: AppChain): VaultChainLookup {
510
- const woc: WocConfig = wocConfigFor(chain)
527
+ const woc: WocConfig | undefined = wocConfigFor(chain)
528
+ // Vault is mainnet-only, so this only fires on a misrouted call. Refuse it
529
+ // rather than answer "no marker": an empty answer is a genuine miss here.
530
+ if (!woc) throw new Error(`Vault chain recovery needs WhatsOnChain, which ${chain} does not have`)
511
531
  const base = `${woc.apiBase}/v1/bsv/${woc.segment}`
512
532
 
513
533
  return {
@@ -626,7 +646,14 @@ function p2pkhAddressFromScript(lockingScriptHex: string, network: 'mainnet' | '
626
646
  } catch {
627
647
  return undefined
628
648
  }
629
- if (bytes.length !== 25 || bytes[0] !== 0x76 || bytes[1] !== 0xa9 || bytes[2] !== 0x14 || bytes[23] !== 0x88 || bytes[24] !== 0xac) {
649
+ if (
650
+ bytes.length !== 25 ||
651
+ bytes[0] !== 0x76 ||
652
+ bytes[1] !== 0xa9 ||
653
+ bytes[2] !== 0x14 ||
654
+ bytes[23] !== 0x88 ||
655
+ bytes[24] !== 0xac
656
+ ) {
630
657
  return undefined
631
658
  }
632
659
  const hash160 = bytes.slice(3, 23)
@@ -149,7 +149,10 @@ export async function verifyVaultMetaAuthorityTag(
149
149
  * tagged: every code path that reads them already requires a fresh
150
150
  * driver.signEcdsa challenge before doing anything with them, so a forged
151
151
  * draft at those levels gains nothing. */
152
- function vaultDraftAuthorityMessage(record: Pick<VaultKeyRecord, 'serial' | 'slot' | 'pubkey'>, scope: VaultStoreScope): number[] {
152
+ function vaultDraftAuthorityMessage(
153
+ record: Pick<VaultKeyRecord, 'serial' | 'slot' | 'pubkey'>,
154
+ scope: VaultStoreScope
155
+ ): number[] {
153
156
  return bytesOf({
154
157
  v: 1,
155
158
  kind: 'vault-enrollment-draft',