@bsv/expo-wallet-toolbox 0.17.0 → 0.19.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.
@@ -0,0 +1,321 @@
1
+ /**
2
+ * DirectPayProvider runs the open wallet's {@link DirectPayManager}, and `useDirectPay` is how a
3
+ * screen reads its state, changes the settings and pays live.
4
+ *
5
+ * Mount it inside `WalletContextProvider`. It does nothing (and `available` is false) unless the
6
+ * host turned direct payments on (`ToolboxConfig.directPay.enabled`) and installed
7
+ * `@bsv/webrtpay` (an optional peer dependency). It starts the manager once the wallet is built,
8
+ * with this wallet's identity key, network and message box, and the device settings: what the
9
+ * user saved, else the host's relay and STUN servers, else the built-in ones. The host's
10
+ * `RTCPeerConnection` (react-native-webrtc's) comes from the same config.
11
+ *
12
+ * Receiving runs only while the app is in the foreground: the provider tells the manager when
13
+ * the app goes to (`background`) and comes back from the background. `inactive` (a Face ID
14
+ * prompt, the control centre) is not leaving: a payment in progress must survive it.
15
+ *
16
+ * Arrivals are announced through `onToast` (as `WalletContextProvider` takes it), once per
17
+ * payment whichever way it came: the inbox credit pass and this manager share the seen store.
18
+ */
19
+ import React, {
20
+ createContext,
21
+ useCallback,
22
+ useContext,
23
+ useEffect,
24
+ useMemo,
25
+ useState,
26
+ useSyncExternalStore
27
+ } from 'react'
28
+ import { AppState } from 'react-native'
29
+ import AsyncStorage from '@react-native-async-storage/async-storage'
30
+ import { useWallet, useWalletManagers, useWalletStatus } from '../context/WalletContext'
31
+ import { getDirectPayConfig } from '../toolboxConfig'
32
+ import { getOnline, subscribeOnline } from '../net/online'
33
+ import { makeCreditClassifier } from '../pay/creditErrors'
34
+ import {
35
+ DEFAULT_MESSAGE_BOX_URL,
36
+ LEGACY_MESSAGE_BOX_URL,
37
+ MESSAGE_BOX_URL_KEY,
38
+ NO_MESSAGE_BOX,
39
+ makePeerPayClient
40
+ } from '../pay/rails/handle'
41
+ import { sendViaDirect, type DirectSendResult } from '../pay/rails/direct'
42
+ import { profileScopedKey } from '../profiles/profileStore'
43
+ import { deviceKVStorage } from './deviceStore'
44
+ import { DirectPayManager, type DirectPaySnapshot, type DirectPayToast } from './DirectPayManager'
45
+ import { NotSentError } from './payFlow'
46
+ import { loadDirectPaySettings, saveDirectPaySettings, type DirectPayHostDefaults } from './settings'
47
+ import { liveStatus } from './status'
48
+ import type { DirectPaySettings, LiveStatus } from './types'
49
+ import { loadWebRTPay, type MessageBoxLike, type WebRTPayModule, type WebRTPayWallet } from './webrtpay'
50
+
51
+ export interface DirectPaySendArgs {
52
+ recipient: string
53
+ satoshis: number
54
+ note?: string
55
+ recipientName?: string
56
+ /** The recipient's message-box host from a BRC-125 `url` extension. */
57
+ recipientHost?: string
58
+ /** Cancels the dial, and stops the payment before it is made. */
59
+ signal?: AbortSignal
60
+ }
61
+
62
+ export interface DirectPayContextValue {
63
+ /** This build offers direct payments and `@bsv/webrtpay` is installed. */
64
+ available: boolean
65
+ snapshot: DirectPaySnapshot
66
+ /** The Receive card for the snapshot (i18n keys). */
67
+ live: LiveStatus
68
+ /** The device settings in effect; null until read. */
69
+ settings: DirectPaySettings | null
70
+ /** Saves the settings (see `saveDirectPaySettings`) and applies them; throws `DirectPaySettingsError`. */
71
+ saveSettings: (input: Partial<DirectPaySettings>) => Promise<DirectPaySettings>
72
+ /** Reads the settings and the message box address again, and applies them. */
73
+ reload: () => Promise<void>
74
+ /** Whether {@link sendDirect} can run now: a client is up and this wallet has a message box to finish through. */
75
+ canSendDirect: boolean
76
+ /**
77
+ * Pays `recipient` live (`sendViaDirect`). Pass it as `payIdentity`'s `direct` route. Throws
78
+ * `NotSentError` when it stopped before the payment was made.
79
+ */
80
+ sendDirect: (args: DirectPaySendArgs) => Promise<DirectSendResult>
81
+ }
82
+
83
+ const OFF_SNAPSHOT: DirectPaySnapshot = {
84
+ client: null,
85
+ status: 'off',
86
+ via: null,
87
+ relayUnreachable: false,
88
+ error: '',
89
+ notice: '',
90
+ received: 0,
91
+ background: false
92
+ }
93
+
94
+ const unavailable = async (): Promise<never> => {
95
+ throw new NotSentError('Direct payments are not available', 'not configured')
96
+ }
97
+
98
+ const DirectPayContext = createContext<DirectPayContextValue>({
99
+ available: false,
100
+ snapshot: OFF_SNAPSHOT,
101
+ live: liveStatus(OFF_SNAPSHOT),
102
+ settings: null,
103
+ saveSettings: unavailable,
104
+ reload: async () => {},
105
+ canSendDirect: false,
106
+ sendDirect: unavailable
107
+ })
108
+
109
+ export const useDirectPay = (): DirectPayContextValue => useContext(DirectPayContext)
110
+
111
+ /** The message box this profile uses, or undefined when the user turned it off (as WalletContext reads it). */
112
+ async function readMessageBoxHost(): Promise<string | undefined> {
113
+ const saved = await AsyncStorage.getItem(profileScopedKey(MESSAGE_BOX_URL_KEY))
114
+ if (saved === NO_MESSAGE_BOX) return undefined
115
+ return !saved || saved === LEGACY_MESSAGE_BOX_URL ? DEFAULT_MESSAGE_BOX_URL : saved
116
+ }
117
+
118
+ /** The device settings (user's, else the host's, else built-in) and this profile's message box. */
119
+ async function readInputs(
120
+ hostDefaults: DirectPayHostDefaults
121
+ ): Promise<{ settings: DirectPaySettings; messageBoxUrl: string | undefined }> {
122
+ const [settings, messageBoxUrl] = await Promise.all([
123
+ loadDirectPaySettings(deviceKVStorage, hostDefaults),
124
+ readMessageBoxHost().catch(() => undefined)
125
+ ])
126
+ return { settings, messageBoxUrl }
127
+ }
128
+
129
+ const subscribeNothing = () => () => {}
130
+ const offSnapshot = () => OFF_SNAPSHOT
131
+
132
+ export const DirectPayProvider: React.FC<{ children: React.ReactNode; onToast?: DirectPayToast }> = ({
133
+ children,
134
+ onToast
135
+ }) => {
136
+ const config = getDirectPayConfig()
137
+ const enabled = config?.enabled === true
138
+ const hostDefaults = useMemo<DirectPayHostDefaults>(
139
+ () => ({ relayUrl: config?.relayUrl, stunUrls: config?.stunUrls }),
140
+ [config?.relayUrl, config?.stunUrls]
141
+ )
142
+ const webrtpay = useMemo<WebRTPayModule | null>(() => (enabled ? loadWebRTPay() : null), [enabled])
143
+
144
+ const { managers, adminOriginator, storage } = useWalletManagers()
145
+ const { walletBuilt, selectedNetwork } = useWalletStatus()
146
+ const { peekLastMissHeight } = useWallet()
147
+
148
+ const manager = useMemo(
149
+ () =>
150
+ webrtpay
151
+ ? new DirectPayManager({
152
+ webrtpay,
153
+ storage: deviceKVStorage,
154
+ subscribeOnline,
155
+ getOnline,
156
+ foreground: AppState.currentState !== 'background'
157
+ })
158
+ : null,
159
+ [webrtpay]
160
+ )
161
+
162
+ // The toast and the classifier's chain-tracker context follow the latest render.
163
+ useEffect(() => {
164
+ manager?.setCallbacks({
165
+ onToast,
166
+ classifier: () => makeCreditClassifier({ getOnline, peekLastMissHeight })
167
+ })
168
+ }, [manager, onToast, peekLastMissHeight])
169
+
170
+ const snapshot = useSyncExternalStore(
171
+ manager ? manager.subscribe : subscribeNothing,
172
+ manager ? manager.getSnapshot : offSnapshot
173
+ )
174
+
175
+ const [settings, setSettings] = useState<DirectPaySettings | null>(null)
176
+ const [messageBoxUrl, setMessageBoxUrl] = useState<string | undefined>(undefined)
177
+
178
+ useEffect(() => {
179
+ if (!manager) return
180
+ let current = true
181
+ void readInputs(hostDefaults).then(inputs => {
182
+ if (!current) return
183
+ setSettings(inputs.settings)
184
+ setMessageBoxUrl(inputs.messageBoxUrl)
185
+ })
186
+ return () => {
187
+ current = false
188
+ }
189
+ }, [manager, hostDefaults])
190
+
191
+ const reload = useCallback(async () => {
192
+ if (!manager) return
193
+ const inputs = await readInputs(hostDefaults)
194
+ setSettings(inputs.settings)
195
+ setMessageBoxUrl(inputs.messageBoxUrl)
196
+ }, [manager, hostDefaults])
197
+
198
+ const wallet = managers.permissionsManager as unknown as WebRTPayWallet | undefined
199
+ // The identity key of the wallet it was read from, so a rebuilt wallet never runs on the last one's.
200
+ const [identityOf, setIdentityOf] = useState<{ wallet: WebRTPayWallet; key: string } | undefined>(undefined)
201
+ const identity = wallet && identityOf?.wallet === wallet ? identityOf.key : undefined
202
+ useEffect(() => {
203
+ if (!manager || !walletBuilt || !wallet) return
204
+ let current = true
205
+ wallet
206
+ .getPublicKey({ identityKey: true }, adminOriginator)
207
+ .then(({ publicKey }) => {
208
+ if (current) setIdentityOf({ wallet, key: publicKey })
209
+ })
210
+ .catch(e => console.warn('[DirectPayProvider] No identity key:', e instanceof Error ? e.message : String(e)))
211
+ return () => {
212
+ current = false
213
+ }
214
+ }, [manager, walletBuilt, wallet, adminOriginator])
215
+
216
+ const peerPayClient = useMemo<MessageBoxLike | null>(
217
+ () =>
218
+ wallet && messageBoxUrl
219
+ ? (makePeerPayClient({
220
+ wallet: wallet as never,
221
+ messageBoxUrl,
222
+ originator: adminOriginator
223
+ }) as MessageBoxLike | null)
224
+ : null,
225
+ [wallet, messageBoxUrl, adminOriginator]
226
+ )
227
+
228
+ // Start with the wallet, follow its inputs, stop when it goes.
229
+ useEffect(() => {
230
+ if (!manager) return
231
+ if (!walletBuilt || !wallet || !identity || !settings) {
232
+ void manager.stop()
233
+ return
234
+ }
235
+ void manager.start({
236
+ wallet,
237
+ originator: adminOriginator,
238
+ identity,
239
+ chain: selectedNetwork,
240
+ peerPayClient,
241
+ messageBoxUrl,
242
+ settings,
243
+ RTCPeerConnection: config?.RTCPeerConnection
244
+ })
245
+ }, [
246
+ manager,
247
+ walletBuilt,
248
+ wallet,
249
+ identity,
250
+ settings,
251
+ adminOriginator,
252
+ selectedNetwork,
253
+ peerPayClient,
254
+ messageBoxUrl,
255
+ config?.RTCPeerConnection
256
+ ])
257
+
258
+ useEffect(() => {
259
+ if (!manager) return
260
+ return () => {
261
+ void manager.stop()
262
+ }
263
+ }, [manager])
264
+
265
+ // Receive only in the foreground; read the message box address again on return (Settings may have changed it).
266
+ useEffect(() => {
267
+ if (!manager) return
268
+ const subscription = AppState.addEventListener('change', next => {
269
+ const foreground = next !== 'background'
270
+ manager.setForeground(foreground)
271
+ if (foreground && next === 'active') void reload()
272
+ })
273
+ return () => subscription.remove()
274
+ }, [manager, reload])
275
+
276
+ const saveSettings = useCallback(
277
+ async (input: Partial<DirectPaySettings>) => {
278
+ const saved = await saveDirectPaySettings(deviceKVStorage, input, hostDefaults)
279
+ setSettings(saved)
280
+ return saved
281
+ },
282
+ [hostDefaults]
283
+ )
284
+
285
+ const canSendDirect = !!snapshot.client && !!storage && !!wallet && !!messageBoxUrl
286
+ const sendDirect = useCallback(
287
+ async (args: DirectPaySendArgs): Promise<DirectSendResult> => {
288
+ const client = manager?.getSnapshot().client
289
+ if (!webrtpay || !manager || !client || !storage || !wallet) {
290
+ throw new NotSentError('Direct payments are not available', 'no client')
291
+ }
292
+ return await sendViaDirect({
293
+ wallet: wallet as never,
294
+ adminOriginator,
295
+ client,
296
+ webrtpay,
297
+ storage,
298
+ messageBoxUrl: messageBoxUrl ?? '',
299
+ signalingDown: manager.signalingDown,
300
+ ...args
301
+ })
302
+ },
303
+ [manager, webrtpay, storage, wallet, adminOriginator, messageBoxUrl]
304
+ )
305
+
306
+ const value = useMemo<DirectPayContextValue>(
307
+ () => ({
308
+ available: !!manager,
309
+ snapshot,
310
+ live: liveStatus(snapshot),
311
+ settings,
312
+ saveSettings,
313
+ reload,
314
+ canSendDirect,
315
+ sendDirect
316
+ }),
317
+ [manager, snapshot, settings, saveSettings, reload, canSendDirect, sendDirect]
318
+ )
319
+
320
+ return <DirectPayContext.Provider value={value}>{children}</DirectPayContext.Provider>
321
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The device-level key/value store direct payments keep their state in: AsyncStorage, not the
3
+ * wallet's own database.
4
+ *
5
+ * Settings are read before sign-in and survive logout. The seen store and the kept payments are
6
+ * keyed by identity key and network, and must outlive the wallet's database: a kept payment was
7
+ * acknowledged to its payer, who will not send it again, and its derivation is on this device
8
+ * only, so removing a profile must not take it along. AsyncStorage is not encrypted; nothing
9
+ * here is a secret (a kept payment can be spent only by this identity's keys).
10
+ */
11
+ import AsyncStorage from '@react-native-async-storage/async-storage'
12
+ import type { KVStorage } from '../localpay/pending'
13
+
14
+ export const deviceKVStorage: KVStorage = {
15
+ getKeyValue: async key => (await AsyncStorage.getItem(key)) ?? undefined,
16
+ setKeyValue: async (key, value) => {
17
+ await AsyncStorage.setItem(key, value)
18
+ }
19
+ }
@@ -1,7 +1,12 @@
1
- // Direct (push) payments: the pure core. No @bsv/webrtpay, no native modules, no UI.
1
+ // Direct (push) payments: the pure core, the @bsv/webrtpay shapes and its lazy loader. Nothing
2
+ // here imports @bsv/webrtpay itself (an optional peer dependency), a native module or a React
3
+ // context. The runtime half (receive, the manager and DirectPayProvider) needs the wallet's
4
+ // contexts and storage, so core/index.ts exports it, not this barrel.
2
5
  export * from './types'
3
6
  export * from './settings'
4
7
  export * from './dialFailure'
5
8
  export * from './payFlow'
6
9
  export * from './status'
7
10
  export * from './paymentKey'
11
+ export * from './webrtpay'
12
+ export * from './reactNativeRtc'
@@ -0,0 +1,81 @@
1
+ /**
2
+ * A stopgap for react-native-webrtc until the fix in `@bsv/webrtpay` (bsv-blockchain/ts-stack#1263)
3
+ * is released. Pure TypeScript: the host passes in its own `RTCPeerConnection`.
4
+ *
5
+ * The payee takes the payer's data channel only when it is reliable, which the package reads
6
+ * from `maxRetransmits` and `maxPacketLifeTime`: the DOM reports `null` for a channel opened
7
+ * with no limit. react-native-webrtc cannot: Android reports -1 for a channel the peer opened,
8
+ * and iOS passes on libwebrtc's `uint16_t`, where unset is 65535. webrtpay 0.2.1 then closes the
9
+ * link ("Unexpected data channel 'webrtpay/1'"), so no payment can reach a phone.
10
+ *
11
+ * `withReactNativeDataChannels(RTCPeerConnection)` returns a subclass whose `datachannel`
12
+ * listeners see those two fields as `null` when they hold -1 or 65535 (an own property on the
13
+ * channel object, shadowing the getter, so the link still uses the real channel). The package
14
+ * listens with `addEventListener('datachannel', …)` only. 65535 is also the largest limit a
15
+ * peer can set, so a channel limited to exactly that reads as unlimited; the released fix makes
16
+ * the same trade. Pass the result as `ToolboxConfig.directPay.RTCPeerConnection`:
17
+ *
18
+ * import { RTCPeerConnection } from 'react-native-webrtc'
19
+ * configureToolbox({ …, directPay: { enabled: true, RTCPeerConnection: withReactNativeDataChannels(RTCPeerConnection) } })
20
+ *
21
+ * Drop it once the host's `@bsv/webrtpay` has the fix; it changes nothing there.
22
+ */
23
+
24
+ /** Values react-native-webrtc reports for "no limit". */
25
+ const UNSET_LIMITS: ReadonlySet<number> = new Set([-1, 65535])
26
+
27
+ /** Reads `maxRetransmits` and `maxPacketLifeTime` as `null` on `channel` when they say "no limit". */
28
+ export function normalizeDataChannelLimits(channel: unknown): void {
29
+ if (typeof channel !== 'object' || channel === null) return
30
+ for (const field of ['maxRetransmits', 'maxPacketLifeTime'] as const) {
31
+ const value = (channel as Record<string, unknown>)[field]
32
+ if (typeof value !== 'number' || !UNSET_LIMITS.has(value)) continue
33
+ try {
34
+ Object.defineProperty(channel, field, { value: null, configurable: true, enumerable: true })
35
+ } catch {
36
+ // A channel that cannot be changed is left as it is; the link refuses it as before.
37
+ }
38
+ }
39
+ }
40
+
41
+ type DataChannelListener =
42
+ | ((event: { channel?: unknown }) => void)
43
+ | { handleEvent(event: { channel?: unknown }): void }
44
+
45
+ interface EventTargetLike {
46
+ addEventListener(type: string, listener: never, options?: never): void
47
+ removeEventListener(type: string, listener: never, options?: never): void
48
+ }
49
+
50
+ /**
51
+ * `Base` with every `datachannel` listener handed a channel whose unset limits read `null`
52
+ * (see the file header). Other events pass through unchanged.
53
+ */
54
+ export function withReactNativeDataChannels<C extends new (...args: any[]) => EventTargetLike>(Base: C): C {
55
+ const wrappers = new WeakMap<object, (event: { channel?: unknown }) => void>()
56
+ const isListener = (l: unknown): l is DataChannelListener =>
57
+ typeof l === 'function' || (typeof l === 'object' && l !== null && 'handleEvent' in l)
58
+
59
+ return class ReactNativeDataChannels extends Base {
60
+ addEventListener(type: string, listener: unknown, options?: unknown): void {
61
+ if (type !== 'datachannel' || !isListener(listener)) {
62
+ return super.addEventListener(type, listener as never, options as never)
63
+ }
64
+ let wrapper = wrappers.get(listener)
65
+ if (!wrapper) {
66
+ wrapper = (event: { channel?: unknown }) => {
67
+ normalizeDataChannelLimits(event?.channel)
68
+ if (typeof listener === 'function') listener.call(this, event)
69
+ else listener.handleEvent(event)
70
+ }
71
+ wrappers.set(listener, wrapper)
72
+ }
73
+ super.addEventListener(type, wrapper as never, options as never)
74
+ }
75
+
76
+ removeEventListener(type: string, listener: unknown, options?: unknown): void {
77
+ const wrapper = type === 'datachannel' && isListener(listener) ? wrappers.get(listener) : undefined
78
+ super.removeEventListener(type, (wrapper ?? listener) as never, options as never)
79
+ }
80
+ }
81
+ }