@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,278 @@
1
+ /**
2
+ * Settings for direct (peer-to-peer) payments, stored on this device.
3
+ *
4
+ * Device-level, not wallet-level: they are read before sign-in and survive logout, so the
5
+ * `storage` passed in must not be the wallet's own database (an AsyncStorage-backed store,
6
+ * not the wallet's key/value table, which is per wallet and cleared with it).
7
+ *
8
+ * Receiving is on by default, and wallets find each other through the public WebRTPay relay by
9
+ * default, with the message box as the other choice. There is no migration: this key is the
10
+ * first, and a stored value that is missing or no longer valid falls back to the default
11
+ * field by field.
12
+ *
13
+ * Addresses are checked with regexes, not `URL`: `URL.hostname` is unreliable on Hermes. A relay
14
+ * must be `wss://` (desktop also allows `ws://` for localhost; a phone has no local relay, so
15
+ * there is no exception here), and an address with `user:password@` in it is refused. A token in
16
+ * the query string cannot be told from any other query, so that is not.
17
+ *
18
+ * The TURN credential is stored as plain JSON beside the other settings, and AsyncStorage is
19
+ * not encrypted: do not give it a secret that matters beyond this one relay.
20
+ */
21
+ import type { KVStorage } from '../localpay/pending'
22
+ import type { DirectPaySettings, DirectPayTurn } from './types'
23
+
24
+ export const DIRECT_PAY_SETTINGS_KEY = 'direct_pay_settings_v1'
25
+
26
+ /** The public WebRTPay relay, the default way wallets find each other. */
27
+ export const DEFAULT_RELAY_URL = 'wss://webrtpay-relay-us-1.bsvblockchain.tech'
28
+
29
+ /** The default `stunUrls` is frozen; `loadDirectPaySettings` hands out copies of it. */
30
+ export const DEFAULT_DIRECT_PAY_SETTINGS: Readonly<Omit<DirectPaySettings, 'stunUrls'>> & {
31
+ readonly stunUrls: readonly string[]
32
+ } = {
33
+ receiveEnabled: true,
34
+ signaling: 'relay',
35
+ relayUrl: DEFAULT_RELAY_URL,
36
+ stunUrls: Object.freeze([
37
+ 'stun:stun-us-1.bsvb.tech:3478',
38
+ 'stun:stun.l.google.com:19302',
39
+ 'stun:stun.cloudflare.com:3478'
40
+ ])
41
+ }
42
+
43
+ // A host is a name or IPv4 address that starts and ends with a letter or digit, or a bracketed
44
+ // IPv6 address, then an optional port. No credentials, and nothing else before the path.
45
+ const HOST = String.raw`(?:[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?|\[[0-9A-Fa-f:.]+\])(?::\d{1,5})?`
46
+ /** wss:// then a host, then an optional path, query or fragment, with no spaces. */
47
+ const RELAY_URL = new RegExp(String.raw`^wss://${HOST}(?:[/?#]\S*)?$`)
48
+ /** stun:/stuns:/turn:/turns: then a host, then an optional query such as `?transport=udp`. */
49
+ const STUN_URL = new RegExp(String.raw`^stuns?:${HOST}(?:\?\S*)?$`)
50
+ const TURN_URL = new RegExp(String.raw`^turns?:${HOST}(?:\?\S*)?$`)
51
+
52
+ /** Whether `text` is a relay address as written: `wss://`, a host, no credentials. Nothing is trimmed. */
53
+ export const isRelayUrl = (text: string): boolean => RELAY_URL.test(text)
54
+
55
+ /** Whether `text` is a `stun:` / `stuns:` server as written. Nothing is trimmed. */
56
+ export const isStunUrl = (text: string): boolean => STUN_URL.test(text)
57
+
58
+ /** Which setting a {@link DirectPaySettingsError} is about. */
59
+ export type DirectPaySettingsField = keyof DirectPaySettings
60
+
61
+ /**
62
+ * Why a setting cannot be saved. `code` is for the screen to word (nothing here is English for
63
+ * the user); `message` is for developers and logs.
64
+ */
65
+ export type DirectPaySettingsProblem =
66
+ | 'receive_invalid'
67
+ | 'signaling_invalid'
68
+ | 'relay_invalid'
69
+ | 'relay_required'
70
+ | 'stun_invalid'
71
+ | 'turn_invalid'
72
+ | 'turn_incomplete'
73
+ | 'storage_failed'
74
+
75
+ export class DirectPaySettingsError extends Error {
76
+ constructor(
77
+ readonly code: DirectPaySettingsProblem,
78
+ message: string,
79
+ readonly field?: DirectPaySettingsField
80
+ ) {
81
+ super(message)
82
+ this.name = 'DirectPaySettingsError'
83
+ }
84
+ }
85
+
86
+ function checkReceiveEnabled(value: unknown): boolean {
87
+ if (typeof value !== 'boolean') {
88
+ throw new DirectPaySettingsError('receive_invalid', 'receiveEnabled must be a boolean', 'receiveEnabled')
89
+ }
90
+ return value
91
+ }
92
+
93
+ function checkSignaling(value: unknown): DirectPaySettings['signaling'] {
94
+ if (value !== 'relay' && value !== 'messagebox') {
95
+ throw new DirectPaySettingsError('signaling_invalid', "signaling must be 'relay' or 'messagebox'", 'signaling')
96
+ }
97
+ return value
98
+ }
99
+
100
+ /** An empty string means no relay is configured. */
101
+ function checkRelayUrl(value: unknown): string {
102
+ if (typeof value !== 'string') {
103
+ throw new DirectPaySettingsError('relay_invalid', 'relayUrl must be a string', 'relayUrl')
104
+ }
105
+ const text = value.trim()
106
+ if (text === '') return ''
107
+ if (!isRelayUrl(text)) {
108
+ throw new DirectPaySettingsError(
109
+ 'relay_invalid',
110
+ 'relayUrl must be a wss:// address (a host, then an optional port and path) without user:password@',
111
+ 'relayUrl'
112
+ )
113
+ }
114
+ return text
115
+ }
116
+
117
+ /** Blank entries are dropped, so a form can pass one line per server. */
118
+ function checkStunUrls(value: unknown): string[] {
119
+ if (!Array.isArray(value)) {
120
+ throw new DirectPaySettingsError('stun_invalid', 'stunUrls must be a list of stun: or stuns: addresses', 'stunUrls')
121
+ }
122
+ const urls: string[] = []
123
+ for (const entry of value) {
124
+ const text = typeof entry === 'string' ? entry.trim() : null
125
+ if (text === '') continue
126
+ if (text === null || !isStunUrl(text)) {
127
+ throw new DirectPaySettingsError(
128
+ 'stun_invalid',
129
+ `STUN server "${String(entry)}" must start with stun: or stuns:`,
130
+ 'stunUrls'
131
+ )
132
+ }
133
+ urls.push(text)
134
+ }
135
+ return urls
136
+ }
137
+
138
+ /** Absent, or a form with every field blank, means no TURN server. */
139
+ function checkTurn(value: unknown): DirectPayTurn | undefined {
140
+ if (value === undefined || value === null) return undefined
141
+ if (typeof value !== 'object') {
142
+ throw new DirectPaySettingsError('turn_invalid', 'turn must be an object', 'turn')
143
+ }
144
+ const { urls, username, credential } = value as Record<string, unknown>
145
+ const text = (field: unknown) => (typeof field === 'string' ? field.trim() : null)
146
+ const [turnUrls, turnUser, turnCredential] = [text(urls), text(username), text(credential)]
147
+ if (!turnUrls && !turnUser && !turnCredential) return undefined
148
+ if (!turnUrls || !TURN_URL.test(turnUrls)) {
149
+ throw new DirectPaySettingsError('turn_invalid', 'the TURN server must start with turn: or turns:', 'turn')
150
+ }
151
+ if (!turnUser || !turnCredential) {
152
+ throw new DirectPaySettingsError('turn_incomplete', 'a TURN server needs both a username and a credential', 'turn')
153
+ }
154
+ return { urls: turnUrls, username: turnUser, credential: turnCredential }
155
+ }
156
+
157
+ function withTurn(settings: Omit<DirectPaySettings, 'turn'>, turn: DirectPayTurn | undefined): DirectPaySettings {
158
+ return turn ? { ...settings, turn } : settings
159
+ }
160
+
161
+ /**
162
+ * This build's own relay and STUN servers (`ToolboxConfig.directPay`), which stand in for the
163
+ * built-in ones. Checked by `configureToolbox` with the same rules as the user's settings.
164
+ */
165
+ export interface DirectPayHostDefaults {
166
+ relayUrl?: string
167
+ stunUrls?: readonly string[]
168
+ }
169
+
170
+ /** The defaults with this build's relay and STUN servers in place of the built-in ones. */
171
+ function defaultsWith(host: DirectPayHostDefaults | undefined): typeof DEFAULT_DIRECT_PAY_SETTINGS {
172
+ if (!host?.relayUrl && !host?.stunUrls) return DEFAULT_DIRECT_PAY_SETTINGS
173
+ return {
174
+ ...DEFAULT_DIRECT_PAY_SETTINGS,
175
+ ...(host.relayUrl ? { relayUrl: host.relayUrl } : {}),
176
+ ...(host.stunUrls ? { stunUrls: Object.freeze([...host.stunUrls]) } : {})
177
+ }
178
+ }
179
+
180
+ /**
181
+ * The stored settings, with the default for each field that is missing or no longer valid.
182
+ * Never throws: unreadable or corrupt storage gives the defaults. `host` replaces the
183
+ * built-in relay and STUN defaults; what the user saved wins over both.
184
+ */
185
+ export async function loadDirectPaySettings(
186
+ storage: KVStorage,
187
+ host?: DirectPayHostDefaults
188
+ ): Promise<DirectPaySettings> {
189
+ const defaults = defaultsWith(host)
190
+ let stored: Record<string, unknown> = {}
191
+ try {
192
+ const parsed: unknown = JSON.parse((await storage.getKeyValue(DIRECT_PAY_SETTINGS_KEY)) ?? 'null')
193
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) stored = parsed as Record<string, unknown>
194
+ } catch {
195
+ // Corrupt or unreadable storage: the defaults apply.
196
+ }
197
+
198
+ const field = <T>(check: (value: unknown) => T, value: unknown, fallback: T): T => {
199
+ try {
200
+ return check(value)
201
+ } catch {
202
+ return fallback
203
+ }
204
+ }
205
+
206
+ const settings = withTurn(
207
+ {
208
+ receiveEnabled: field(checkReceiveEnabled, stored.receiveEnabled, defaults.receiveEnabled),
209
+ signaling: field(checkSignaling, stored.signaling, defaults.signaling),
210
+ relayUrl: field(checkRelayUrl, stored.relayUrl, defaults.relayUrl),
211
+ stunUrls: field(checkStunUrls, stored.stunUrls, [...defaults.stunUrls])
212
+ },
213
+ field(checkTurn, stored.turn, undefined)
214
+ )
215
+ // `saveDirectPaySettings` never stores relay signaling with no relay; a store edited by hand might.
216
+ if (settings.signaling === 'relay' && !settings.relayUrl) settings.relayUrl = defaults.relayUrl
217
+ return settings
218
+ }
219
+
220
+ /**
221
+ * Validates and stores the settings. Fields left out take their defaults (`host`'s relay and
222
+ * STUN servers in place of the built-in ones), so the argument describes the whole stored
223
+ * state. Throws a {@link DirectPaySettingsError} and stores nothing when a value is not
224
+ * acceptable; relay signaling needs a relay URL.
225
+ */
226
+ export async function saveDirectPaySettings(
227
+ storage: KVStorage,
228
+ input: Partial<DirectPaySettings>,
229
+ host?: DirectPayHostDefaults
230
+ ): Promise<DirectPaySettings> {
231
+ const defaults = defaultsWith(host)
232
+ const settings = withTurn(
233
+ {
234
+ receiveEnabled: checkReceiveEnabled(input.receiveEnabled ?? defaults.receiveEnabled),
235
+ signaling: checkSignaling(input.signaling ?? defaults.signaling),
236
+ relayUrl: checkRelayUrl(input.relayUrl ?? defaults.relayUrl),
237
+ stunUrls: checkStunUrls(input.stunUrls ?? defaults.stunUrls)
238
+ },
239
+ checkTurn(input.turn)
240
+ )
241
+ if (settings.signaling === 'relay' && !settings.relayUrl) {
242
+ throw new DirectPaySettingsError(
243
+ 'relay_required',
244
+ 'relay signaling needs a relayUrl; use the message box instead',
245
+ 'relayUrl'
246
+ )
247
+ }
248
+ try {
249
+ await storage.setKeyValue(DIRECT_PAY_SETTINGS_KEY, JSON.stringify(settings))
250
+ } catch (e) {
251
+ throw new DirectPaySettingsError(
252
+ 'storage_failed',
253
+ `direct payment settings could not be stored: ${e instanceof Error ? e.message : String(e)}`
254
+ )
255
+ }
256
+ return settings
257
+ }
258
+
259
+ /** An ICE server as WebRTC takes it. Declared here so this module needs no DOM or WebRTC types. */
260
+ export interface IceServer {
261
+ urls: string | string[]
262
+ username?: string
263
+ credential?: string
264
+ }
265
+
266
+ /** The ICE servers for a connection: the STUN list, then TURN with its credentials. */
267
+ export function iceServersFrom(settings: { stunUrls: readonly string[]; turn?: DirectPayTurn }): IceServer[] {
268
+ const servers: IceServer[] = []
269
+ if (settings.stunUrls.length > 0) servers.push({ urls: [...settings.stunUrls] })
270
+ if (settings.turn) {
271
+ servers.push({
272
+ urls: settings.turn.urls,
273
+ username: settings.turn.username,
274
+ credential: settings.turn.credential
275
+ })
276
+ }
277
+ return servers
278
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * What the direct-pay manager's state means for the user: the Receive tab's card about taking
3
+ * live payments. Returns i18n keys, never English, so the screen words it in the user's
4
+ * language; the state itself comes from the manager (a later change), as plain data.
5
+ */
6
+ import type { DirectPayState, DirectPayStatusInput, LiveStatus } from './types'
7
+
8
+ /** The manager's state, reduced to what the user is told. */
9
+ export function directPayState(
10
+ s: Pick<DirectPayStatusInput, 'status' | 'via' | 'notice' | 'relayUnreachable'>
11
+ ): DirectPayState {
12
+ switch (s.status) {
13
+ case 'starting':
14
+ return 'starting'
15
+ case 'online':
16
+ return s.via === 'relay' ? 'online_relay' : s.relayUnreachable ? 'online_fallback' : 'online_messagebox'
17
+ case 'error':
18
+ return 'failed'
19
+ default:
20
+ return s.notice ? 'not_set_up' : 'off'
21
+ }
22
+ }
23
+
24
+ /** The Receive card for `s`, naming the way it receives. */
25
+ export function liveStatus(s: DirectPayStatusInput): LiveStatus {
26
+ switch (directPayState(s)) {
27
+ case 'online_relay':
28
+ return { tone: 'on', titleKey: 'direct_pay_status_on_title', bodyKey: 'direct_pay_status_on_relay' }
29
+ case 'online_messagebox':
30
+ return { tone: 'on', titleKey: 'direct_pay_status_on_title', bodyKey: 'direct_pay_status_on_messagebox' }
31
+ case 'online_fallback':
32
+ return { tone: 'on', titleKey: 'direct_pay_status_on_title', bodyKey: 'direct_pay_status_on_fallback' }
33
+ case 'starting':
34
+ return {
35
+ tone: 'connecting',
36
+ titleKey: 'direct_pay_status_connecting_title',
37
+ bodyKey: 'direct_pay_status_connecting_body'
38
+ }
39
+ // No message box to signal through: off, and the body says why.
40
+ case 'not_set_up':
41
+ return { tone: 'off', titleKey: 'direct_pay_status_off_title', bodyKey: 'direct_pay_status_not_set_up_body' }
42
+ case 'failed':
43
+ return {
44
+ tone: 'error',
45
+ titleKey: 'direct_pay_status_error_title',
46
+ bodyKey: 'direct_pay_status_error_body',
47
+ ...(s.error && { detail: s.error })
48
+ }
49
+ default:
50
+ return { tone: 'off', titleKey: 'direct_pay_status_off_title', bodyKey: 'direct_pay_status_off_body' }
51
+ }
52
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Shapes shared by the direct-pay (push payment) core: the device settings, why a dial
3
+ * failed, how paying a wallet identity ended, and what the Receive card shows.
4
+ *
5
+ * Direct payments are a live link between two wallets (WebRTC), tried before the message box.
6
+ * Nothing in this folder imports `@bsv/webrtpay` or a native module: `webrtpay.ts` requires the
7
+ * package lazily, and the rest is handed it (and the host's `RTCPeerConnection`) as plain
8
+ * dependencies.
9
+ */
10
+ import type { TranslationKey } from '../i18n/translations'
11
+
12
+ /** A TURN server, for testing; it may relay the encrypted link when two wallets cannot connect directly. */
13
+ export interface DirectPayTurn {
14
+ urls: string
15
+ username: string
16
+ credential: string
17
+ }
18
+
19
+ /**
20
+ * Settings for direct payments, one set per device (not per wallet or profile) so they are
21
+ * readable before sign-in and survive logout.
22
+ *
23
+ * Receiving is on by default. While it is on, any wallet that knows the identity key can learn
24
+ * this device's public IP address and when the wallet is open, by starting a connection without
25
+ * paying. On mobile receiving only runs while the app is in the foreground; the switch here is
26
+ * the user's choice, and the manager that listens enforces the foreground rule.
27
+ * Sending directly needs no setting, and reveals the payer's IP address to the recipient's wallet.
28
+ */
29
+ export interface DirectPaySettings {
30
+ /** Answer direct payments from other wallets. On unless the user turns it off. */
31
+ receiveEnabled: boolean
32
+ /** How the two wallets find each other before connecting. */
33
+ signaling: 'relay' | 'messagebox'
34
+ /** wss:// signaling relay. Used when `signaling` is 'relay'. */
35
+ relayUrl: string
36
+ /** stun: / stuns: servers used to discover this device's public address. */
37
+ stunUrls: string[]
38
+ /** Optional TURN server. */
39
+ turn?: DirectPayTurn
40
+ }
41
+
42
+ /**
43
+ * Why dialing a recipient failed, for choosing what to offer the user (see `payIdentity`):
44
+ *
45
+ * - `offline`: no reply within the presence window, or the signaling relay could not be
46
+ * reached at all (the package raises `peer_unreachable` for both).
47
+ * - `rejected`: their wallet answered and is not taking direct payments, or is busy.
48
+ * - `unavailable`: the signaling service answered but could not do its part (the relay could
49
+ * not issue TURN credentials, or MessageBox could not deliver the signal).
50
+ * - `timeout`: they answered, but the link or its identity handshake did not come up in time.
51
+ * - `wrong_network`: the two wallets are on different networks.
52
+ * - `aborted`: the dial was cancelled.
53
+ * - `unknown`: anything else (a refusal with some other reason, a closed link, a bad handshake).
54
+ */
55
+ export type DialFailure = 'offline' | 'rejected' | 'unavailable' | 'timeout' | 'wrong_network' | 'aborted' | 'unknown'
56
+
57
+ /** Some wording for the user, as an i18n key and its parameters (core modules never return English). */
58
+ export interface DirectPayMessage {
59
+ key: TranslationKey
60
+ params?: { name: string }
61
+ }
62
+
63
+ /** Why a live attempt is offering the message box: the recipient is not there, or the link failed. */
64
+ export type FallbackReason = 'offline' | 'link_failed'
65
+
66
+ /** Paying stopped, and nothing more is offered. */
67
+ export interface PayFailure extends DirectPayMessage {
68
+ kind: 'failed'
69
+ /**
70
+ * Whether money may have left the wallet. `no`: the attempt stopped before any payment was
71
+ * made (a `NotSentError`). `maybe`: the payment was made and may have been delivered, so the
72
+ * caller must not start a second one; the wording says so.
73
+ */
74
+ spent: 'no' | 'maybe'
75
+ /** The error's own words (English), when the wording cannot carry them. For logs and diagnosis. */
76
+ detail?: string
77
+ }
78
+
79
+ /** How paying a wallet identity ended, or what the user is asked next. */
80
+ export type PayOutcome =
81
+ | { kind: 'paid_live'; ackStatus: string }
82
+ | { kind: 'paid_messagebox' }
83
+ | { kind: 'ask_fallback'; reason: FallbackReason }
84
+ | PayFailure
85
+
86
+ /**
87
+ * `off`: not receiving; `starting`: setting up receiving, or connecting to the relay;
88
+ * `online`: receiving; `error`: see `error`.
89
+ */
90
+ export type DirectPayStatus = 'off' | 'starting' | 'online' | 'error'
91
+
92
+ /** The part of the manager's state the Receive card is drawn from. */
93
+ export interface DirectPayStatusInput {
94
+ status: DirectPayStatus
95
+ /** How this wallet reaches others by identity key; null when it cannot. */
96
+ via: 'messagebox' | 'relay' | null
97
+ /** Why `status` is `error`, for the log; empty otherwise. */
98
+ error: string
99
+ /** Why direct payments are not set up when that is not a failure (no message box); empty otherwise. */
100
+ notice: string
101
+ /**
102
+ * The settings choose the relay but it cannot be reached, so `via` is the message box until it
103
+ * can be. False or absent otherwise.
104
+ */
105
+ relayUnreachable?: boolean
106
+ }
107
+
108
+ /**
109
+ * What the manager's state means. `not_set_up`: receiving is off because there is nothing to
110
+ * signal through, which is not a failure. `failed`: a real error. `online_fallback`: receiving
111
+ * through the message box because the relay the settings choose cannot be reached.
112
+ */
113
+ export type DirectPayState =
114
+ | 'off'
115
+ | 'starting'
116
+ | 'online_messagebox'
117
+ | 'online_relay'
118
+ | 'online_fallback'
119
+ | 'not_set_up'
120
+ | 'failed'
121
+
122
+ /** The Receive tab's card about receiving live payments. */
123
+ export interface LiveStatus {
124
+ tone: 'on' | 'off' | 'connecting' | 'error'
125
+ titleKey: TranslationKey
126
+ bodyKey: TranslationKey
127
+ /** The manager's own error text, on `error`, for the log. Not for the user. */
128
+ detail?: string
129
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * `@bsv/webrtpay` as the toolbox uses it. It is an optional peer dependency: a host that offers
3
+ * direct payments installs it (with react-native-webrtc), and every other host has none.
4
+ *
5
+ * So nothing in the toolbox imports it, not even for types. The package ships as TypeScript
6
+ * source, and a type import of a module a host does not have fails that host's type check. The
7
+ * shapes below are the slices the toolbox calls, written out by hand;
8
+ * `__tests__/directpay/webrtpayShape.test.ts` checks at type level that the real package fits
9
+ * them, so a release that changes one fails there rather than on a phone.
10
+ *
11
+ * The package is required lazily, inside a `try`, the way `services/vault/driver.ts` requires
12
+ * react-native-yubikey: Metro skips a missing module there because Expo's Metro config turns on
13
+ * `allowOptionalDependencies`, and requiring it only on first use keeps the barrel import free
14
+ * of it. `loadWebRTPay()` is null when it is not installed (or will not load).
15
+ */
16
+ import type { WalletInterface } from '@bsv/sdk'
17
+ import type { IceServer } from './settings'
18
+
19
+ /** The slice of a BRC-100 wallet `@bsv/webrtpay` uses (its `WalletLike`). */
20
+ export type WebRTPayWallet = Pick<
21
+ WalletInterface,
22
+ | 'getPublicKey'
23
+ | 'createSignature'
24
+ | 'verifySignature'
25
+ | 'encrypt'
26
+ | 'decrypt'
27
+ | 'createHmac'
28
+ | 'verifyHmac'
29
+ | 'internalizeAction'
30
+ >
31
+
32
+ /** `WebRTPayError`: `code` says what failed; `reason` is a refusal's reason (`busy`, …). */
33
+ export interface WebRTPayErrorLike extends Error {
34
+ readonly code: string
35
+ readonly reason?: string
36
+ }
37
+
38
+ /** A payment token as it goes over the link (PeerPay's `PaymentToken`). */
39
+ export interface DirectPaymentToken {
40
+ customInstructions: { derivationPrefix: string; derivationSuffix: string }
41
+ transaction: number[]
42
+ amount: number
43
+ outputIndex?: number
44
+ }
45
+
46
+ /** A payment from an authenticated peer: `sender` is the peer's proven identity key. */
47
+ export interface IncomingDirectPayment {
48
+ messageId: string
49
+ sender: string
50
+ token: DirectPaymentToken
51
+ outputIndex?: number
52
+ }
53
+
54
+ /** What this wallet answers a payment with: in the wallet, kept for a retry, or refused. */
55
+ export type DirectPaymentDecision = 'accepted' | 'received' | { status: 'rejected'; reason: string }
56
+
57
+ /** The payee's answer to a payment. */
58
+ export interface DirectPaymentAck {
59
+ status: 'accepted' | 'received' | 'rejected'
60
+ txid?: string
61
+ reason?: string
62
+ }
63
+
64
+ /** An authenticated link to one peer. */
65
+ export interface DirectPeer {
66
+ readonly peerIdentityKey: string
67
+ readonly isOpen: boolean
68
+ close(): void
69
+ }
70
+
71
+ export interface DirectReceiveHandlers {
72
+ onPayment(p: IncomingDirectPayment, ctx: { note?: string; txid: string }): Promise<DirectPaymentDecision>
73
+ onError?(e: unknown): void
74
+ }
75
+
76
+ /** `DirectPayClient`: dials, sends, and receives while listening. */
77
+ export interface DirectPayClientLike {
78
+ startReceiving(h: DirectReceiveHandlers): Promise<void>
79
+ stopReceiving(): Promise<void>
80
+ connect(recipient: string, o?: { signal?: AbortSignal }): Promise<DirectPeer>
81
+ sendPayment(peer: DirectPeer, token: DirectPaymentToken, o?: { note?: string }): Promise<DirectPaymentAck>
82
+ close(): Promise<void>
83
+ }
84
+
85
+ /** An encrypted signal as a carrier moves it; the toolbox never opens one. */
86
+ export interface SignalEnvelopeLike {
87
+ v: 1
88
+ sid: string
89
+ ciphertext: string
90
+ }
91
+
92
+ /** A carrier for signals: the message box or a relay. */
93
+ export interface SignalerLike {
94
+ send(to: string, e: SignalEnvelopeLike): Promise<void>
95
+ listen(fn: (from: string, e: SignalEnvelopeLike) => void): Promise<() => Promise<void>>
96
+ }
97
+
98
+ /** `connecting` while it opens, `online` once the relay accepted this wallet, else `offline`. */
99
+ export type RelayState = 'connecting' | 'online' | 'offline'
100
+
101
+ export interface RelaySignalerLike extends SignalerLike {
102
+ close(): Promise<void>
103
+ /** The relay's short-lived TURN servers, for `iceServersProvider`. */
104
+ turnProvider(): () => Promise<IceServer[]>
105
+ }
106
+
107
+ /**
108
+ * The message box client as the signaler uses it. message-box-client's `PeerPayClient` is one
109
+ * (pinned at type level in `__tests__/directpay/webrtpayShape.test.ts`); its live websocket
110
+ * calls make the signaler fast enough for the dial's presence window.
111
+ */
112
+ export interface MessageBoxLike {
113
+ sendMessage(a: { recipient: string; messageBox: string; body: string }, overrideHost?: string): Promise<unknown>
114
+ listMessages(a: {
115
+ messageBox: string
116
+ host?: string
117
+ limit?: number
118
+ pageSize?: number
119
+ maxPages?: number
120
+ acceptPayments?: boolean
121
+ }): Promise<{ messageId: string; sender: string; body: string | Record<string, unknown> }[]>
122
+ acknowledgeMessage(a: { messageIds: string[]; host?: string }): Promise<unknown>
123
+ resolveHostForRecipient?(identityKey: string): Promise<string>
124
+ sendLiveMessage?(a: { recipient: string; messageBox: string; body: string }, overrideHost?: string): Promise<unknown>
125
+ listenForLiveMessages?(a: {
126
+ messageBox: string
127
+ overrideHost?: string
128
+ onMessage: (m: { messageId: string; sender: string; body: string | Record<string, unknown> }) => void
129
+ }): Promise<void>
130
+ joinRoom?(messageBox: string, overrideHost?: string): Promise<void>
131
+ leaveRoom?(messageBox: string): Promise<void>
132
+ }
133
+
134
+ export interface DirectPayClientOptions {
135
+ wallet: WebRTPayWallet
136
+ originator?: string
137
+ signaler?: SignalerLike
138
+ rtc?: {
139
+ iceServers?: IceServer[]
140
+ /**
141
+ * The host's constructor (react-native-webrtc's on a phone). `any` because the package
142
+ * wants the DOM's `typeof RTCPeerConnection`, and the toolbox has no WebRTC types.
143
+ */
144
+ RTCPeerConnection?: any
145
+ }
146
+ iceServersProvider?: () => Promise<IceServer[]>
147
+ onIceServersProviderError?: (e: unknown) => void
148
+ chain?: string
149
+ timeouts?: { connectMs?: number; ackMs?: number; presenceMs?: number; dialMs?: number }
150
+ }
151
+
152
+ export interface RelaySignalerOptions {
153
+ url: string
154
+ wallet: Pick<WebRTPayWallet, 'getPublicKey' | 'createSignature'>
155
+ originator?: string
156
+ onStateChange?: (state: RelayState, error?: WebRTPayErrorLike) => void
157
+ }
158
+
159
+ /** A seen store: which payments were already taken (`paymentKey`). */
160
+ export interface DirectPaySeenStore {
161
+ has(key: string): boolean | Promise<boolean>
162
+ add(key: string): void | Promise<void>
163
+ }
164
+
165
+ /** The module, as far as the toolbox calls it. */
166
+ export interface WebRTPayModule {
167
+ DirectPayClient: new (o: DirectPayClientOptions) => DirectPayClientLike
168
+ MessageBoxSignaler: new (client: MessageBoxLike, o?: { messageBox?: string; host?: string }) => SignalerLike
169
+ RelaySignaler: new (o: RelaySignalerOptions) => RelaySignalerLike
170
+ WebRTPayError: new (
171
+ code: 'rejected' | 'invalid_payment',
172
+ message?: string,
173
+ o?: { cause?: unknown; reason?: string }
174
+ ) => WebRTPayErrorLike
175
+ acceptDirectPayment(
176
+ wallet: WebRTPayWallet,
177
+ p: IncomingDirectPayment,
178
+ o?: { originator?: string; seen?: DirectPaySeenStore; labels?: string[]; description?: string }
179
+ ): Promise<{ txid: string; status: 'accepted' | 'duplicate' }>
180
+ validatePaymentToken(token: DirectPaymentToken, note?: string): void
181
+ readonly MAX_DIRECT_TRANSACTION_BYTES: number
182
+ }
183
+
184
+ let loaded: WebRTPayModule | null | undefined
185
+
186
+ /** `@bsv/webrtpay`, or null when this host does not have it. Required once, on first use. */
187
+ export function loadWebRTPay(): WebRTPayModule | null {
188
+ if (loaded !== undefined) return loaded
189
+ try {
190
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
191
+ loaded = require('@bsv/webrtpay') as WebRTPayModule
192
+ } catch (e) {
193
+ console.warn('[directpay] @bsv/webrtpay is not available:', e instanceof Error ? e.message : String(e))
194
+ loaded = null
195
+ }
196
+ return loaded
197
+ }
198
+
199
+ /** Replaces what {@link loadWebRTPay} returns; `undefined` loads the package again. Tests only. */
200
+ export function setWebRTPayForTests(m: WebRTPayModule | null | undefined): void {
201
+ loaded = m
202
+ }
203
+
204
+ /** Whether `e` is a `WebRTPayError` of `mod`, or one that lost its prototype on the way (duck-typed). */
205
+ export function isWebRTPayError(mod: Pick<WebRTPayModule, 'WebRTPayError'>, e: unknown): e is WebRTPayErrorLike {
206
+ if (e instanceof mod.WebRTPayError) return true
207
+ return typeof e === 'object' && e !== null && (e as { name?: unknown }).name === 'WebRTPayError'
208
+ }