@cloak.dev/sdk 0.2.11 → 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,36 @@ 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
+
25
+ ## [0.2.12]
26
+
27
+ ### Fixed
28
+
29
+ * A proof no longer fails with "Failed to execute 'postMessage' on 'Worker': Data cannot be cloned, out of
30
+ memory" when the browser cannot hold one prover worker per core. On that error the SDK frees the
31
+ workers, retries with 4, and if that also runs out of memory proves single-threaded. Previously
32
+ every retry in the same tab failed the same way, because the workers are cached for the page's
33
+ lifetime. Other proving errors are thrown unchanged.
34
+
35
+ ### Changed
36
+
37
+ * The `Network` type and note validation no longer accept `"devnet"`; the accepted values are
38
+ `"localnet"`, `"testnet"` and `"mainnet"`.
39
+
10
40
  ## [0.2.11]
11
41
 
12
42
  ### 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.11 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.11
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
@@ -73,22 +73,27 @@ registration step (some of the shipped examples set it on a local fork); it is n
73
73
  Do not expose `programId`, the relay URL or the circuits base as end-user input. Wallet adapters are
74
74
  the in-app signer; keypair files belong to scripts only.
75
75
 
76
- ### Devnet and local
76
+ ### Mainnet only
77
77
 
78
- The same SDK runs against a devnet or local deployment by pointing the three coordinates at it:
78
+ Cloak runs on Solana mainnet only. Test with small amounts (the
79
+ minimum deposit is 0.01 SOL). The published package talks to the mainnet program and
80
+ `https://api.cloak.ag` and nothing else.
81
+
82
+ ### Local fork (SDK contributors)
83
+
84
+ The shipped examples and scripts default to a local mainnet fork (`http://127.0.0.1:8899`) with a
85
+ local relay (`http://127.0.0.1:5500`), configured through environment variables they read
86
+ themselves:
79
87
 
80
88
  ```bash
81
- SOLANA_RPC_URL=https://api.devnet.solana.com # or http://127.0.0.1:8899 for a local fork
82
- CLOAK_RELAY_URL=<endpoint serving that deployment> # read by examples/ and scripts/, NOT by the SDK
83
- CLOAK_PROGRAM_ID=<program id of that deployment> # examples read this; pass it as programId in your code
89
+ SOLANA_RPC_URL=http://127.0.0.1:8899
90
+ CLOAK_RELAY_URL=http://127.0.0.1:5500 # read by examples/ and scripts/, NOT by the SDK
91
+ CLOAK_PROGRAM_ID=<program id of the local deployment>
84
92
  ```
85
93
 
86
- `CLOAK_RELAY_URL` configures the shipped examples and scripts, which pass its value as `relayUrl`.
87
- The SDK itself does not read it: the endpoint a build may talk to comes from `src/config/relay.ts`,
88
- so pointing at a devnet or local deployment means editing that file in a checkout and building it.
89
-
90
- The shipped examples default to a local fork (`http://127.0.0.1:8899`) with a local relay
91
- (`http://127.0.0.1:5500`); see [Examples](#examples).
94
+ The SDK itself does not read `CLOAK_RELAY_URL`: the endpoint a build may talk to comes from
95
+ `src/config/relay.ts`, so running against a local deployment means editing that file in a checkout
96
+ and building it, as described above. See [Examples](#examples).
92
97
 
93
98
  ## Quick start: private SOL send (single file, keypair)
94
99
 
@@ -131,8 +136,10 @@ async function main() {
131
136
  const amount = BigInt(lamportsArg);
132
137
 
133
138
  // The wallet's long-lived UTXO keypair and its viewing base (nk). A real wallet derives the
134
- // keypair from its seed (deriveUtxoKeypairFromSpendKey); a throwaway keypair keeps this script
135
- // self-contained.
139
+ // keypair from a seed it stores (deriveSpendKey(seed) -> deriveUtxoKeypairFromSpendKey); a
140
+ // throwaway keypair keeps this script self-contained. Throwaway means exactly that: if the run
141
+ // stops between the deposit and the withdrawal, the key is gone and so is the deposited note.
142
+ // Never use one for more than test amounts.
136
143
  const owner = await generateUtxoKeypair();
137
144
  const nk = getNkFromUtxoPrivateKey(owner.privateKey);
138
145
 
@@ -225,6 +232,7 @@ await transact(params, {
225
232
  walletPublicKey: signer.address,
226
233
  chainNoteViewingKeyNk: nk,
227
234
  chainNoteSalt: noteSalt,
235
+ ownerUtxoKeypair: owner, // the user's seed-derived UTXO keypair; it owns the note
228
236
  });
229
237
  ```
230
238
 
@@ -251,6 +259,7 @@ await transact(
251
259
  signMessage: (message) => wallet.signMessage(message),
252
260
  walletPublicKey: signer.address, // becomes the authenticated sender
253
261
  chainNoteViewingKeyNk: nk,
262
+ ownerUtxoKeypair: owner, // mandatory on every spend flow: it owns any change
254
263
  },
255
264
  );
256
265
  ```
@@ -790,7 +799,7 @@ relay endpoint and the localhost-RPC check.
790
799
 
791
800
  ## Version and compatibility
792
801
 
793
- - SDK 0.2.11 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
802
+ - SDK 0.2.13 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
794
803
  (deployed 2026-08-24) and the 0.2.0 circuit bundle — the program and circuit bundle are unchanged
795
804
  since 0.2.0; only the SDK package version has moved. The 0.2.5 flows were exercised on mainnet on
796
805
  2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to USDC and USDT;
@@ -821,6 +830,12 @@ relay endpoint and the localhost-RPC check.
821
830
  [CHANGELOG.md](CHANGELOG.md)).
822
831
  - 0.2.11 lets that bridge send a transaction the wallet added its own instructions to (Solflare's
823
832
  guard instructions); 0.2.10 refused it (see [CHANGELOG.md](CHANGELOG.md)).
833
+ - 0.2.12 retries a proof with fewer workers, then single-threaded, when the browser runs out of
834
+ memory handing data to the prover workers; it changes no wire format, hash or signature (see
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)).
824
839
  - Proofs generated with the 0.1.x circuits are rejected by the mainnet program. SDK 0.1.x builds
825
840
  (which ship the 0.1.0 bundle) are not usable against it; upgrade to 0.2.x.
826
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
@@ -979,8 +979,8 @@ function validateNote(note) {
979
979
  if (typeof note.timestamp !== "number" || note.timestamp <= 0) {
980
980
  throw new Error("Timestamp must be a positive number");
981
981
  }
982
- if (!["localnet", "devnet", "testnet", "mainnet"].includes(note.network)) {
983
- throw new Error("Network must be localnet, devnet, testnet, or mainnet");
982
+ if (!["localnet", "testnet", "mainnet"].includes(note.network)) {
983
+ throw new Error("Network must be localnet, testnet, or mainnet");
984
984
  }
985
985
  if (note.depositSignature !== void 0 && typeof note.depositSignature !== "string") {
986
986
  throw new Error("Deposit signature must be a string");
@@ -1206,9 +1206,6 @@ function detectNetworkFromRpcUrl(rpcUrl) {
1206
1206
  if (lowerUrl.includes("testnet") || lowerUrl.includes("api.testnet")) {
1207
1207
  return "testnet";
1208
1208
  }
1209
- if (lowerUrl.includes("devnet") || lowerUrl.includes("api.devnet")) {
1210
- return "devnet";
1211
- }
1212
1209
  if (lowerUrl.includes("localhost") || lowerUrl.includes("127.0.0.1") || lowerUrl.includes("local")) {
1213
1210
  return "localnet";
1214
1211
  }
@@ -1218,8 +1215,6 @@ function getRpcUrlForNetwork(network) {
1218
1215
  switch (network) {
1219
1216
  case "mainnet":
1220
1217
  return "https://api.mainnet-beta.solana.com";
1221
- case "devnet":
1222
- return "https://api.devnet.solana.com";
1223
1218
  case "localnet":
1224
1219
  return "http://localhost:8899";
1225
1220
  default:
@@ -1234,11 +1229,11 @@ function isValidRpcUrl(url) {
1234
1229
  return false;
1235
1230
  }
1236
1231
  }
1237
- function getExplorerUrl(signature, network = "devnet") {
1232
+ function getExplorerUrl(signature, network = "mainnet") {
1238
1233
  const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
1239
1234
  return `https://explorer.solana.com/tx/${signature}${cluster}`;
1240
1235
  }
1241
- function getAddressExplorerUrl(address2, network = "devnet") {
1236
+ function getAddressExplorerUrl(address2, network = "mainnet") {
1242
1237
  const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
1243
1238
  return `https://explorer.solana.com/address/${address2}${cluster}`;
1244
1239
  }
@@ -4467,10 +4462,6 @@ function buildRangeRiskScoreJob(OracleJob, walletAddress) {
4467
4462
  });
4468
4463
  }
4469
4464
  async function getQueue(sb, rpcUrl) {
4470
- const network = detectNetworkFromRpcUrl(rpcUrl);
4471
- if (network === "devnet") {
4472
- return await sb.getDefaultDevnetQueue(rpcUrl);
4473
- }
4474
4465
  return await sb.getDefaultQueue(rpcUrl);
4475
4466
  }
4476
4467
  async function fetchRiskQuoteIx(connection, wallet, rangeApiKey) {
@@ -6678,13 +6669,75 @@ async function circuitArtifactFetch(url, init) {
6678
6669
  var IS_REACT_NATIVE = isReactNative();
6679
6670
  var IS_BROWSER = IS_REACT_NATIVE || typeof window !== "undefined" || typeof globalThis !== "undefined" && typeof globalThis.document !== "undefined";
6680
6671
  var DEFAULT_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
6681
- async function fetchFileAsBuffer(url) {
6682
- const response = await circuitArtifactFetch(url);
6683
- if (!response.ok) {
6684
- 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);
6685
6740
  }
6686
- const arrayBuffer = await response.arrayBuffer();
6687
- return new CapturedUint8Array(arrayBuffer);
6688
6741
  }
6689
6742
  var CapturedUint8Array = Uint8Array;
6690
6743
  var capturedTypedArraySet = Uint8Array.prototype.set;
@@ -6734,9 +6787,9 @@ async function getNodeFs() {
6734
6787
  _nodeFs = await loadNodeModule("fs");
6735
6788
  return _nodeFs;
6736
6789
  }
6737
- async function loadCircuitArtifact(path) {
6790
+ async function loadCircuitArtifact(path, onBytes) {
6738
6791
  if (isCircuitArtifactUrl(path)) {
6739
- return fetchFileAsBuffer(path);
6792
+ return fetchFileAsBuffer(path, onBytes);
6740
6793
  }
6741
6794
  if (IS_BROWSER) {
6742
6795
  throw new Error(
@@ -6777,10 +6830,24 @@ function resolveVerificationBase(circuitsPath2) {
6777
6830
  return assertAllowedCircuitsBase(circuitsPath2);
6778
6831
  }
6779
6832
  var _verifiedArtifacts = /* @__PURE__ */ new Map();
6780
- 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
+ };
6781
6840
  const [wasm, zkey] = await Promise.all([
6782
- loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`),
6783
- 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
+ })
6784
6851
  ]);
6785
6852
  return { wasm, zkey };
6786
6853
  }
@@ -6800,11 +6867,11 @@ function copyAndVerify(base, canonical) {
6800
6867
  }
6801
6868
  return Object.freeze({ wasm, zkey, digests: Object.freeze(digests) });
6802
6869
  }
6803
- async function loadVerifiedCircuitArtifacts(circuitsPath2) {
6870
+ async function loadVerifiedCircuitArtifacts(circuitsPath2, onDownload) {
6804
6871
  const base = resolveVerificationBase(circuitsPath2);
6805
6872
  const cached = _verifiedArtifacts.get(base);
6806
6873
  if (cached) return copyAndVerify(base, cached);
6807
- const loaded = await loadArtifactPair(base);
6874
+ const loaded = await loadArtifactPair(base, onDownload);
6808
6875
  const artifacts = copyAndVerify(base, loaded);
6809
6876
  _verifiedArtifacts.set(base, loaded);
6810
6877
  return artifacts;
@@ -6860,8 +6927,8 @@ function canRebuildMerkleTreeFromChain() {
6860
6927
  }
6861
6928
  var DEFAULT_TRANSACTION_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
6862
6929
  var circuitsPath = DEFAULT_TRANSACTION_CIRCUITS_URL;
6863
- async function resolveTransactionCircuitFiles() {
6864
- const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath);
6930
+ async function resolveTransactionCircuitFiles(onDownload) {
6931
+ const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath, onDownload);
6865
6932
  return { wasmPath: wasm, zkeyPath: zkey };
6866
6933
  }
6867
6934
  var _transactPaddingSaltCounter = 0;
@@ -7411,17 +7478,125 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
7411
7478
  }
7412
7479
  _registeredViewingKeys.add(cacheKey);
7413
7480
  }
7414
- async function generateTransactionProof(inputs, onProgress) {
7481
+ async function generateTransactionProof(inputs, onProgress, onStatus) {
7415
7482
  onProgress?.(10);
7416
7483
  onProgress?.(30);
7417
- const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles();
7418
- const { proof, publicSignals } = await snarkjs.groth16.fullProve(
7419
- inputs,
7420
- wasmInput,
7421
- zkeyInput
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
7422
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();
7504
+ let result;
7505
+ try {
7506
+ result = await threaded(
7507
+ () => withReportedCores(workers, () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput))
7508
+ );
7509
+ } catch (err) {
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;
7515
+ await terminateThreadedCurve();
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
+ }
7527
+ }
7528
+ }
7423
7529
  onProgress?.(100);
7424
- return { proof, publicSignals };
7530
+ return { proof: result.proof, publicSignals: result.publicSignals };
7531
+ }
7532
+ function isProverOutOfMemory(err) {
7533
+ const name = err?.name;
7534
+ const message = String(err?.message ?? err ?? "");
7535
+ if (name === "DataCloneError") return true;
7536
+ if (/out of memory/i.test(message)) return true;
7537
+ return name === "RangeError" && /(allocat|array buffer|memory)/i.test(message);
7538
+ }
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
+ }
7574
+ async function withReportedCores(cores, fn) {
7575
+ const nav = globalThis.navigator;
7576
+ const reported = nav?.hardwareConcurrency;
7577
+ let shadowed = false;
7578
+ if (nav && typeof reported === "number" && reported > cores) {
7579
+ try {
7580
+ Object.defineProperty(nav, "hardwareConcurrency", { value: cores, configurable: true });
7581
+ shadowed = true;
7582
+ } catch {
7583
+ }
7584
+ }
7585
+ try {
7586
+ return await fn();
7587
+ } finally {
7588
+ if (shadowed) delete nav.hardwareConcurrency;
7589
+ }
7590
+ }
7591
+ async function terminateThreadedCurve() {
7592
+ const g = globalThis;
7593
+ const curve = g.curve_bn128;
7594
+ if (!curve) return;
7595
+ try {
7596
+ await curve.terminate?.();
7597
+ } catch {
7598
+ }
7599
+ g.curve_bn128 = null;
7425
7600
  }
7426
7601
  function proofToBytesLocal(proof) {
7427
7602
  const result = new Uint8Array(256);
@@ -9509,7 +9684,7 @@ async function transact(params, rawOptions) {
9509
9684
  let publicSignals;
9510
9685
  const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
9511
9686
  try {
9512
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
9687
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
9513
9688
  proof = result.proof;
9514
9689
  publicSignals = result.publicSignals;
9515
9690
  releaseProofSlot?.();
@@ -10811,7 +10986,7 @@ async function swapUtxo(params, rawOptions) {
10811
10986
  let proof;
10812
10987
  let publicSignals;
10813
10988
  try {
10814
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
10989
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
10815
10990
  proof = result.proof;
10816
10991
  publicSignals = result.publicSignals;
10817
10992
  } catch (proofError) {
@@ -15779,7 +15954,7 @@ async function withShieldRetries(attempt, hooks = {}) {
15779
15954
  }
15780
15955
 
15781
15956
  // src/index.ts
15782
- var VERSION = "0.2.11";
15957
+ var VERSION = "0.2.13";
15783
15958
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15784
15959
  // Annotate the CommonJS export names for ESM import in node:
15785
15960
  0 && (module.exports = {
package/dist/index.d.cts CHANGED
@@ -84,7 +84,7 @@ interface EncryptedMetadataBundle {
84
84
  /**
85
85
  * Supported Solana networks
86
86
  */
87
- type Network = "localnet" | "devnet" | "mainnet" | "testnet";
87
+ type Network = "localnet" | "mainnet" | "testnet";
88
88
  /**
89
89
  * Minimal wallet adapter interface
90
90
  * Compatible with @solana/wallet-adapter-base
@@ -1449,7 +1449,7 @@ declare function validateTransfers(recipients: Array<{
1449
1449
  * Detect network from RPC URL
1450
1450
  *
1451
1451
  * Attempts to detect the Solana network from common RPC URL patterns.
1452
- * Falls back to devnet if unable to detect.
1452
+ * Falls back to mainnet if unable to detect.
1453
1453
  */
1454
1454
  declare function detectNetworkFromRpcUrl(rpcUrl?: string): Network;
1455
1455
  /**
@@ -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.11";
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
@@ -84,7 +84,7 @@ interface EncryptedMetadataBundle {
84
84
  /**
85
85
  * Supported Solana networks
86
86
  */
87
- type Network = "localnet" | "devnet" | "mainnet" | "testnet";
87
+ type Network = "localnet" | "mainnet" | "testnet";
88
88
  /**
89
89
  * Minimal wallet adapter interface
90
90
  * Compatible with @solana/wallet-adapter-base
@@ -1449,7 +1449,7 @@ declare function validateTransfers(recipients: Array<{
1449
1449
  * Detect network from RPC URL
1450
1450
  *
1451
1451
  * Attempts to detect the Solana network from common RPC URL patterns.
1452
- * Falls back to devnet if unable to detect.
1452
+ * Falls back to mainnet if unable to detect.
1453
1453
  */
1454
1454
  declare function detectNetworkFromRpcUrl(rpcUrl?: string): Network;
1455
1455
  /**
@@ -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.11";
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
@@ -86,8 +86,8 @@ function validateNote(note) {
86
86
  if (typeof note.timestamp !== "number" || note.timestamp <= 0) {
87
87
  throw new Error("Timestamp must be a positive number");
88
88
  }
89
- if (!["localnet", "devnet", "testnet", "mainnet"].includes(note.network)) {
90
- throw new Error("Network must be localnet, devnet, testnet, or mainnet");
89
+ if (!["localnet", "testnet", "mainnet"].includes(note.network)) {
90
+ throw new Error("Network must be localnet, testnet, or mainnet");
91
91
  }
92
92
  if (note.depositSignature !== void 0 && typeof note.depositSignature !== "string") {
93
93
  throw new Error("Deposit signature must be a string");
@@ -309,9 +309,6 @@ function detectNetworkFromRpcUrl(rpcUrl) {
309
309
  if (lowerUrl.includes("testnet") || lowerUrl.includes("api.testnet")) {
310
310
  return "testnet";
311
311
  }
312
- if (lowerUrl.includes("devnet") || lowerUrl.includes("api.devnet")) {
313
- return "devnet";
314
- }
315
312
  if (lowerUrl.includes("localhost") || lowerUrl.includes("127.0.0.1") || lowerUrl.includes("local")) {
316
313
  return "localnet";
317
314
  }
@@ -321,8 +318,6 @@ function getRpcUrlForNetwork(network) {
321
318
  switch (network) {
322
319
  case "mainnet":
323
320
  return "https://api.mainnet-beta.solana.com";
324
- case "devnet":
325
- return "https://api.devnet.solana.com";
326
321
  case "localnet":
327
322
  return "http://localhost:8899";
328
323
  default:
@@ -337,11 +332,11 @@ function isValidRpcUrl(url) {
337
332
  return false;
338
333
  }
339
334
  }
340
- function getExplorerUrl(signature, network = "devnet") {
335
+ function getExplorerUrl(signature, network = "mainnet") {
341
336
  const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
342
337
  return `https://explorer.solana.com/tx/${signature}${cluster}`;
343
338
  }
344
- function getAddressExplorerUrl(address2, network = "devnet") {
339
+ function getAddressExplorerUrl(address2, network = "mainnet") {
345
340
  const cluster = network === "mainnet" ? "" : `?cluster=${network}`;
346
341
  return `https://explorer.solana.com/address/${address2}${cluster}`;
347
342
  }
@@ -3579,10 +3574,6 @@ function buildRangeRiskScoreJob(OracleJob, walletAddress) {
3579
3574
  });
3580
3575
  }
3581
3576
  async function getQueue(sb, rpcUrl) {
3582
- const network = detectNetworkFromRpcUrl(rpcUrl);
3583
- if (network === "devnet") {
3584
- return await sb.getDefaultDevnetQueue(rpcUrl);
3585
- }
3586
3577
  return await sb.getDefaultQueue(rpcUrl);
3587
3578
  }
3588
3579
  async function fetchRiskQuoteIx(connection, wallet, rangeApiKey) {
@@ -5780,13 +5771,75 @@ async function circuitArtifactFetch(url, init) {
5780
5771
  var IS_REACT_NATIVE = isReactNative();
5781
5772
  var IS_BROWSER = IS_REACT_NATIVE || typeof window !== "undefined" || typeof globalThis !== "undefined" && typeof globalThis.document !== "undefined";
5782
5773
  var DEFAULT_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
5783
- async function fetchFileAsBuffer(url) {
5784
- const response = await circuitArtifactFetch(url);
5785
- if (!response.ok) {
5786
- 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);
5787
5842
  }
5788
- const arrayBuffer = await response.arrayBuffer();
5789
- return new CapturedUint8Array(arrayBuffer);
5790
5843
  }
5791
5844
  var CapturedUint8Array = Uint8Array;
5792
5845
  var capturedTypedArraySet = Uint8Array.prototype.set;
@@ -5836,9 +5889,9 @@ async function getNodeFs() {
5836
5889
  _nodeFs = await loadNodeModule("fs");
5837
5890
  return _nodeFs;
5838
5891
  }
5839
- async function loadCircuitArtifact(path) {
5892
+ async function loadCircuitArtifact(path, onBytes) {
5840
5893
  if (isCircuitArtifactUrl(path)) {
5841
- return fetchFileAsBuffer(path);
5894
+ return fetchFileAsBuffer(path, onBytes);
5842
5895
  }
5843
5896
  if (IS_BROWSER) {
5844
5897
  throw new Error(
@@ -5879,10 +5932,24 @@ function resolveVerificationBase(circuitsPath2) {
5879
5932
  return assertAllowedCircuitsBase(circuitsPath2);
5880
5933
  }
5881
5934
  var _verifiedArtifacts = /* @__PURE__ */ new Map();
5882
- 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
+ };
5883
5942
  const [wasm, zkey] = await Promise.all([
5884
- loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`),
5885
- 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
+ })
5886
5953
  ]);
5887
5954
  return { wasm, zkey };
5888
5955
  }
@@ -5902,11 +5969,11 @@ function copyAndVerify(base, canonical) {
5902
5969
  }
5903
5970
  return Object.freeze({ wasm, zkey, digests: Object.freeze(digests) });
5904
5971
  }
5905
- async function loadVerifiedCircuitArtifacts(circuitsPath2) {
5972
+ async function loadVerifiedCircuitArtifacts(circuitsPath2, onDownload) {
5906
5973
  const base = resolveVerificationBase(circuitsPath2);
5907
5974
  const cached = _verifiedArtifacts.get(base);
5908
5975
  if (cached) return copyAndVerify(base, cached);
5909
- const loaded = await loadArtifactPair(base);
5976
+ const loaded = await loadArtifactPair(base, onDownload);
5910
5977
  const artifacts = copyAndVerify(base, loaded);
5911
5978
  _verifiedArtifacts.set(base, loaded);
5912
5979
  return artifacts;
@@ -5962,8 +6029,8 @@ function canRebuildMerkleTreeFromChain() {
5962
6029
  }
5963
6030
  var DEFAULT_TRANSACTION_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
5964
6031
  var circuitsPath = DEFAULT_TRANSACTION_CIRCUITS_URL;
5965
- async function resolveTransactionCircuitFiles() {
5966
- const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath);
6032
+ async function resolveTransactionCircuitFiles(onDownload) {
6033
+ const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath, onDownload);
5967
6034
  return { wasmPath: wasm, zkeyPath: zkey };
5968
6035
  }
5969
6036
  var _transactPaddingSaltCounter = 0;
@@ -6513,17 +6580,125 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6513
6580
  }
6514
6581
  _registeredViewingKeys.add(cacheKey);
6515
6582
  }
6516
- async function generateTransactionProof(inputs, onProgress) {
6583
+ async function generateTransactionProof(inputs, onProgress, onStatus) {
6517
6584
  onProgress?.(10);
6518
6585
  onProgress?.(30);
6519
- const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles();
6520
- const { proof, publicSignals } = await snarkjs.groth16.fullProve(
6521
- inputs,
6522
- wasmInput,
6523
- zkeyInput
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
6524
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();
6606
+ let result;
6607
+ try {
6608
+ result = await threaded(
6609
+ () => withReportedCores(workers, () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput))
6610
+ );
6611
+ } catch (err) {
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;
6617
+ await terminateThreadedCurve();
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
+ }
6629
+ }
6630
+ }
6525
6631
  onProgress?.(100);
6526
- return { proof, publicSignals };
6632
+ return { proof: result.proof, publicSignals: result.publicSignals };
6633
+ }
6634
+ function isProverOutOfMemory(err) {
6635
+ const name = err?.name;
6636
+ const message = String(err?.message ?? err ?? "");
6637
+ if (name === "DataCloneError") return true;
6638
+ if (/out of memory/i.test(message)) return true;
6639
+ return name === "RangeError" && /(allocat|array buffer|memory)/i.test(message);
6640
+ }
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
+ }
6676
+ async function withReportedCores(cores, fn) {
6677
+ const nav = globalThis.navigator;
6678
+ const reported = nav?.hardwareConcurrency;
6679
+ let shadowed = false;
6680
+ if (nav && typeof reported === "number" && reported > cores) {
6681
+ try {
6682
+ Object.defineProperty(nav, "hardwareConcurrency", { value: cores, configurable: true });
6683
+ shadowed = true;
6684
+ } catch {
6685
+ }
6686
+ }
6687
+ try {
6688
+ return await fn();
6689
+ } finally {
6690
+ if (shadowed) delete nav.hardwareConcurrency;
6691
+ }
6692
+ }
6693
+ async function terminateThreadedCurve() {
6694
+ const g = globalThis;
6695
+ const curve = g.curve_bn128;
6696
+ if (!curve) return;
6697
+ try {
6698
+ await curve.terminate?.();
6699
+ } catch {
6700
+ }
6701
+ g.curve_bn128 = null;
6527
6702
  }
6528
6703
  function proofToBytesLocal(proof) {
6529
6704
  const result = new Uint8Array(256);
@@ -8611,7 +8786,7 @@ async function transact(params, rawOptions) {
8611
8786
  let publicSignals;
8612
8787
  const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
8613
8788
  try {
8614
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
8789
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
8615
8790
  proof = result.proof;
8616
8791
  publicSignals = result.publicSignals;
8617
8792
  releaseProofSlot?.();
@@ -9913,7 +10088,7 @@ async function swapUtxo(params, rawOptions) {
9913
10088
  let proof;
9914
10089
  let publicSignals;
9915
10090
  try {
9916
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
10091
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
9917
10092
  proof = result.proof;
9918
10093
  publicSignals = result.publicSignals;
9919
10094
  } catch (proofError) {
@@ -14872,7 +15047,7 @@ async function withShieldRetries(attempt, hooks = {}) {
14872
15047
  }
14873
15048
 
14874
15049
  // src/index.ts
14875
- var VERSION = "0.2.11";
15050
+ var VERSION = "0.2.13";
14876
15051
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
14877
15052
  export {
14878
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.11",
4
+ "version": "0.2.13",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",