@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.
@@ -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
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Classifies why dialing a recipient failed. Duck-typed on `name`, `code` and `reason`, so this
3
+ * needs no import of `@bsv/webrtpay`, and an error that crossed a worker or bridge boundary
4
+ * (own properties kept, prototype lost) is read the same.
5
+ *
6
+ * The codes are those `DirectPayClient.connect` rejects with:
7
+ * `peer_unreachable` (no reply in the presence window, or the relay socket could not be
8
+ * opened or closed on the dial), `rejected` (the recipient refused; `reason` is `busy`,
9
+ * `not_receiving` or `wrong_network`, or whatever else it said), `unavailable` (the signaling
10
+ * service could not do its part: the relay had no TURN credentials, or MessageBox could not
11
+ * deliver the signal), `timeout` (it replied but the link did not come up), and `closed` (the
12
+ * channel closed; `Dial cancelled` when the caller's signal aborted).
13
+ *
14
+ * Two things for the caller that dials. `peer_unreachable` is also what a payer with no
15
+ * network on relay signaling gets, so check this wallet's own relay connection before taking
16
+ * `offline` to mean the recipient is away. And a cancelled dial is told apart by that message
17
+ * text alone (or an abort error): the dial's catch should check its own `signal.aborted` and
18
+ * throw `NotSentError(..., 'aborted')` itself, so a reworded message cannot turn Cancel into
19
+ * an offer to use the message box.
20
+ */
21
+ import type { DialFailure } from './types'
22
+
23
+ interface DialError {
24
+ name?: unknown
25
+ code?: unknown
26
+ reason?: unknown
27
+ message?: unknown
28
+ }
29
+
30
+ /** The {@link DialFailure} for an error from a dial. */
31
+ export function dialFailure(error: unknown): DialFailure {
32
+ if (typeof error !== 'object' || error === null) return 'unknown'
33
+ const { name, code, reason, message } = error as DialError
34
+
35
+ // A native or DOM abort, however the dial's caller cancelled it.
36
+ if (name === 'AbortError' || code === 'ABORT_ERR') return 'aborted'
37
+ if (name !== 'WebRTPayError') return 'unknown'
38
+
39
+ switch (code) {
40
+ case 'peer_unreachable':
41
+ return 'offline'
42
+ case 'unavailable':
43
+ return 'unavailable'
44
+ case 'timeout':
45
+ return 'timeout'
46
+ case 'rejected':
47
+ if (reason === 'wrong_network') return 'wrong_network'
48
+ if (reason === 'not_receiving' || reason === 'busy') return 'rejected'
49
+ return 'unknown'
50
+ case 'closed':
51
+ // The package reports a cancelled dial as a closed one, worded "Dial cancelled".
52
+ return typeof message === 'string' && /dial cancelled/i.test(message) ? 'aborted' : 'unknown'
53
+ default:
54
+ return 'unknown'
55
+ }
56
+ }
@@ -0,0 +1,12 @@
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.
5
+ export * from './types'
6
+ export * from './settings'
7
+ export * from './dialFailure'
8
+ export * from './payFlow'
9
+ export * from './status'
10
+ export * from './paymentKey'
11
+ export * from './webrtpay'
12
+ export * from './reactNativeRtc'
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Paying a wallet identity: live (direct) first, the message box second. The user never picks
3
+ * a route; when the live attempt stopped before anything was made (a {@link NotSentError}
4
+ * whose dial failed because the recipient is offline, not receiving, or the link did not come
5
+ * up), the caller asks before sending it to their message box instead. One payment is always
6
+ * one transaction: a failure after the payment was made is never offered the fallback, since
7
+ * that would build a second one (the caller keeps it saved to retry). That failure says the
8
+ * payment may have been sent (`spent: 'maybe'`), so the user does not pay again by hand.
9
+ *
10
+ * Pure: both routes are functions the caller passes in, and every word for the user comes back
11
+ * as an i18n key.
12
+ */
13
+ import type { DialFailure, DirectPayMessage, FallbackReason, PayFailure, PayOutcome } from './types'
14
+
15
+ /**
16
+ * A payment that stopped before anything was made or broadcast, so nothing was spent (and,
17
+ * for a dial that failed, the message box fallback may be offered). Either route throws this,
18
+ * and only this, for every failure it can promise left no payment behind; any other error
19
+ * from it is taken to mean the payment may have been delivered.
20
+ *
21
+ * `failure` is why the dial failed (see `dialFailure`), and is for the live route; without it
22
+ * the payment stopped for some other reason, and `message` and `detail` are the reason, in
23
+ * English, for the log.
24
+ */
25
+ export class NotSentError extends Error {
26
+ constructor(
27
+ message: string,
28
+ readonly detail = '',
29
+ readonly failure?: DialFailure
30
+ ) {
31
+ super(message)
32
+ this.name = 'NotSentError'
33
+ }
34
+ }
35
+
36
+ const messageOf = (error: unknown) => (error instanceof Error && error.message) || ''
37
+
38
+ const failed = (
39
+ spent: PayFailure['spent'],
40
+ key: DirectPayMessage['key'],
41
+ params?: DirectPayMessage['params'],
42
+ detail?: string
43
+ ): PayFailure => ({
44
+ kind: 'failed',
45
+ spent,
46
+ key,
47
+ ...(params && { params }),
48
+ ...(detail && { detail })
49
+ })
50
+
51
+ /**
52
+ * A stop that is no dial failure. Only a {@link NotSentError} proves nothing was spent; any
53
+ * other error may come after the payment was made, so it says the payment may have been sent.
54
+ */
55
+ function stopped(error: unknown, name: string): PayFailure {
56
+ if (error instanceof NotSentError) {
57
+ return failed('no', 'direct_pay_failed_not_sent', undefined, error.detail || error.message)
58
+ }
59
+ return failed('maybe', 'direct_pay_failed_maybe_sent', { name }, messageOf(error))
60
+ }
61
+
62
+ /**
63
+ * Runs `direct` when given, else `messageBox`. A direct attempt that could not reach the
64
+ * recipient asks for the message box fallback when `messageBox` is given; the caller runs it
65
+ * after the user agrees (call again without `direct`). Either route throws a
66
+ * {@link NotSentError} when it stopped before making the payment.
67
+ */
68
+ export async function payIdentity(o: {
69
+ direct?: () => Promise<{ ackStatus: string }>
70
+ messageBox?: () => Promise<void>
71
+ /** Who is being paid, as the user knows them: a name, a handle or a short key. */
72
+ name: string
73
+ }): Promise<PayOutcome> {
74
+ if (o.direct) {
75
+ try {
76
+ const { ackStatus } = await o.direct()
77
+ return { kind: 'paid_live', ackStatus }
78
+ } catch (error) {
79
+ // Anything but a NotSentError may have reached the recipient: never offer a second payment.
80
+ if (!(error instanceof NotSentError)) return stopped(error, o.name)
81
+ switch (error.failure) {
82
+ case 'offline':
83
+ case 'rejected':
84
+ if (o.messageBox) return { kind: 'ask_fallback', reason: 'offline' }
85
+ return failed('no', 'direct_pay_failed_offline', { name: o.name })
86
+ case 'timeout':
87
+ case 'unknown':
88
+ if (o.messageBox) return { kind: 'ask_fallback', reason: 'link_failed' }
89
+ return failed('no', 'direct_pay_failed_link', { name: o.name })
90
+ case 'unavailable':
91
+ return failed('no', 'direct_pay_failed_network')
92
+ case 'wrong_network':
93
+ return failed('no', 'direct_pay_failed_wrong_network', { name: o.name })
94
+ case 'aborted':
95
+ // The user cancelled: not a reason to offer anything else.
96
+ return failed('no', 'direct_pay_failed_cancelled')
97
+ default:
98
+ return stopped(error, o.name)
99
+ }
100
+ }
101
+ }
102
+ if (!o.messageBox) return failed('no', 'direct_pay_failed_no_message_box')
103
+ try {
104
+ await o.messageBox()
105
+ return { kind: 'paid_messagebox' }
106
+ } catch (error) {
107
+ return stopped(error, o.name)
108
+ }
109
+ }
110
+
111
+ /** The fallback prompt for `reason`, naming the recipient. */
112
+ export function fallbackPrompt(reason: FallbackReason, name: string): Required<DirectPayMessage> {
113
+ return {
114
+ key: reason === 'offline' ? 'direct_pay_fallback_offline' : 'direct_pay_fallback_link_failed',
115
+ params: { name }
116
+ }
117
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The idempotency key of one payment output: `txid:outputIndex:derivationPrefix:derivationSuffix`.
3
+ * The parts cannot contain `:` (hex, digits, base64), so distinct payments never share a key.
4
+ *
5
+ * One payment is one key on every path it can arrive by (the live link, the live message box,
6
+ * the inbox list), so it is credited, and announced, once. It is the same key BSV Desktop uses
7
+ * and `@bsv/webrtpay` computes; keep the format, since a peer's `seen` store may hold it.
8
+ */
9
+ export function paymentKey(
10
+ txid: string,
11
+ outputIndex: number,
12
+ derivationPrefix: string,
13
+ derivationSuffix: string
14
+ ): string {
15
+ return `${txid}:${outputIndex}:${derivationPrefix}:${derivationSuffix}`
16
+ }
@@ -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
+ }