@bsv/expo-wallet-toolbox 0.1.3 → 0.2.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/core/backup/RemoteSyncReader.ts +59 -9
- package/core/backup/client.ts +60 -27
- package/core/backup/restore.ts +54 -4
- package/core/backup/restoreOnImport.ts +1 -0
- package/core/context/WalletContext.tsx +24 -12
- package/core/localpay/transport/ble.ts +6 -6
- package/core/localpay/transport/socket.ts +31 -22
- package/core/pay/creditInbox.ts +3 -1
- package/core/peerpay/outbox.ts +75 -35
- package/core/storage/StorageExpoSQLite.ts +16 -17
- package/package.json +1 -1
- package/ui/components/pay/AddressReceive.tsx +2 -1
- package/ui/components/pay/HandleReceive.tsx +2 -1
- package/ui/components/pay/NearbyFlow.tsx +9 -5
- package/ui/components/pay/PaymentSuccessOverlay.tsx +2 -1
- package/ui/components/pay/UniversalSend.tsx +9 -5
- package/ui/components/wallet/ActivityRow.tsx +20 -13
- package/ui/components/wallet/AmountDisplay.tsx +4 -7
- package/ui/dismissTarget.ts +19 -0
- package/ui/hooks/useSpendableBalance.ts +44 -17
- package/ui/hooks/useVaultBalance.ts +48 -17
- package/ui/index.ts +1 -0
- package/ui/screens/PayScreen.tsx +4 -2
- package/ui/screens/WalletHomeScreen.tsx +3 -1
package/core/peerpay/outbox.ts
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
// ── Types ──────────────────────────────────────────────────────────────────────
|
|
18
18
|
|
|
19
19
|
export interface OutboxEntry {
|
|
20
|
-
/**
|
|
20
|
+
/** `${timestamp}_${recipientKey.slice(0, 8)}`, with a suffix on collision. */
|
|
21
21
|
id: string
|
|
22
22
|
/** ISO 8601 creation timestamp */
|
|
23
23
|
createdAt: string
|
|
@@ -87,14 +87,33 @@ export const SENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000
|
|
|
87
87
|
|
|
88
88
|
// ── Private helpers ───────────────────────────────────────────────────────────
|
|
89
89
|
|
|
90
|
+
// A send and the background retry/prune task can update this same JSON blob.
|
|
91
|
+
// Serialize each storage's entire read-modify-write, not just the final write,
|
|
92
|
+
// so delivery checkpoints and newly saved payment tokens cannot be overwritten
|
|
93
|
+
// by another operation's stale snapshot. Separate wallet stores stay independent.
|
|
94
|
+
const mutationTails = new WeakMap<StorageLike, Promise<void>>()
|
|
95
|
+
|
|
96
|
+
function withOutboxLock<T>(storage: StorageLike, fn: () => Promise<T>): Promise<T> {
|
|
97
|
+
const run = (mutationTails.get(storage) ?? Promise.resolve()).then(fn)
|
|
98
|
+
// A failed storage operation must reject its caller without poisoning retries.
|
|
99
|
+
mutationTails.set(
|
|
100
|
+
storage,
|
|
101
|
+
run.then(
|
|
102
|
+
() => undefined,
|
|
103
|
+
() => undefined
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
return run
|
|
107
|
+
}
|
|
108
|
+
|
|
90
109
|
async function readEntries(storage: StorageLike): Promise<OutboxEntry[]> {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
110
|
+
// Mutations must fail closed: treating an unreadable queue as empty would
|
|
111
|
+
// erase persisted tokens when the subsequent write succeeds.
|
|
112
|
+
const raw = await storage.getKeyValue(OUTBOX_KEY)
|
|
113
|
+
if (raw === undefined) return []
|
|
114
|
+
const parsed: unknown = JSON.parse(raw)
|
|
115
|
+
if (!Array.isArray(parsed)) throw new Error('Outbox data is not an array')
|
|
116
|
+
return parsed as OutboxEntry[]
|
|
98
117
|
}
|
|
99
118
|
|
|
100
119
|
async function writeEntries(storage: StorageLike, entries: OutboxEntry[]): Promise<void> {
|
|
@@ -107,7 +126,12 @@ async function writeEntries(storage: StorageLike, entries: OutboxEntry[]): Promi
|
|
|
107
126
|
* Returns all outbox entries (any status).
|
|
108
127
|
*/
|
|
109
128
|
export async function getOutboxEntries(storage: StorageLike): Promise<OutboxEntry[]> {
|
|
110
|
-
|
|
129
|
+
try {
|
|
130
|
+
return await readEntries(storage)
|
|
131
|
+
} catch {
|
|
132
|
+
// Preserve the best-effort read API; mutations use the strict reader above.
|
|
133
|
+
return []
|
|
134
|
+
}
|
|
111
135
|
}
|
|
112
136
|
|
|
113
137
|
/**
|
|
@@ -136,10 +160,18 @@ export async function saveOutboxEntry(
|
|
|
136
160
|
...(txid ? { txid } : {}),
|
|
137
161
|
...(recipientHost ? { recipientHost } : {})
|
|
138
162
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
163
|
+
return withOutboxLock(storage, async () => {
|
|
164
|
+
const all = await readEntries(storage)
|
|
165
|
+
// Concurrent sends to the same recipient can share a millisecond. Choose
|
|
166
|
+
// against the current queue while holding the lock so later updates and
|
|
167
|
+
// removals still identify exactly one payment; existing IDs stay unchanged.
|
|
168
|
+
const usedIds = new Set(all.map(e => e.id))
|
|
169
|
+
let suffix = 0
|
|
170
|
+
while (usedIds.has(entry.id)) entry.id = `${id}_${++suffix}`
|
|
171
|
+
all.push(entry)
|
|
172
|
+
await writeEntries(storage, all)
|
|
173
|
+
return entry.id
|
|
174
|
+
})
|
|
143
175
|
}
|
|
144
176
|
|
|
145
177
|
/**
|
|
@@ -147,12 +179,14 @@ export async function saveOutboxEntry(
|
|
|
147
179
|
* Called immediately after `sendMessage()` returns without error.
|
|
148
180
|
*/
|
|
149
181
|
export async function markOutboxSent(storage: StorageLike, id: string): Promise<void> {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
entry
|
|
154
|
-
|
|
155
|
-
|
|
182
|
+
return withOutboxLock(storage, async () => {
|
|
183
|
+
const all = await readEntries(storage)
|
|
184
|
+
const entry = all.find(e => e.id === id)
|
|
185
|
+
if (entry) {
|
|
186
|
+
entry.status = 'sent'
|
|
187
|
+
await writeEntries(storage, all)
|
|
188
|
+
}
|
|
189
|
+
})
|
|
156
190
|
}
|
|
157
191
|
|
|
158
192
|
/**
|
|
@@ -160,12 +194,14 @@ export async function markOutboxSent(storage: StorageLike, id: string): Promise<
|
|
|
160
194
|
* Used to record `lastAttemptAt` and `lastError` on failed retry attempts.
|
|
161
195
|
*/
|
|
162
196
|
export async function updateOutboxEntry(storage: StorageLike, id: string, patch: Partial<OutboxEntry>): Promise<void> {
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
197
|
+
return withOutboxLock(storage, async () => {
|
|
198
|
+
const all = await readEntries(storage)
|
|
199
|
+
const idx = all.findIndex(e => e.id === id)
|
|
200
|
+
if (idx !== -1) {
|
|
201
|
+
all[idx] = { ...all[idx], ...patch }
|
|
202
|
+
await writeEntries(storage, all)
|
|
203
|
+
}
|
|
204
|
+
})
|
|
169
205
|
}
|
|
170
206
|
|
|
171
207
|
/**
|
|
@@ -173,11 +209,13 @@ export async function updateOutboxEntry(storage: StorageLike, id: string, patch:
|
|
|
173
209
|
* Called when the user explicitly dismisses an entry.
|
|
174
210
|
*/
|
|
175
211
|
export async function removeOutboxEntry(storage: StorageLike, id: string): Promise<void> {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
212
|
+
return withOutboxLock(storage, async () => {
|
|
213
|
+
const all = await readEntries(storage)
|
|
214
|
+
await writeEntries(
|
|
215
|
+
storage,
|
|
216
|
+
all.filter(e => e.id !== id)
|
|
217
|
+
)
|
|
218
|
+
})
|
|
181
219
|
}
|
|
182
220
|
|
|
183
221
|
/**
|
|
@@ -196,11 +234,13 @@ export function isSentExpired(entry: OutboxEntry, now: number = Date.now()): boo
|
|
|
196
234
|
* Remove only expired sent rows. Returns how many were removed.
|
|
197
235
|
*/
|
|
198
236
|
export async function pruneExpiredSent(storage: StorageLike, now: number = Date.now()): Promise<number> {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
237
|
+
return withOutboxLock(storage, async () => {
|
|
238
|
+
const all = await readEntries(storage)
|
|
239
|
+
const kept = all.filter(e => !isSentExpired(e, now))
|
|
240
|
+
const removed = all.length - kept.length
|
|
241
|
+
if (removed > 0) await writeEntries(storage, kept)
|
|
242
|
+
return removed
|
|
243
|
+
})
|
|
204
244
|
}
|
|
205
245
|
|
|
206
246
|
/** Entries that still need Retry/Cancel — everything not yet marked sent. */
|
|
@@ -1676,26 +1676,25 @@ export class StorageExpoSQLite extends StorageProvider {
|
|
|
1676
1676
|
|
|
1677
1677
|
async getLabelsForTransactionId(transactionId?: number, trx?: TrxToken): Promise<TableTxLabel[]> {
|
|
1678
1678
|
if (!transactionId) return []
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1679
|
+
// Resolve the associations in one read instead of one bridge round trip
|
|
1680
|
+
// for the maps followed by another for every label.
|
|
1681
|
+
const rows = await this.getDB(trx).getAllAsync(
|
|
1682
|
+
`SELECT l.* FROM tx_labels_map m JOIN tx_labels l ON l.txLabelId = m.txLabelId
|
|
1683
|
+
WHERE m.transactionId = ? AND m.isDeleted = 0 AND l.isDeleted = 0
|
|
1684
|
+
ORDER BY m.txLabelId ASC`,
|
|
1685
|
+
[transactionId]
|
|
1686
|
+
)
|
|
1687
|
+
return this.validateEntities(rows, undefined, ['isDeleted'])
|
|
1686
1688
|
}
|
|
1687
1689
|
|
|
1688
1690
|
async getTagsForOutputId(outputId: number, trx?: TrxToken): Promise<TableOutputTag[]> {
|
|
1689
|
-
const
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
if (results.length > 0) tags.push(results[0])
|
|
1697
|
-
}
|
|
1698
|
-
return tags
|
|
1691
|
+
const rows = await this.getDB(trx).getAllAsync(
|
|
1692
|
+
`SELECT t.* FROM output_tags_map m JOIN output_tags t ON t.outputTagId = m.outputTagId
|
|
1693
|
+
WHERE m.outputId = ? AND m.isDeleted = 0 AND t.isDeleted = 0
|
|
1694
|
+
ORDER BY m.outputTagId ASC`,
|
|
1695
|
+
[outputId]
|
|
1696
|
+
)
|
|
1697
|
+
return this.validateEntities(rows, undefined, ['isDeleted'])
|
|
1699
1698
|
}
|
|
1700
1699
|
|
|
1701
1700
|
// Change input allocation
|
package/package.json
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
type ProcessedTx,
|
|
33
33
|
watchAddress
|
|
34
34
|
} from '@bsv/expo-wallet-toolbox'
|
|
35
|
+
import type { DismissTarget } from '../../dismissTarget'
|
|
35
36
|
|
|
36
37
|
/**
|
|
37
38
|
* @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
|
|
@@ -125,7 +126,7 @@ const HISTORY_POLL_MS = 5000
|
|
|
125
126
|
export default function AddressReceive({
|
|
126
127
|
initialSats,
|
|
127
128
|
dismissTo = '/'
|
|
128
|
-
}: { initialSats?: number; dismissTo?:
|
|
129
|
+
}: { initialSats?: number; dismissTo?: DismissTarget } = {}) {
|
|
129
130
|
const { t } = useTranslation()
|
|
130
131
|
const { colors } = useTheme()
|
|
131
132
|
const Ionicons = loadIonicons()
|
|
@@ -63,6 +63,7 @@ import {
|
|
|
63
63
|
peerPayLinkFor,
|
|
64
64
|
type InboxAttempt
|
|
65
65
|
} from '@bsv/expo-wallet-toolbox'
|
|
66
|
+
import type { DismissTarget } from '../../dismissTarget'
|
|
66
67
|
|
|
67
68
|
/**
|
|
68
69
|
* @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
|
|
@@ -349,7 +350,7 @@ function AttentionRow({
|
|
|
349
350
|
export default function HandleReceive({
|
|
350
351
|
initialSats,
|
|
351
352
|
dismissTo = '/'
|
|
352
|
-
}: { initialSats?: number; dismissTo?:
|
|
353
|
+
}: { initialSats?: number; dismissTo?: DismissTarget } = {}) {
|
|
353
354
|
const { t } = useTranslation()
|
|
354
355
|
const { colors } = useTheme()
|
|
355
356
|
const Ionicons = loadIonicons()
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
* easings.out. Nothing eases in; nothing starts from scale(0).
|
|
88
88
|
*/
|
|
89
89
|
|
|
90
|
-
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
90
|
+
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
91
91
|
import { ActivityIndicator, Linking, Modal, Platform, ScrollView, StyleSheet, Text, View } from 'react-native'
|
|
92
92
|
import Animated, { FadeIn, FadeInDown, useReducedMotion } from 'react-native-reanimated'
|
|
93
93
|
import { useSafeAreaInsets } from 'react-native-safe-area-context'
|
|
@@ -114,7 +114,7 @@ import {
|
|
|
114
114
|
typography,
|
|
115
115
|
durations,
|
|
116
116
|
springs,
|
|
117
|
-
|
|
117
|
+
useWalletManagers,
|
|
118
118
|
sounds,
|
|
119
119
|
updateOfflineAction,
|
|
120
120
|
AirGapDecoder,
|
|
@@ -166,6 +166,7 @@ import {
|
|
|
166
166
|
type DerivingWallet,
|
|
167
167
|
type VerifiedPayment
|
|
168
168
|
} from '@bsv/expo-wallet-toolbox'
|
|
169
|
+
import type { DismissTarget } from '../../dismissTarget'
|
|
169
170
|
|
|
170
171
|
/**
|
|
171
172
|
* @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
|
|
@@ -388,10 +389,10 @@ export interface NearbyFlowProps {
|
|
|
388
389
|
/** Payee only: mint immediately for this amount (undefined = open request). Skips receive_amount. */
|
|
389
390
|
initialRequest?: { sats?: number }
|
|
390
391
|
/** Where the post-payment overlay and an exited QR flow send the user. Defaults to `/`. */
|
|
391
|
-
dismissTo?:
|
|
392
|
+
dismissTo?: DismissTarget
|
|
392
393
|
}
|
|
393
394
|
|
|
394
|
-
|
|
395
|
+
function NearbyFlow({
|
|
395
396
|
role: initialRole,
|
|
396
397
|
onExit,
|
|
397
398
|
initialSession,
|
|
@@ -407,7 +408,7 @@ export default function NearbyFlow({
|
|
|
407
408
|
const navigation = useNavigation()
|
|
408
409
|
const insets = useSafeAreaInsets()
|
|
409
410
|
const reducedMotion = useReducedMotion()
|
|
410
|
-
const { managers, adminOriginator, storage } =
|
|
411
|
+
const { managers, adminOriginator, storage } = useWalletManagers()
|
|
411
412
|
const wallet = managers?.permissionsManager ?? null
|
|
412
413
|
|
|
413
414
|
const [phase, setPhase] = useState<Phase>('entry')
|
|
@@ -2549,3 +2550,6 @@ function makeStyles() {
|
|
|
2549
2550
|
noticeText: { ...typography.footnote, flex: 1 }
|
|
2550
2551
|
})
|
|
2551
2552
|
}
|
|
2553
|
+
|
|
2554
|
+
// Wallet status updates in the parent do not change this form's inputs.
|
|
2555
|
+
export default memo(NearbyFlow)
|
|
@@ -27,6 +27,7 @@ import { useTheme, durations, springs, spacing, typography, radii, sounds } from
|
|
|
27
27
|
import AmountDisplay from '../wallet/AmountDisplay'
|
|
28
28
|
import Celebration from '../ui/Celebration'
|
|
29
29
|
import PressableScale from '../ui/PressableScale'
|
|
30
|
+
import type { DismissTarget } from '../../dismissTarget'
|
|
30
31
|
|
|
31
32
|
/**
|
|
32
33
|
* expo-router is required lazily rather than imported at module scope: this
|
|
@@ -75,7 +76,7 @@ export interface ReceivedOverlayProps {
|
|
|
75
76
|
* wallet's own home route. A host that embeds the wallet as a sub-screen
|
|
76
77
|
* (rather than as the app root) should pass its own wallet-home route here.
|
|
77
78
|
*/
|
|
78
|
-
dismissTo?:
|
|
79
|
+
dismissTo?: DismissTarget
|
|
79
80
|
/**
|
|
80
81
|
* Acknowledged. The only way this screen closes. Clean up local state here —
|
|
81
82
|
* the overlay itself then returns the user to the wallet, so the updated
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* load-bearing — a user who pastes an address expecting messaging-style
|
|
14
14
|
* delivery has effectively posted cash.
|
|
15
15
|
*/
|
|
16
|
-
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
|
16
|
+
import React, { memo, useCallback, useEffect, useMemo, useState } from 'react'
|
|
17
17
|
import { ActivityIndicator, Modal, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'
|
|
18
18
|
import { useTranslation } from 'react-i18next'
|
|
19
19
|
|
|
@@ -37,7 +37,7 @@ import {
|
|
|
37
37
|
typography,
|
|
38
38
|
radii,
|
|
39
39
|
hitTargets,
|
|
40
|
-
|
|
40
|
+
useWalletManagers,
|
|
41
41
|
CONSEQUENCE_KEYS,
|
|
42
42
|
NO_MESSAGE_BOX,
|
|
43
43
|
cancelOutboxPayment,
|
|
@@ -54,6 +54,7 @@ import {
|
|
|
54
54
|
haptics,
|
|
55
55
|
listPendingResendRequests
|
|
56
56
|
} from '@bsv/expo-wallet-toolbox'
|
|
57
|
+
import type { DismissTarget } from '../../dismissTarget'
|
|
57
58
|
|
|
58
59
|
/**
|
|
59
60
|
* expo-status-bar's package.json `main` points straight at its raw
|
|
@@ -189,10 +190,10 @@ export interface UniversalSendProps {
|
|
|
189
190
|
/** A nearby-session code was scanned. The Pay screen swaps this form for NearbyFlow. */
|
|
190
191
|
onNearbySession: (session: Session) => void
|
|
191
192
|
/** Where the post-payment overlay sends the user. Defaults to `/`. */
|
|
192
|
-
dismissTo?:
|
|
193
|
+
dismissTo?: DismissTarget
|
|
193
194
|
}
|
|
194
195
|
|
|
195
|
-
|
|
196
|
+
function UniversalSend({
|
|
196
197
|
initialTarget,
|
|
197
198
|
initialSats,
|
|
198
199
|
initialNotice,
|
|
@@ -203,7 +204,7 @@ export default function UniversalSend({
|
|
|
203
204
|
const { t } = useTranslation()
|
|
204
205
|
const { colors } = useTheme()
|
|
205
206
|
const StatusBar = loadStatusBar()
|
|
206
|
-
const { managers, adminOriginator, storage } =
|
|
207
|
+
const { managers, adminOriginator, storage } = useWalletManagers()
|
|
207
208
|
const wallet = managers?.permissionsManager || null
|
|
208
209
|
|
|
209
210
|
// Read-only here: the server is configured in Settings › Advanced.
|
|
@@ -689,3 +690,6 @@ const styles = StyleSheet.create({
|
|
|
689
690
|
paddingVertical: spacing.md
|
|
690
691
|
}
|
|
691
692
|
})
|
|
693
|
+
|
|
694
|
+
// Wallet status updates in the parent do not change this form's inputs.
|
|
695
|
+
export default memo(UniversalSend)
|
|
@@ -56,6 +56,8 @@ export type ActivityAction = WalletAction & {
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
interface Props {
|
|
59
|
+
/** Pass the screen currency to avoid subscribing every row to wallet updates. */
|
|
60
|
+
currency?: string
|
|
59
61
|
action: ActivityAction
|
|
60
62
|
/** Identity of this row in the list's expanded/busy bookkeeping. Passed back
|
|
61
63
|
* to `onToggle` so the handler can stay referentially stable across renders —
|
|
@@ -99,6 +101,7 @@ export function formatRowTime(value?: string | number | Date): string {
|
|
|
99
101
|
}
|
|
100
102
|
|
|
101
103
|
function ActivityRowBase({
|
|
104
|
+
currency,
|
|
102
105
|
action,
|
|
103
106
|
rowKey,
|
|
104
107
|
offlineStatus,
|
|
@@ -112,14 +115,12 @@ function ActivityRowBase({
|
|
|
112
115
|
onSendPaymentDetails,
|
|
113
116
|
onSendAgain,
|
|
114
117
|
onCancelParked
|
|
115
|
-
}: Props) {
|
|
118
|
+
}: Props & { currency: string }) {
|
|
116
119
|
const { t } = useTranslation()
|
|
117
120
|
const { colors } = useTheme()
|
|
118
|
-
const { settings } = useWallet()
|
|
119
121
|
const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
|
|
120
122
|
const MaterialCommunityIcons = loadMaterialCommunityIcons()
|
|
121
123
|
|
|
122
|
-
const currency = settings?.currency || 'BSV'
|
|
123
124
|
const view = txStatusView(action.status, offlineStatus)
|
|
124
125
|
const settled = view.tone === 'settled'
|
|
125
126
|
const tone = toneColor(view.tone, colors as unknown as Record<string, string>)
|
|
@@ -396,13 +397,19 @@ const styles = StyleSheet.create({
|
|
|
396
397
|
chipLabel: { fontSize: 12, fontWeight: '600' }
|
|
397
398
|
})
|
|
398
399
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
400
|
+
// Compare every prop: callbacks and busyLabel must also update, otherwise a
|
|
401
|
+
// retained row can invoke a previous network's handler or show stale progress.
|
|
402
|
+
const MemoActivityRow = memo(ActivityRowBase)
|
|
403
|
+
|
|
404
|
+
function ConnectedActivityRow(props: Props) {
|
|
405
|
+
const { settings } = useWallet()
|
|
406
|
+
return <MemoActivityRow {...props} currency={settings?.currency || 'BSV'} />
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Preserve the existing package API for hosts that omit currency; the home
|
|
410
|
+
* screen supplies it so background wallet updates cannot invalidate each row. */
|
|
411
|
+
export default function ActivityRow(props: Props) {
|
|
412
|
+
return props.currency === undefined
|
|
413
|
+
? <ConnectedActivityRow {...props} />
|
|
414
|
+
: <MemoActivityRow {...props} currency={props.currency} />
|
|
415
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import React, { ReactNode,
|
|
1
|
+
import React, { ReactNode, useMemo, useContext } from 'react'
|
|
2
2
|
import { formatAmount, ExchangeRateContext, useWallet } from '@bsv/expo-wallet-toolbox'
|
|
3
3
|
|
|
4
4
|
type Props = {
|
|
@@ -25,21 +25,18 @@ type Props = {
|
|
|
25
25
|
* @param {number|string} props.children - The amount in satoshis to display
|
|
26
26
|
*/
|
|
27
27
|
const AmountDisplay: React.FC<Props> = ({ abbreviate, showPlus, children, showFiatAsInteger }) => {
|
|
28
|
-
const [formatted, setFormatted] = useState('...')
|
|
29
|
-
|
|
30
28
|
const { settings } = useWallet()
|
|
31
29
|
const currency = settings?.currency || 'BSV'
|
|
32
30
|
|
|
33
31
|
const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
|
|
34
32
|
|
|
35
|
-
|
|
33
|
+
const formatted = useMemo(() => {
|
|
36
34
|
const numValue = Number(children)
|
|
37
35
|
if (!Number.isInteger(numValue)) {
|
|
38
|
-
|
|
39
|
-
return
|
|
36
|
+
return '...'
|
|
40
37
|
}
|
|
41
38
|
|
|
42
|
-
|
|
39
|
+
return formatAmount(numValue, currency, satoshisPerUSD, { showPlus, abbreviate, showFiatAsInteger, usdToFiat })
|
|
43
40
|
}, [children, currency, satoshisPerUSD, usdToFiat, showPlus, abbreviate, showFiatAsInteger])
|
|
44
41
|
|
|
45
42
|
return <>{formatted}</>
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route target for the `dismissTo` props on this package's payment screens.
|
|
3
|
+
*
|
|
4
|
+
* expo-router's `router.dismissTo` takes `Href`, which is not a fixed type: a
|
|
5
|
+
* host app with `experiments.typedRoutes` on generates a `declare module
|
|
6
|
+
* 'expo-router'` augmentation narrowing `Href` to that app's literal route
|
|
7
|
+
* union. Because that augmentation is global and this package ships raw `.ts`
|
|
8
|
+
* that the host compiles itself, a `dismissTo?: string` prop stops being
|
|
9
|
+
* assignable to `dismissTo()` inside our own files (TS2345). Typing the prop
|
|
10
|
+
* as `Href` resolves against whatever the host's `Href` is: a typed-routes
|
|
11
|
+
* host gets its routes checked, a host without it sees `Href` ~ `string`.
|
|
12
|
+
*
|
|
13
|
+
* `import type` is fully erased at compile time and emits no `require`, so
|
|
14
|
+
* this does not reintroduce the untransformed-JSX problem that the lazy
|
|
15
|
+
* `loadExpoRouter()` pattern exists to avoid.
|
|
16
|
+
*/
|
|
17
|
+
import type { Href } from 'expo-router'
|
|
18
|
+
|
|
19
|
+
export type DismissTarget = Href
|
|
@@ -11,48 +11,75 @@ import { useEffect, useRef, useState } from 'react'
|
|
|
11
11
|
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
12
12
|
import { sdk } from '@bsv/wallet-toolbox-mobile'
|
|
13
13
|
import { useWallet, readWalletBalance } from '@bsv/expo-wallet-toolbox'
|
|
14
|
+
import { storageMatchesNetwork } from '../../core/net/chainMatch'
|
|
14
15
|
|
|
15
16
|
export function useSpendableBalance(): number | null {
|
|
16
17
|
const { managers, adminOriginator, selectedNetwork, storage, txStatusVersion, walletUserId } = useWallet()
|
|
17
|
-
const [balance, setBalance] = useState<number | null>(null)
|
|
18
18
|
const cacheKey = `cached_wallet_balance_${selectedNetwork}`
|
|
19
|
-
|
|
19
|
+
const [balance, setBalance] = useState<{ key: string; value: number } | null>(null)
|
|
20
|
+
// Serialize reads, retaining the latest invalidation while one is in flight.
|
|
21
|
+
// A plain busy flag loses it: the old effect is cancelled, while the new one
|
|
22
|
+
// sees the flag and returns, so neither can update the displayed figure.
|
|
20
23
|
const inFlightRef = useRef(false)
|
|
24
|
+
const pendingRef = useRef<(() => Promise<void>) | null>(null)
|
|
21
25
|
|
|
22
26
|
useEffect(() => {
|
|
23
27
|
let cancelled = false
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
const refresh = async () => {
|
|
29
|
+
try {
|
|
30
|
+
const cached = await AsyncStorage.getItem(cacheKey)
|
|
31
|
+
const value = cached == null ? NaN : Number(cached)
|
|
32
|
+
if (!cancelled && Number.isFinite(value)) {
|
|
33
|
+
setBalance(prev => prev?.key === cacheKey ? prev : { key: cacheKey, value })
|
|
34
|
+
}
|
|
35
|
+
} catch {
|
|
36
|
+
// A broken cache must not prevent the live read below.
|
|
37
|
+
}
|
|
38
|
+
if (cancelled) return
|
|
39
|
+
// During a network rebuild the previous chain's storage can still be
|
|
40
|
+
// mounted. Never read it or write its figure into the new chain's cache.
|
|
41
|
+
if (storage && !storageMatchesNetwork(storage, selectedNetwork)) return
|
|
30
42
|
try {
|
|
31
43
|
let total: number | null = null
|
|
32
44
|
if (storage && walletUserId != null) {
|
|
33
45
|
total = await readWalletBalance(storage, walletUserId)
|
|
34
46
|
}
|
|
47
|
+
if (cancelled) return
|
|
35
48
|
if (total == null) {
|
|
36
49
|
const pm = managers?.permissionsManager
|
|
37
50
|
if (!pm) return
|
|
38
51
|
const { totalOutputs } = await pm.listOutputs({ basket: sdk.specOpWalletBalance }, adminOriginator)
|
|
39
52
|
total = totalOutputs ?? 0
|
|
40
53
|
}
|
|
41
|
-
if (
|
|
54
|
+
if (cancelled) return
|
|
55
|
+
setBalance(prev => prev?.key === cacheKey && prev.value === total ? prev : { key: cacheKey, value: total })
|
|
42
56
|
await AsyncStorage.setItem(cacheKey, String(total))
|
|
43
57
|
} catch {
|
|
44
58
|
// Keep the last known figure: a failed read is not "zero satoshis".
|
|
45
|
-
} finally {
|
|
46
|
-
inFlightRef.current = false
|
|
47
59
|
}
|
|
48
|
-
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
pendingRef.current = refresh
|
|
63
|
+
if (!inFlightRef.current) {
|
|
64
|
+
inFlightRef.current = true
|
|
65
|
+
void (async () => {
|
|
66
|
+
try {
|
|
67
|
+
while (pendingRef.current) {
|
|
68
|
+
const next = pendingRef.current
|
|
69
|
+
pendingRef.current = null
|
|
70
|
+
await next()
|
|
71
|
+
}
|
|
72
|
+
} finally {
|
|
73
|
+
inFlightRef.current = false
|
|
74
|
+
}
|
|
75
|
+
})()
|
|
76
|
+
}
|
|
49
77
|
return () => {
|
|
50
78
|
cancelled = true
|
|
79
|
+
if (pendingRef.current === refresh) pendingRef.current = null
|
|
51
80
|
}
|
|
52
|
-
|
|
53
|
-
// be a dependency here.
|
|
54
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
55
|
-
}, [cacheKey, storage, walletUserId, managers?.permissionsManager, txStatusVersion])
|
|
81
|
+
}, [cacheKey, selectedNetwork, storage, walletUserId, managers?.permissionsManager, adminOriginator, txStatusVersion])
|
|
56
82
|
|
|
57
|
-
|
|
83
|
+
// Hide the old chain's figure immediately, before the new effect reads cache.
|
|
84
|
+
return balance?.key === cacheKey ? balance.value : null
|
|
58
85
|
}
|