@bsv/expo-wallet-toolbox 0.11.8 → 0.12.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.
@@ -137,6 +137,14 @@ export interface WocConfig {
137
137
  apiBase: string
138
138
  segment: string
139
139
  network: 'mainnet' | 'testnet'
140
+ /**
141
+ * A WhatsOnChain key, sent only as the `woc-api-key` header (see
142
+ * `wocRequestInit`); never logged. `wocConfigFor` does not set it: the
143
+ * host's app-wide key is shared with broadcast, and a 5 s sweep across the
144
+ * whole fleet would drain that quota. A caller with a key of its own may set
145
+ * it explicitly.
146
+ */
147
+ apiKey?: string
140
148
  }
141
149
 
142
150
  export function wocConfigFor(network: AppChain): WocConfig {
@@ -147,6 +155,35 @@ export function wocConfigFor(network: AppChain): WocConfig {
147
155
  }[network]
148
156
  }
149
157
 
158
+ /**
159
+ * HTTP 429 from WhatsOnChain. A type of its own because it is the one failure
160
+ * of these fetches the caller must not treat like the rest: the sweep polls
161
+ * every 5 s, so "try again next tick" is exactly the behaviour that keeps a
162
+ * rate limit alive. It lets the sweep stop the pass and back off instead.
163
+ */
164
+ export class WocRateLimited extends Error {
165
+ constructor() {
166
+ super('WhatsOnChain rate limit reached')
167
+ this.name = 'WocRateLimited'
168
+ }
169
+ }
170
+
171
+ /**
172
+ * The request options carrying the WhatsOnChain key, or undefined when the
173
+ * config has none — so that a config without a key sends the same bare request
174
+ * it always did.
175
+ */
176
+ export function wocRequestInit(woc: WocConfig): { headers: Record<string, string> } | undefined {
177
+ return woc.apiKey ? { headers: { 'woc-api-key': woc.apiKey } } : undefined
178
+ }
179
+
180
+ async function wocFetch(woc: WocConfig, url: string): Promise<Response> {
181
+ const init = wocRequestInit(woc)
182
+ const response = init ? await fetch(url, init) : await fetch(url)
183
+ if (response.status === 429) throw new WocRateLimited()
184
+ return response
185
+ }
186
+
150
187
  export interface AddressDerivingWallet {
151
188
  getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
152
189
  }
@@ -201,7 +238,7 @@ export const MAX_UTXO_LISTING_ROWS = 2000
201
238
  export const MAX_HEX_RESPONSE_CHARS = 8_000_000
202
239
 
203
240
  export async function getUtxosForAddress(woc: WocConfig, address: string): Promise<Utxo[]> {
204
- const response = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/address/${address}/unspent/all`)
241
+ const response = await wocFetch(woc, `${woc.apiBase}/v1/bsv/${woc.segment}/address/${address}/unspent/all`)
205
242
  const rp = await response.json()
206
243
  // A live receive address never legitimately carries anywhere near this many
207
244
  // UTXOs; sweepAddress fetches one BEEF per distinct txid in the result, so
@@ -396,7 +433,7 @@ export async function sweepAddress(args: {
396
433
  for (const txid of txids) {
397
434
  const relevant = byTxid.get(txid) as Utxo[]
398
435
  try {
399
- const resp = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
436
+ const resp = await wocFetch(woc, `${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
400
437
  const bytes = parseWocBeefBody({ ok: resp.ok, text: await resp.text() })
401
438
  if (!bytes) {
402
439
  failureCount++
@@ -450,7 +487,10 @@ export async function sweepAddress(args: {
450
487
  if (response?.accepted) {
451
488
  importedSatoshis += verified.reduce((sum, o) => sum + (tx.outputs[o.vout]?.satoshis ?? 0), 0)
452
489
  } else failureCount++
453
- } catch {
490
+ } catch (error) {
491
+ // A rate limit is not this payment's failure: the rest of the pass would
492
+ // only be refused the same way, so let it stop the sweep (see runSweep).
493
+ if (error instanceof WocRateLimited) throw error
454
494
  failureCount++
455
495
  }
456
496
  }
@@ -26,7 +26,7 @@ import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
26
26
  import type { MandalaRuntime, TokenSendResult } from '../../mandala/runtime'
27
27
 
28
28
  export const MESSAGE_BOX_URL_KEY = 'message_box_url'
29
- export const DEFAULT_MESSAGE_BOX_URL = 'https://gmb.bsvblockchain.tech'
29
+ export const DEFAULT_MESSAGE_BOX_URL = 'https://messagebox.bsvblockchain.tech'
30
30
  /** The previous default. A saved preference equal to it is treated as "use the
31
31
  * default", so existing installs follow the default forward. */
32
32
  export const LEGACY_MESSAGE_BOX_URL = 'https://messagebox.babbage.systems'
@@ -10,11 +10,43 @@
10
10
  * Every bound is deliberate and tested: see shouldSweepNow for when a pass may
11
11
  * run at all, and pay/watchlist.ts for which addresses it may touch.
12
12
  */
13
- import { sweepAddress, type AddressRailWallet, type WocConfig } from './rails/address'
13
+ import { sweepAddress, WocRateLimited, type AddressRailWallet, type WocConfig } from './rails/address'
14
14
  import { getWatchlist, touchWatched, type KVStorage } from './watchlist'
15
15
 
16
- /** One poll every 30s — an order of magnitude cheaper than the 3s screen poll it replaces. */
17
- export const SWEEP_INTERVAL_MS = 30_000
16
+ /**
17
+ * One poll every 5s, foreground only (shouldSweepNow refuses in the background).
18
+ *
19
+ * An address payment announces itself to no one: unlike the handle and nearby
20
+ * rails there is no MessageBox message to push, so the only way this wallet
21
+ * learns of one is to look. 5s is what makes "show the address, money appears"
22
+ * feel immediate to a user watching the screen. The cost is up to ~1.6 WhatsOnChain
23
+ * requests/s on a device with the full 8 watched addresses. The requests carry
24
+ * no API key on purpose: the host's app-wide key is shared with broadcast, and
25
+ * a fleet polling at 5s would drain its quota. So the sweep runs on WhatsOnChain's
26
+ * anonymous limit, and a 429 backs it off (SWEEP_BACKOFF_TICKS) rather than
27
+ * being retried on the next tick.
28
+ */
29
+ export const SWEEP_INTERVAL_MS = 5_000
30
+
31
+ /** Ticks to sit out after a WhatsOnChain 429: 30s at SWEEP_INTERVAL_MS. */
32
+ export const SWEEP_BACKOFF_TICKS = 6
33
+
34
+ /**
35
+ * Spend one tick of a pending backoff. Pure so the caller's counter (a plain
36
+ * variable in the sweep effect's closure) is tested here rather than through a
37
+ * provider.
38
+ */
39
+ export function consumeBackoff(remaining: number): { skip: boolean; remaining: number } {
40
+ return remaining > 0 ? { skip: true, remaining: remaining - 1 } : { skip: false, remaining: 0 }
41
+ }
42
+
43
+ /**
44
+ * The backoff after a failed pass: a full SWEEP_BACKOFF_TICKS for a rate limit,
45
+ * unchanged for anything else (those stay best-effort — the next tick retries).
46
+ */
47
+ export function backoffAfterSweepError(error: unknown, remaining: number): number {
48
+ return error instanceof WocRateLimited ? SWEEP_BACKOFF_TICKS : remaining
49
+ }
18
50
 
19
51
  export interface SweepOutcome {
20
52
  address: string
@@ -61,7 +93,10 @@ export async function runSweep(args: {
61
93
  // rather than retiring it the moment it pays out. A funded address whose
62
94
  // import failed must stay watched too, or a bad BEEF fetch TTL-drops it.
63
95
  if (importedSatoshis > 0 || foundOnChain) await touchWatched(storage, watched.address)
64
- } catch {
96
+ } catch (error) {
97
+ // A rate limit is the one failure that does stop the pass: the other
98
+ // addresses would be refused the same way and only deepen the limit.
99
+ if (error instanceof WocRateLimited) throw error
65
100
  // A dead WoC host or a locked wallet must not stop the rest of the pass.
66
101
  // The entry stays watched and the next pass retries it.
67
102
  }
@@ -0,0 +1,142 @@
1
+ import type { PushAdapter } from './types'
2
+
3
+ let initialConsumed = false
4
+ /** Test-only. */
5
+ export function __resetInitialNotificationForTests(): void {
6
+ initialConsumed = false
7
+ }
8
+
9
+ /**
10
+ * Push failures are contained, never thrown, but they are not silent: a
11
+ * swallowed failure with no trace is how "push never works on this build"
12
+ * becomes impossible to diagnose. Only the error message is logged — never the
13
+ * push payload, the FCM token or an identity key.
14
+ */
15
+ function warn(what: string, e: unknown): void {
16
+ console.warn(`[push] ${what} failed: ${e instanceof Error ? e.message : String(e)}`)
17
+ }
18
+
19
+ /** Run `fn`, containing a throw: push is an enhancement and must never break its caller. */
20
+ function guarded(what: string, fn: () => void): void {
21
+ try {
22
+ fn()
23
+ } catch (e) {
24
+ warn(what, e)
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Subscribe inside its own try/catch. An adapter can throw synchronously when
30
+ * subscribing (the native Firebase app missing on an old dev-client binary);
31
+ * that listener is then simply absent, and the others still attach.
32
+ */
33
+ function subscribe(what: string, attach: () => () => void): () => void {
34
+ try {
35
+ const off = attach()
36
+ return typeof off === 'function' ? off : () => {}
37
+ } catch (e) {
38
+ warn(`${what} subscribe`, e)
39
+ return () => {}
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Route push events into the existing inbox machinery. A push only ever means
45
+ * "look at the inbox now": the credit, sound and toast come from the normal
46
+ * TaskCreditInbox pass, so nothing is shown or credited twice.
47
+ *
48
+ * Never throws — a broken adapter leaves the wallet exactly as it was without
49
+ * push.
50
+ */
51
+ export function attachPushHandlers(args: {
52
+ adapter: PushAdapter
53
+ requestInboxPass: () => void
54
+ openActivity: () => void
55
+ onTokenRefresh: () => void
56
+ }): () => void {
57
+ const { adapter, requestInboxPass, openActivity, onTokenRefresh } = args
58
+ const opened = () => {
59
+ guarded('requestInboxPass', requestInboxPass)
60
+ guarded('openActivity', openActivity)
61
+ }
62
+ if (!initialConsumed) {
63
+ initialConsumed = true
64
+ try {
65
+ void adapter
66
+ .getInitialNotification()
67
+ .then(e => {
68
+ if (e) opened()
69
+ })
70
+ .catch(e => warn('getInitialNotification', e))
71
+ } catch (e) {
72
+ warn('getInitialNotification', e)
73
+ }
74
+ }
75
+ const offs = [
76
+ subscribe('onNotificationOpened', () => adapter.onNotificationOpened(opened)),
77
+ subscribe('onForegroundMessage', () =>
78
+ adapter.onForegroundMessage(() => guarded('requestInboxPass', requestInboxPass))
79
+ ),
80
+ subscribe('onTokenRefresh', () => adapter.onTokenRefresh(() => guarded('onTokenRefresh', onTokenRefresh)))
81
+ ]
82
+ return () => offs.forEach(off => guarded('unsubscribe', off))
83
+ }
84
+
85
+ /**
86
+ * How long one registration sync may run before it is given up on. React
87
+ * Native's Android fetch has no default timeout, so a stalled connection would
88
+ * otherwise hold the lock below until the next wallet build.
89
+ */
90
+ export const PUSH_SYNC_TIMEOUT_MS = 30_000
91
+
92
+ /**
93
+ * Race one run against PUSH_SYNC_TIMEOUT_MS. The run itself cannot be cancelled,
94
+ * so on a timeout it is simply abandoned: whatever it settles with later (its
95
+ * rejection included) is handled by the race and ignored.
96
+ */
97
+ async function runWithTimeout(run: () => Promise<void>): Promise<void> {
98
+ let timer: ReturnType<typeof setTimeout> | undefined
99
+ const timeout = new Promise<never>((_, reject) => {
100
+ timer = setTimeout(() => reject(new Error('timed out')), PUSH_SYNC_TIMEOUT_MS)
101
+ })
102
+ try {
103
+ await Promise.race([run(), timeout])
104
+ } finally {
105
+ clearTimeout(timer)
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Serialize an async job that several triggers can fire at once (startup,
111
+ * token refresh, return to foreground). Never two runs at the same time; calls
112
+ * that land while one is in flight are folded into a single rerun after it
113
+ * finishes, not one rerun each. A run that does not finish within
114
+ * PUSH_SYNC_TIMEOUT_MS is logged and let go, so a hung request cannot block
115
+ * every later sync. The returned promise settles once the work it asked for
116
+ * has run, and never rejects.
117
+ */
118
+ export function coalesceRuns(run: () => Promise<void>): () => Promise<void> {
119
+ let inFlight: Promise<void> | undefined
120
+ let rerun = false
121
+ return () => {
122
+ if (inFlight) {
123
+ rerun = true
124
+ return inFlight
125
+ }
126
+ inFlight = (async () => {
127
+ try {
128
+ do {
129
+ rerun = false
130
+ try {
131
+ await runWithTimeout(run)
132
+ } catch (e) {
133
+ warn('registration sync', e)
134
+ }
135
+ } while (rerun)
136
+ } finally {
137
+ inFlight = undefined
138
+ }
139
+ })()
140
+ return inFlight
141
+ }
142
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Has this device already seen the push notification advisory?
3
+ *
4
+ * This flag gates the one-time NotificationAdvisoryModal shown the first time
5
+ * the user picks "Share remote link" on "Get paid". The modal explains that
6
+ * the phone will next ask to allow notifications so BSV Wallet can tell the
7
+ * user when a MessageBox payment arrives, even while the app is in the
8
+ * background. This flag is a device-level UX preference, not a security
9
+ * record, so unlike backupAttestation it is not scoped per wallet identity —
10
+ * there is no per-identity harm in a shared device remembering "already
11
+ * explained this."
12
+ */
13
+ import AsyncStorage from '@react-native-async-storage/async-storage'
14
+
15
+ const KEY = 'push_advisory_shown_v1'
16
+
17
+ export const pushAdvisory = {
18
+ async get(): Promise<boolean> {
19
+ try {
20
+ return (await AsyncStorage.getItem(KEY)) === 'true'
21
+ } catch {
22
+ return false
23
+ }
24
+ },
25
+
26
+ async set(): Promise<void> {
27
+ try {
28
+ await AsyncStorage.setItem(KEY, 'true')
29
+ } catch {
30
+ // Advisory only — a failed write just means the modal shows again next time.
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,53 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage'
2
+ import type { PushAdapter } from './types'
3
+
4
+ export const PUSH_REGISTRATION_KEY = 'push_registration_v1'
5
+
6
+ export interface RegisterDeviceClient {
7
+ registerDevice(
8
+ params: { fcmToken: string; platform?: 'ios' | 'android'; deviceId?: string },
9
+ overrideHost?: string
10
+ ): Promise<unknown>
11
+ }
12
+
13
+ export type SyncResult = 'registered' | 'unchanged' | 'skipped' | 'failed'
14
+
15
+ /**
16
+ * Make sure the MessageBox host knows this device's FCM token for this
17
+ * identity. Idempotent: the last successful (host, identity, token) triple is
18
+ * remembered, so the common case is no network call at all. Never throws —
19
+ * push is an enhancement and must not take any caller down with it.
20
+ */
21
+ export async function syncPushRegistration(args: {
22
+ adapter: PushAdapter | undefined
23
+ host: string | undefined
24
+ identityKey: string | undefined
25
+ makeClient: (host: string) => RegisterDeviceClient
26
+ storage?: { getItem(k: string): Promise<string | null>; setItem(k: string, v: string): Promise<void> }
27
+ }): Promise<SyncResult> {
28
+ const { adapter, host, identityKey, makeClient } = args
29
+ const storage = args.storage ?? AsyncStorage
30
+ if (!adapter || !host || !identityKey) return 'skipped'
31
+ let token: string | null | undefined
32
+ try {
33
+ if ((await adapter.getPermission()) !== 'granted') return 'skipped'
34
+ token = await adapter.getToken()
35
+ if (!token) return 'skipped'
36
+ const marker = `${host}|${identityKey}|${token}`
37
+ if ((await storage.getItem(PUSH_REGISTRATION_KEY)) === marker) return 'unchanged'
38
+ await makeClient(host).registerDevice({ fcmToken: token, platform: adapter.platform }, host)
39
+ await storage.setItem(PUSH_REGISTRATION_KEY, marker)
40
+ return 'registered'
41
+ } catch (e) {
42
+ // Only the error's message is logged, so a failure is diagnosable without
43
+ // the log ever carrying the token or the identity key. A message that
44
+ // happens to quote the token, the identity key or the host has them cut out.
45
+ const raw = e instanceof Error ? e.message : String(e)
46
+ const message = [token, identityKey, host].reduce<string>(
47
+ (text, secret) => (secret ? text.split(secret).join('[redacted]') : text),
48
+ raw
49
+ )
50
+ console.warn('[push] registerDevice failed: ' + message)
51
+ return 'failed'
52
+ }
53
+ }
@@ -0,0 +1,31 @@
1
+ export type PushPermission = 'granted' | 'denied' | 'undetermined'
2
+
3
+ export interface PushOpenedEvent {
4
+ /** Data payload from the push (messageId, originator). */
5
+ data: Record<string, string>
6
+ }
7
+
8
+ /**
9
+ * The host's push implementation. This package never imports a push SDK: the
10
+ * host wraps whichever one it ships (e.g. React Native Firebase Messaging) in
11
+ * this shape and hands it over through `configureToolbox({ push })`.
12
+ *
13
+ * New members will be added as optional, so an adapter written against this
14
+ * shape keeps compiling and working when the package is updated.
15
+ */
16
+ export interface PushAdapter {
17
+ readonly platform: 'ios' | 'android'
18
+ getPermission(): Promise<PushPermission>
19
+ /** Shows the OS dialog when undetermined; resolves to the result. */
20
+ requestPermission(): Promise<PushPermission>
21
+ /** FCM registration token, or null when unavailable. */
22
+ getToken(): Promise<string | null>
23
+ onTokenRefresh(cb: (token: string) => void): () => void
24
+ /** Tap while backgrounded. */
25
+ onNotificationOpened(cb: (e: PushOpenedEvent) => void): () => void
26
+ /** Tap that launched the app from killed; null when not launched by a tap. */
27
+ getInitialNotification(): Promise<PushOpenedEvent | null>
28
+ /** Push received while app is foreground. */
29
+ onForegroundMessage(cb: (e: PushOpenedEvent) => void): () => void
30
+ openSettings(): Promise<void>
31
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AppChain } from './config'
2
+ import type { PushAdapter } from './push/types'
2
3
 
3
4
  /**
4
5
  * Service endpoints and API keys for one chain.
@@ -108,6 +109,14 @@ export interface ToolboxConfig {
108
109
  * never read from process.env here.
109
110
  */
110
111
  vaultEnabled?: boolean
112
+ /**
113
+ * The host's push implementation. Optional: a host that ships no push SDK
114
+ * omits it and every push feature stays off. The package never imports a
115
+ * push SDK itself — the SDK's native module would have to be linked by every
116
+ * host that merely installs this package — so the host wraps its own and
117
+ * states it here, like the URLs above.
118
+ */
119
+ push?: PushAdapter
111
120
  }
112
121
 
113
122
  interface ResolvedConfig {
@@ -116,6 +125,7 @@ interface ResolvedConfig {
116
125
  mandala: Partial<Record<AppChain, MandalaEndpointConfig>>
117
126
  handleRegistry: Partial<Record<AppChain, HandleRegistryConfig>>
118
127
  vaultEnabled: boolean
128
+ push: PushAdapter | undefined
119
129
  }
120
130
 
121
131
  let current: ResolvedConfig | null = null
@@ -193,7 +203,8 @@ export function configureToolbox(config: ToolboxConfig): void {
193
203
  services: config.services ?? {},
194
204
  mandala: config.mandala ?? {},
195
205
  handleRegistry: config.handleRegistry ?? {},
196
- vaultEnabled: config.vaultEnabled === true
206
+ vaultEnabled: config.vaultEnabled === true,
207
+ push: config.push
197
208
  }
198
209
  }
199
210
 
@@ -318,6 +329,18 @@ export function isVaultEnabled(): boolean {
318
329
  return current?.vaultEnabled ?? false
319
330
  }
320
331
 
332
+ /**
333
+ * The host's push implementation, if it wired one. The package never imports a
334
+ * push SDK itself.
335
+ *
336
+ * Deliberately NOT throwing when unconfigured, like `isVaultEnabled`: push
337
+ * listeners are set up while rendering, and "unconfigured" must look like
338
+ * "no push" rather than crash a wallet that never wanted notifications.
339
+ */
340
+ export function getPushAdapter(): PushAdapter | undefined {
341
+ return current?.push
342
+ }
343
+
321
344
  /**
322
345
  * Whether the vault may be used on this network.
323
346
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.11.8",
3
+ "version": "0.12.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",