@bsv/expo-wallet-toolbox 0.16.0 → 0.17.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.
@@ -41,8 +41,18 @@ export interface ProfileRecord {
41
41
  network: AppChain
42
42
  /** Recorded after this profile's first successful build on this device. Public. */
43
43
  identityKey?: string
44
- /** Replay this profile's remote backup on its next build (set by discovery / add). */
45
- needsRestore?: boolean
44
+ /**
45
+ * The networks whose remote backup this profile still has to replay. Set when the
46
+ * profile is imported, discovered or added; a network leaves the list once its
47
+ * restore has run (or found nothing). Each one restores the first time this
48
+ * device builds the profile there. A profile created on this device has none.
49
+ */
50
+ restorePending?: AppChain[]
51
+ /**
52
+ * The network of this profile's last successful build on this device: where a
53
+ * cold start falls back to when its own network cannot finish its restore.
54
+ */
55
+ lastBuiltNetwork?: AppChain
46
56
  /**
47
57
  * Private label, device-only (not backed up, never published). Trimmed, at most
48
58
  * MAX_PROFILE_NAME_LENGTH characters; absent = the default `profile<n+1>`.
@@ -59,6 +69,13 @@ export interface ProfilesState {
59
69
 
60
70
  const CHAINS: readonly AppChain[] = ['main', 'test', 'teratest']
61
71
 
72
+ /** Known networks only, once each, in CHAINS order; undefined when none is left. */
73
+ export function normalizeRestorePending(raw: unknown): AppChain[] | undefined {
74
+ if (!Array.isArray(raw)) return undefined
75
+ const chains = CHAINS.filter(c => raw.includes(c))
76
+ return chains.length > 0 ? chains : undefined
77
+ }
78
+
62
79
  export function defaultProfilesState(): ProfilesState {
63
80
  return { active: 0, profiles: [{ index: 0, network: DEFAULT_CHAIN }] }
64
81
  }
@@ -103,11 +120,17 @@ export function parseProfilesState(raw: string | null): ProfilesState {
103
120
  if (!r || !Number.isInteger(r.index) || (r.index as number) < 0 || (r.index as number) >= MAX_PROFILES) continue
104
121
  if (byIndex.has(r.index as number)) continue
105
122
  const name = normalizeProfileName(r.name)
123
+ // A record written before restores were per network carries `needsRestore: true`
124
+ // for a profile that has not been built since it was found: every network waits.
125
+ const restorePending = normalizeRestorePending(
126
+ (r as { needsRestore?: unknown }).needsRestore === true ? CHAINS : r.restorePending
127
+ )
106
128
  byIndex.set(r.index as number, {
107
129
  index: r.index as number,
108
130
  network: CHAINS.includes(r.network as AppChain) ? (r.network as AppChain) : DEFAULT_CHAIN,
109
131
  ...(typeof r.identityKey === 'string' ? { identityKey: r.identityKey } : {}),
110
- ...(r.needsRestore === true ? { needsRestore: true } : {}),
132
+ ...(restorePending ? { restorePending } : {}),
133
+ ...(CHAINS.includes(r.lastBuiltNetwork as AppChain) ? { lastBuiltNetwork: r.lastBuiltNetwork as AppChain } : {}),
111
134
  ...(name ? { name } : {}),
112
135
  // Profile 0 anchors the seed (vault, discovery, the bare keys): it is never a tombstone.
113
136
  ...(r.deleted === true && r.index !== 0 ? { deleted: true as const } : {})
@@ -185,11 +208,12 @@ export async function setActiveProfile(n: number): Promise<void> {
185
208
  /** Append the next profile (index = current count). Does not activate it. */
186
209
  export async function appendProfile(
187
210
  network: AppChain = DEFAULT_CHAIN,
188
- opts: { needsRestore?: boolean } = {}
211
+ opts: { restorePending?: readonly AppChain[] } = {}
189
212
  ): Promise<ProfileRecord> {
190
213
  const index = state.profiles.length
191
214
  if (index >= MAX_PROFILES) throw new Error('Too many profiles')
192
- const record: ProfileRecord = { index, network, ...(opts.needsRestore ? { needsRestore: true } : {}) }
215
+ const restorePending = normalizeRestorePending(opts.restorePending)
216
+ const record: ProfileRecord = { index, network, ...(restorePending ? { restorePending } : {}) }
193
217
  publish({ ...state, profiles: [...state.profiles, record] })
194
218
  await persist()
195
219
  return record
@@ -205,17 +229,20 @@ export async function updateProfile(n: number, patch: Partial<Omit<ProfileRecord
205
229
  if (n === state.active) throw new Error('The active profile cannot be removed')
206
230
  }
207
231
  const next: ProfileRecord = { ...current, ...patch, index: n }
208
- if (!next.needsRestore) delete next.needsRestore
232
+ const restorePending = normalizeRestorePending(next.restorePending)
233
+ if (restorePending) next.restorePending = restorePending
234
+ else delete next.restorePending
209
235
  if (!next.deleted) delete next.deleted
210
236
  const name = normalizeProfileName(next.name)
211
237
  if (name) next.name = name
212
238
  else delete next.name
213
239
  if (
214
240
  next.network === current.network &&
241
+ next.lastBuiltNetwork === current.lastBuiltNetwork &&
215
242
  next.identityKey === current.identityKey &&
216
243
  next.name === current.name &&
217
244
  !!next.deleted === !!current.deleted &&
218
- !!next.needsRestore === !!current.needsRestore
245
+ String(next.restorePending ?? '') === String(current.restorePending ?? '')
219
246
  ) {
220
247
  return
221
248
  }
@@ -11,6 +11,13 @@ import { Hash, Utils, type KeyDeriver } from '@bsv/sdk'
11
11
  * Instead derive a BRC-42 private key under a fixed protocol/keyID for
12
12
  * counterparty 'self' and hash it. Deterministic per wallet build, but only
13
13
  * this wallet's root key can compute it — unlike the public identity key.
14
+ *
15
+ * This derivation is shared with BSV Desktop (deriveArcadeCallbackToken in
16
+ * bsv-desktop src/lib/services/createServices.ts), so a wallet open in both
17
+ * apps hears one Arcade status stream. Change it in both or neither: the
18
+ * known-answer vectors in __tests__/services/callbackToken.test.ts are the
19
+ * same ones bsv-desktop's test/arcade.test.ts checks. The private key is
20
+ * hashed unpadded, so one with a leading zero byte hashes as 31 bytes.
14
21
  */
15
22
  export function deriveCallbackToken(keyDeriver: Pick<KeyDeriver, 'derivePrivateKey'>): string {
16
23
  const priv = keyDeriver.derivePrivateKey([2, 'arcade callback token'], '1', 'self')
@@ -1,6 +1,7 @@
1
1
  import type { AppChain } from './config'
2
2
  import type { PushAdapter } from './push/types'
3
3
  import { trimTrailingSlashes } from './net/trimTrailingSlashes'
4
+ import { isRelayUrl, isStunUrl } from './directpay/settings'
4
5
 
5
6
  /**
6
7
  * Service endpoints and API keys for one chain.
@@ -45,6 +46,35 @@ export interface HandleRegistryConfig {
45
46
  url: string
46
47
  }
47
48
 
49
+ /**
50
+ * What the host states about direct (push) payments, the live WebRTC link tried before the
51
+ * message box. Every field is optional, and the whole entry is: a host that states nothing
52
+ * here keeps today's behaviour. The package never imports a WebRTC implementation itself —
53
+ * the native module would have to be linked by every host that merely installs it — so the
54
+ * host that ships one passes it in.
55
+ *
56
+ * `relayUrl` and `stunUrls` are checked when the toolbox is configured, by the same rules as
57
+ * the user's own settings (`isRelayUrl`, `isStunUrl`). They are this build's defaults: they
58
+ * stand in for the built-in ones, and what the user saves in `DirectPaySettings` wins over both.
59
+ */
60
+ export interface DirectPayHostConfig {
61
+ /**
62
+ * Whether this build offers direct payments at all, as `vaultEnabled` gates the vault. The
63
+ * user's own receive switch is a separate setting (`DirectPaySettings.receiveEnabled`).
64
+ * Unset means off.
65
+ */
66
+ enabled?: boolean
67
+ /** This build's signaling relay, `wss://` only, a host with no credentials. Unset means the built-in one. */
68
+ relayUrl?: string
69
+ /** This build's `stun:` / `stuns:` servers, as written (none is trimmed). Unset means the built-in ones. */
70
+ stunUrls?: string[]
71
+ /**
72
+ * The host's `RTCPeerConnection` constructor (e.g. from react-native-webrtc). Typed
73
+ * `unknown` because this package ships no WebRTC types and must not depend on any.
74
+ */
75
+ RTCPeerConnection?: unknown
76
+ }
77
+
48
78
  /**
49
79
  * Runtime configuration supplied by the host app.
50
80
  *
@@ -125,6 +155,11 @@ export interface ToolboxConfig {
125
155
  * states it here, like the URLs above.
126
156
  */
127
157
  push?: PushAdapter
158
+ /**
159
+ * Direct (push) payments. Optional, and unset by default: a host that omits it sees no
160
+ * change.
161
+ */
162
+ directPay?: DirectPayHostConfig
128
163
  }
129
164
 
130
165
  interface ResolvedConfig {
@@ -135,6 +170,7 @@ interface ResolvedConfig {
135
170
  handleMinLength: 1 | 2 | 3
136
171
  vaultEnabled: boolean
137
172
  push: PushAdapter | undefined
173
+ directPay: DirectPayHostConfig | undefined
138
174
  }
139
175
 
140
176
  let current: ResolvedConfig | null = null
@@ -197,6 +233,20 @@ function normalizeBackupUrl(raw: string): string {
197
233
  return trimmed
198
234
  }
199
235
 
236
+ /** Throws unless the host's direct pay addresses are acceptable; unset fields are fine. */
237
+ function checkDirectPayHostConfig(directPay: DirectPayHostConfig | undefined): void {
238
+ if (directPay === undefined) return
239
+ const { relayUrl, stunUrls } = directPay
240
+ if (relayUrl !== undefined && !(typeof relayUrl === 'string' && isRelayUrl(relayUrl))) {
241
+ throw new Error(`configureToolbox: directPay.relayUrl must be a wss:// address without credentials: ${relayUrl}`)
242
+ }
243
+ if (stunUrls !== undefined && !(Array.isArray(stunUrls) && stunUrls.every(url => isStunUrl(url)))) {
244
+ throw new Error(
245
+ `configureToolbox: directPay.stunUrls must be a list of stun: or stuns: addresses: ${JSON.stringify(stunUrls)}`
246
+ )
247
+ }
248
+ }
249
+
200
250
  /**
201
251
  * Install the host's runtime configuration. Call once, at app entry, before
202
252
  * anything from this package renders or builds a wallet.
@@ -207,6 +257,7 @@ export function configureToolbox(config: ToolboxConfig): void {
207
257
  if (config == null || !('backupUrl' in config)) {
208
258
  throw new Error('configureToolbox: backupUrl is required. Pass null to disable backup.')
209
259
  }
260
+ checkDirectPayHostConfig(config.directPay)
210
261
  current = {
211
262
  backupUrl: config.backupUrl == null ? '' : normalizeBackupUrl(config.backupUrl),
212
263
  services: config.services ?? {},
@@ -214,7 +265,8 @@ export function configureToolbox(config: ToolboxConfig): void {
214
265
  handleRegistry: config.handleRegistry ?? {},
215
266
  handleMinLength: config.handleMinLength === 1 || config.handleMinLength === 2 ? config.handleMinLength : 3,
216
267
  vaultEnabled: config.vaultEnabled === true,
217
- push: config.push
268
+ push: config.push,
269
+ directPay: config.directPay
218
270
  }
219
271
  }
220
272
 
@@ -359,6 +411,16 @@ export function getPushAdapter(): PushAdapter | undefined {
359
411
  return current?.push
360
412
  }
361
413
 
414
+ /**
415
+ * What the host stated about direct payments, or undefined when it stated nothing.
416
+ *
417
+ * Deliberately NOT throwing when unconfigured, like `getPushAdapter`: it is read while
418
+ * building the wallet, and "unconfigured" must look like "not stated".
419
+ */
420
+ export function getDirectPayConfig(): DirectPayHostConfig | undefined {
421
+ return current?.directPay
422
+ }
423
+
362
424
  /**
363
425
  * Whether the vault may be used on this network.
364
426
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",