@cloak.dev/sdk 0.2.12 → 0.2.13

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
@@ -7,6 +7,21 @@ the README's "Version and compatibility" section and in the git history.
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.13]
11
+
12
+ ### Fixed
13
+
14
+ * The threaded prover starts at most 8 workers (2 in a 32-bit browser) instead of one per reported
15
+ core, up to 64. Measured in Chrome on one real proof: 64 workers peak at +3.2 GB, 8 at +1.2 GB,
16
+ 2 at +0.7 GB, and the proof barely gets faster past 8 (1.6 s at 64, 2.1 s at 8). A many-core
17
+ Windows PC in a 32-bit Chrome hung on "Generating the proof" and then crashed the tab "Out of
18
+ Memory" at about 1 GB.
19
+ * A threaded proof that neither finishes nor fails (a worker that never answers) is abandoned after
20
+ 60 s and retried single-threaded, instead of waiting forever.
21
+ * The circuit download (~23 MB, first proof of a page) aborts after 20 s without data and retries,
22
+ up to 3 attempts, instead of waiting forever. It reports "Downloading circuit files (n of m MB)..."
23
+ through the flow's status callback, then "Generating zero-knowledge proof..." once it finishes.
24
+
10
25
  ## [0.2.12]
11
26
 
12
27
  ### Fixed
package/README.md CHANGED
@@ -5,13 +5,13 @@ per-mint pool, send privately inside the pool, withdraw to any address, or swap
5
5
  USDC/USDT with the output landing in a public token account. Groth16 proofs are generated
6
6
  client-side (snarkjs) and verified on-chain by the Cloak program.
7
7
 
8
- Version 0.2.12 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
8
+ Version 0.2.13 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
9
9
  `cloak-transaction-0.2.0` circuit bundle. See [Version and compatibility](#version-and-compatibility).
10
10
 
11
11
  ## Installation
12
12
 
13
13
  ```bash
14
- npm install @cloak.dev/sdk@^0.2.12
14
+ npm install @cloak.dev/sdk@^0.2.13
15
15
  ```
16
16
 
17
17
  The SDK is built on [`@solana/kit`](https://github.com/anza-xyz/kit) and re-exports the pieces an
@@ -799,7 +799,7 @@ relay endpoint and the localhost-RPC check.
799
799
 
800
800
  ## Version and compatibility
801
801
 
802
- - SDK 0.2.12 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
802
+ - SDK 0.2.13 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
803
803
  (deployed 2026-08-24) and the 0.2.0 circuit bundle — the program and circuit bundle are unchanged
804
804
  since 0.2.0; only the SDK package version has moved. The 0.2.5 flows were exercised on mainnet on
805
805
  2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to USDC and USDT;
@@ -833,6 +833,9 @@ relay endpoint and the localhost-RPC check.
833
833
  - 0.2.12 retries a proof with fewer workers, then single-threaded, when the browser runs out of
834
834
  memory handing data to the prover workers; it changes no wire format, hash or signature (see
835
835
  [CHANGELOG.md](CHANGELOG.md)).
836
+ - 0.2.13 caps the prover at 8 workers (2 in a 32-bit browser), bounds the circuit download and
837
+ retries a stalled proof single-threaded; it changes no wire format, hash or signature (see
838
+ [CHANGELOG.md](CHANGELOG.md)).
836
839
  - Proofs generated with the 0.1.x circuits are rejected by the mainnet program. SDK 0.1.x builds
837
840
  (which ship the 0.1.0 bundle) are not usable against it; upgrade to 0.2.x.
838
841
  - The note-based `CloakSDK` class is removed in 0.2.0. It targeted the pre-0.2.0 instruction layout
package/dist/index.cjs CHANGED
@@ -6669,13 +6669,75 @@ async function circuitArtifactFetch(url, init) {
6669
6669
  var IS_REACT_NATIVE = isReactNative();
6670
6670
  var IS_BROWSER = IS_REACT_NATIVE || typeof window !== "undefined" || typeof globalThis !== "undefined" && typeof globalThis.document !== "undefined";
6671
6671
  var DEFAULT_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
6672
- async function fetchFileAsBuffer(url) {
6673
- const response = await circuitArtifactFetch(url);
6674
- if (!response.ok) {
6675
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
6672
+ var ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS = 2e4;
6673
+ var ARTIFACT_DOWNLOAD_ATTEMPTS = 3;
6674
+ var ARTIFACT_DOWNLOAD_BACKOFF_MS = 1e3;
6675
+ var RETRYABLE_ARTIFACT_STATUSES = /* @__PURE__ */ new Set([408, 425, 429, 500, 502, 503, 504]);
6676
+ async function fetchFileAsBuffer(url, onBytes) {
6677
+ let lastError;
6678
+ for (let attempt = 1; attempt <= ARTIFACT_DOWNLOAD_ATTEMPTS; attempt++) {
6679
+ try {
6680
+ return await fetchFileAttempt(url, onBytes);
6681
+ } catch (err) {
6682
+ lastError = err;
6683
+ if (err.retryable === false) throw err;
6684
+ if (attempt < ARTIFACT_DOWNLOAD_ATTEMPTS) {
6685
+ await new Promise((resolve) => setTimeout(resolve, ARTIFACT_DOWNLOAD_BACKOFF_MS * attempt));
6686
+ }
6687
+ }
6688
+ }
6689
+ throw new Error(
6690
+ `Failed to download ${url} after ${ARTIFACT_DOWNLOAD_ATTEMPTS} attempts: ` + String(lastError?.message ?? lastError)
6691
+ );
6692
+ }
6693
+ async function fetchFileAttempt(url, onBytes) {
6694
+ const controller = new AbortController();
6695
+ let idleTimer;
6696
+ const armIdle = () => {
6697
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
6698
+ idleTimer = setTimeout(() => controller.abort(), ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS);
6699
+ };
6700
+ armIdle();
6701
+ try {
6702
+ const response = await circuitArtifactFetch(url, { signal: controller.signal });
6703
+ if (!response.ok) {
6704
+ const error = new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
6705
+ error.retryable = RETRYABLE_ARTIFACT_STATUSES.has(response.status);
6706
+ throw error;
6707
+ }
6708
+ const lengthHeader = Number(response.headers?.get?.("content-length"));
6709
+ const total = Number.isFinite(lengthHeader) && lengthHeader > 0 ? lengthHeader : null;
6710
+ const reader = response.body?.getReader?.();
6711
+ if (!reader) {
6712
+ const arrayBuffer = await response.arrayBuffer();
6713
+ onBytes?.(arrayBuffer.byteLength, total);
6714
+ return new CapturedUint8Array(arrayBuffer);
6715
+ }
6716
+ const chunks = [];
6717
+ let received = 0;
6718
+ for (; ; ) {
6719
+ const { done, value } = await reader.read();
6720
+ if (done) break;
6721
+ armIdle();
6722
+ chunks.push(value);
6723
+ received += value.byteLength;
6724
+ onBytes?.(received, total);
6725
+ }
6726
+ const out = new CapturedUint8Array(received);
6727
+ let offset = 0;
6728
+ for (const chunk of chunks) {
6729
+ out.set(chunk, offset);
6730
+ offset += chunk.byteLength;
6731
+ }
6732
+ return out;
6733
+ } catch (err) {
6734
+ if (controller.signal.aborted) {
6735
+ throw new Error(`Download of ${url} stalled: no data for ${ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS / 1e3}s`);
6736
+ }
6737
+ throw err;
6738
+ } finally {
6739
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
6676
6740
  }
6677
- const arrayBuffer = await response.arrayBuffer();
6678
- return new CapturedUint8Array(arrayBuffer);
6679
6741
  }
6680
6742
  var CapturedUint8Array = Uint8Array;
6681
6743
  var capturedTypedArraySet = Uint8Array.prototype.set;
@@ -6725,9 +6787,9 @@ async function getNodeFs() {
6725
6787
  _nodeFs = await loadNodeModule("fs");
6726
6788
  return _nodeFs;
6727
6789
  }
6728
- async function loadCircuitArtifact(path) {
6790
+ async function loadCircuitArtifact(path, onBytes) {
6729
6791
  if (isCircuitArtifactUrl(path)) {
6730
- return fetchFileAsBuffer(path);
6792
+ return fetchFileAsBuffer(path, onBytes);
6731
6793
  }
6732
6794
  if (IS_BROWSER) {
6733
6795
  throw new Error(
@@ -6768,10 +6830,24 @@ function resolveVerificationBase(circuitsPath2) {
6768
6830
  return assertAllowedCircuitsBase(circuitsPath2);
6769
6831
  }
6770
6832
  var _verifiedArtifacts = /* @__PURE__ */ new Map();
6771
- async function loadArtifactPair(base) {
6833
+ async function loadArtifactPair(base, onDownload) {
6834
+ const progress = { wasm: 0, zkey: 0, wasmTotal: null, zkeyTotal: null };
6835
+ const report = () => {
6836
+ if (!onDownload) return;
6837
+ const total = progress.wasmTotal !== null && progress.zkeyTotal !== null ? progress.wasmTotal + progress.zkeyTotal : null;
6838
+ onDownload(progress.wasm + progress.zkey, total);
6839
+ };
6772
6840
  const [wasm, zkey] = await Promise.all([
6773
- loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`),
6774
- loadCircuitArtifact(`${base}/transaction_final.zkey`)
6841
+ loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`, (r, t) => {
6842
+ progress.wasm = r;
6843
+ progress.wasmTotal = t;
6844
+ report();
6845
+ }),
6846
+ loadCircuitArtifact(`${base}/transaction_final.zkey`, (r, t) => {
6847
+ progress.zkey = r;
6848
+ progress.zkeyTotal = t;
6849
+ report();
6850
+ })
6775
6851
  ]);
6776
6852
  return { wasm, zkey };
6777
6853
  }
@@ -6791,11 +6867,11 @@ function copyAndVerify(base, canonical) {
6791
6867
  }
6792
6868
  return Object.freeze({ wasm, zkey, digests: Object.freeze(digests) });
6793
6869
  }
6794
- async function loadVerifiedCircuitArtifacts(circuitsPath2) {
6870
+ async function loadVerifiedCircuitArtifacts(circuitsPath2, onDownload) {
6795
6871
  const base = resolveVerificationBase(circuitsPath2);
6796
6872
  const cached = _verifiedArtifacts.get(base);
6797
6873
  if (cached) return copyAndVerify(base, cached);
6798
- const loaded = await loadArtifactPair(base);
6874
+ const loaded = await loadArtifactPair(base, onDownload);
6799
6875
  const artifacts = copyAndVerify(base, loaded);
6800
6876
  _verifiedArtifacts.set(base, loaded);
6801
6877
  return artifacts;
@@ -6851,8 +6927,8 @@ function canRebuildMerkleTreeFromChain() {
6851
6927
  }
6852
6928
  var DEFAULT_TRANSACTION_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
6853
6929
  var circuitsPath = DEFAULT_TRANSACTION_CIRCUITS_URL;
6854
- async function resolveTransactionCircuitFiles() {
6855
- const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath);
6930
+ async function resolveTransactionCircuitFiles(onDownload) {
6931
+ const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath, onDownload);
6856
6932
  return { wasmPath: wasm, zkeyPath: zkey };
6857
6933
  }
6858
6934
  var _transactPaddingSaltCounter = 0;
@@ -7402,27 +7478,52 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
7402
7478
  }
7403
7479
  _registeredViewingKeys.add(cacheKey);
7404
7480
  }
7405
- async function generateTransactionProof(inputs, onProgress) {
7481
+ async function generateTransactionProof(inputs, onProgress, onStatus) {
7406
7482
  onProgress?.(10);
7407
7483
  onProgress?.(30);
7408
- const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles();
7484
+ let lastReportedMb = -1;
7485
+ const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles(
7486
+ onStatus ? (received, total) => {
7487
+ const mb = Math.floor(received / 1e6);
7488
+ if (mb === lastReportedMb) return;
7489
+ lastReportedMb = mb;
7490
+ onStatus(
7491
+ total ? `Downloading circuit files (${mb} of ${Math.ceil(total / 1e6)} MB)...` : `Downloading circuit files (${mb} MB)...`
7492
+ );
7493
+ } : void 0
7494
+ );
7495
+ if (lastReportedMb >= 0) onStatus?.("Generating zero-knowledge proof...");
7496
+ const threaded = (run) => withProveWatchdog(run(), PROVE_WATCHDOG_MS);
7497
+ const singleThread = async () => {
7498
+ await terminateThreadedCurve();
7499
+ return snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput, void 0, void 0, {
7500
+ singleThread: true
7501
+ });
7502
+ };
7503
+ const workers = await defaultProverWorkers();
7409
7504
  let result;
7410
7505
  try {
7411
- result = await snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput);
7506
+ result = await threaded(
7507
+ () => withReportedCores(workers, () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput))
7508
+ );
7412
7509
  } catch (err) {
7413
- if (!isProverOutOfMemory(err)) throw err;
7414
- await terminateThreadedCurve();
7415
- try {
7416
- result = await withReportedCores(
7417
- REDUCED_PROVER_WORKERS,
7418
- () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput)
7419
- );
7420
- } catch (retryErr) {
7421
- if (!isProverOutOfMemory(retryErr)) throw retryErr;
7510
+ if (err instanceof ProveWatchdogTimeout) {
7511
+ onStatus?.("Proof is taking longer than expected, retrying on a single thread...");
7512
+ result = await singleThread();
7513
+ } else {
7514
+ if (!isProverOutOfMemory(err)) throw err;
7422
7515
  await terminateThreadedCurve();
7423
- result = await snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput, void 0, void 0, {
7424
- singleThread: true
7425
- });
7516
+ try {
7517
+ result = await threaded(
7518
+ () => withReportedCores(
7519
+ REDUCED_PROVER_WORKERS,
7520
+ () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput)
7521
+ )
7522
+ );
7523
+ } catch (retryErr) {
7524
+ if (!isProverOutOfMemory(retryErr) && !(retryErr instanceof ProveWatchdogTimeout)) throw retryErr;
7525
+ result = await singleThread();
7526
+ }
7426
7527
  }
7427
7528
  }
7428
7529
  onProgress?.(100);
@@ -7436,6 +7537,40 @@ function isProverOutOfMemory(err) {
7436
7537
  return name === "RangeError" && /(allocat|array buffer|memory)/i.test(message);
7437
7538
  }
7438
7539
  var REDUCED_PROVER_WORKERS = 4;
7540
+ var MAX_PROVER_WORKERS = 8;
7541
+ var MAX_PROVER_WORKERS_32BIT = 2;
7542
+ async function is32BitBrowser() {
7543
+ const nav = globalThis.navigator;
7544
+ if (!nav) return false;
7545
+ try {
7546
+ const hints = await nav.userAgentData?.getHighEntropyValues?.(["bitness", "wow64"]);
7547
+ if (hints) return hints.bitness === "32" || hints.wow64 === true;
7548
+ } catch {
7549
+ }
7550
+ return /\bWOW64\b/.test(nav.userAgent ?? "");
7551
+ }
7552
+ async function defaultProverWorkers() {
7553
+ return await is32BitBrowser() ? MAX_PROVER_WORKERS_32BIT : MAX_PROVER_WORKERS;
7554
+ }
7555
+ var PROVE_WATCHDOG_MS = 6e4;
7556
+ var ProveWatchdogTimeout = class extends Error {
7557
+ constructor(ms) {
7558
+ super(`Threaded proof did not finish within ${Math.round(ms / 1e3)}s`);
7559
+ this.name = "ProveWatchdogTimeout";
7560
+ }
7561
+ };
7562
+ function withProveWatchdog(work, ms) {
7563
+ work.catch(() => {
7564
+ });
7565
+ let timer;
7566
+ const timeout = new Promise((_, reject) => {
7567
+ timer = setTimeout(() => reject(new ProveWatchdogTimeout(ms)), ms);
7568
+ timer.unref?.();
7569
+ });
7570
+ return Promise.race([work, timeout]).finally(() => {
7571
+ if (timer !== void 0) clearTimeout(timer);
7572
+ });
7573
+ }
7439
7574
  async function withReportedCores(cores, fn) {
7440
7575
  const nav = globalThis.navigator;
7441
7576
  const reported = nav?.hardwareConcurrency;
@@ -9549,7 +9684,7 @@ async function transact(params, rawOptions) {
9549
9684
  let publicSignals;
9550
9685
  const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
9551
9686
  try {
9552
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
9687
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
9553
9688
  proof = result.proof;
9554
9689
  publicSignals = result.publicSignals;
9555
9690
  releaseProofSlot?.();
@@ -10851,7 +10986,7 @@ async function swapUtxo(params, rawOptions) {
10851
10986
  let proof;
10852
10987
  let publicSignals;
10853
10988
  try {
10854
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
10989
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
10855
10990
  proof = result.proof;
10856
10991
  publicSignals = result.publicSignals;
10857
10992
  } catch (proofError) {
@@ -15819,7 +15954,7 @@ async function withShieldRetries(attempt, hooks = {}) {
15819
15954
  }
15820
15955
 
15821
15956
  // src/index.ts
15822
- var VERSION = "0.2.12";
15957
+ var VERSION = "0.2.13";
15823
15958
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15824
15959
  // Annotate the CommonJS export names for ESM import in node:
15825
15960
  0 && (module.exports = {
package/dist/index.d.cts CHANGED
@@ -3982,6 +3982,12 @@ declare function swapWithChange(inputUtxos: Utxo[], swapAmount: bigint, outputMi
3982
3982
  * verified against the bundle's digests.
3983
3983
  */
3984
3984
  declare const DEFAULT_CIRCUITS_URL: string;
3985
+ /**
3986
+ * Fetch a file from a URL and return as Uint8Array
3987
+ * Works in both browser and Node.js environments
3988
+ */
3989
+ /** Bytes received so far by one artifact download. */
3990
+ type ArtifactDownloadProgress = (received: number, total: number | null) => void;
3985
3991
  /**
3986
3992
  * Pinned circuit artifact hashes (SHA-256), flattened from the release table in
3987
3993
  * `proving/circuits.ts`.
@@ -4066,7 +4072,9 @@ interface VerifiedCircuitArtifacts {
4066
4072
  * different artifacts it needs different DIGESTS, which is a source edit and a rebuild, exactly
4067
4073
  * like the endpoint pin.
4068
4074
  */
4069
- declare function loadVerifiedCircuitArtifacts(circuitsPath: string | null): Promise<VerifiedCircuitArtifacts>;
4075
+ declare function loadVerifiedCircuitArtifacts(circuitsPath: string | null,
4076
+ /** Called while the artifacts download (first proof of a page only; later calls hit the memo). */
4077
+ onDownload?: ArtifactDownloadProgress): Promise<VerifiedCircuitArtifacts>;
4070
4078
  /**
4071
4079
  * Report whether a circuit's artifacts match the digests pinned in this SDK.
4072
4080
  *
@@ -6559,7 +6567,7 @@ declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>
6559
6567
  * @packageDocumentation
6560
6568
  */
6561
6569
 
6562
- declare const VERSION = "0.2.12";
6570
+ declare const VERSION = "0.2.13";
6563
6571
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
6564
6572
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
6565
6573
 
package/dist/index.d.ts CHANGED
@@ -3982,6 +3982,12 @@ declare function swapWithChange(inputUtxos: Utxo[], swapAmount: bigint, outputMi
3982
3982
  * verified against the bundle's digests.
3983
3983
  */
3984
3984
  declare const DEFAULT_CIRCUITS_URL: string;
3985
+ /**
3986
+ * Fetch a file from a URL and return as Uint8Array
3987
+ * Works in both browser and Node.js environments
3988
+ */
3989
+ /** Bytes received so far by one artifact download. */
3990
+ type ArtifactDownloadProgress = (received: number, total: number | null) => void;
3985
3991
  /**
3986
3992
  * Pinned circuit artifact hashes (SHA-256), flattened from the release table in
3987
3993
  * `proving/circuits.ts`.
@@ -4066,7 +4072,9 @@ interface VerifiedCircuitArtifacts {
4066
4072
  * different artifacts it needs different DIGESTS, which is a source edit and a rebuild, exactly
4067
4073
  * like the endpoint pin.
4068
4074
  */
4069
- declare function loadVerifiedCircuitArtifacts(circuitsPath: string | null): Promise<VerifiedCircuitArtifacts>;
4075
+ declare function loadVerifiedCircuitArtifacts(circuitsPath: string | null,
4076
+ /** Called while the artifacts download (first proof of a page only; later calls hit the memo). */
4077
+ onDownload?: ArtifactDownloadProgress): Promise<VerifiedCircuitArtifacts>;
4070
4078
  /**
4071
4079
  * Report whether a circuit's artifacts match the digests pinned in this SDK.
4072
4080
  *
@@ -6559,7 +6567,7 @@ declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>
6559
6567
  * @packageDocumentation
6560
6568
  */
6561
6569
 
6562
- declare const VERSION = "0.2.12";
6570
+ declare const VERSION = "0.2.13";
6563
6571
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
6564
6572
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
6565
6573
 
package/dist/index.js CHANGED
@@ -5771,13 +5771,75 @@ async function circuitArtifactFetch(url, init) {
5771
5771
  var IS_REACT_NATIVE = isReactNative();
5772
5772
  var IS_BROWSER = IS_REACT_NATIVE || typeof window !== "undefined" || typeof globalThis !== "undefined" && typeof globalThis.document !== "undefined";
5773
5773
  var DEFAULT_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
5774
- async function fetchFileAsBuffer(url) {
5775
- const response = await circuitArtifactFetch(url);
5776
- if (!response.ok) {
5777
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
5774
+ var ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS = 2e4;
5775
+ var ARTIFACT_DOWNLOAD_ATTEMPTS = 3;
5776
+ var ARTIFACT_DOWNLOAD_BACKOFF_MS = 1e3;
5777
+ var RETRYABLE_ARTIFACT_STATUSES = /* @__PURE__ */ new Set([408, 425, 429, 500, 502, 503, 504]);
5778
+ async function fetchFileAsBuffer(url, onBytes) {
5779
+ let lastError;
5780
+ for (let attempt = 1; attempt <= ARTIFACT_DOWNLOAD_ATTEMPTS; attempt++) {
5781
+ try {
5782
+ return await fetchFileAttempt(url, onBytes);
5783
+ } catch (err) {
5784
+ lastError = err;
5785
+ if (err.retryable === false) throw err;
5786
+ if (attempt < ARTIFACT_DOWNLOAD_ATTEMPTS) {
5787
+ await new Promise((resolve) => setTimeout(resolve, ARTIFACT_DOWNLOAD_BACKOFF_MS * attempt));
5788
+ }
5789
+ }
5790
+ }
5791
+ throw new Error(
5792
+ `Failed to download ${url} after ${ARTIFACT_DOWNLOAD_ATTEMPTS} attempts: ` + String(lastError?.message ?? lastError)
5793
+ );
5794
+ }
5795
+ async function fetchFileAttempt(url, onBytes) {
5796
+ const controller = new AbortController();
5797
+ let idleTimer;
5798
+ const armIdle = () => {
5799
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
5800
+ idleTimer = setTimeout(() => controller.abort(), ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS);
5801
+ };
5802
+ armIdle();
5803
+ try {
5804
+ const response = await circuitArtifactFetch(url, { signal: controller.signal });
5805
+ if (!response.ok) {
5806
+ const error = new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
5807
+ error.retryable = RETRYABLE_ARTIFACT_STATUSES.has(response.status);
5808
+ throw error;
5809
+ }
5810
+ const lengthHeader = Number(response.headers?.get?.("content-length"));
5811
+ const total = Number.isFinite(lengthHeader) && lengthHeader > 0 ? lengthHeader : null;
5812
+ const reader = response.body?.getReader?.();
5813
+ if (!reader) {
5814
+ const arrayBuffer = await response.arrayBuffer();
5815
+ onBytes?.(arrayBuffer.byteLength, total);
5816
+ return new CapturedUint8Array(arrayBuffer);
5817
+ }
5818
+ const chunks = [];
5819
+ let received = 0;
5820
+ for (; ; ) {
5821
+ const { done, value } = await reader.read();
5822
+ if (done) break;
5823
+ armIdle();
5824
+ chunks.push(value);
5825
+ received += value.byteLength;
5826
+ onBytes?.(received, total);
5827
+ }
5828
+ const out = new CapturedUint8Array(received);
5829
+ let offset = 0;
5830
+ for (const chunk of chunks) {
5831
+ out.set(chunk, offset);
5832
+ offset += chunk.byteLength;
5833
+ }
5834
+ return out;
5835
+ } catch (err) {
5836
+ if (controller.signal.aborted) {
5837
+ throw new Error(`Download of ${url} stalled: no data for ${ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS / 1e3}s`);
5838
+ }
5839
+ throw err;
5840
+ } finally {
5841
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
5778
5842
  }
5779
- const arrayBuffer = await response.arrayBuffer();
5780
- return new CapturedUint8Array(arrayBuffer);
5781
5843
  }
5782
5844
  var CapturedUint8Array = Uint8Array;
5783
5845
  var capturedTypedArraySet = Uint8Array.prototype.set;
@@ -5827,9 +5889,9 @@ async function getNodeFs() {
5827
5889
  _nodeFs = await loadNodeModule("fs");
5828
5890
  return _nodeFs;
5829
5891
  }
5830
- async function loadCircuitArtifact(path) {
5892
+ async function loadCircuitArtifact(path, onBytes) {
5831
5893
  if (isCircuitArtifactUrl(path)) {
5832
- return fetchFileAsBuffer(path);
5894
+ return fetchFileAsBuffer(path, onBytes);
5833
5895
  }
5834
5896
  if (IS_BROWSER) {
5835
5897
  throw new Error(
@@ -5870,10 +5932,24 @@ function resolveVerificationBase(circuitsPath2) {
5870
5932
  return assertAllowedCircuitsBase(circuitsPath2);
5871
5933
  }
5872
5934
  var _verifiedArtifacts = /* @__PURE__ */ new Map();
5873
- async function loadArtifactPair(base) {
5935
+ async function loadArtifactPair(base, onDownload) {
5936
+ const progress = { wasm: 0, zkey: 0, wasmTotal: null, zkeyTotal: null };
5937
+ const report = () => {
5938
+ if (!onDownload) return;
5939
+ const total = progress.wasmTotal !== null && progress.zkeyTotal !== null ? progress.wasmTotal + progress.zkeyTotal : null;
5940
+ onDownload(progress.wasm + progress.zkey, total);
5941
+ };
5874
5942
  const [wasm, zkey] = await Promise.all([
5875
- loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`),
5876
- loadCircuitArtifact(`${base}/transaction_final.zkey`)
5943
+ loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`, (r, t) => {
5944
+ progress.wasm = r;
5945
+ progress.wasmTotal = t;
5946
+ report();
5947
+ }),
5948
+ loadCircuitArtifact(`${base}/transaction_final.zkey`, (r, t) => {
5949
+ progress.zkey = r;
5950
+ progress.zkeyTotal = t;
5951
+ report();
5952
+ })
5877
5953
  ]);
5878
5954
  return { wasm, zkey };
5879
5955
  }
@@ -5893,11 +5969,11 @@ function copyAndVerify(base, canonical) {
5893
5969
  }
5894
5970
  return Object.freeze({ wasm, zkey, digests: Object.freeze(digests) });
5895
5971
  }
5896
- async function loadVerifiedCircuitArtifacts(circuitsPath2) {
5972
+ async function loadVerifiedCircuitArtifacts(circuitsPath2, onDownload) {
5897
5973
  const base = resolveVerificationBase(circuitsPath2);
5898
5974
  const cached = _verifiedArtifacts.get(base);
5899
5975
  if (cached) return copyAndVerify(base, cached);
5900
- const loaded = await loadArtifactPair(base);
5976
+ const loaded = await loadArtifactPair(base, onDownload);
5901
5977
  const artifacts = copyAndVerify(base, loaded);
5902
5978
  _verifiedArtifacts.set(base, loaded);
5903
5979
  return artifacts;
@@ -5953,8 +6029,8 @@ function canRebuildMerkleTreeFromChain() {
5953
6029
  }
5954
6030
  var DEFAULT_TRANSACTION_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
5955
6031
  var circuitsPath = DEFAULT_TRANSACTION_CIRCUITS_URL;
5956
- async function resolveTransactionCircuitFiles() {
5957
- const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath);
6032
+ async function resolveTransactionCircuitFiles(onDownload) {
6033
+ const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath, onDownload);
5958
6034
  return { wasmPath: wasm, zkeyPath: zkey };
5959
6035
  }
5960
6036
  var _transactPaddingSaltCounter = 0;
@@ -6504,27 +6580,52 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6504
6580
  }
6505
6581
  _registeredViewingKeys.add(cacheKey);
6506
6582
  }
6507
- async function generateTransactionProof(inputs, onProgress) {
6583
+ async function generateTransactionProof(inputs, onProgress, onStatus) {
6508
6584
  onProgress?.(10);
6509
6585
  onProgress?.(30);
6510
- const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles();
6586
+ let lastReportedMb = -1;
6587
+ const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles(
6588
+ onStatus ? (received, total) => {
6589
+ const mb = Math.floor(received / 1e6);
6590
+ if (mb === lastReportedMb) return;
6591
+ lastReportedMb = mb;
6592
+ onStatus(
6593
+ total ? `Downloading circuit files (${mb} of ${Math.ceil(total / 1e6)} MB)...` : `Downloading circuit files (${mb} MB)...`
6594
+ );
6595
+ } : void 0
6596
+ );
6597
+ if (lastReportedMb >= 0) onStatus?.("Generating zero-knowledge proof...");
6598
+ const threaded = (run) => withProveWatchdog(run(), PROVE_WATCHDOG_MS);
6599
+ const singleThread = async () => {
6600
+ await terminateThreadedCurve();
6601
+ return snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput, void 0, void 0, {
6602
+ singleThread: true
6603
+ });
6604
+ };
6605
+ const workers = await defaultProverWorkers();
6511
6606
  let result;
6512
6607
  try {
6513
- result = await snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput);
6608
+ result = await threaded(
6609
+ () => withReportedCores(workers, () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput))
6610
+ );
6514
6611
  } catch (err) {
6515
- if (!isProverOutOfMemory(err)) throw err;
6516
- await terminateThreadedCurve();
6517
- try {
6518
- result = await withReportedCores(
6519
- REDUCED_PROVER_WORKERS,
6520
- () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput)
6521
- );
6522
- } catch (retryErr) {
6523
- if (!isProverOutOfMemory(retryErr)) throw retryErr;
6612
+ if (err instanceof ProveWatchdogTimeout) {
6613
+ onStatus?.("Proof is taking longer than expected, retrying on a single thread...");
6614
+ result = await singleThread();
6615
+ } else {
6616
+ if (!isProverOutOfMemory(err)) throw err;
6524
6617
  await terminateThreadedCurve();
6525
- result = await snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput, void 0, void 0, {
6526
- singleThread: true
6527
- });
6618
+ try {
6619
+ result = await threaded(
6620
+ () => withReportedCores(
6621
+ REDUCED_PROVER_WORKERS,
6622
+ () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput)
6623
+ )
6624
+ );
6625
+ } catch (retryErr) {
6626
+ if (!isProverOutOfMemory(retryErr) && !(retryErr instanceof ProveWatchdogTimeout)) throw retryErr;
6627
+ result = await singleThread();
6628
+ }
6528
6629
  }
6529
6630
  }
6530
6631
  onProgress?.(100);
@@ -6538,6 +6639,40 @@ function isProverOutOfMemory(err) {
6538
6639
  return name === "RangeError" && /(allocat|array buffer|memory)/i.test(message);
6539
6640
  }
6540
6641
  var REDUCED_PROVER_WORKERS = 4;
6642
+ var MAX_PROVER_WORKERS = 8;
6643
+ var MAX_PROVER_WORKERS_32BIT = 2;
6644
+ async function is32BitBrowser() {
6645
+ const nav = globalThis.navigator;
6646
+ if (!nav) return false;
6647
+ try {
6648
+ const hints = await nav.userAgentData?.getHighEntropyValues?.(["bitness", "wow64"]);
6649
+ if (hints) return hints.bitness === "32" || hints.wow64 === true;
6650
+ } catch {
6651
+ }
6652
+ return /\bWOW64\b/.test(nav.userAgent ?? "");
6653
+ }
6654
+ async function defaultProverWorkers() {
6655
+ return await is32BitBrowser() ? MAX_PROVER_WORKERS_32BIT : MAX_PROVER_WORKERS;
6656
+ }
6657
+ var PROVE_WATCHDOG_MS = 6e4;
6658
+ var ProveWatchdogTimeout = class extends Error {
6659
+ constructor(ms) {
6660
+ super(`Threaded proof did not finish within ${Math.round(ms / 1e3)}s`);
6661
+ this.name = "ProveWatchdogTimeout";
6662
+ }
6663
+ };
6664
+ function withProveWatchdog(work, ms) {
6665
+ work.catch(() => {
6666
+ });
6667
+ let timer;
6668
+ const timeout = new Promise((_, reject) => {
6669
+ timer = setTimeout(() => reject(new ProveWatchdogTimeout(ms)), ms);
6670
+ timer.unref?.();
6671
+ });
6672
+ return Promise.race([work, timeout]).finally(() => {
6673
+ if (timer !== void 0) clearTimeout(timer);
6674
+ });
6675
+ }
6541
6676
  async function withReportedCores(cores, fn) {
6542
6677
  const nav = globalThis.navigator;
6543
6678
  const reported = nav?.hardwareConcurrency;
@@ -8651,7 +8786,7 @@ async function transact(params, rawOptions) {
8651
8786
  let publicSignals;
8652
8787
  const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
8653
8788
  try {
8654
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
8789
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
8655
8790
  proof = result.proof;
8656
8791
  publicSignals = result.publicSignals;
8657
8792
  releaseProofSlot?.();
@@ -9953,7 +10088,7 @@ async function swapUtxo(params, rawOptions) {
9953
10088
  let proof;
9954
10089
  let publicSignals;
9955
10090
  try {
9956
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
10091
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
9957
10092
  proof = result.proof;
9958
10093
  publicSignals = result.publicSignals;
9959
10094
  } catch (proofError) {
@@ -14912,7 +15047,7 @@ async function withShieldRetries(attempt, hooks = {}) {
14912
15047
  }
14913
15048
 
14914
15049
  // src/index.ts
14915
- var VERSION = "0.2.12";
15050
+ var VERSION = "0.2.13";
14916
15051
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
14917
15052
  export {
14918
15053
  AccountRole,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cloak.dev/sdk",
3
3
  "description": "Shield, send, and swap on Solana privately — TypeScript SDK with UTXO-based zero-knowledge transactions",
4
- "version": "0.2.12",
4
+ "version": "0.2.13",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",