@bsv/expo-wallet-toolbox 0.1.3 → 0.2.1

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.
@@ -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
- this.entries = await this.client.index(this.deviceId, this.generation)
55
- this.verifyChain(this.entries)
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
- const ciphertext = await this.client.blob(this.deviceId, this.generation, entry.seq)
65
- return await decodeChunk(this.wallet, Array.from(ciphertext), this.chain)
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 = 0; i < entries.length; 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(
@@ -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 (baseUrl: string, primaryKey: number[], chain: BackupChain, fetchImpl?: typeof fetch) {
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: withTimeout(fetchImpl ?? ((input, init) => fetch(input, init)))
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, sha256: string, size: 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 every request the client makes.
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
- * A race rather than an AbortController, kept from the previous client: losing
86
- * the race abandons the in-flight promise, which is acceptable because the
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 withTimeout (transport: typeof fetch): typeof fetch {
91
+ export function withBackupRequestTimeout(transport: typeof fetch): typeof fetch {
91
92
  return async (input, init) => {
92
- let timer: ReturnType<typeof setTimeout> | undefined
93
- try {
94
- return await Promise.race([
95
- transport(input, init),
96
- new Promise<never>((_resolve, reject) => {
97
- timer = setTimeout(
98
- () =>
99
- reject(
100
- new Error(`Backup request timed out after ${BACKUP_REQUEST_TIMEOUT_MS}ms: ${String(input)}`)
101
- ),
102
- BACKUP_REQUEST_TIMEOUT_MS
103
- )
104
- ;(timer as { unref?: () => void }).unref?.()
105
- })
106
- ])
107
- } finally {
108
- if (timer != null) clearTimeout(timer)
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
  }
@@ -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 reader = new RemoteSyncReader(client, wallet, deps.chain, chosen.deviceId, chosen.generation, settings)
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) break
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) break
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
- return null
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
- restoreIntentRef.current = opts?.restoreFromBackup === true
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
- restoreIntentRef.current = opts?.restoreFromBackup === true
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
- // If still not built (no mnemonic), try recovered key. walletBuiltRef is
2016
- // the reliable signal here — this closure's walletBuilt is frozen at
2017
- // false, and the old `!walletBuildingRef.current` check was wrong twice
2018
- // over: it reads false after a SUCCESSFUL build too (both builders clear
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)
@@ -792,6 +792,7 @@ const resources = {
792
792
  pay_offline_kv_pending: '{{count}} nearby payment(s) waiting to be added to this wallet.',
793
793
  pay_offline_kv_stuck: '{{count}} nearby payment(s) could not be added. Ask the sender to send again.',
794
794
  pay_offline_kv_corrupt: 'Damaged payment data was found on this device.',
795
+ pay_offline_kv_corrupt_body: 'The affected payments were set aside on this device, not deleted. Some of them may already have been added to your balance, so only ask a sender to send again if their payment is still missing.',
795
796
  pay_offline_show_code: 'Show code again',
796
797
  pay_parked_cancel: 'Cancel payment',
797
798
  pay_parked_already_sent: 'This payment was already sent',
@@ -1427,6 +1428,7 @@ const resources = {
1427
1428
  pay_offline_kv_pending: '有 {{count}} 笔附近付款等待加入此钱包。',
1428
1429
  pay_offline_kv_stuck: '有 {{count}} 笔附近付款无法添加。请让付款方重新发送。',
1429
1430
  pay_offline_kv_corrupt: '在此设备上发现了损坏的付款数据。',
1431
+ pay_offline_kv_corrupt_body: '受影响的付款已被移到此设备上的一旁保存,并未删除。其中一些可能已经计入你的余额,因此只有在某笔付款仍然缺失时,才请付款方重新发送。',
1430
1432
  pay_offline_show_code: '再次显示付款码',
1431
1433
  pay_parked_cancel: '取消付款',
1432
1434
  pay_parked_already_sent: '此付款已发送',
@@ -2086,6 +2088,7 @@ const resources = {
2086
2088
  pay_offline_kv_pending: '{{count}} आस-पास के भुगतान इस वॉलेट में जुड़ने के इंतज़ार में हैं।',
2087
2089
  pay_offline_kv_stuck: '{{count}} नज़दीकी भुगतान जोड़े नहीं जा सके। भेजने वाले से दोबारा भेजने को कहें।',
2088
2090
  pay_offline_kv_corrupt: 'इस डिवाइस पर क्षतिग्रस्त भुगतान डेटा मिला।',
2091
+ pay_offline_kv_corrupt_body: 'प्रभावित भुगतान इस डिवाइस पर अलग रख दिए गए हैं, मिटाए नहीं गए। इनमें से कुछ पहले ही आपके बैलेंस में जुड़ चुके हो सकते हैं, इसलिए भेजने वाले से दोबारा भेजने को तभी कहें जब उनका भुगतान अब भी नहीं मिला हो।',
2089
2092
  pay_offline_show_code: 'कोड फिर दिखाएँ',
2090
2093
  pay_parked_cancel: 'भुगतान रद्द करें',
2091
2094
  pay_parked_already_sent: 'यह भुगतान पहले ही भेज दिया गया है',
@@ -2755,6 +2758,7 @@ const resources = {
2755
2758
  pay_offline_kv_stuck:
2756
2759
  'No se pudieron añadir {{count}} pago(s) cercano(s). Pide a quien pagó que lo envíe otra vez.',
2757
2760
  pay_offline_kv_corrupt: 'Se encontraron datos de pago dañados en este dispositivo.',
2761
+ pay_offline_kv_corrupt_body: 'Los pagos afectados se apartaron en este dispositivo, no se borraron. Puede que algunos ya se hayan sumado a tu saldo, así que pide a alguien que vuelva a enviar solo si su pago sigue sin aparecer.',
2758
2762
  pay_offline_show_code: 'Mostrar el código otra vez',
2759
2763
  pay_parked_cancel: 'Cancelar el pago',
2760
2764
  pay_parked_already_sent: 'Este pago ya se envió',
@@ -3428,6 +3432,7 @@ const resources = {
3428
3432
  pay_offline_kv_stuck:
3429
3433
  'Impossible d’ajouter {{count}} paiement(s) à proximité. Demandez à l’expéditeur de renvoyer.',
3430
3434
  pay_offline_kv_corrupt: 'Des données de paiement endommagées ont été trouvées sur cet appareil.',
3435
+ pay_offline_kv_corrupt_body: 'Les paiements concernés ont été mis de côté sur cet appareil, pas supprimés. Certains ont peut-être déjà été ajoutés à votre solde : ne demandez un nouvel envoi que si le paiement manque toujours.',
3431
3436
  pay_offline_show_code: 'Réafficher le code',
3432
3437
  pay_parked_cancel: 'Annuler le paiement',
3433
3438
  pay_parked_already_sent: 'Ce paiement a déjà été envoyé',
@@ -4072,6 +4077,7 @@ const resources = {
4072
4077
  pay_offline_kv_pending: '{{count}} دفعة قريبة في انتظار الإضافة إلى هذه المحفظة.',
4073
4078
  pay_offline_kv_stuck: 'تعذّرت إضافة {{count}} دفعة قريبة. اطلب من المُرسِل الإرسال مرة أخرى.',
4074
4079
  pay_offline_kv_corrupt: 'تم العثور على بيانات دفع تالفة على هذا الجهاز.',
4080
+ pay_offline_kv_corrupt_body: 'تم وضع المدفوعات المتأثرة جانبًا على هذا الجهاز ولم تُحذف. ربما أُضيف بعضها إلى رصيدك بالفعل، لذا اطلب من المُرسِل الإرسال مرة أخرى فقط إذا كانت دفعته ما زالت مفقودة.',
4075
4081
  pay_offline_show_code: 'إظهار الرمز مرة أخرى',
4076
4082
  pay_parked_cancel: 'إلغاء الدفعة',
4077
4083
  pay_parked_already_sent: 'تم إرسال هذه الدفعة بالفعل',
@@ -4739,6 +4745,7 @@ const resources = {
4739
4745
  pay_offline_kv_pending: '{{count}} pagamento(s) por proximidade à espera de serem adicionados a esta carteira.',
4740
4746
  pay_offline_kv_stuck: 'Não foi possível adicionar {{count}} pagamento(s) próximo(s). Peça para enviarem de novo.',
4741
4747
  pay_offline_kv_corrupt: 'Foram encontrados dados de pagamento danificados neste dispositivo.',
4748
+ pay_offline_kv_corrupt_body: 'Os pagamentos afetados foram guardados à parte neste dispositivo, não foram apagados. Alguns podem já ter entrado no seu saldo, por isso peça para enviarem de novo apenas se o pagamento continuar a faltar.',
4742
4749
  pay_offline_show_code: 'Mostrar o código novamente',
4743
4750
  pay_parked_cancel: 'Cancelar pagamento',
4744
4751
  pay_parked_already_sent: 'Este pagamento já foi enviado',
@@ -5398,6 +5405,7 @@ const resources = {
5398
5405
  pay_offline_kv_pending: '{{count}}টি কাছাকাছি পেমেন্ট এই ওয়ালেটে যুক্ত হওয়ার অপেক্ষায়।',
5399
5406
  pay_offline_kv_stuck: '{{count}}টি কাছাকাছি পেমেন্ট যোগ করা যায়নি। প্রেরককে আবার পাঠাতে বলুন।',
5400
5407
  pay_offline_kv_corrupt: 'এই ডিভাইসে ক্ষতিগ্রস্ত পেমেন্ট ডেটা পাওয়া গেছে।',
5408
+ pay_offline_kv_corrupt_body: 'ক্ষতিগ্রস্ত পেমেন্টগুলো এই ডিভাইসে আলাদা করে রাখা হয়েছে, মুছে ফেলা হয়নি। এর কিছু হয়তো ইতিমধ্যেই আপনার ব্যালেন্সে যোগ হয়ে গেছে, তাই কোনো পেমেন্ট এখনও না পেলে তবেই প্রেরককে আবার পাঠাতে বলুন।',
5401
5409
  pay_offline_show_code: 'কোড আবার দেখান',
5402
5410
  pay_parked_cancel: 'পেমেন্ট বাতিল করুন',
5403
5411
  pay_parked_already_sent: 'এই পেমেন্ট ইতিমধ্যে পাঠানো হয়েছে',
@@ -6063,6 +6071,7 @@ const resources = {
6063
6071
  pay_offline_kv_pending: 'Платежей поблизости, ожидающих добавления в этот кошелёк: {{count}}.',
6064
6072
  pay_offline_kv_stuck: 'Не удалось добавить {{count}} ближайших платежей. Попросите отправителя отправить снова.',
6065
6073
  pay_offline_kv_corrupt: 'На этом устройстве найдены повреждённые данные платежа.',
6074
+ pay_offline_kv_corrupt_body: 'Затронутые платежи отложены на этом устройстве, а не удалены. Некоторые из них могли уже попасть в ваш баланс, поэтому просите отправителя отправить снова только если его платёж всё ещё не пришёл.',
6066
6075
  pay_offline_show_code: 'Показать код снова',
6067
6076
  pay_parked_cancel: 'Отменить платёж',
6068
6077
  pay_parked_already_sent: 'Этот платёж уже отправлен',
@@ -6728,6 +6737,7 @@ const resources = {
6728
6737
  pay_offline_kv_pending: '{{count}} pembayaran terdekat menunggu untuk ditambahkan ke dompet ini.',
6729
6738
  pay_offline_kv_stuck: '{{count}} pembayaran terdekat tidak bisa ditambahkan. Minta pengirim mengirim ulang.',
6730
6739
  pay_offline_kv_corrupt: 'Ditemukan data pembayaran yang rusak di perangkat ini.',
6740
+ pay_offline_kv_corrupt_body: 'Pembayaran yang terdampak disimpan terpisah di perangkat ini, bukan dihapus. Sebagian mungkin sudah masuk ke saldo Anda, jadi minta pengirim mengirim ulang hanya jika pembayarannya masih belum ada.',
6731
6741
  pay_offline_show_code: 'Tampilkan kode lagi',
6732
6742
  pay_parked_cancel: 'Batalkan pembayaran',
6733
6743
  pay_parked_already_sent: 'Pembayaran ini sudah terkirim',
@@ -7403,6 +7413,7 @@ const resources = {
7403
7413
  pay_offline_kv_pending: 'このウォレットへの追加を待っている近くの支払いが {{count}} 件あります。',
7404
7414
  pay_offline_kv_stuck: '{{count}} 件の近くの支払いを追加できませんでした。送り主に再送を依頼してください。',
7405
7415
  pay_offline_kv_corrupt: 'この端末で破損した支払いデータが見つかりました。',
7416
+ pay_offline_kv_corrupt_body: '該当する支払いはこの端末に取り分けてあり、削除されていません。すでに残高に加算されているものもあるため、支払いがまだ届いていない場合にのみ、送り主に再送を依頼してください。',
7406
7417
  pay_offline_show_code: 'コードをもう一度表示',
7407
7418
  pay_parked_cancel: '支払いをキャンセル',
7408
7419
  pay_parked_already_sent: 'この支払いはすでに送信されました',
@@ -8088,6 +8099,7 @@ const resources = {
8088
8099
  pay_offline_kv_pending: 'Płatności w pobliżu czekające na dodanie do tego portfela: {{count}}.',
8089
8100
  pay_offline_kv_stuck: 'Nie udało się dodać {{count}} płatności w pobliżu. Poproś nadawcę o ponowne wysłanie.',
8090
8101
  pay_offline_kv_corrupt: 'Na tym urządzeniu znaleziono uszkodzone dane płatności.',
8102
+ pay_offline_kv_corrupt_body: 'Objęte tym płatności zostały odłożone na tym urządzeniu, a nie usunięte. Część z nich mogła już trafić do Twojego salda, więc poproś nadawcę o ponowne wysłanie tylko wtedy, gdy jego płatność nadal nie dotarła.',
8091
8103
  pay_offline_show_code: 'Pokaż kod ponownie',
8092
8104
  pay_parked_cancel: 'Anuluj płatność',
8093
8105
  pay_parked_already_sent: 'Ta płatność została już wysłana',
@@ -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