@bsv/expo-wallet-toolbox 0.16.0 → 0.17.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.
- package/CHANGELOG.md +41 -0
- package/core/backup/restore.ts +26 -4
- package/core/backup/restoreOnImport.ts +13 -4
- package/core/context/WalletContext.tsx +251 -74
- package/core/directpay/dialFailure.ts +56 -0
- package/core/directpay/index.ts +7 -0
- package/core/directpay/payFlow.ts +117 -0
- package/core/directpay/paymentKey.ts +16 -0
- package/core/directpay/settings.ts +253 -0
- package/core/directpay/status.ts +52 -0
- package/core/directpay/types.ts +128 -0
- package/core/i18n/translations.tsx +354 -12
- package/core/index.ts +12 -1
- package/core/profiles/discovery.ts +17 -8
- package/core/profiles/profileStore.ts +34 -7
- package/core/services/callbackToken.ts +7 -0
- package/core/toolboxConfig.ts +63 -1
- package/package.json +1 -1
|
@@ -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,253 @@
|
|
|
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
|
+
* The stored settings, with the default for each field that is missing or no longer valid.
|
|
163
|
+
* Never throws: unreadable or corrupt storage gives the defaults.
|
|
164
|
+
*/
|
|
165
|
+
export async function loadDirectPaySettings(storage: KVStorage): Promise<DirectPaySettings> {
|
|
166
|
+
const defaults = DEFAULT_DIRECT_PAY_SETTINGS
|
|
167
|
+
let stored: Record<string, unknown> = {}
|
|
168
|
+
try {
|
|
169
|
+
const parsed: unknown = JSON.parse((await storage.getKeyValue(DIRECT_PAY_SETTINGS_KEY)) ?? 'null')
|
|
170
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) stored = parsed as Record<string, unknown>
|
|
171
|
+
} catch {
|
|
172
|
+
// Corrupt or unreadable storage: the defaults apply.
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const field = <T>(check: (value: unknown) => T, value: unknown, fallback: T): T => {
|
|
176
|
+
try {
|
|
177
|
+
return check(value)
|
|
178
|
+
} catch {
|
|
179
|
+
return fallback
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const settings = withTurn(
|
|
184
|
+
{
|
|
185
|
+
receiveEnabled: field(checkReceiveEnabled, stored.receiveEnabled, defaults.receiveEnabled),
|
|
186
|
+
signaling: field(checkSignaling, stored.signaling, defaults.signaling),
|
|
187
|
+
relayUrl: field(checkRelayUrl, stored.relayUrl, defaults.relayUrl),
|
|
188
|
+
stunUrls: field(checkStunUrls, stored.stunUrls, [...defaults.stunUrls])
|
|
189
|
+
},
|
|
190
|
+
field(checkTurn, stored.turn, undefined)
|
|
191
|
+
)
|
|
192
|
+
// `saveDirectPaySettings` never stores relay signaling with no relay; a store edited by hand might.
|
|
193
|
+
if (settings.signaling === 'relay' && !settings.relayUrl) settings.relayUrl = defaults.relayUrl
|
|
194
|
+
return settings
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Validates and stores the settings. Fields left out take their defaults, so the argument
|
|
199
|
+
* describes the whole stored state. Throws a {@link DirectPaySettingsError} and stores nothing
|
|
200
|
+
* when a value is not acceptable; relay signaling needs a relay URL.
|
|
201
|
+
*/
|
|
202
|
+
export async function saveDirectPaySettings(
|
|
203
|
+
storage: KVStorage,
|
|
204
|
+
input: Partial<DirectPaySettings>
|
|
205
|
+
): Promise<DirectPaySettings> {
|
|
206
|
+
const defaults = DEFAULT_DIRECT_PAY_SETTINGS
|
|
207
|
+
const settings = withTurn(
|
|
208
|
+
{
|
|
209
|
+
receiveEnabled: checkReceiveEnabled(input.receiveEnabled ?? defaults.receiveEnabled),
|
|
210
|
+
signaling: checkSignaling(input.signaling ?? defaults.signaling),
|
|
211
|
+
relayUrl: checkRelayUrl(input.relayUrl ?? defaults.relayUrl),
|
|
212
|
+
stunUrls: checkStunUrls(input.stunUrls ?? defaults.stunUrls)
|
|
213
|
+
},
|
|
214
|
+
checkTurn(input.turn)
|
|
215
|
+
)
|
|
216
|
+
if (settings.signaling === 'relay' && !settings.relayUrl) {
|
|
217
|
+
throw new DirectPaySettingsError(
|
|
218
|
+
'relay_required',
|
|
219
|
+
'relay signaling needs a relayUrl; use the message box instead',
|
|
220
|
+
'relayUrl'
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
await storage.setKeyValue(DIRECT_PAY_SETTINGS_KEY, JSON.stringify(settings))
|
|
225
|
+
} catch (e) {
|
|
226
|
+
throw new DirectPaySettingsError(
|
|
227
|
+
'storage_failed',
|
|
228
|
+
`direct payment settings could not be stored: ${e instanceof Error ? e.message : String(e)}`
|
|
229
|
+
)
|
|
230
|
+
}
|
|
231
|
+
return settings
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** An ICE server as WebRTC takes it. Declared here so this module needs no DOM or WebRTC types. */
|
|
235
|
+
export interface IceServer {
|
|
236
|
+
urls: string | string[]
|
|
237
|
+
username?: string
|
|
238
|
+
credential?: string
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** The ICE servers for a connection: the STUN list, then TURN with its credentials. */
|
|
242
|
+
export function iceServersFrom(settings: { stunUrls: readonly string[]; turn?: DirectPayTurn }): IceServer[] {
|
|
243
|
+
const servers: IceServer[] = []
|
|
244
|
+
if (settings.stunUrls.length > 0) servers.push({ urls: [...settings.stunUrls] })
|
|
245
|
+
if (settings.turn) {
|
|
246
|
+
servers.push({
|
|
247
|
+
urls: settings.turn.urls,
|
|
248
|
+
username: settings.turn.username,
|
|
249
|
+
credential: settings.turn.credential
|
|
250
|
+
})
|
|
251
|
+
}
|
|
252
|
+
return servers
|
|
253
|
+
}
|
|
@@ -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,128 @@
|
|
|
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; the pieces that do arrive
|
|
7
|
+
* in later changes and are handed to these functions as plain dependencies.
|
|
8
|
+
*/
|
|
9
|
+
import type { TranslationKey } from '../i18n/translations'
|
|
10
|
+
|
|
11
|
+
/** A TURN server, for testing; it may relay the encrypted link when two wallets cannot connect directly. */
|
|
12
|
+
export interface DirectPayTurn {
|
|
13
|
+
urls: string
|
|
14
|
+
username: string
|
|
15
|
+
credential: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Settings for direct payments, one set per device (not per wallet or profile) so they are
|
|
20
|
+
* readable before sign-in and survive logout.
|
|
21
|
+
*
|
|
22
|
+
* Receiving is on by default. While it is on, any wallet that knows the identity key can learn
|
|
23
|
+
* this device's public IP address and when the wallet is open, by starting a connection without
|
|
24
|
+
* paying. On mobile receiving only runs while the app is in the foreground; the switch here is
|
|
25
|
+
* the user's choice, and the manager that listens enforces the foreground rule.
|
|
26
|
+
* Sending directly needs no setting, and reveals the payer's IP address to the recipient's wallet.
|
|
27
|
+
*/
|
|
28
|
+
export interface DirectPaySettings {
|
|
29
|
+
/** Answer direct payments from other wallets. On unless the user turns it off. */
|
|
30
|
+
receiveEnabled: boolean
|
|
31
|
+
/** How the two wallets find each other before connecting. */
|
|
32
|
+
signaling: 'relay' | 'messagebox'
|
|
33
|
+
/** wss:// signaling relay. Used when `signaling` is 'relay'. */
|
|
34
|
+
relayUrl: string
|
|
35
|
+
/** stun: / stuns: servers used to discover this device's public address. */
|
|
36
|
+
stunUrls: string[]
|
|
37
|
+
/** Optional TURN server. */
|
|
38
|
+
turn?: DirectPayTurn
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Why dialing a recipient failed, for choosing what to offer the user (see `payIdentity`):
|
|
43
|
+
*
|
|
44
|
+
* - `offline`: no reply within the presence window, or the signaling relay could not be
|
|
45
|
+
* reached at all (the package raises `peer_unreachable` for both).
|
|
46
|
+
* - `rejected`: their wallet answered and is not taking direct payments, or is busy.
|
|
47
|
+
* - `unavailable`: the signaling service answered but could not do its part (the relay could
|
|
48
|
+
* not issue TURN credentials, or MessageBox could not deliver the signal).
|
|
49
|
+
* - `timeout`: they answered, but the link or its identity handshake did not come up in time.
|
|
50
|
+
* - `wrong_network`: the two wallets are on different networks.
|
|
51
|
+
* - `aborted`: the dial was cancelled.
|
|
52
|
+
* - `unknown`: anything else (a refusal with some other reason, a closed link, a bad handshake).
|
|
53
|
+
*/
|
|
54
|
+
export type DialFailure = 'offline' | 'rejected' | 'unavailable' | 'timeout' | 'wrong_network' | 'aborted' | 'unknown'
|
|
55
|
+
|
|
56
|
+
/** Some wording for the user, as an i18n key and its parameters (core modules never return English). */
|
|
57
|
+
export interface DirectPayMessage {
|
|
58
|
+
key: TranslationKey
|
|
59
|
+
params?: { name: string }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Why a live attempt is offering the message box: the recipient is not there, or the link failed. */
|
|
63
|
+
export type FallbackReason = 'offline' | 'link_failed'
|
|
64
|
+
|
|
65
|
+
/** Paying stopped, and nothing more is offered. */
|
|
66
|
+
export interface PayFailure extends DirectPayMessage {
|
|
67
|
+
kind: 'failed'
|
|
68
|
+
/**
|
|
69
|
+
* Whether money may have left the wallet. `no`: the attempt stopped before any payment was
|
|
70
|
+
* made (a `NotSentError`). `maybe`: the payment was made and may have been delivered, so the
|
|
71
|
+
* caller must not start a second one; the wording says so.
|
|
72
|
+
*/
|
|
73
|
+
spent: 'no' | 'maybe'
|
|
74
|
+
/** The error's own words (English), when the wording cannot carry them. For logs and diagnosis. */
|
|
75
|
+
detail?: string
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** How paying a wallet identity ended, or what the user is asked next. */
|
|
79
|
+
export type PayOutcome =
|
|
80
|
+
| { kind: 'paid_live'; ackStatus: string }
|
|
81
|
+
| { kind: 'paid_messagebox' }
|
|
82
|
+
| { kind: 'ask_fallback'; reason: FallbackReason }
|
|
83
|
+
| PayFailure
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `off`: not receiving; `starting`: setting up receiving, or connecting to the relay;
|
|
87
|
+
* `online`: receiving; `error`: see `error`.
|
|
88
|
+
*/
|
|
89
|
+
export type DirectPayStatus = 'off' | 'starting' | 'online' | 'error'
|
|
90
|
+
|
|
91
|
+
/** The part of the manager's state the Receive card is drawn from. */
|
|
92
|
+
export interface DirectPayStatusInput {
|
|
93
|
+
status: DirectPayStatus
|
|
94
|
+
/** How this wallet reaches others by identity key; null when it cannot. */
|
|
95
|
+
via: 'messagebox' | 'relay' | null
|
|
96
|
+
/** Why `status` is `error`, for the log; empty otherwise. */
|
|
97
|
+
error: string
|
|
98
|
+
/** Why direct payments are not set up when that is not a failure (no message box); empty otherwise. */
|
|
99
|
+
notice: string
|
|
100
|
+
/**
|
|
101
|
+
* The settings choose the relay but it cannot be reached, so `via` is the message box until it
|
|
102
|
+
* can be. False or absent otherwise.
|
|
103
|
+
*/
|
|
104
|
+
relayUnreachable?: boolean
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* What the manager's state means. `not_set_up`: receiving is off because there is nothing to
|
|
109
|
+
* signal through, which is not a failure. `failed`: a real error. `online_fallback`: receiving
|
|
110
|
+
* through the message box because the relay the settings choose cannot be reached.
|
|
111
|
+
*/
|
|
112
|
+
export type DirectPayState =
|
|
113
|
+
| 'off'
|
|
114
|
+
| 'starting'
|
|
115
|
+
| 'online_messagebox'
|
|
116
|
+
| 'online_relay'
|
|
117
|
+
| 'online_fallback'
|
|
118
|
+
| 'not_set_up'
|
|
119
|
+
| 'failed'
|
|
120
|
+
|
|
121
|
+
/** The Receive tab's card about receiving live payments. */
|
|
122
|
+
export interface LiveStatus {
|
|
123
|
+
tone: 'on' | 'off' | 'connecting' | 'error'
|
|
124
|
+
titleKey: TranslationKey
|
|
125
|
+
bodyKey: TranslationKey
|
|
126
|
+
/** The manager's own error text, on `error`, for the log. Not for the user. */
|
|
127
|
+
detail?: string
|
|
128
|
+
}
|