@bsv/expo-wallet-toolbox 0.16.0 → 0.18.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.
@@ -5,8 +5,9 @@
5
5
  * pushed its history to its own remote-backup account (the pseudonym derives from
6
6
  * that profile's primary key). So probe profile 1, 2, … in turn: a profile with a
7
7
  * backup on any network exists; the first index with none on every network ends
8
- * the search. Found profiles are only registered here — each replays its backup
9
- * the first time the user switches to it, so an import never stalls on them.
8
+ * the search. Found profiles are only registered here, with the networks their
9
+ * backups are on — each network replays the first time the profile is built
10
+ * there, so an import never stalls on them.
10
11
  *
11
12
  * A profile removed on this device keeps its slot as a tombstone. Discovery
12
13
  * leaves it exactly as it is: no probe, no registration, and it does not end the
@@ -28,8 +29,11 @@ export type ProfileProbe = (primaryKey: number[], chain: BackupChain) => Promise
28
29
  export interface DiscoverProfilesDeps {
29
30
  mnemonic: string
30
31
  probe: ProfileProbe
31
- /** Record profile `index` as existing on `network`. Called in index order. */
32
- register: (index: number, network: AppChain) => Promise<void>
32
+ /**
33
+ * Record profile `index` as existing on `network`, with backups on `chains` (which
34
+ * include `network`). Called in index order.
35
+ */
36
+ register: (index: number, network: AppChain, chains: BackupChain[]) => Promise<void>
33
37
  /** Indices to pass over (profiles removed on this device): not probed, not registered, not a stop. */
34
38
  skip?: (index: number) => boolean
35
39
  /** First index to probe. Default 1 — profile 0 is the wallet being imported. */
@@ -60,21 +64,26 @@ export async function discoverProfiles(deps: DiscoverProfilesDeps): Promise<numb
60
64
  break
61
65
  }
62
66
  if (found.length === 0) break
63
- await deps.register(n, found.includes('main') ? 'main' : found[0])
67
+ await deps.register(n, found.includes('main') ? 'main' : found[0], found)
64
68
  registered++
65
69
  }
66
70
  return registered
67
71
  }
68
72
 
69
73
  /**
70
- * Add a discovered profile to the store, awaiting its first restore. Idempotent:
74
+ * Add a discovered profile to the store, with a restore pending on each network in
75
+ * `chains`. Idempotent:
71
76
  * only the next free slot is appended, so an index the store already holds (live
72
77
  * or removed) is left untouched and a second import of the same seed adds
73
78
  * nothing. Slots are counted with tombstones, never without them.
74
79
  */
75
- export async function registerDiscoveredProfile(index: number, network: AppChain): Promise<void> {
80
+ export async function registerDiscoveredProfile(
81
+ index: number,
82
+ network: AppChain,
83
+ chains: readonly AppChain[] = [network]
84
+ ): Promise<void> {
76
85
  if (index === getProfilesState().profiles.length) {
77
- await appendProfile(network, { needsRestore: true })
86
+ await appendProfile(network, { restorePending: chains })
78
87
  }
79
88
  }
80
89
 
@@ -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.18.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",
@@ -37,6 +37,7 @@
37
37
  "@bsv/react-native-localpay-transport": "*",
38
38
  "@bsv/sdk": "^2.8.11",
39
39
  "@bsv/templates": "^2.0.0",
40
+ "@bsv/webrtpay": "^0.2.1",
40
41
  "@bsv/wallet-toolbox-mobile": "^2.14.3",
41
42
  "@expo/vector-icons": "^15.0.3",
42
43
  "@noble/curves": "^2.3.0",
@@ -83,6 +84,9 @@
83
84
  "react-native-yubikey": "*"
84
85
  },
85
86
  "peerDependenciesMeta": {
87
+ "@bsv/webrtpay": {
88
+ "optional": true
89
+ },
86
90
  "react-native-yubikey": {
87
91
  "optional": true
88
92
  }
@@ -48,6 +48,7 @@ import { makeCreditClassifier } from '../../../core/pay/creditErrors'
48
48
  import { satoshisFromToken } from '../../../core/pay/tokenAmount'
49
49
  import { userFacingPayError } from '../../../core/pay/userError'
50
50
  import { creditInboxOnce, type CreditInboxResult } from '../../../core/pay/creditInbox'
51
+ import { inboxSeenStore } from '../../../core/directpay/receive'
51
52
  import { setReceiveInboxFocused } from '../../../core/pay/receiveFocus'
52
53
  import { TaskCreditInbox } from '../../../core/monitor/TaskCreditInbox'
53
54
  import { useOnline } from '../../hooks/useOnline'
@@ -547,16 +548,20 @@ export default function HandleReceive({
547
548
  [selectedNetwork]
548
549
  )
549
550
 
551
+ // With direct payments on, a payment that arrived live as well is credited,
552
+ // and celebrated, once (see core/directpay/receive.ts).
553
+ const seen = useMemo(() => inboxSeenStore(identityKey, selectedNetwork), [identityKey, selectedNetwork])
554
+
550
555
  const internalize = useCallback(
551
556
  async (payment: IncomingPayment) => {
552
557
  const client = peerPayClient
553
558
  if (!client || !wallet) throw new Error(t('wallet_not_ready'))
554
- await internalizeIncoming(wallet as any, client, adminOriginator, payment, repairBeef)
559
+ return await internalizeIncoming(wallet as any, client, adminOriginator, payment, repairBeef, seen)
555
560
  },
556
- [peerPayClient, wallet, adminOriginator, t, repairBeef]
561
+ [peerPayClient, wallet, adminOriginator, t, repairBeef, seen]
557
562
  )
558
563
 
559
- const applyCreditResult = useCallback((outcome: CreditInboxResult) => {
564
+ const applyCreditResult = useCallback((outcome: CreditInboxResult, duplicates: ReadonlySet<string> = new Set()) => {
560
565
  TaskCreditInbox.lastAttentionCount = outcome.attentionCount
561
566
  attemptsRef.current = outcome.attempts
562
567
  setAttempts(outcome.attempts)
@@ -568,7 +573,10 @@ export default function HandleReceive({
568
573
  // looked at — and whether it landed is the one thing a payee must never
569
574
  // be left unsure about. Everything not left in the attempt map was
570
575
  // credited, so that is what the figure sums.
571
- const credited = outcome.payments.filter(p => !outcome.attempts[String(p.messageId)])
576
+ // A duplicate (taken live first) left the box but was celebrated then.
577
+ const credited = outcome.payments.filter(
578
+ p => !outcome.attempts[String(p.messageId)] && !duplicates.has(String(p.messageId))
579
+ )
572
580
  setReceived({
573
581
  amount: credited.reduce((sum, p) => sum + (satoshisFromToken(p.token)?.satoshis ?? 0), 0),
574
582
  count: outcome.accepted
@@ -584,15 +592,20 @@ export default function HandleReceive({
584
592
  getOnline: () => online,
585
593
  peekLastMissHeight
586
594
  })
595
+ const duplicates = new Set<string>()
587
596
  const outcome = await creditInboxOnce({
588
597
  client,
589
598
  messageBoxUrl,
590
599
  storage: storage ?? undefined,
591
600
  force,
592
601
  classify,
593
- accept: payment => acceptWithRetry(client, messageBoxUrl, payment, internalize)
602
+ accept: async payment => {
603
+ const credited = await acceptWithRetry(client, messageBoxUrl, payment, internalize)
604
+ if (credited === 'duplicate') duplicates.add(String(payment.messageId))
605
+ return credited
606
+ }
594
607
  })
595
- applyCreditResult(outcome)
608
+ applyCreditResult(outcome, duplicates)
596
609
  return outcome
597
610
  },
598
611
  [peerPayClient, messageBoxUrl, storage, online, peekLastMissHeight, internalize, applyCreditResult]
@@ -18,6 +18,7 @@ import { PeerPayClient } from '@bsv/message-box-client'
18
18
  import { showAlert } from '../components/ui/AlertCard'
19
19
  import { makeCreditClassifier } from '../../core/pay/creditErrors'
20
20
  import { creditInboxOnce } from '../../core/pay/creditInbox'
21
+ import { inboxSeenStore } from '../../core/directpay/receive'
21
22
  import { makeBeefRepair } from '../../core/pay/beefRepair'
22
23
  import {
23
24
  acceptWithRetry,
@@ -199,6 +200,12 @@ function useWalletCheckPorts(): WalletCheckPorts {
199
200
  })
200
201
  const repairBeef = makeBeefRepair({ woc: wocConfigFor(selectedNetwork), online: getOnline })
201
202
  const classify = await makeCreditClassifier({ getOnline, peekLastMissHeight })
203
+ // With direct payments on, one that arrived live as well is credited once.
204
+ const identity = await wallet
205
+ .getPublicKey({ identityKey: true }, adminOriginator)
206
+ .then(r => r.publicKey)
207
+ .catch(() => undefined)
208
+ const seen = inboxSeenStore(identity, selectedNetwork)
202
209
  const outcome = await creditInboxOnce({
203
210
  client,
204
211
  messageBoxUrl,
@@ -206,7 +213,7 @@ function useWalletCheckPorts(): WalletCheckPorts {
206
213
  classify,
207
214
  accept: payment =>
208
215
  acceptWithRetry(client, messageBoxUrl, payment, p =>
209
- internalizeIncoming(wallet as never, client, adminOriginator, p, repairBeef)
216
+ internalizeIncoming(wallet as never, client, adminOriginator, p, repairBeef, seen)
210
217
  )
211
218
  })
212
219
  return { accepted: outcome.accepted }