@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
|
@@ -23,9 +23,19 @@ export class BackupChainError extends Error {
|
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
// The server caps each index page at 500 entries. Reading only its first page
|
|
27
|
+
// can otherwise look like a successful restore of a truncated wallet.
|
|
28
|
+
const INDEX_PAGE_SIZE = 500
|
|
29
|
+
// At most one small ciphertext is fetched ahead while SQLite replays the
|
|
30
|
+
// current chunk. Large chunks remain sequential to bound mobile memory use.
|
|
31
|
+
const PREFETCH_MAX_BYTES = 1024 * 1024
|
|
32
|
+
|
|
33
|
+
type BlobResult = { bytes: Uint8Array, error?: never } | { bytes?: never, error: unknown }
|
|
34
|
+
|
|
26
35
|
export class RemoteSyncReader {
|
|
27
36
|
private entries: LogEntry[] | null = null
|
|
28
37
|
private next = 0
|
|
38
|
+
private prefetched: { seq: number, result: Promise<BlobResult> } | null = null
|
|
29
39
|
|
|
30
40
|
constructor (
|
|
31
41
|
private readonly client: BackupClient,
|
|
@@ -33,7 +43,8 @@ export class RemoteSyncReader {
|
|
|
33
43
|
private readonly chain: BackupChain,
|
|
34
44
|
private readonly deviceId: string,
|
|
35
45
|
private readonly generation: number,
|
|
36
|
-
private readonly settings: TableSettings
|
|
46
|
+
private readonly settings: TableSettings,
|
|
47
|
+
private readonly expectedHeadSeq?: number
|
|
37
48
|
) {}
|
|
38
49
|
|
|
39
50
|
/** Settings for the storage being restored into. */
|
|
@@ -51,18 +62,57 @@ export class RemoteSyncReader {
|
|
|
51
62
|
*/
|
|
52
63
|
async getSyncChunk (_args: RequestSyncChunkArgs): Promise<SyncChunk> {
|
|
53
64
|
if (this.entries == null) {
|
|
54
|
-
|
|
55
|
-
this.
|
|
65
|
+
const entries: LogEntry[] = []
|
|
66
|
+
let page = await this.client.index(this.deviceId, this.generation)
|
|
67
|
+
for (;;) {
|
|
68
|
+
const pageStart = entries.length
|
|
69
|
+
entries.push(...page)
|
|
70
|
+
this.verifyChain(entries, pageStart)
|
|
71
|
+
const missingHead = this.expectedHeadSeq != null && entries.length < this.expectedHeadSeq
|
|
72
|
+
if (page.length === 0) {
|
|
73
|
+
if (missingHead) throw new BackupChainError('backup index ended before its advertised head')
|
|
74
|
+
break
|
|
75
|
+
}
|
|
76
|
+
if (page.length < INDEX_PAGE_SIZE && !missingHead) break
|
|
77
|
+
page = await this.client.index(this.deviceId, this.generation, entries.length + 1)
|
|
78
|
+
}
|
|
79
|
+
// Publish only a fully verified index. A failed read/validation must not
|
|
80
|
+
// let a retry skip verification or mistake a partial index for completion.
|
|
81
|
+
this.entries = entries
|
|
56
82
|
}
|
|
57
83
|
|
|
58
84
|
if (this.next >= this.entries.length) {
|
|
59
|
-
// All twelve arrays present and empty: the completion sentinel.
|
|
60
85
|
return emptyChunk(this.deviceId, this.settings.storageIdentityKey, '')
|
|
61
86
|
}
|
|
62
87
|
|
|
63
|
-
const entry = this.entries[this.next
|
|
64
|
-
|
|
65
|
-
|
|
88
|
+
const entry = this.entries[this.next]
|
|
89
|
+
let ciphertext: Uint8Array
|
|
90
|
+
if (this.prefetched?.seq === entry.seq) {
|
|
91
|
+
const pending = this.prefetched
|
|
92
|
+
this.prefetched = null
|
|
93
|
+
const result = await pending.result
|
|
94
|
+
if ('error' in result) throw result.error
|
|
95
|
+
ciphertext = result.bytes
|
|
96
|
+
} else {
|
|
97
|
+
ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
|
|
98
|
+
}
|
|
99
|
+
const chunk = await decodeChunk(this.wallet, Array.from(ciphertext), this.chain)
|
|
100
|
+
// Advance only after successful download AND decryption. Retrying this
|
|
101
|
+
// reader after either fails must retry the same entry rather than lose it.
|
|
102
|
+
this.next++
|
|
103
|
+
const following = this.entries[this.next]
|
|
104
|
+
if (following && entry.size > 0 && entry.size <= PREFETCH_MAX_BYTES &&
|
|
105
|
+
following.size > 0 && following.size <= PREFETCH_MAX_BYTES) {
|
|
106
|
+
this.prefetched = {
|
|
107
|
+
seq: following.seq,
|
|
108
|
+
// Store failures as values until consumed, so a stopped replay never
|
|
109
|
+
// leaves an unhandled rejection from a speculative download.
|
|
110
|
+
result: this.client.blob(this.deviceId, this.generation, following.seq).then(
|
|
111
|
+
bytes => ({ bytes }), error => ({ error })
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return chunk
|
|
66
116
|
}
|
|
67
117
|
|
|
68
118
|
/** Number of chunks in this generation, once the index has been read. */
|
|
@@ -76,8 +126,8 @@ export class RemoteSyncReader {
|
|
|
76
126
|
* A restore that silently stops halfway is worse than one that fails: the wallet would
|
|
77
127
|
* look healthy while missing the outputs it needs to spend.
|
|
78
128
|
*/
|
|
79
|
-
private verifyChain (entries: LogEntry[]): void {
|
|
80
|
-
for (let i =
|
|
129
|
+
private verifyChain (entries: LogEntry[], start = 0): void {
|
|
130
|
+
for (let i = start; i < entries.length; i++) {
|
|
81
131
|
const expectedSeq = i + 1
|
|
82
132
|
if (entries[i].seq !== expectedSeq) {
|
|
83
133
|
throw new BackupChainError(
|
package/core/backup/client.ts
CHANGED
|
@@ -55,11 +55,11 @@ export class BackupClient extends BackupCacheClient {
|
|
|
55
55
|
* pseudonym, so each network's log lives in its own server account.
|
|
56
56
|
* @param fetchImpl injectable transport for tests; defaults to global fetch.
|
|
57
57
|
*/
|
|
58
|
-
constructor
|
|
58
|
+
constructor(baseUrl: string, primaryKey: number[], chain: BackupChain, fetchImpl?: typeof fetch) {
|
|
59
59
|
super({
|
|
60
60
|
baseUrl,
|
|
61
61
|
wallet: deriveBackupWallet(primaryKey, chain),
|
|
62
|
-
fetch:
|
|
62
|
+
fetch: withBackupRequestTimeout(fetchImpl ?? ((input, init) => fetch(input, init)))
|
|
63
63
|
})
|
|
64
64
|
}
|
|
65
65
|
|
|
@@ -67,45 +67,78 @@ export class BackupClient extends BackupCacheClient {
|
|
|
67
67
|
* Append a chunk. Accepts the codec's `number[]` ciphertext alongside the
|
|
68
68
|
* package's own body shapes, so encodeChunk's output flows straight through.
|
|
69
69
|
*/
|
|
70
|
-
override async append
|
|
70
|
+
override async append(
|
|
71
71
|
deviceId: string,
|
|
72
72
|
generation: number,
|
|
73
73
|
seq: number,
|
|
74
74
|
prevSha256: string | undefined,
|
|
75
75
|
body: Uint8Array | Blob | number[]
|
|
76
|
-
): Promise<{ seq: number
|
|
76
|
+
): Promise<{ seq: number; sha256: string; size: number }> {
|
|
77
77
|
const bytes = Array.isArray(body) ? new Uint8Array(body) : body
|
|
78
78
|
return await super.append(deviceId, generation, seq, prevSha256, bytes)
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
/**
|
|
83
|
-
* Bound
|
|
83
|
+
* Bound the request and the body readers used by BackupCacheClient with one
|
|
84
|
+
* deadline. React Native's XHR fetch resolves after the download, but its
|
|
85
|
+
* Blob/FileReader conversion is still asynchronous; browser fetch can resolve
|
|
86
|
+
* before any body bytes arrive. Neither phase may strand the monitor.
|
|
84
87
|
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
* caller retries the whole pass and nothing downstream depends on the
|
|
88
|
-
* abandoned result.
|
|
88
|
+
* Wrap the existing readers instead of rebuilding/cloning the Response: a
|
|
89
|
+
* large backup still allocates only the buffer the package itself requests.
|
|
89
90
|
*/
|
|
90
|
-
function
|
|
91
|
+
export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch {
|
|
91
92
|
return async (input, init) => {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
93
|
+
const controller = new AbortController()
|
|
94
|
+
const callerSignal =
|
|
95
|
+
init?.signal ?? (typeof Request !== 'undefined' && input instanceof Request ? input.signal : null)
|
|
96
|
+
const deadline = Date.now() + BACKUP_REQUEST_TIMEOUT_MS
|
|
97
|
+
|
|
98
|
+
async function bounded<T>(operation: () => Promise<T>): Promise<T> {
|
|
99
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
100
|
+
let rejectStopped!: (reason: unknown) => void
|
|
101
|
+
const stopped = new Promise<never>((_resolve, reject) => {
|
|
102
|
+
rejectStopped = reject
|
|
103
|
+
})
|
|
104
|
+
const cancel = (reason: unknown) => {
|
|
105
|
+
// Reject before aborting: a transport's synchronous AbortError must not
|
|
106
|
+
// mask the more useful timeout or caller-supplied cancellation reason.
|
|
107
|
+
rejectStopped(reason)
|
|
108
|
+
controller.abort(reason)
|
|
109
|
+
}
|
|
110
|
+
const onAbort = () => {
|
|
111
|
+
const error = new Error('Backup request aborted')
|
|
112
|
+
error.name = 'AbortError'
|
|
113
|
+
cancel(callerSignal?.reason ?? error)
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
const remaining = deadline - Date.now()
|
|
117
|
+
if (callerSignal?.aborted) {
|
|
118
|
+
onAbort()
|
|
119
|
+
return await stopped
|
|
120
|
+
}
|
|
121
|
+
callerSignal?.addEventListener('abort', onAbort)
|
|
122
|
+
const onTimeout = () =>
|
|
123
|
+
cancel(new Error(`Backup request timed out after ${BACKUP_REQUEST_TIMEOUT_MS}ms: ${String(input)}`))
|
|
124
|
+
if (remaining <= 0) {
|
|
125
|
+
onTimeout()
|
|
126
|
+
return await stopped
|
|
127
|
+
}
|
|
128
|
+
timer = setTimeout(onTimeout, remaining)
|
|
129
|
+
;(timer as { unref?: () => void }).unref?.()
|
|
130
|
+
return await Promise.race([operation(), stopped])
|
|
131
|
+
} finally {
|
|
132
|
+
if (timer != null) clearTimeout(timer)
|
|
133
|
+
callerSignal?.removeEventListener('abort', onAbort)
|
|
134
|
+
}
|
|
109
135
|
}
|
|
136
|
+
|
|
137
|
+
const response = await bounded(() => transport(input, { ...init, signal: controller.signal }))
|
|
138
|
+
const readJson = response.json.bind(response)
|
|
139
|
+
const readArrayBuffer = response.arrayBuffer.bind(response)
|
|
140
|
+
response.json = () => bounded(readJson)
|
|
141
|
+
response.arrayBuffer = () => bounded(readArrayBuffer)
|
|
142
|
+
return response
|
|
110
143
|
}
|
|
111
144
|
}
|
package/core/backup/restore.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface RestoreDeps {
|
|
|
24
24
|
client?: BackupClient
|
|
25
25
|
/** Defaults to the most recently updated device in the manifest. */
|
|
26
26
|
deviceId?: string
|
|
27
|
+
/** A manifest already read by the import flow; avoids a duplicate request. */
|
|
28
|
+
manifest?: DeviceSummary[]
|
|
27
29
|
/** Defaults to the newest generation for that device. */
|
|
28
30
|
generation?: number
|
|
29
31
|
/**
|
|
@@ -60,7 +62,7 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
|
|
|
60
62
|
const client = resolveClient(deps)
|
|
61
63
|
const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
|
|
62
64
|
|
|
63
|
-
const devices = await client.manifest()
|
|
65
|
+
const devices = deps.manifest ?? await client.manifest()
|
|
64
66
|
if (devices.length === 0) {
|
|
65
67
|
throw new Error('No backup found for this wallet')
|
|
66
68
|
}
|
|
@@ -83,7 +85,8 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
|
|
|
83
85
|
'backup-restore'
|
|
84
86
|
)
|
|
85
87
|
|
|
86
|
-
const
|
|
88
|
+
const headSeq = devices.find(d => d.deviceId === chosen.deviceId && d.generation === chosen.generation)?.headSeq
|
|
89
|
+
const reader = new RemoteSyncReader(client, wallet, deps.chain, chosen.deviceId, chosen.generation, settings, headSeq)
|
|
87
90
|
|
|
88
91
|
let chunks = 0
|
|
89
92
|
for (;;) {
|
|
@@ -105,17 +108,64 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
|
|
|
105
108
|
offsets: []
|
|
106
109
|
}, chunk)
|
|
107
110
|
|
|
108
|
-
if (result.done)
|
|
111
|
+
if (result.done) {
|
|
112
|
+
if (chunks < reader.length) throw new Error('Backup replay completed before all indexed chunks were applied')
|
|
113
|
+
break
|
|
114
|
+
}
|
|
109
115
|
chunks++
|
|
110
116
|
deps.onProgress?.(chunks, reader.length)
|
|
111
117
|
|
|
112
118
|
// The reader is finite; this guards against a processSyncChunk that never reports done.
|
|
113
|
-
if (chunks > reader.length)
|
|
119
|
+
if (chunks > reader.length) throw new Error('Backup replay did not acknowledge completion')
|
|
114
120
|
}
|
|
115
121
|
|
|
122
|
+
await reconcileRestoredProofs(deps.storage)
|
|
116
123
|
return { chunks, deviceId: chosen.deviceId, generation: chosen.generation }
|
|
117
124
|
}
|
|
118
125
|
|
|
126
|
+
/**
|
|
127
|
+
* Toolbox sync merges transaction status but only history/notify for an
|
|
128
|
+
* existing proof request. An unsent request followed by its completed version
|
|
129
|
+
* can therefore replay beside a completed transaction and keep rebroadcasting
|
|
130
|
+
* it. Reuse proofs already in storage through the normal completion method,
|
|
131
|
+
* which also reconciles notification IDs and preserves completed transactions.
|
|
132
|
+
* Run only after the entire log lands, before the wallet/monitor is published.
|
|
133
|
+
*/
|
|
134
|
+
async function reconcileRestoredProofs (storage: StorageExpoSQLite): Promise<void> {
|
|
135
|
+
const limit = 1
|
|
136
|
+
for (let offset = 0; ; offset += limit) {
|
|
137
|
+
// Page over every status so completing a request cannot shift the next
|
|
138
|
+
// page's offsets. A request may contain a large expanded inputBEEF, so
|
|
139
|
+
// retain only one request at a time while completion reloads its proof.
|
|
140
|
+
const requests = await storage.findProvenTxReqs({ partial: {}, paged: { limit, offset } })
|
|
141
|
+
for (const req of requests) {
|
|
142
|
+
if (req.status === 'completed' && req.notified && (req.provenTxId ?? 0) > 0) continue
|
|
143
|
+
const proofs = await storage.findProvenTxs({ partial: { txid: req.txid } })
|
|
144
|
+
if (proofs.length === 0) continue
|
|
145
|
+
if (proofs.length !== 1) throw new Error('Restored transaction has conflicting stored proofs')
|
|
146
|
+
const proof = proofs[0]
|
|
147
|
+
const result = await storage.updateProvenTxReqWithNewProvenTx({
|
|
148
|
+
provenTxReqId: req.provenTxReqId,
|
|
149
|
+
txid: req.txid,
|
|
150
|
+
status: req.status,
|
|
151
|
+
attempts: req.attempts,
|
|
152
|
+
history: req.history,
|
|
153
|
+
height: proof.height,
|
|
154
|
+
index: proof.index,
|
|
155
|
+
blockHash: proof.blockHash,
|
|
156
|
+
merkleRoot: proof.merkleRoot,
|
|
157
|
+
merklePath: proof.merklePath
|
|
158
|
+
})
|
|
159
|
+
// The toolbox can report incomplete notification after a failed row
|
|
160
|
+
// update. Do not advertise a completed restore in that case.
|
|
161
|
+
if (result.status !== 'completed' || result.provenTxId !== proof.provenTxId || result.notified === false) {
|
|
162
|
+
throw new Error('Restored transaction proof reconciliation did not complete')
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (requests.length < limit) break
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
119
169
|
function pickTarget (
|
|
120
170
|
devices: DeviceSummary[],
|
|
121
171
|
deviceId?: string,
|
|
@@ -82,6 +82,7 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
|
|
|
82
82
|
chain: deps.chain,
|
|
83
83
|
identityKey: deps.identityKey,
|
|
84
84
|
client,
|
|
85
|
+
manifest: devices,
|
|
85
86
|
deviceId: target.deviceId,
|
|
86
87
|
generation: target.generation,
|
|
87
88
|
onProgress: deps.onProgress
|
|
@@ -554,6 +554,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
554
554
|
*/
|
|
555
555
|
const walletBuiltRef = useRef<boolean>(false)
|
|
556
556
|
const walletBuildingRef = useRef<boolean>(false)
|
|
557
|
+
// A failed mnemonic build must not silently fall back to a different stored key.
|
|
558
|
+
const mnemonicMissingRef = useRef(false)
|
|
557
559
|
const [walletBuilding, setWalletBuilding] = useState<boolean>(false)
|
|
558
560
|
const [backupRestore, setBackupRestoreState] = useState<BackupRestoreState>({
|
|
559
561
|
phase: 'idle',
|
|
@@ -1197,6 +1199,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1197
1199
|
const message = e instanceof Error ? e.message : String(e)
|
|
1198
1200
|
console.error('[WalletContext] backup restore failed:', message)
|
|
1199
1201
|
setBackupRestore({ phase: 'failed', chunks: 0, total: 0, error: message })
|
|
1202
|
+
// This storage was never published to the app. Release its
|
|
1203
|
+
// connection before a retry opens the same database again.
|
|
1204
|
+
try {
|
|
1205
|
+
await phoneStorage.destroy()
|
|
1206
|
+
} catch {}
|
|
1200
1207
|
throw e
|
|
1201
1208
|
}
|
|
1202
1209
|
}
|
|
@@ -1711,7 +1718,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1711
1718
|
console.error('Error building wallet:', error)
|
|
1712
1719
|
onToast?.('Failed to build wallet: ' + error.message, { type: 'error' })
|
|
1713
1720
|
logWithTimestamp(F, 'Error building wallet', error.message)
|
|
1714
|
-
|
|
1721
|
+
// SimpleWalletManager authenticates whenever its builder resolves,
|
|
1722
|
+
// even to null. Reject so a failed restore cannot mark a wallet built.
|
|
1723
|
+
throw error
|
|
1715
1724
|
}
|
|
1716
1725
|
},
|
|
1717
1726
|
[
|
|
@@ -1755,6 +1764,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1755
1764
|
}
|
|
1756
1765
|
|
|
1757
1766
|
walletBuildingRef.current = true
|
|
1767
|
+
mnemonicMissingRef.current = false
|
|
1758
1768
|
setWalletBuilding(true)
|
|
1759
1769
|
|
|
1760
1770
|
try {
|
|
@@ -1767,6 +1777,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1767
1777
|
if (__DEV__)
|
|
1768
1778
|
console.warn(`[perf] getMnemonic (auth/keychain): ${(performance.now() - __tMnemonicStart).toFixed(0)}ms`)
|
|
1769
1779
|
if (!mnemonic) {
|
|
1780
|
+
mnemonicMissingRef.current = true
|
|
1770
1781
|
walletBuildingRef.current = false
|
|
1771
1782
|
setWalletBuilding(false)
|
|
1772
1783
|
return
|
|
@@ -1790,7 +1801,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1790
1801
|
|
|
1791
1802
|
// Armed before the keys go in, because providing both is what triggers
|
|
1792
1803
|
// buildWallet — the only place a fresh, empty database exists to replay into.
|
|
1793
|
-
|
|
1804
|
+
// An automatic build has no options: preserve the request armed by
|
|
1805
|
+
// rebuildWallet until buildWallet consumes it. Explicit false still
|
|
1806
|
+
// allows the import screen to continue without restoring on retry.
|
|
1807
|
+
if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
|
|
1794
1808
|
|
|
1795
1809
|
// Provide the primary key and privileged key manager to authenticate the wallet
|
|
1796
1810
|
await swm.providePrimaryKey(primaryKey)
|
|
@@ -1858,7 +1872,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1858
1872
|
const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
|
|
1859
1873
|
|
|
1860
1874
|
// Same arming point as the mnemonic path — see the comment there.
|
|
1861
|
-
|
|
1875
|
+
// An automatic build has no options: preserve the request armed by
|
|
1876
|
+
// rebuildWallet until buildWallet consumes it. Explicit false still
|
|
1877
|
+
// allows the import screen to continue without restoring on retry.
|
|
1878
|
+
if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
|
|
1862
1879
|
|
|
1863
1880
|
await swm.providePrimaryKey(primaryKey)
|
|
1864
1881
|
|
|
@@ -2012,15 +2029,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2012
2029
|
;(async () => {
|
|
2013
2030
|
// Try mnemonic-based build first (calls getMnemonic internally)
|
|
2014
2031
|
await buildWalletFromMnemonic()
|
|
2015
|
-
//
|
|
2016
|
-
//
|
|
2017
|
-
//
|
|
2018
|
-
|
|
2019
|
-
// it on completion), so a wallet holding both a mnemonic and a leftover
|
|
2020
|
-
// recoveredKey would build TWICE — two wallet stacks, two monitors.
|
|
2021
|
-
if (!walletBuiltRef.current && !walletBuildingRef.current) {
|
|
2022
|
-
// buildWalletFromMnemonic finished without building (no mnemonic found).
|
|
2023
|
-
// Try recovered key as a fallback.
|
|
2032
|
+
// Only missing mnemonic material allows a recovered-key fallback. A
|
|
2033
|
+
// restore failure must remain failed so the import screen can offer a
|
|
2034
|
+
// retry; a leftover WIF must not build over that partial replay.
|
|
2035
|
+
if (mnemonicMissingRef.current && !walletBuiltRef.current && !walletBuildingRef.current) {
|
|
2024
2036
|
const recoveredWif = await getRecoveredKey()
|
|
2025
2037
|
if (recoveredWif) {
|
|
2026
2038
|
await buildWalletFromRecoveredKey(recoveredWif)
|
|
@@ -4,7 +4,7 @@ import { unsealFrame, sealFrame, type PaymentFrame } from '../codec'
|
|
|
4
4
|
import { instanceName, type Session } from '../session'
|
|
5
5
|
import type { Ack, LocalPaymentTransport, ReceivedFrame } from '../types'
|
|
6
6
|
import { bleRole } from './select'
|
|
7
|
-
import { SEND_TIMEOUT_MS, declineQuietly, fromBase64, makeConfirm, parseAck, toBase64 } from './socket'
|
|
7
|
+
import { SEND_TIMEOUT_MS, declineQuietly, fromBase64, makeConfirm, nativePromise, parseAck, toBase64 } from './socket'
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Connect-phase budget before the payer gives up and falls back to the QR:
|
|
@@ -54,7 +54,7 @@ export function makeBleTransport(
|
|
|
54
54
|
if (settled) return
|
|
55
55
|
settled = true
|
|
56
56
|
signal.removeEventListener('abort', onAbort)
|
|
57
|
-
if (teardown) void backend.stopListening().catch(() => {})
|
|
57
|
+
if (teardown) void nativePromise(() => backend.stopListening()).catch(() => {})
|
|
58
58
|
fn()
|
|
59
59
|
}
|
|
60
60
|
const onAbort = () => finish(true, () => reject(new Error('cancelled')))
|
|
@@ -74,8 +74,7 @@ export function makeBleTransport(
|
|
|
74
74
|
}
|
|
75
75
|
const onError = (message: string) => finish(true, () => reject(new Error(message)))
|
|
76
76
|
|
|
77
|
-
backend
|
|
78
|
-
.startListening(name, psk, onFrame, onError)
|
|
77
|
+
nativePromise(() => backend.startListening(name, psk, onFrame, onError))
|
|
79
78
|
.then(() => {
|
|
80
79
|
// Reversed role: only where this device's central is trusted
|
|
81
80
|
// against a peer that advertises. A scan that cannot start leaves
|
|
@@ -83,7 +82,7 @@ export function makeBleTransport(
|
|
|
83
82
|
// terminal. Started AFTER startListening resolves: the native
|
|
84
83
|
// self-reset inside startListening would otherwise tear it down.
|
|
85
84
|
if (Platform.OS !== 'ios' || settled) return
|
|
86
|
-
return backend.startScanning(name, psk, onFrame, onError).catch((e: unknown) => {
|
|
85
|
+
return nativePromise(() => backend.startScanning(name, psk, onFrame, onError)).catch((e: unknown) => {
|
|
87
86
|
if (settled) return
|
|
88
87
|
console.warn('[localpay] ble scan unavailable:', e instanceof Error ? e.message : String(e))
|
|
89
88
|
})
|
|
@@ -125,8 +124,9 @@ export function makeBleTransport(
|
|
|
125
124
|
reject(e)
|
|
126
125
|
return
|
|
127
126
|
}
|
|
128
|
-
const pending =
|
|
127
|
+
const pending = nativePromise(() =>
|
|
129
128
|
bleRole(session) === 'peripheral' ? backend.sendFrameAdvertising(...args) : backend.sendFrame(...args)
|
|
129
|
+
)
|
|
130
130
|
pending.then(
|
|
131
131
|
ackBase64 => {
|
|
132
132
|
if (settled) return
|
|
@@ -29,6 +29,15 @@ export const SEND_TIMEOUT_MS = 30_000
|
|
|
29
29
|
*/
|
|
30
30
|
export type LocalPayNative = Pick<LocalPayTransport, 'startListening' | 'stopListening' | 'confirmFrame' | 'sendFrame'>
|
|
31
31
|
|
|
32
|
+
/** Normalize synchronous bridge failures to the native method's promise contract. */
|
|
33
|
+
export function nativePromise<T>(call: () => Promise<T>): Promise<T> {
|
|
34
|
+
try {
|
|
35
|
+
return call()
|
|
36
|
+
} catch (e) {
|
|
37
|
+
return Promise.reject(e)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
32
41
|
export function toBase64(b: Uint8Array): string {
|
|
33
42
|
let s = ''
|
|
34
43
|
for (const byte of b) s += String.fromCharCode(byte)
|
|
@@ -153,14 +162,14 @@ export function makeSocketTransport(
|
|
|
153
162
|
if (settled) return
|
|
154
163
|
settled = true
|
|
155
164
|
signal.removeEventListener('abort', onAbort)
|
|
156
|
-
if (teardown) void backend.stopListening().catch(() => {})
|
|
165
|
+
if (teardown) void nativePromise(() => backend.stopListening()).catch(() => {})
|
|
157
166
|
fn()
|
|
158
167
|
}
|
|
159
168
|
const onAbort = () => finish(true, () => reject(new Error('cancelled')))
|
|
160
169
|
signal.addEventListener('abort', onAbort)
|
|
161
170
|
|
|
162
|
-
|
|
163
|
-
.startListening(
|
|
171
|
+
nativePromise(() =>
|
|
172
|
+
backend.startListening(
|
|
164
173
|
name,
|
|
165
174
|
toBase64(session.psk),
|
|
166
175
|
frameBase64 => {
|
|
@@ -192,7 +201,7 @@ export function makeSocketTransport(
|
|
|
192
201
|
},
|
|
193
202
|
message => finish(true, () => reject(new Error(message)))
|
|
194
203
|
)
|
|
195
|
-
|
|
204
|
+
).catch(e => finish(true, () => reject(e)))
|
|
196
205
|
})
|
|
197
206
|
},
|
|
198
207
|
|
|
@@ -212,32 +221,32 @@ export function makeSocketTransport(
|
|
|
212
221
|
}
|
|
213
222
|
signal.addEventListener('abort', onAbort)
|
|
214
223
|
|
|
215
|
-
|
|
216
|
-
.sendFrame(
|
|
224
|
+
nativePromise(() =>
|
|
225
|
+
backend.sendFrame(
|
|
217
226
|
instanceName(session.sessionId),
|
|
218
227
|
toBase64(session.psk),
|
|
219
228
|
toBase64(sealFrame(frame, session.psk)),
|
|
220
229
|
SEND_TIMEOUT_MS,
|
|
221
230
|
connectTimeoutMs
|
|
222
231
|
)
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
reject(e)
|
|
232
|
-
}
|
|
233
|
-
},
|
|
234
|
-
e => {
|
|
235
|
-
if (settled) return
|
|
236
|
-
settled = true
|
|
237
|
-
cleanup()
|
|
232
|
+
).then(
|
|
233
|
+
ackBase64 => {
|
|
234
|
+
if (settled) return
|
|
235
|
+
settled = true
|
|
236
|
+
cleanup()
|
|
237
|
+
try {
|
|
238
|
+
resolve(parseAck(ackBase64))
|
|
239
|
+
} catch (e) {
|
|
238
240
|
reject(e)
|
|
239
241
|
}
|
|
240
|
-
|
|
242
|
+
},
|
|
243
|
+
e => {
|
|
244
|
+
if (settled) return
|
|
245
|
+
settled = true
|
|
246
|
+
cleanup()
|
|
247
|
+
reject(e)
|
|
248
|
+
}
|
|
249
|
+
)
|
|
241
250
|
})
|
|
242
251
|
},
|
|
243
252
|
}
|
package/core/pay/creditInbox.ts
CHANGED
|
@@ -191,7 +191,9 @@ export async function creditInboxOnce(args: {
|
|
|
191
191
|
}): Promise<CreditInboxResult> {
|
|
192
192
|
const force = args.force ?? []
|
|
193
193
|
if (inFlight && force.length === 0) return inFlight
|
|
194
|
-
|
|
194
|
+
// Several manual retries can be waiting on the same pass. Recheck after
|
|
195
|
+
// each wait so only one acquires the slot; the others wait for it in turn.
|
|
196
|
+
while (inFlight) await inFlight.catch(() => {})
|
|
195
197
|
const run = runCreditInbox(args)
|
|
196
198
|
inFlight = run
|
|
197
199
|
try {
|