@bsv/expo-wallet-toolbox 0.11.8 → 0.13.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 +159 -0
- package/core/backup/erase.ts +7 -1
- package/core/backup/preference.ts +12 -4
- package/core/backup/push.ts +8 -1
- package/core/backup/status.ts +6 -2
- package/core/config.tsx +1 -1
- package/core/context/WalletContext.tsx +904 -184
- package/core/i18n/translations.tsx +496 -12
- package/core/identity/handleRegistry/registration.ts +57 -3
- package/core/index.ts +26 -1
- package/core/mandala/createRuntime.ts +3 -3
- package/core/mandala/runtime.ts +7 -2
- package/core/mnemonicWallet.ts +46 -40
- package/core/monitor/MonitorSupervisor.ts +35 -1
- package/core/monitor/TaskCreditInbox.ts +24 -0
- package/core/pay/beefRepair.ts +8 -3
- package/core/pay/rails/address.ts +43 -3
- package/core/pay/rails/handle.ts +5 -3
- package/core/pay/sweeper.ts +39 -4
- package/core/peerpay/outbox.ts +11 -1
- package/core/profiles/assertProfileEmpty.ts +287 -0
- package/core/profiles/discovery.ts +84 -0
- package/core/profiles/profileLabel.ts +13 -0
- package/core/profiles/profileStore.ts +265 -0
- package/core/profiles/purgeProfile.ts +76 -0
- package/core/profiles/removeProfile.ts +257 -0
- package/core/push/events.ts +189 -0
- package/core/push/identities.ts +55 -0
- package/core/push/profilePush.ts +143 -0
- package/core/push/pushAdvisory.ts +33 -0
- package/core/push/registration.ts +391 -0
- package/core/push/types.ts +35 -0
- package/core/services/arcTokenStorage.ts +17 -2
- package/core/services/vault/transfers.ts +6 -1
- package/core/services/vault/vaultStore.ts +16 -3
- package/core/stores/ConnectionStore.ts +11 -7
- package/core/toolboxConfig.ts +31 -4
- package/core/userAvatar.ts +12 -5
- package/core/walletDbRegistry.ts +73 -0
- package/package.json +1 -1
- package/ui/backupShares.ts +2 -3
- package/ui/components/pay/HandleReceive.tsx +141 -16
- package/ui/components/pay/MessageBoxConfig.tsx +6 -5
- package/ui/components/pay/NotificationAdvisoryModal.tsx +124 -0
- package/ui/components/ui/PencilEditField.tsx +5 -2
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ProfileButton.tsx +92 -18
- package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
- package/ui/hooks/useOfflineNoticeActions.ts +2 -1
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/index.ts +1 -0
- package/ui/printRecoveryShares.ts +6 -7
- package/ui/screens/PairScreen.tsx +2 -1
- package/ui/screens/PayScreen.tsx +53 -0
- package/ui/screens/ProfileScreen.tsx +195 -4
- package/ui/screens/SettingsScreen.tsx +80 -6
- package/ui/screens/VaultScreen.tsx +31 -2
- package/ui/screens/VaultTransferScreen.tsx +25 -2
- package/ui/screens/WalletCheckScreen.tsx +2 -1
- package/ui/screens/WalletConfigScreen.tsx +51 -21
- package/ui/screens/WalletHomeScreen.tsx +6 -3
- package/ui/tokenSeen.ts +13 -9
|
@@ -45,6 +45,9 @@ export interface VaultStoreScope {
|
|
|
45
45
|
/** Compressed secp256k1 wallet identity key, lowercase hex. */
|
|
46
46
|
identityKey: string
|
|
47
47
|
chain: VaultScopeChain
|
|
48
|
+
/** The wallet profile this identity belongs to (default 0). The vault is only
|
|
49
|
+
* ever available on profile 0; transfers check the captured value. */
|
|
50
|
+
profileIndex?: number
|
|
48
51
|
}
|
|
49
52
|
|
|
50
53
|
/** Opaque capability binding an async operation to one configured scope. */
|
|
@@ -52,6 +55,7 @@ export interface VaultScopeToken {
|
|
|
52
55
|
readonly generation: number
|
|
53
56
|
readonly storageKey: string
|
|
54
57
|
readonly chain: VaultScopeChain
|
|
58
|
+
readonly profileIndex?: number
|
|
55
59
|
}
|
|
56
60
|
|
|
57
61
|
export interface VaultKeyRecord {
|
|
@@ -173,7 +177,11 @@ function normalizeScope(scope: VaultStoreScope): VaultStoreScope {
|
|
|
173
177
|
if (scope.chain !== 'main' && scope.chain !== 'test' && scope.chain !== 'teratest') {
|
|
174
178
|
throw new VaultError('template-invalid', 'Vault scope requires a supported chain')
|
|
175
179
|
}
|
|
176
|
-
|
|
180
|
+
const profileIndex = scope.profileIndex ?? 0
|
|
181
|
+
if (!Number.isInteger(profileIndex) || profileIndex < 0) {
|
|
182
|
+
throw new VaultError('template-invalid', 'Vault scope requires a valid profile index')
|
|
183
|
+
}
|
|
184
|
+
return { identityKey: scope.identityKey, chain: scope.chain, profileIndex }
|
|
177
185
|
}
|
|
178
186
|
|
|
179
187
|
function scopedKey(scope = activeScope): string | null {
|
|
@@ -297,11 +305,16 @@ function captureScope(required: boolean): VaultScopeToken | null {
|
|
|
297
305
|
if (required) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
|
|
298
306
|
return null
|
|
299
307
|
}
|
|
300
|
-
return { generation: scopeGeneration, storageKey, chain: activeScope!.chain }
|
|
308
|
+
return { generation: scopeGeneration, storageKey, chain: activeScope!.chain, profileIndex: activeScope!.profileIndex ?? 0 }
|
|
301
309
|
}
|
|
302
310
|
|
|
303
311
|
function assertScope(token: VaultScopeToken): void {
|
|
304
|
-
if (
|
|
312
|
+
if (
|
|
313
|
+
token.generation !== scopeGeneration ||
|
|
314
|
+
token.storageKey !== scopedKey() ||
|
|
315
|
+
token.chain !== activeScope?.chain ||
|
|
316
|
+
(token.profileIndex ?? 0) !== (activeScope?.profileIndex ?? 0)
|
|
317
|
+
) {
|
|
305
318
|
throw new VaultError('scope-changed', 'Wallet or network changed during the vault operation')
|
|
306
319
|
}
|
|
307
320
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { makeAutoObservable, runInAction } from 'mobx'
|
|
2
2
|
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
3
|
+
import { profileScopedKey } from '../profiles/profileStore'
|
|
3
4
|
|
|
4
5
|
export interface Connection {
|
|
5
6
|
sessionId: string
|
|
@@ -81,20 +82,23 @@ class ConnectionStore {
|
|
|
81
82
|
|
|
82
83
|
private async save() {
|
|
83
84
|
try {
|
|
84
|
-
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(this.connections))
|
|
85
|
+
await AsyncStorage.setItem(profileScopedKey(STORAGE_KEY), JSON.stringify(this.connections))
|
|
85
86
|
} catch (e) {
|
|
86
87
|
console.warn('[ConnectionStore] save failed', e)
|
|
87
88
|
}
|
|
88
89
|
}
|
|
89
90
|
|
|
91
|
+
/** Pairings belong to one wallet profile: re-read after every profile switch. */
|
|
92
|
+
async reload() {
|
|
93
|
+
await this.load()
|
|
94
|
+
}
|
|
95
|
+
|
|
90
96
|
private async load() {
|
|
91
97
|
try {
|
|
92
|
-
const raw = await AsyncStorage.getItem(STORAGE_KEY)
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
})
|
|
97
|
-
}
|
|
98
|
+
const raw = await AsyncStorage.getItem(profileScopedKey(STORAGE_KEY))
|
|
99
|
+
runInAction(() => {
|
|
100
|
+
this.connections = raw ? (JSON.parse(raw) as Connection[]) : []
|
|
101
|
+
})
|
|
98
102
|
} catch (e) {
|
|
99
103
|
console.warn('[ConnectionStore] load failed', e)
|
|
100
104
|
}
|
package/core/toolboxConfig.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AppChain } from './config'
|
|
2
|
+
import type { PushAdapter } from './push/types'
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Service endpoints and API keys for one chain.
|
|
@@ -108,6 +109,14 @@ export interface ToolboxConfig {
|
|
|
108
109
|
* never read from process.env here.
|
|
109
110
|
*/
|
|
110
111
|
vaultEnabled?: boolean
|
|
112
|
+
/**
|
|
113
|
+
* The host's push implementation. Optional: a host that ships no push SDK
|
|
114
|
+
* omits it and every push feature stays off. The package never imports a
|
|
115
|
+
* push SDK itself — the SDK's native module would have to be linked by every
|
|
116
|
+
* host that merely installs this package — so the host wraps its own and
|
|
117
|
+
* states it here, like the URLs above.
|
|
118
|
+
*/
|
|
119
|
+
push?: PushAdapter
|
|
111
120
|
}
|
|
112
121
|
|
|
113
122
|
interface ResolvedConfig {
|
|
@@ -116,6 +125,7 @@ interface ResolvedConfig {
|
|
|
116
125
|
mandala: Partial<Record<AppChain, MandalaEndpointConfig>>
|
|
117
126
|
handleRegistry: Partial<Record<AppChain, HandleRegistryConfig>>
|
|
118
127
|
vaultEnabled: boolean
|
|
128
|
+
push: PushAdapter | undefined
|
|
119
129
|
}
|
|
120
130
|
|
|
121
131
|
let current: ResolvedConfig | null = null
|
|
@@ -193,7 +203,8 @@ export function configureToolbox(config: ToolboxConfig): void {
|
|
|
193
203
|
services: config.services ?? {},
|
|
194
204
|
mandala: config.mandala ?? {},
|
|
195
205
|
handleRegistry: config.handleRegistry ?? {},
|
|
196
|
-
vaultEnabled: config.vaultEnabled === true
|
|
206
|
+
vaultEnabled: config.vaultEnabled === true,
|
|
207
|
+
push: config.push
|
|
197
208
|
}
|
|
198
209
|
}
|
|
199
210
|
|
|
@@ -318,6 +329,18 @@ export function isVaultEnabled(): boolean {
|
|
|
318
329
|
return current?.vaultEnabled ?? false
|
|
319
330
|
}
|
|
320
331
|
|
|
332
|
+
/**
|
|
333
|
+
* The host's push implementation, if it wired one. The package never imports a
|
|
334
|
+
* push SDK itself.
|
|
335
|
+
*
|
|
336
|
+
* Deliberately NOT throwing when unconfigured, like `isVaultEnabled`: push
|
|
337
|
+
* listeners are set up while rendering, and "unconfigured" must look like
|
|
338
|
+
* "no push" rather than crash a wallet that never wanted notifications.
|
|
339
|
+
*/
|
|
340
|
+
export function getPushAdapter(): PushAdapter | undefined {
|
|
341
|
+
return current?.push
|
|
342
|
+
}
|
|
343
|
+
|
|
321
344
|
/**
|
|
322
345
|
* Whether the vault may be used on this network.
|
|
323
346
|
*
|
|
@@ -329,13 +352,17 @@ export function isVaultEnabled(): boolean {
|
|
|
329
352
|
* across all of them, so a testnet wizard could offer to factory-reset a live
|
|
330
353
|
* mainnet signer.
|
|
331
354
|
*
|
|
332
|
-
*
|
|
355
|
+
* Only the default wallet profile (index 0) has a vault: a YubiKey is enrolled
|
|
356
|
+
* against one identity, and showing an empty vault on another profile would read
|
|
357
|
+
* as the user's vault being gone.
|
|
358
|
+
*
|
|
359
|
+
* Chain and profile are parameters, not module reads: screens must re-render when the user
|
|
333
360
|
* switches network, and `selectedNetwork` from the wallet context is what makes
|
|
334
361
|
* that reactive. Keeping it a parameter also keeps this module a leaf — it must
|
|
335
362
|
* never import `vaultStore`.
|
|
336
363
|
*/
|
|
337
|
-
export function isVaultAvailable(chain: AppChain): boolean {
|
|
338
|
-
return isVaultEnabled() && chain === 'main'
|
|
364
|
+
export function isVaultAvailable(chain: AppChain, profileIndex: number): boolean {
|
|
365
|
+
return isVaultEnabled() && chain === 'main' && profileIndex === 0
|
|
339
366
|
}
|
|
340
367
|
|
|
341
368
|
/** Test-only: drop the installed configuration. */
|
package/core/userAvatar.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { useSyncExternalStore } from 'react'
|
|
16
16
|
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
17
|
+
import { profileScopedKey } from './profiles/profileStore'
|
|
17
18
|
|
|
18
19
|
export type AvatarIconFamily = 'ionicons' | 'material-community'
|
|
19
20
|
|
|
@@ -38,8 +39,10 @@ export function setUserAvatarIcon(next: AvatarIcon | null): void {
|
|
|
38
39
|
listeners.forEach(l => l())
|
|
39
40
|
// Fire-and-forget: the choice is already live in memory, and a failed write
|
|
40
41
|
// costs the next launch's avatar, never the one on screen now.
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
// Per wallet profile: the avatar is how the user tells profiles apart.
|
|
43
|
+
const key = profileScopedKey(STORAGE_KEY)
|
|
44
|
+
if (next) void AsyncStorage.setItem(key, `${next.family}/${next.name}`).catch(() => {})
|
|
45
|
+
else void AsyncStorage.removeItem(key).catch(() => {})
|
|
43
46
|
}
|
|
44
47
|
|
|
45
48
|
export function subscribeUserAvatar(listener: () => void): () => void {
|
|
@@ -60,11 +63,15 @@ function parse(stored: string | null): AvatarIcon | null {
|
|
|
60
63
|
return { family, name }
|
|
61
64
|
}
|
|
62
65
|
|
|
63
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* Restore the active profile's stored choice. Call at startup and after every
|
|
68
|
+
* profile switch; safe to call twice. A profile with no choice gets the default
|
|
69
|
+
* disc, never the previous profile's icon.
|
|
70
|
+
*/
|
|
64
71
|
export async function loadUserAvatarIcon(): Promise<void> {
|
|
65
72
|
try {
|
|
66
|
-
const next = parse(await AsyncStorage.getItem(STORAGE_KEY))
|
|
67
|
-
if (next
|
|
73
|
+
const next = parse(await AsyncStorage.getItem(profileScopedKey(STORAGE_KEY)))
|
|
74
|
+
if (next?.family !== icon?.family || next?.name !== icon?.name) {
|
|
68
75
|
icon = next
|
|
69
76
|
listeners.forEach(l => l())
|
|
70
77
|
}
|
package/core/walletDbRegistry.ts
CHANGED
|
@@ -113,6 +113,19 @@ export async function getRegisteredDbs(keySuffix: string, chain: string): Promis
|
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
/** The networks a wallet database can belong to. */
|
|
117
|
+
const WALLET_DB_CHAINS = ['main', 'test', 'teratest'] as const
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Every registered wallet DB filename for an identity, on every network. Unlike
|
|
121
|
+
* the purge below, a registry that cannot be read rejects: this answers "what
|
|
122
|
+
* exists", and a guess of "nothing" would be wrong in the dangerous direction.
|
|
123
|
+
*/
|
|
124
|
+
export async function getAllRegisteredDbs(keySuffix: string): Promise<string[]> {
|
|
125
|
+
const perChain = await Promise.all(WALLET_DB_CHAINS.map(chain => getRegisteredDbs(keySuffix, chain)))
|
|
126
|
+
return [...new Set(perChain.flat())]
|
|
127
|
+
}
|
|
128
|
+
|
|
116
129
|
/**
|
|
117
130
|
* Append a filename to the registry (no-op if already present).
|
|
118
131
|
*/
|
|
@@ -185,3 +198,63 @@ export async function purgeRegisteredDbFiles(
|
|
|
185
198
|
}
|
|
186
199
|
}
|
|
187
200
|
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* What a failed delete means: the file is already gone (expo-sqlite throws
|
|
204
|
+
* "Database ... not found" for it, on Android and iOS alike) or it is still there.
|
|
205
|
+
*/
|
|
206
|
+
function alreadyGone(error: unknown): boolean {
|
|
207
|
+
return /not found/i.test(error instanceof Error ? error.message : String(error))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Delete Wallet with profiles: every wallet profile has its own identity and so
|
|
212
|
+
* its own registry, one per network. Purges every file this identity's registry
|
|
213
|
+
* knows on every network — the other profiles are not open at logout, so there
|
|
214
|
+
* is no current `dbName` to anchor on as `purgeRegisteredDbFiles` does.
|
|
215
|
+
* Best-effort per file, for the same reasons as that function.
|
|
216
|
+
*
|
|
217
|
+
* Resolves true when every file is gone. By default a file that could not be
|
|
218
|
+
* deleted is unregistered anyway: after Delete Wallet the registry must not point
|
|
219
|
+
* a rebuilt wallet back at it (XQ-008).
|
|
220
|
+
*
|
|
221
|
+
* `keepFailed` is for removing one profile, which has a retry at every startup
|
|
222
|
+
* (core/profiles/purgeProfile) and that retry finds the files only through this
|
|
223
|
+
* registry: an entry dropped with its file still on disk would leave the removed
|
|
224
|
+
* profile's plaintext history there for good. So an entry stays when its file
|
|
225
|
+
* could not be deleted, and goes when the file is gone, whether this call or an
|
|
226
|
+
* earlier one deleted it.
|
|
227
|
+
*/
|
|
228
|
+
export async function purgeIdentityDbFiles(
|
|
229
|
+
keySuffix: string,
|
|
230
|
+
deleteFile: (filename: string) => Promise<void>,
|
|
231
|
+
options: { keepFailed?: boolean } = {}
|
|
232
|
+
): Promise<boolean> {
|
|
233
|
+
let clean = true
|
|
234
|
+
for (const chain of WALLET_DB_CHAINS) {
|
|
235
|
+
let filenames: string[] = []
|
|
236
|
+
try {
|
|
237
|
+
filenames = await getRegisteredDbs(keySuffix, chain)
|
|
238
|
+
} catch {
|
|
239
|
+
clean = false
|
|
240
|
+
continue
|
|
241
|
+
}
|
|
242
|
+
for (const filename of filenames) {
|
|
243
|
+
let deleted = true
|
|
244
|
+
try {
|
|
245
|
+
await deleteFile(filename)
|
|
246
|
+
} catch (error) {
|
|
247
|
+
// Best-effort — see purgeRegisteredDbFiles.
|
|
248
|
+
deleted = alreadyGone(error)
|
|
249
|
+
if (!deleted) clean = false
|
|
250
|
+
}
|
|
251
|
+
if (options.keepFailed && !deleted) continue
|
|
252
|
+
try {
|
|
253
|
+
await unregisterDb(keySuffix, chain, filename)
|
|
254
|
+
} catch {
|
|
255
|
+
// Best-effort — see purgeRegisteredDbFiles.
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return clean
|
|
260
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bsv/expo-wallet-toolbox",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE.txt",
|
package/ui/backupShares.ts
CHANGED
|
@@ -40,9 +40,8 @@ async function generateQRCodeSVG(data: string, size: number = 180): Promise<stri
|
|
|
40
40
|
*
|
|
41
41
|
* `only`, when given, renders a single page (share index `only` of `shares`,
|
|
42
42
|
* still labelled "Share <only+1> of <shares.length>") as a standalone
|
|
43
|
-
* one-page document instead of every share in one multi-page document.
|
|
44
|
-
* printRecoveryShares.ts (XR-110
|
|
45
|
-
* share so no single print job carries more than one of the threshold.
|
|
43
|
+
* one-page document instead of every share in one multi-page document.
|
|
44
|
+
* printRecoveryShares.ts no longer uses it (XR-110 reverted, see there).
|
|
46
45
|
*/
|
|
47
46
|
export async function generatePrintHTML(
|
|
48
47
|
shares: string[],
|
|
@@ -158,6 +158,13 @@ function loadQRCode(): QRCodeComponent {
|
|
|
158
158
|
*/
|
|
159
159
|
const INBOX_POLL_MS = 5000
|
|
160
160
|
|
|
161
|
+
/**
|
|
162
|
+
* While the live socket is up the satoshi inbox is only re-read on every Nth
|
|
163
|
+
* poll tick: the socket tells us the moment something lands, so the poll is the
|
|
164
|
+
* safety net for a missed event, not the delivery path.
|
|
165
|
+
*/
|
|
166
|
+
const LIVE_SATOSHI_POLL_EVERY = 3
|
|
167
|
+
|
|
161
168
|
// ── Needs attention ──────────────────────────────────────────────────────────
|
|
162
169
|
//
|
|
163
170
|
// Replaces the old accept list. An arriving payment is credited automatically
|
|
@@ -444,6 +451,8 @@ export default function HandleReceive({
|
|
|
444
451
|
|
|
445
452
|
/** One inbox read at a time — see fetchPayments. */
|
|
446
453
|
const fetchingRef = useRef(false)
|
|
454
|
+
/** A live payment arrived mid-read: read once more when that read finishes. */
|
|
455
|
+
const rereadRef = useRef(false)
|
|
447
456
|
/** The live attempt map, for discard copy that must not close over stale state. */
|
|
448
457
|
const attemptsRef = useRef<Record<string, InboxAttempt>>({})
|
|
449
458
|
useEffect(() => {
|
|
@@ -482,7 +491,7 @@ export default function HandleReceive({
|
|
|
482
491
|
}, [identityKey, loadIdentityKey])
|
|
483
492
|
)
|
|
484
493
|
|
|
485
|
-
const
|
|
494
|
+
const newPeerPayClient = useCallback((): PeerPayClient | null => {
|
|
486
495
|
if (!isConfigured || !messageBoxUrl || !wallet) return null
|
|
487
496
|
try {
|
|
488
497
|
return new PeerPayClient({
|
|
@@ -494,6 +503,8 @@ export default function HandleReceive({
|
|
|
494
503
|
return null
|
|
495
504
|
}
|
|
496
505
|
}, [isConfigured, messageBoxUrl, wallet, adminOriginator])
|
|
506
|
+
/** The client every inbox read, accept and discard goes through. */
|
|
507
|
+
const peerPayClient = useMemo(() => newPeerPayClient(), [newPeerPayClient])
|
|
497
508
|
|
|
498
509
|
// BRC-125 with this app's url extension: the payer learns where to deliver
|
|
499
510
|
// without an overlay lookup. Omitted when no server is configured, since
|
|
@@ -588,13 +599,19 @@ export default function HandleReceive({
|
|
|
588
599
|
)
|
|
589
600
|
|
|
590
601
|
const fetchPayments = useCallback(
|
|
591
|
-
async (options: { silent?: boolean } = {}) => {
|
|
602
|
+
async (options: { silent?: boolean; queueIfBusy?: boolean } = {}) => {
|
|
592
603
|
const client = peerPayClient
|
|
593
604
|
if (!client || !messageBoxUrl || messageBoxUrl === NO_MESSAGE_BOX) return
|
|
594
605
|
// One read at a time. The poll, the refresh button and every accept all
|
|
595
606
|
// reach this, and two overlapping reads can land out of order — the older
|
|
596
607
|
// response winning would resurrect a row that was just internalized.
|
|
597
|
-
if (fetchingRef.current)
|
|
608
|
+
if (fetchingRef.current) {
|
|
609
|
+
// A live payment must not be dropped here: the read in flight may have
|
|
610
|
+
// listed the inbox before it landed, and the poll is slow while the
|
|
611
|
+
// socket is up. Run one more read when this one finishes.
|
|
612
|
+
if (options.queueIfBusy) rereadRef.current = true
|
|
613
|
+
return
|
|
614
|
+
}
|
|
598
615
|
fetchingRef.current = true
|
|
599
616
|
try {
|
|
600
617
|
const outcome = await runCredit()
|
|
@@ -614,6 +631,10 @@ export default function HandleReceive({
|
|
|
614
631
|
}
|
|
615
632
|
} finally {
|
|
616
633
|
fetchingRef.current = false
|
|
634
|
+
if (rereadRef.current) {
|
|
635
|
+
rereadRef.current = false
|
|
636
|
+
void fetchRef.current({ silent: true })
|
|
637
|
+
}
|
|
617
638
|
}
|
|
618
639
|
},
|
|
619
640
|
[peerPayClient, messageBoxUrl, wallet, adminOriginator, t, runCredit]
|
|
@@ -668,22 +689,120 @@ export default function HandleReceive({
|
|
|
668
689
|
tokenTickRef.current = tokenTick
|
|
669
690
|
}, [tokenTick])
|
|
670
691
|
|
|
671
|
-
// ──
|
|
692
|
+
// ── Watch the inbox ──
|
|
693
|
+
//
|
|
694
|
+
// While someone is actually looking at this screen, a MessageBox WebSocket
|
|
695
|
+
// tells us the moment a payment lands, and a poll backs it up. The socket is
|
|
696
|
+
// the fast path; the poll covers a listener that could not start, a socket
|
|
697
|
+
// that dropped without telling us, and everything the socket does not carry
|
|
698
|
+
// (the Mandala token inbox has no live channel). Only the satoshi read
|
|
699
|
+
// slows while the socket is up — the token drain stays on the 5s tick.
|
|
672
700
|
//
|
|
673
|
-
//
|
|
674
|
-
//
|
|
675
|
-
//
|
|
676
|
-
//
|
|
677
|
-
//
|
|
678
|
-
//
|
|
701
|
+
// Both run only while the screen is focused and the app active. Blur and
|
|
702
|
+
// background disconnect the socket (a backgrounded app cannot hold one, and
|
|
703
|
+
// one that looked alive on return would quietly slow the poll for nothing),
|
|
704
|
+
// and coming back to the foreground re-listens and reads at once. The
|
|
705
|
+
// callback never credits anything itself: it only triggers the same read the
|
|
706
|
+
// poll does, so there is one crediting path and the shared creditInboxOnce
|
|
707
|
+
// mutex still serializes with TaskCreditInbox.
|
|
708
|
+
//
|
|
709
|
+
// Each listening session gets its OWN short-lived client, never the one the
|
|
710
|
+
// reads use. A MessageBoxClient remembers the rooms it joined across a
|
|
711
|
+
// disconnect, so a second listen on the same instance authenticates a fresh
|
|
712
|
+
// socket but never re-joins the room: listenForLivePayments would resolve,
|
|
713
|
+
// the poll would slow, and no push would ever arrive. A new instance starts
|
|
714
|
+
// with no rooms, no half-finished connection attempt and no socket, and
|
|
715
|
+
// throwing it away on stop discards all three.
|
|
716
|
+
//
|
|
717
|
+
// Blur is a ref, not state, so the interval notices it (within one tick)
|
|
718
|
+
// rather than this effect re-running; the effect itself restarts only with
|
|
719
|
+
// the client.
|
|
679
720
|
useEffect(() => {
|
|
680
721
|
if (!peerPayClient) return
|
|
681
722
|
let cancelled = false
|
|
723
|
+
/** A session is starting, up, or has failed and is not to be retried yet. */
|
|
724
|
+
let listening = false
|
|
725
|
+
/** The current session's client, while one is open. */
|
|
726
|
+
let sessionClient: PeerPayClient | null = null
|
|
727
|
+
/** The socket is confirmed up — the only state in which the poll slows. */
|
|
728
|
+
let live = false
|
|
729
|
+
/** Bumped on every stop so a late start result cannot revive a dead session. */
|
|
730
|
+
let generation = 0
|
|
731
|
+
/** Poll ticks since the socket came up, for the slow satoshi cadence. */
|
|
732
|
+
let liveTicks = 0
|
|
733
|
+
|
|
734
|
+
const visible = () => !cancelled && focusedRef.current && AppState.currentState === 'active'
|
|
735
|
+
|
|
736
|
+
const readSatoshiInbox = (queueIfBusy = false) => {
|
|
737
|
+
void fetchRef.current({ silent: true, queueIfBusy })
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** Close a session's socket. Safe to repeat and on a session that never connected. */
|
|
741
|
+
const closeSession = (session: PeerPayClient) => {
|
|
742
|
+
void session.disconnectWebSocket().catch(() => {})
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
const startListener = () => {
|
|
746
|
+
if (listening) return
|
|
747
|
+
listening = true
|
|
748
|
+
const mine = ++generation
|
|
749
|
+
const session = newPeerPayClient()
|
|
750
|
+
if (!session) {
|
|
751
|
+
console.warn('[pay] live inbox listener unavailable: client not created')
|
|
752
|
+
return
|
|
753
|
+
}
|
|
754
|
+
sessionClient = session
|
|
755
|
+
void (async () => {
|
|
756
|
+
try {
|
|
757
|
+
// The session client is built with this same MessageBox host, so no
|
|
758
|
+
// overrideHost: the socket goes where the inbox reads go.
|
|
759
|
+
await session.listenForLivePayments({
|
|
760
|
+
onPayment: () => {
|
|
761
|
+
if (mine === generation && visible()) readSatoshiInbox(true)
|
|
762
|
+
}
|
|
763
|
+
})
|
|
764
|
+
if (mine === generation) {
|
|
765
|
+
live = true
|
|
766
|
+
liveTicks = 0
|
|
767
|
+
} else {
|
|
768
|
+
// Stopped while it was still connecting. The stop could not close a
|
|
769
|
+
// socket that did not exist yet, so close it now it does.
|
|
770
|
+
closeSession(session)
|
|
771
|
+
}
|
|
772
|
+
} catch (error: any) {
|
|
773
|
+
// Whatever half-open socket the failed attempt left would otherwise
|
|
774
|
+
// keep retrying in the background.
|
|
775
|
+
closeSession(session)
|
|
776
|
+
if (mine !== generation) return
|
|
777
|
+
live = false
|
|
778
|
+
sessionClient = null
|
|
779
|
+
// `listening` stays set so a failed start is not retried every tick;
|
|
780
|
+
// the next blur or background resets it. Full 5s polling carries on.
|
|
781
|
+
console.warn(`[pay] live inbox listener unavailable: ${error?.message || 'unknown error'}`)
|
|
782
|
+
}
|
|
783
|
+
})()
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const stopListener = () => {
|
|
787
|
+
if (!listening) return
|
|
788
|
+
listening = false
|
|
789
|
+
live = false
|
|
790
|
+
generation++
|
|
791
|
+
const session = sessionClient
|
|
792
|
+
sessionClient = null
|
|
793
|
+
if (session) closeSession(session)
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** Listen exactly while the screen can be seen. */
|
|
797
|
+
const syncListener = () => {
|
|
798
|
+
if (visible()) startListener()
|
|
799
|
+
else stopListener()
|
|
800
|
+
}
|
|
682
801
|
|
|
683
802
|
const tick = () => {
|
|
684
|
-
|
|
685
|
-
if (
|
|
686
|
-
|
|
803
|
+
syncListener()
|
|
804
|
+
if (!visible()) return
|
|
805
|
+
if (!live || ++liveTicks % LIVE_SATOSHI_POLL_EVERY === 0) readSatoshiInbox()
|
|
687
806
|
// The token inbox is a SIBLING drain, not a widened one: Mandala delivers
|
|
688
807
|
// to its own message box and the two never meet. Same 5s focused tick,
|
|
689
808
|
// because a payee standing in front of this screen expects both kinds of
|
|
@@ -691,19 +810,25 @@ export default function HandleReceive({
|
|
|
691
810
|
void tokenTickRef.current()
|
|
692
811
|
}
|
|
693
812
|
|
|
813
|
+
syncListener()
|
|
694
814
|
const interval = setInterval(tick, INBOX_POLL_MS)
|
|
695
815
|
// Returning to the app should show what arrived while it was away, rather
|
|
696
|
-
// than waiting out the rest of an interval
|
|
816
|
+
// than waiting out the rest of an interval — both inboxes, whatever point
|
|
817
|
+
// the slow cadence had reached.
|
|
697
818
|
const appSubscription = AppState.addEventListener('change', next => {
|
|
698
|
-
|
|
819
|
+
syncListener()
|
|
820
|
+
if (next !== 'active' || !visible()) return
|
|
821
|
+
readSatoshiInbox()
|
|
822
|
+
void tokenTickRef.current()
|
|
699
823
|
})
|
|
700
824
|
|
|
701
825
|
return () => {
|
|
702
826
|
cancelled = true
|
|
703
827
|
clearInterval(interval)
|
|
704
828
|
appSubscription.remove()
|
|
829
|
+
stopListener()
|
|
705
830
|
}
|
|
706
|
-
}, [peerPayClient])
|
|
831
|
+
}, [peerPayClient, newPeerPayClient])
|
|
707
832
|
|
|
708
833
|
/** Retry one row that had given up. Runs the whole pass, forcing this id. */
|
|
709
834
|
const handleRetry = useCallback(
|
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
MESSAGE_BOX_URL_KEY,
|
|
22
22
|
NO_MESSAGE_BOX
|
|
23
23
|
} from '@bsv/expo-wallet-toolbox'
|
|
24
|
+
import { profileScopedKey } from '../../../core/profiles/profileStore'
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
27
|
* @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
|
|
@@ -46,11 +47,11 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
|
|
|
46
47
|
const [showConfig, setShowConfig] = useState(false)
|
|
47
48
|
|
|
48
49
|
useEffect(() => {
|
|
49
|
-
AsyncStorage.getItem(MESSAGE_BOX_URL_KEY).then(saved => {
|
|
50
|
+
AsyncStorage.getItem(profileScopedKey(MESSAGE_BOX_URL_KEY)).then(saved => {
|
|
50
51
|
// A preference equal to the retired default means "default", not a
|
|
51
52
|
// deliberate choice of that server — follow the new default instead.
|
|
52
53
|
if (saved === LEGACY_MESSAGE_BOX_URL) {
|
|
53
|
-
void AsyncStorage.removeItem(MESSAGE_BOX_URL_KEY)
|
|
54
|
+
void AsyncStorage.removeItem(profileScopedKey(MESSAGE_BOX_URL_KEY))
|
|
54
55
|
return
|
|
55
56
|
}
|
|
56
57
|
if (saved) {
|
|
@@ -85,7 +86,7 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
|
|
|
85
86
|
}
|
|
86
87
|
setIsSaving(true)
|
|
87
88
|
try {
|
|
88
|
-
await AsyncStorage.setItem(MESSAGE_BOX_URL_KEY, trimmed)
|
|
89
|
+
await AsyncStorage.setItem(profileScopedKey(MESSAGE_BOX_URL_KEY), trimmed)
|
|
89
90
|
setMessageBoxUrl(trimmed)
|
|
90
91
|
setShowConfig(false)
|
|
91
92
|
showToast(t('message_box_saved'), { type: 'success' })
|
|
@@ -99,7 +100,7 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
|
|
|
99
100
|
)
|
|
100
101
|
|
|
101
102
|
const handleReset = useCallback(async () => {
|
|
102
|
-
await AsyncStorage.removeItem(MESSAGE_BOX_URL_KEY)
|
|
103
|
+
await AsyncStorage.removeItem(profileScopedKey(MESSAGE_BOX_URL_KEY))
|
|
103
104
|
setMessageBoxUrl(DEFAULT_MESSAGE_BOX_URL)
|
|
104
105
|
setUrlInput(DEFAULT_MESSAGE_BOX_URL)
|
|
105
106
|
setShowConfig(false)
|
|
@@ -110,7 +111,7 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
|
|
|
110
111
|
const noneValue = NO_MESSAGE_BOX
|
|
111
112
|
setIsSaving(true)
|
|
112
113
|
try {
|
|
113
|
-
await AsyncStorage.setItem(MESSAGE_BOX_URL_KEY, noneValue)
|
|
114
|
+
await AsyncStorage.setItem(profileScopedKey(MESSAGE_BOX_URL_KEY), noneValue)
|
|
114
115
|
setMessageBoxUrl(noneValue)
|
|
115
116
|
setUrlInput(noneValue)
|
|
116
117
|
setShowConfig(true)
|