@bsv/expo-wallet-toolbox 0.24.0 → 0.24.2

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 CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.24.2
6
+
7
+ Progress events for the sweep rail. No native change: hosts do not rebuild.
8
+
9
+ ### Added
10
+
11
+ - **`onProgress` on `scanMnemonic`, `decideMnemonicImport`, `sweepWif` and
12
+ `sweepMnemonic`.** A scan of a recovery phrase takes a request or two per
13
+ address, paced, so a host had nothing to show for a long time. The listener
14
+ gets a `SweepProgress` event for the backup check, for each address about to
15
+ be checked (path name, chain path and index), for coins found, for each
16
+ finished path, and before and after each sweep transaction. Events carry
17
+ derivation paths and totals, never an address or a key. A listener that
18
+ throws does not stop the scan or the sweep.
19
+
20
+ ## 0.24.1
21
+
22
+ One fix: the iOS native fetch. Hosts must rebuild their native apps.
23
+
24
+ ### Fixed
25
+
26
+ - **iOS: `BsvBoundedFetch` refused every request** with `ERR_INVALID_REQUEST`
27
+ ("Invalid bounded HTTPS request"). The module read `maxBytes` from an untyped
28
+ dictionary with `as? Int`; over JSI the value is a Swift `Double`, and that
29
+ cast is always nil. Backup, handle registry and trust-list requests all go
30
+ through this module, so none of them worked on iOS in 0.24.0. The value is
31
+ now read as a whole number from either representation. Android was not
32
+ affected (it uses a typed record).
33
+
5
34
  ## 0.24.0
6
35
 
7
36
  BSV Broadcaster as the broadcast path (#97), sweep of external keys (#93), the
@@ -357,6 +357,48 @@ export async function planWifSweep(args: { wif: string; woc: WocConfig } & FeeOp
357
357
  )
358
358
  }
359
359
 
360
+ /**
361
+ * What a scan or a sweep is doing right now, for a screen that shows it.
362
+ * Events carry derivation paths and totals, never an address or a key.
363
+ *
364
+ * - `backup`: the backup cache is asked about the phrase (decideMnemonicImport).
365
+ * - `address`: one address is about to be checked. `chainPath` is the chain
366
+ * (receive or change) and `index` the child under it.
367
+ * - `found`: an address has coins. Raw figures, before tokens and dust are
368
+ * taken out; the plan has the figures the sweep will spend.
369
+ * - `path-done`: both chains of one path are finished.
370
+ * - `batch`: one sweep transaction is about to be built. `index` counts from 0.
371
+ * - `batch-done`: that transaction went through (`txid`), failed (`error`),
372
+ * or had nothing to spend (neither).
373
+ */
374
+ export type SweepProgress =
375
+ | { stage: 'backup' }
376
+ | {
377
+ stage: 'address'
378
+ name: string
379
+ pathIndex: number
380
+ pathCount: number
381
+ chain: 'receive' | 'change'
382
+ chainPath: string
383
+ index: number
384
+ }
385
+ | { stage: 'found'; name: string; pathIndex: number; path: string; utxoCount: number; satoshis: number }
386
+ | { stage: 'path-done'; name: string; pathIndex: number; usedAddresses: number; utxoCount: number; satoshis: number }
387
+ | { stage: 'batch'; index: number; count: number; inputCount: number }
388
+ | { stage: 'batch-done'; index: number; count: number; txid?: string; error?: string }
389
+
390
+ export type SweepProgressListener = (progress: SweepProgress) => void
391
+
392
+ /** A listener is for display only: one that throws must not stop a scan or a sweep. */
393
+ function report(listener: SweepProgressListener | undefined, progress: SweepProgress): void {
394
+ if (!listener) return
395
+ try {
396
+ listener(progress)
397
+ } catch {
398
+ // Display only.
399
+ }
400
+ }
401
+
360
402
  export interface SweepBatchResult {
361
403
  txid?: string
362
404
  inputCount: number
@@ -393,6 +435,8 @@ interface ExecuteArgs {
393
435
  maxInputsPerTx?: number
394
436
  maxFeeRate?: number
395
437
  minRequestIntervalMs?: number
438
+ /** Called before and after each sweep transaction. */
439
+ onProgress?: SweepProgressListener
396
440
  }
397
441
 
398
442
  /**
@@ -443,6 +487,8 @@ export interface MnemonicScanArgs extends FeeOptions {
443
487
  paths?: readonly SweepPathSpec[]
444
488
  gapLimit?: number
445
489
  minRequestIntervalMs?: number
490
+ /** Called as the scan moves from address to address, and when it finds coins. */
491
+ onProgress?: SweepProgressListener
446
492
  }
447
493
 
448
494
  /**
@@ -490,12 +536,17 @@ export async function scanMnemonic(args: MnemonicScanArgs): Promise<MnemonicScan
490
536
  const found: SweepInput[] = []
491
537
  const summaries: PathScanSummary[] = []
492
538
 
493
- const walk = async (node: HD, prefix: string): Promise<{ used: number; inputs: SweepInput[] }> => {
539
+ const walk = async (
540
+ node: HD,
541
+ prefix: string,
542
+ at: { name: string; pathIndex: number; chain: 'receive' | 'change' }
543
+ ): Promise<{ used: number; inputs: SweepInput[] }> => {
494
544
  let used = 0
495
545
  let unusedRun = 0
496
546
  const inputs: SweepInput[] = []
497
547
  for (let i = 0; i < MAX_SCAN_INDEX && unusedRun < gapLimit; i++) {
498
548
  const address = addressForKey(node.deriveChild(i).privKey, true, network)
549
+ report(args.onProgress, { stage: 'address', ...at, pathCount: chains.length, chainPath: prefix, index: i })
499
550
  await pace()
500
551
  if (!(await addressHasHistory(args.woc, address))) {
501
552
  unusedRun++
@@ -506,16 +557,35 @@ export async function scanMnemonic(args: MnemonicScanArgs): Promise<MnemonicScan
506
557
  await pace()
507
558
  const utxos = await getUtxosForAddress(args.woc, address)
508
559
  inputs.push(...utxos.map(u => ({ ...u, address, path: `${prefix}/${i}` })))
560
+ if (utxos.length > 0) {
561
+ report(args.onProgress, {
562
+ stage: 'found',
563
+ name: at.name,
564
+ pathIndex: at.pathIndex,
565
+ path: `${prefix}/${i}`,
566
+ utxoCount: utxos.length,
567
+ satoshis: utxos.reduce((n, u) => n + u.satoshis, 0)
568
+ })
569
+ }
509
570
  }
510
571
  return { used, inputs }
511
572
  }
512
573
 
513
- for (const chain of chains) {
514
- const receive = await walk(chain.receive, chain.spec.receive)
574
+ for (const [pathIndex, chain] of chains.entries()) {
575
+ const at = { name: chain.spec.name, pathIndex }
576
+ const receive = await walk(chain.receive, chain.spec.receive, { ...at, chain: 'receive' })
515
577
  let change = { used: 0, inputs: [] as SweepInput[] }
516
578
  const changeScanned = receive.used > 0 && chain.change !== undefined
517
- if (changeScanned) change = await walk(chain.change!, chain.spec.change!)
579
+ if (changeScanned) change = await walk(chain.change!, chain.spec.change!, { ...at, chain: 'change' })
518
580
  found.push(...receive.inputs, ...change.inputs)
581
+ const all = [...receive.inputs, ...change.inputs]
582
+ report(args.onProgress, {
583
+ stage: 'path-done',
584
+ ...at,
585
+ usedAddresses: receive.used + change.used,
586
+ utxoCount: all.length,
587
+ satoshis: all.reduce((n, u) => n + u.satoshis, 0)
588
+ })
519
589
  summaries.push({
520
590
  name: chain.spec.name,
521
591
  receive: chain.spec.receive,
@@ -623,6 +693,7 @@ export async function decideMnemonicImport(
623
693
  }
624
694
  ): Promise<MnemonicImportDecision> {
625
695
  if (args.probe) {
696
+ report(args.onProgress, { stage: 'backup' })
626
697
  // Profile 0 of the phrase, derived exactly as the wallet derives it (deriveProfileKeys).
627
698
  const primaryKey = withSeed(args.mnemonic, args.passphrase ?? '', root => deriveProfileKeys(root, 0).primaryKey)
628
699
  try {
@@ -664,9 +735,20 @@ async function executeSweep(
664
735
  const keyed = plan.inputs.map(input => ({ input, ...args.keyFor(input) }))
665
736
  const sources = new Map<string, Beef>()
666
737
 
738
+ const batchCount = Math.ceil(keyed.length / maxInputs)
667
739
  for (let start = 0; start < keyed.length; start += maxInputs) {
668
740
  const candidates = keyed.slice(start, start + maxInputs)
669
741
  const batch: SweepBatchResult = { inputCount: 0, inputSatoshis: 0, importedSatoshis: 0, feeSatoshis: 0 }
742
+ const index = start / maxInputs
743
+ const finished = (): void =>
744
+ report(args.onProgress, {
745
+ stage: 'batch-done',
746
+ index,
747
+ count: batchCount,
748
+ ...(batch.txid ? { txid: batch.txid } : {}),
749
+ ...(batch.error ? { error: batch.error } : {})
750
+ })
751
+ report(args.onProgress, { stage: 'batch', index, count: batchCount, inputCount: candidates.length })
670
752
  let reference: string | undefined
671
753
  try {
672
754
  // Verify each input against the real source transaction: its real value
@@ -694,7 +776,10 @@ async function executeSweep(
694
776
  inputBeef.mergeBeef(source.toBinaryAtomic(k.input.txid))
695
777
  spend.set(`${k.input.txid}.${k.input.vout}`, { ...k, satoshis })
696
778
  }
697
- if (spend.size === 0) continue
779
+ if (spend.size === 0) {
780
+ finished()
781
+ continue
782
+ }
698
783
  batches.push(batch)
699
784
 
700
785
  const created = await wallet.createAction(
@@ -759,9 +844,11 @@ async function executeSweep(
759
844
  feeSatoshis: fee
760
845
  })
761
846
  for (const k of spend.values()) spent.push({ ...k.input, satoshis: k.satoshis })
847
+ finished()
762
848
  } catch (error) {
763
849
  if (!batches.includes(batch)) batches.push(batch)
764
850
  batch.error = error instanceof Error ? error.message : String(error)
851
+ finished()
765
852
  if (reference) {
766
853
  try {
767
854
  await wallet.abortAction({ reference }, adminOriginator)
@@ -1,6 +1,19 @@
1
1
  import ExpoModulesCore
2
2
  import Foundation
3
3
 
4
+ /// A JS number in an untyped dictionary arrives as a Swift `Double` over JSI
5
+ /// and as an `NSNumber` over the old bridge. `Double as? Int` is always nil, so
6
+ /// a plain cast refused every request on the JSI path. Whole, finite values in
7
+ /// the JS safe-integer range are accepted; anything else is not a byte count.
8
+ private func wholeNumber(_ value: Any?) -> Int? {
9
+ if let int = value as? Int { return int }
10
+ if let double = value as? Double, double.isFinite, double == double.rounded(),
11
+ abs(double) <= 9_007_199_254_740_991 {
12
+ return Int(double)
13
+ }
14
+ return nil
15
+ }
16
+
4
17
  public final class BsvBoundedFetchModule: Module {
5
18
  private let lock = NSLock()
6
19
  private var requests: [String: BoundedRequest] = [:]
@@ -12,7 +25,7 @@ public final class BsvBoundedFetchModule: Module {
12
25
  guard let id = options["id"] as? String,
13
26
  let address = options["url"] as? String,
14
27
  let url = URL(string: address), url.scheme == "https",
15
- let limit = options["maxBytes"] as? Int, (0...67108864).contains(limit) else {
28
+ let limit = wholeNumber(options["maxBytes"]), (0...67108864).contains(limit) else {
16
29
  promise.reject("ERR_INVALID_REQUEST", "Invalid bounded HTTPS request")
17
30
  return
18
31
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.24.0",
3
+ "version": "0.24.2",
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",