@cloak.dev/sdk 0.2.12 → 0.2.14

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/dist/index.js CHANGED
@@ -627,7 +627,7 @@ function messageSignerFromCallback(address2, signMessage) {
627
627
  }
628
628
 
629
629
  // src/scanning/compliance-keys.ts
630
- import nacl2 from "tweetnacl";
630
+ import nacl3 from "tweetnacl";
631
631
  import { blake3 as blake32 } from "@noble/hashes/blake3";
632
632
  import { sha256 as sha2562 } from "@noble/hashes/sha2";
633
633
 
@@ -897,8 +897,14 @@ function connectionRpcEndpoint(connection) {
897
897
  // src/relay/payload.ts
898
898
  import { sha256 } from "@noble/hashes/sha2";
899
899
  import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils";
900
- import { createNoopSigner, getBase58Decoder as getBase58Decoder2 } from "@solana/kit";
900
+ import {
901
+ createNoopSigner,
902
+ getBase58Decoder as getBase58Decoder2,
903
+ getCompiledTransactionMessageDecoder,
904
+ getCompiledTransactionMessageEncoder
905
+ } from "@solana/kit";
901
906
  import { getTransferSolInstruction } from "@solana-program/system";
907
+ import nacl2 from "tweetnacl";
902
908
 
903
909
  // src/solana/transaction.ts
904
910
  import {
@@ -1369,6 +1375,61 @@ function buildAuthTransactionMessage(sender, digest) {
1369
1375
  function serializeAuthTransactionMessage(sender, digest) {
1370
1376
  return new Uint8Array(compileUnsigned(buildAuthTransactionMessage(sender, digest)).messageBytes);
1371
1377
  }
1378
+ var MAX_AUTH_TX_MESSAGE_BYTES = 1232;
1379
+ var TRANSFER_ZERO_LAMPORTS = Uint8Array.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1380
+ var SYSTEM_PROGRAM_ADDRESS2 = "11111111111111111111111111111111";
1381
+ function sameBytes(a, b) {
1382
+ return a.length === b.length && a.every((byte, i) => byte === b[i]);
1383
+ }
1384
+ function walletAuthTransactionMessageBinds(sender, payload, bytes) {
1385
+ if (bytes.length > MAX_AUTH_TX_MESSAGE_BYTES) return false;
1386
+ let compiled;
1387
+ try {
1388
+ compiled = getCompiledTransactionMessageDecoder().decode(bytes);
1389
+ if (compiled.version !== "legacy" && compiled.version !== 0) return false;
1390
+ if (!sameBytes(new Uint8Array(getCompiledTransactionMessageEncoder().encode(compiled)), bytes)) return false;
1391
+ } catch {
1392
+ return false;
1393
+ }
1394
+ if (!sanitizes(compiled)) return false;
1395
+ const accounts = compiled.staticAccounts;
1396
+ if (compiled.header.numSignerAccounts !== 1 || accounts[0] !== sender) return false;
1397
+ const lifetimeToken = compiled.lifetimeToken;
1398
+ if (lifetimeToken !== getBase58Decoder2().decode(sha256(payload))) return false;
1399
+ let ours = false;
1400
+ for (const instruction of compiled.instructions) {
1401
+ const program = accounts[instruction.programAddressIndex];
1402
+ if (program === SYSTEM_PROGRAM_ADDRESS2 && instruction.accountIndices?.length === 2 && instruction.accountIndices[0] === 0 && instruction.accountIndices[1] === 0 && sameBytes(new Uint8Array(instruction.data ?? []), TRANSFER_ZERO_LAMPORTS)) {
1403
+ ours = true;
1404
+ } else if (!WALLET_ADDED_PROGRAMS.includes(program)) {
1405
+ return false;
1406
+ }
1407
+ }
1408
+ return ours;
1409
+ }
1410
+ var WALLET_ADDED_PROGRAMS = [
1411
+ "ComputeBudget111111111111111111111111111111",
1412
+ "L2TExMFKdjpN9kozasaurPirfHy9P8sbXoAN1qA3S95"
1413
+ ];
1414
+ function sanitizes(compiled) {
1415
+ const { header, staticAccounts, instructions } = compiled;
1416
+ const lookups = compiled.addressTableLookups ?? [];
1417
+ if (header.numReadonlySignerAccounts >= header.numSignerAccounts) return false;
1418
+ if (header.numSignerAccounts + header.numReadonlyNonSignerAccounts > staticAccounts.length) return false;
1419
+ let total = staticAccounts.length;
1420
+ for (const lookup of lookups) {
1421
+ const loaded = lookup.writableIndexes.length + lookup.readonlyIndexes.length;
1422
+ if (loaded === 0) return false;
1423
+ total += loaded;
1424
+ }
1425
+ if (total > 256) return false;
1426
+ return instructions.every(
1427
+ (instruction) => (
1428
+ // Programs come from static keys only and are never the fee payer.
1429
+ instruction.programAddressIndex > 0 && instruction.programAddressIndex < staticAccounts.length && (instruction.accountIndices ?? []).every((index) => index < total)
1430
+ )
1431
+ );
1432
+ }
1372
1433
  async function signRelayAuthPayload(signer, payload) {
1373
1434
  if (isMessageSigner(signer)) {
1374
1435
  const signature = await signMessageBytes(signer, payload);
@@ -1392,7 +1453,21 @@ async function signRelayAuthPayload(signer, payload) {
1392
1453
  }
1393
1454
  const signature = new Uint8Array(own);
1394
1455
  assertDetachedSignature(signature, "signTransaction");
1395
- return { signature, mode: "transaction" };
1456
+ const signedMessage = new Uint8Array(signed.messageBytes);
1457
+ if (!nacl2.sign.detached.verify(signedMessage, signature, addressBytes(signer.address))) {
1458
+ throw new Error(
1459
+ "The wallet's signature does not match the Cloak auth transaction it returned. Nothing was submitted."
1460
+ );
1461
+ }
1462
+ if (sameBytes(signedMessage, new Uint8Array(compileUnsigned(message).messageBytes))) {
1463
+ return { signature, mode: "transaction" };
1464
+ }
1465
+ if (!walletAuthTransactionMessageBinds(signer.address, payload, signedMessage)) {
1466
+ throw new Error(
1467
+ "The wallet changed the Cloak auth transaction into one that no longer authorizes this request (another fee payer or signer, another blockhash, or no 0 SOL self-transfer). Nothing was submitted."
1468
+ );
1469
+ }
1470
+ return { signature, mode: "transaction", txMessage: signedMessage };
1396
1471
  }
1397
1472
  throw new Error("Relay auth signer can neither sign messages nor transactions.");
1398
1473
  }
@@ -1454,14 +1529,15 @@ async function buildRelayAuthFields(endpoint, programId, body, signers, fields =
1454
1529
  fields
1455
1530
  );
1456
1531
  const approvalStartedMs = Date.now();
1457
- const { signature, mode } = await signRelayAuthPayload(wallet, preimage.message);
1532
+ const { signature, mode, txMessage } = await signRelayAuthPayload(wallet, preimage.message);
1458
1533
  assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
1459
1534
  return {
1460
1535
  sender: preimage.sender,
1461
1536
  auth_issued_at: preimage.auth_issued_at,
1462
1537
  auth_nonce: preimage.auth_nonce,
1463
1538
  auth_signature: Buffer.from(signature).toString("base64"),
1464
- ...mode === "transaction" ? { auth_mode: mode } : {}
1539
+ ...mode === "transaction" ? { auth_mode: mode } : {},
1540
+ ...txMessage ? { auth_tx_message: Buffer.from(txMessage).toString("base64") } : {}
1465
1541
  };
1466
1542
  }
1467
1543
  var REQUEST_AUTH_BATCH_DOMAIN = "CLOAK_RELAY_BATCH_AUTH_V1";
@@ -1512,7 +1588,7 @@ function deriveViewingKeyFromNk(nk) {
1512
1588
  preimage.set(nk, CHAIN_NOTE_VK_DOMAIN.length);
1513
1589
  const derived = blake32(preimage);
1514
1590
  const privateKey = clampX25519Secret(derived);
1515
- const publicKey = nacl2.scalarMult.base(privateKey);
1591
+ const publicKey = nacl3.scalarMult.base(privateKey);
1516
1592
  return { privateKey, publicKey };
1517
1593
  }
1518
1594
  function deriveDiversifier(nk, commitmentHex, outputIndex) {
@@ -1547,7 +1623,7 @@ function deriveDiversifiedViewingKey(nk, diversifier) {
1547
1623
  preimage.set(diversifier, SK_D_DOMAIN.length + nk.length);
1548
1624
  const derived = blake32(preimage);
1549
1625
  const privateKey = clampX25519Secret(derived);
1550
- const publicKey = nacl2.scalarMult.base(privateKey);
1626
+ const publicKey = nacl3.scalarMult.base(privateKey);
1551
1627
  return { privateKey, publicKey };
1552
1628
  }
1553
1629
  function deriveViewingKeyFromSpendKey(skSpend) {
@@ -1610,7 +1686,7 @@ async function deriveUserCompliancePublicKey(masterCompliancePublicKey, userPubl
1610
1686
  masterCompliancePublicKey,
1611
1687
  userPublicKey
1612
1688
  );
1613
- return nacl2.scalarMult(factor, masterCompliancePublicKey);
1689
+ return nacl3.scalarMult(factor, masterCompliancePublicKey);
1614
1690
  }
1615
1691
  function bytesToHex3(bytes) {
1616
1692
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
@@ -1657,7 +1733,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1657
1733
  nonce: challenge.nonce,
1658
1734
  identifier: keyId,
1659
1735
  signature,
1660
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
1736
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
1737
+ ...signed.txMessage ? { tx_message: Buffer.from(signed.txMessage).toString("base64") } : {}
1661
1738
  })
1662
1739
  });
1663
1740
  if (!response.ok) {
@@ -1666,7 +1743,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1666
1743
  }
1667
1744
 
1668
1745
  // src/scanning/metadata-encryption.ts
1669
- import nacl3 from "tweetnacl";
1746
+ import nacl4 from "tweetnacl";
1670
1747
  var AES_GCM_NONCE_LENGTH = 12;
1671
1748
  var AES_GCM_TAG_LENGTH = 16;
1672
1749
  var X25519_KEY_LENGTH2 = 32;
@@ -1763,8 +1840,8 @@ async function aesGcmDecrypt(ciphertext, keyBytes, nonce) {
1763
1840
  }
1764
1841
  async function encryptForRecipient(plaintext, recipientPublicKey) {
1765
1842
  assert32Bytes2(recipientPublicKey, "recipientPublicKey");
1766
- const ephemeral = nacl3.box.keyPair();
1767
- const sharedSecret = nacl3.scalarMult(ephemeral.secretKey, recipientPublicKey);
1843
+ const ephemeral = nacl4.box.keyPair();
1844
+ const sharedSecret = nacl4.scalarMult(ephemeral.secretKey, recipientPublicKey);
1768
1845
  const nonce = randomBytes(AES_GCM_NONCE_LENGTH);
1769
1846
  const ciphertext = await aesGcmEncrypt(plaintext, sharedSecret, nonce);
1770
1847
  return {
@@ -1823,7 +1900,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
1823
1900
  const plaintext = new TextEncoder().encode(JSON.stringify(metadata));
1824
1901
  const basePoint = new Uint8Array(32);
1825
1902
  basePoint[0] = 9;
1826
- const viewingKeyPublic = nacl3.scalarMult(viewingKeyPrivate, basePoint);
1903
+ const viewingKeyPublic = nacl4.scalarMult(viewingKeyPrivate, basePoint);
1827
1904
  const [userPayload, compliancePayload] = await Promise.all([
1828
1905
  encryptForRecipient(plaintext, viewingKeyPublic),
1829
1906
  encryptForRecipient(plaintext, viewingKeyPublic)
@@ -1842,7 +1919,7 @@ async function decryptTransactionMetadata(encrypted, viewKeySecret) {
1842
1919
  const payload = decodePayload(encrypted);
1843
1920
  const ephemeralPk = hexToBytes(payload.ephemeral_pk);
1844
1921
  assert32Bytes2(ephemeralPk, "ephemeral public key");
1845
- const sharedSecret = nacl3.scalarMult(viewKeySecret, ephemeralPk);
1922
+ const sharedSecret = nacl4.scalarMult(viewKeySecret, ephemeralPk);
1846
1923
  return decryptWithSharedSecret(payload, sharedSecret);
1847
1924
  }
1848
1925
  async function decryptComplianceMetadataWithMasterKey(encrypted, masterCompliancePrivateKey, masterCompliancePublicKey, userPublicKey) {
@@ -1855,8 +1932,8 @@ async function decryptComplianceMetadataWithMasterKey(encrypted, masterComplianc
1855
1932
  masterCompliancePublicKey,
1856
1933
  userPublicKey
1857
1934
  );
1858
- const scaledEphemeral = nacl3.scalarMult(userFactor, ephemeralPk);
1859
- const sharedSecret = nacl3.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1935
+ const scaledEphemeral = nacl4.scalarMult(userFactor, ephemeralPk);
1936
+ const sharedSecret = nacl4.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1860
1937
  return decryptWithSharedSecret(payload, sharedSecret);
1861
1938
  }
1862
1939
 
@@ -3503,7 +3580,8 @@ var RelayService = class {
3503
3580
  nonce: challenge.nonce,
3504
3581
  identifier,
3505
3582
  signature,
3506
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
3583
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
3584
+ ...signed.txMessage ? { tx_message: this.bytesToBase64(signed.txMessage) } : {}
3507
3585
  })
3508
3586
  });
3509
3587
  if (!response.ok) {
@@ -4920,7 +4998,7 @@ function chainNoteFromBase64(base64) {
4920
4998
  }
4921
4999
 
4922
5000
  // src/notes/delivery-note.ts
4923
- import nacl4 from "tweetnacl";
5001
+ import nacl5 from "tweetnacl";
4924
5002
  var RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN = 32;
4925
5003
  var RECIPIENT_DELIVERY_NONCE_LEN = 24;
4926
5004
  var RECIPIENT_DELIVERY_PLAINTEXT_LEN = 40;
@@ -4971,10 +5049,10 @@ function encodeRecipientDeliveryNote(note, recipientViewingPublicKey) {
4971
5049
  const plaintext = new Uint8Array(RECIPIENT_DELIVERY_PLAINTEXT_LEN);
4972
5050
  writeU64LE2(plaintext, 0, note.amount);
4973
5051
  writeU256BE2(plaintext, 8, note.blinding);
4974
- const ephemeral = nacl4.box.keyPair();
4975
- const shared = nacl4.box.before(recipientViewingPublicKey, ephemeral.secretKey);
4976
- const nonce = nacl4.randomBytes(nacl4.secretbox.nonceLength);
4977
- const ciphertext = nacl4.secretbox(plaintext, nonce, shared);
5052
+ const ephemeral = nacl5.box.keyPair();
5053
+ const shared = nacl5.box.before(recipientViewingPublicKey, ephemeral.secretKey);
5054
+ const nonce = nacl5.randomBytes(nacl5.secretbox.nonceLength);
5055
+ const ciphertext = nacl5.secretbox(plaintext, nonce, shared);
4978
5056
  if (ciphertext.length !== RECIPIENT_DELIVERY_CIPHERTEXT_LEN) {
4979
5057
  throw new Error(
4980
5058
  `delivery ciphertext must be ${RECIPIENT_DELIVERY_CIPHERTEXT_LEN} bytes, got ${ciphertext.length}`
@@ -5000,8 +5078,8 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
5000
5078
  const ciphertext = envelope.slice(
5001
5079
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5002
5080
  );
5003
- const shared = nacl4.box.before(ephemeralPk, viewingSecretKey);
5004
- const plaintext = nacl4.secretbox.open(ciphertext, nonce, shared);
5081
+ const shared = nacl5.box.before(ephemeralPk, viewingSecretKey);
5082
+ const plaintext = nacl5.secretbox.open(ciphertext, nonce, shared);
5005
5083
  if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5006
5084
  return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5007
5085
  } catch {
@@ -5037,7 +5115,7 @@ async function createRecipientDeliveryOpener(viewingSecretKey) {
5037
5115
  }
5038
5116
  const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5039
5117
  const subtle = globalThis.crypto?.subtle;
5040
- const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
5118
+ const hsalsa = nacl5.lowlevel?.crypto_core_hsalsa20;
5041
5119
  if (!subtle || typeof hsalsa !== "function") return slow;
5042
5120
  let privateKey;
5043
5121
  const sharedKey = async (ephemeralPk) => {
@@ -5054,9 +5132,9 @@ async function createRecipientDeliveryOpener(viewingSecretKey) {
5054
5132
  pkcs8.set(X25519_PKCS8_PREFIX);
5055
5133
  pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5056
5134
  privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5057
- const probe = nacl4.box.keyPair().publicKey;
5135
+ const probe = nacl5.box.keyPair().publicKey;
5058
5136
  const fast = await sharedKey(probe);
5059
- const reference = nacl4.box.before(probe, viewingSecretKey);
5137
+ const reference = nacl5.box.before(probe, viewingSecretKey);
5060
5138
  if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5061
5139
  } catch {
5062
5140
  return slow;
@@ -5076,7 +5154,7 @@ async function createRecipientDeliveryOpener(viewingSecretKey) {
5076
5154
  return openRecipientDeliveryNote(envelope, viewingSecretKey);
5077
5155
  }
5078
5156
  try {
5079
- return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
5157
+ return decodeOpened(nacl5.secretbox.open(ciphertext, nonce, key));
5080
5158
  } catch {
5081
5159
  return null;
5082
5160
  }
@@ -5670,7 +5748,7 @@ async function matchChangeNote(params) {
5670
5748
 
5671
5749
  // src/flows/transact.ts
5672
5750
  import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
5673
- import nacl5 from "tweetnacl";
5751
+ import nacl6 from "tweetnacl";
5674
5752
 
5675
5753
  // src/relay/chain-note-time.ts
5676
5754
  async function relayChainNoteTimestampMs(relayUrl) {
@@ -5771,13 +5849,75 @@ async function circuitArtifactFetch(url, init) {
5771
5849
  var IS_REACT_NATIVE = isReactNative();
5772
5850
  var IS_BROWSER = IS_REACT_NATIVE || typeof window !== "undefined" || typeof globalThis !== "undefined" && typeof globalThis.document !== "undefined";
5773
5851
  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}`);
5852
+ var ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS = 2e4;
5853
+ var ARTIFACT_DOWNLOAD_ATTEMPTS = 3;
5854
+ var ARTIFACT_DOWNLOAD_BACKOFF_MS = 1e3;
5855
+ var RETRYABLE_ARTIFACT_STATUSES = /* @__PURE__ */ new Set([408, 425, 429, 500, 502, 503, 504]);
5856
+ async function fetchFileAsBuffer(url, onBytes) {
5857
+ let lastError;
5858
+ for (let attempt = 1; attempt <= ARTIFACT_DOWNLOAD_ATTEMPTS; attempt++) {
5859
+ try {
5860
+ return await fetchFileAttempt(url, onBytes);
5861
+ } catch (err) {
5862
+ lastError = err;
5863
+ if (err.retryable === false) throw err;
5864
+ if (attempt < ARTIFACT_DOWNLOAD_ATTEMPTS) {
5865
+ await new Promise((resolve) => setTimeout(resolve, ARTIFACT_DOWNLOAD_BACKOFF_MS * attempt));
5866
+ }
5867
+ }
5868
+ }
5869
+ throw new Error(
5870
+ `Failed to download ${url} after ${ARTIFACT_DOWNLOAD_ATTEMPTS} attempts: ` + String(lastError?.message ?? lastError)
5871
+ );
5872
+ }
5873
+ async function fetchFileAttempt(url, onBytes) {
5874
+ const controller = new AbortController();
5875
+ let idleTimer;
5876
+ const armIdle = () => {
5877
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
5878
+ idleTimer = setTimeout(() => controller.abort(), ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS);
5879
+ };
5880
+ armIdle();
5881
+ try {
5882
+ const response = await circuitArtifactFetch(url, { signal: controller.signal });
5883
+ if (!response.ok) {
5884
+ const error = new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
5885
+ error.retryable = RETRYABLE_ARTIFACT_STATUSES.has(response.status);
5886
+ throw error;
5887
+ }
5888
+ const lengthHeader = Number(response.headers?.get?.("content-length"));
5889
+ const total = Number.isFinite(lengthHeader) && lengthHeader > 0 ? lengthHeader : null;
5890
+ const reader = response.body?.getReader?.();
5891
+ if (!reader) {
5892
+ const arrayBuffer = await response.arrayBuffer();
5893
+ onBytes?.(arrayBuffer.byteLength, total);
5894
+ return new CapturedUint8Array(arrayBuffer);
5895
+ }
5896
+ const chunks = [];
5897
+ let received = 0;
5898
+ for (; ; ) {
5899
+ const { done, value } = await reader.read();
5900
+ if (done) break;
5901
+ armIdle();
5902
+ chunks.push(value);
5903
+ received += value.byteLength;
5904
+ onBytes?.(received, total);
5905
+ }
5906
+ const out = new CapturedUint8Array(received);
5907
+ let offset = 0;
5908
+ for (const chunk of chunks) {
5909
+ out.set(chunk, offset);
5910
+ offset += chunk.byteLength;
5911
+ }
5912
+ return out;
5913
+ } catch (err) {
5914
+ if (controller.signal.aborted) {
5915
+ throw new Error(`Download of ${url} stalled: no data for ${ARTIFACT_DOWNLOAD_IDLE_TIMEOUT_MS / 1e3}s`);
5916
+ }
5917
+ throw err;
5918
+ } finally {
5919
+ if (idleTimer !== void 0) clearTimeout(idleTimer);
5778
5920
  }
5779
- const arrayBuffer = await response.arrayBuffer();
5780
- return new CapturedUint8Array(arrayBuffer);
5781
5921
  }
5782
5922
  var CapturedUint8Array = Uint8Array;
5783
5923
  var capturedTypedArraySet = Uint8Array.prototype.set;
@@ -5827,9 +5967,9 @@ async function getNodeFs() {
5827
5967
  _nodeFs = await loadNodeModule("fs");
5828
5968
  return _nodeFs;
5829
5969
  }
5830
- async function loadCircuitArtifact(path) {
5970
+ async function loadCircuitArtifact(path, onBytes) {
5831
5971
  if (isCircuitArtifactUrl(path)) {
5832
- return fetchFileAsBuffer(path);
5972
+ return fetchFileAsBuffer(path, onBytes);
5833
5973
  }
5834
5974
  if (IS_BROWSER) {
5835
5975
  throw new Error(
@@ -5870,10 +6010,24 @@ function resolveVerificationBase(circuitsPath2) {
5870
6010
  return assertAllowedCircuitsBase(circuitsPath2);
5871
6011
  }
5872
6012
  var _verifiedArtifacts = /* @__PURE__ */ new Map();
5873
- async function loadArtifactPair(base) {
6013
+ async function loadArtifactPair(base, onDownload) {
6014
+ const progress = { wasm: 0, zkey: 0, wasmTotal: null, zkeyTotal: null };
6015
+ const report = () => {
6016
+ if (!onDownload) return;
6017
+ const total = progress.wasmTotal !== null && progress.zkeyTotal !== null ? progress.wasmTotal + progress.zkeyTotal : null;
6018
+ onDownload(progress.wasm + progress.zkey, total);
6019
+ };
5874
6020
  const [wasm, zkey] = await Promise.all([
5875
- loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`),
5876
- loadCircuitArtifact(`${base}/transaction_final.zkey`)
6021
+ loadCircuitArtifact(`${base}/transaction_js/transaction.wasm`, (r, t) => {
6022
+ progress.wasm = r;
6023
+ progress.wasmTotal = t;
6024
+ report();
6025
+ }),
6026
+ loadCircuitArtifact(`${base}/transaction_final.zkey`, (r, t) => {
6027
+ progress.zkey = r;
6028
+ progress.zkeyTotal = t;
6029
+ report();
6030
+ })
5877
6031
  ]);
5878
6032
  return { wasm, zkey };
5879
6033
  }
@@ -5893,11 +6047,11 @@ function copyAndVerify(base, canonical) {
5893
6047
  }
5894
6048
  return Object.freeze({ wasm, zkey, digests: Object.freeze(digests) });
5895
6049
  }
5896
- async function loadVerifiedCircuitArtifacts(circuitsPath2) {
6050
+ async function loadVerifiedCircuitArtifacts(circuitsPath2, onDownload) {
5897
6051
  const base = resolveVerificationBase(circuitsPath2);
5898
6052
  const cached = _verifiedArtifacts.get(base);
5899
6053
  if (cached) return copyAndVerify(base, cached);
5900
- const loaded = await loadArtifactPair(base);
6054
+ const loaded = await loadArtifactPair(base, onDownload);
5901
6055
  const artifacts = copyAndVerify(base, loaded);
5902
6056
  _verifiedArtifacts.set(base, loaded);
5903
6057
  return artifacts;
@@ -5953,8 +6107,8 @@ function canRebuildMerkleTreeFromChain() {
5953
6107
  }
5954
6108
  var DEFAULT_TRANSACTION_CIRCUITS_URL = TRANSACTION_CIRCUITS_BASE_URL;
5955
6109
  var circuitsPath = DEFAULT_TRANSACTION_CIRCUITS_URL;
5956
- async function resolveTransactionCircuitFiles() {
5957
- const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath);
6110
+ async function resolveTransactionCircuitFiles(onDownload) {
6111
+ const { wasm, zkey } = await loadVerifiedCircuitArtifacts(circuitsPath, onDownload);
5958
6112
  return { wasmPath: wasm, zkeyPath: zkey };
5959
6113
  }
5960
6114
  var _transactPaddingSaltCounter = 0;
@@ -6464,6 +6618,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6464
6618
  );
6465
6619
  let signatureBase64;
6466
6620
  let authMode = "message";
6621
+ let txMessageBase64;
6467
6622
  const messageBytes = new TextEncoder().encode(challenge.message);
6468
6623
  if (options.signMessage) {
6469
6624
  const sig = await options.signMessage(messageBytes);
@@ -6481,6 +6636,7 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6481
6636
  const signed = await signRelayAuthPayload(options.signer, messageBytes);
6482
6637
  signatureBase64 = Buffer.from(signed.signature).toString("base64");
6483
6638
  authMode = signed.mode;
6639
+ if (signed.txMessage) txMessageBase64 = Buffer.from(signed.txMessage).toString("base64");
6484
6640
  } else {
6485
6641
  throw new Error(
6486
6642
  "Viewing key registration is mandatory: signMessage or signer (wallet) or depositorKeypair is required."
@@ -6495,7 +6651,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6495
6651
  viewing_key: viewingKeyHex,
6496
6652
  nonce: challenge.nonce,
6497
6653
  signature: signatureBase64,
6498
- ...authMode === "transaction" ? { auth_mode: authMode } : {}
6654
+ ...authMode === "transaction" ? { auth_mode: authMode } : {},
6655
+ ...txMessageBase64 ? { tx_message: txMessageBase64 } : {}
6499
6656
  })
6500
6657
  });
6501
6658
  if (!response.ok) {
@@ -6504,27 +6661,52 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6504
6661
  }
6505
6662
  _registeredViewingKeys.add(cacheKey);
6506
6663
  }
6507
- async function generateTransactionProof(inputs, onProgress) {
6664
+ async function generateTransactionProof(inputs, onProgress, onStatus) {
6508
6665
  onProgress?.(10);
6509
6666
  onProgress?.(30);
6510
- const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles();
6667
+ let lastReportedMb = -1;
6668
+ const { wasmPath: wasmInput, zkeyPath: zkeyInput } = await resolveTransactionCircuitFiles(
6669
+ onStatus ? (received, total) => {
6670
+ const mb = Math.floor(received / 1e6);
6671
+ if (mb === lastReportedMb) return;
6672
+ lastReportedMb = mb;
6673
+ onStatus(
6674
+ total ? `Downloading circuit files (${mb} of ${Math.ceil(total / 1e6)} MB)...` : `Downloading circuit files (${mb} MB)...`
6675
+ );
6676
+ } : void 0
6677
+ );
6678
+ if (lastReportedMb >= 0) onStatus?.("Generating zero-knowledge proof...");
6679
+ const threaded = (run) => withProveWatchdog(run(), PROVE_WATCHDOG_MS);
6680
+ const singleThread = async () => {
6681
+ await terminateThreadedCurve();
6682
+ return snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput, void 0, void 0, {
6683
+ singleThread: true
6684
+ });
6685
+ };
6686
+ const workers = await defaultProverWorkers();
6511
6687
  let result;
6512
6688
  try {
6513
- result = await snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput);
6689
+ result = await threaded(
6690
+ () => withReportedCores(workers, () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput))
6691
+ );
6514
6692
  } 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;
6693
+ if (err instanceof ProveWatchdogTimeout) {
6694
+ onStatus?.("Proof is taking longer than expected, retrying on a single thread...");
6695
+ result = await singleThread();
6696
+ } else {
6697
+ if (!isProverOutOfMemory(err)) throw err;
6524
6698
  await terminateThreadedCurve();
6525
- result = await snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput, void 0, void 0, {
6526
- singleThread: true
6527
- });
6699
+ try {
6700
+ result = await threaded(
6701
+ () => withReportedCores(
6702
+ REDUCED_PROVER_WORKERS,
6703
+ () => snarkjs.groth16.fullProve(inputs, wasmInput, zkeyInput)
6704
+ )
6705
+ );
6706
+ } catch (retryErr) {
6707
+ if (!isProverOutOfMemory(retryErr) && !(retryErr instanceof ProveWatchdogTimeout)) throw retryErr;
6708
+ result = await singleThread();
6709
+ }
6528
6710
  }
6529
6711
  }
6530
6712
  onProgress?.(100);
@@ -6538,6 +6720,40 @@ function isProverOutOfMemory(err) {
6538
6720
  return name === "RangeError" && /(allocat|array buffer|memory)/i.test(message);
6539
6721
  }
6540
6722
  var REDUCED_PROVER_WORKERS = 4;
6723
+ var MAX_PROVER_WORKERS = 8;
6724
+ var MAX_PROVER_WORKERS_32BIT = 2;
6725
+ async function is32BitBrowser() {
6726
+ const nav = globalThis.navigator;
6727
+ if (!nav) return false;
6728
+ try {
6729
+ const hints = await nav.userAgentData?.getHighEntropyValues?.(["bitness", "wow64"]);
6730
+ if (hints) return hints.bitness === "32" || hints.wow64 === true;
6731
+ } catch {
6732
+ }
6733
+ return /\bWOW64\b/.test(nav.userAgent ?? "");
6734
+ }
6735
+ async function defaultProverWorkers() {
6736
+ return await is32BitBrowser() ? MAX_PROVER_WORKERS_32BIT : MAX_PROVER_WORKERS;
6737
+ }
6738
+ var PROVE_WATCHDOG_MS = 6e4;
6739
+ var ProveWatchdogTimeout = class extends Error {
6740
+ constructor(ms) {
6741
+ super(`Threaded proof did not finish within ${Math.round(ms / 1e3)}s`);
6742
+ this.name = "ProveWatchdogTimeout";
6743
+ }
6744
+ };
6745
+ function withProveWatchdog(work, ms) {
6746
+ work.catch(() => {
6747
+ });
6748
+ let timer;
6749
+ const timeout = new Promise((_, reject) => {
6750
+ timer = setTimeout(() => reject(new ProveWatchdogTimeout(ms)), ms);
6751
+ timer.unref?.();
6752
+ });
6753
+ return Promise.race([work, timeout]).finally(() => {
6754
+ if (timer !== void 0) clearTimeout(timer);
6755
+ });
6756
+ }
6541
6757
  async function withReportedCores(cores, fn) {
6542
6758
  const nav = globalThis.navigator;
6543
6759
  const reported = nav?.hardwareConcurrency;
@@ -7701,7 +7917,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
7701
7917
  `Invalid risk quote response: invalid lengths (sig=${signatureBuf.length}, msg=${messageArr.length}, pk=${publicKeyBytes.length}; expected msg 33/41/50/82/146)`
7702
7918
  );
7703
7919
  }
7704
- if (!nacl5.sign.detached.verify(messageArr, new Uint8Array(signatureBuf), publicKeyBytes)) {
7920
+ if (!nacl6.sign.detached.verify(messageArr, new Uint8Array(signatureBuf), publicKeyBytes)) {
7705
7921
  throw new Error(
7706
7922
  "Invalid risk quote response: signature does not verify under signer_pubkey"
7707
7923
  );
@@ -8651,7 +8867,7 @@ async function transact(params, rawOptions) {
8651
8867
  let publicSignals;
8652
8868
  const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
8653
8869
  try {
8654
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
8870
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
8655
8871
  proof = result.proof;
8656
8872
  publicSignals = result.publicSignals;
8657
8873
  releaseProofSlot?.();
@@ -9953,7 +10169,7 @@ async function swapUtxo(params, rawOptions) {
9953
10169
  let proof;
9954
10170
  let publicSignals;
9955
10171
  try {
9956
- const result = await generateTransactionProof(circuitInputs, onProofProgress);
10172
+ const result = await generateTransactionProof(circuitInputs, onProofProgress, onProgress);
9957
10173
  proof = result.proof;
9958
10174
  publicSignals = result.publicSignals;
9959
10175
  } catch (proofError) {
@@ -10628,7 +10844,7 @@ var RelayBatchAuthCoordinator = class {
10628
10844
  );
10629
10845
  }
10630
10846
  const approvalStartedMs = Date.now();
10631
- const { signature, mode } = await signRelayAuthPayload(this.signer, message);
10847
+ const { signature, mode, txMessage } = await signRelayAuthPayload(this.signer, message);
10632
10848
  if (!isKeyPairSigner2(this.signer)) {
10633
10849
  assertApprovalWithinFreshnessWindow(
10634
10850
  Date.now() - approvalStartedMs,
@@ -10646,6 +10862,9 @@ var RelayBatchAuthCoordinator = class {
10646
10862
  auth_nonce: preimage.auth_nonce,
10647
10863
  auth_signature: signatureB64,
10648
10864
  ...mode === "transaction" ? { auth_mode: mode } : {},
10865
+ // The wallet's own message when it changed the envelope; one approval, so the same
10866
+ // message for every item, exactly like the signature.
10867
+ ...txMessage ? { auth_tx_message: Buffer.from(txMessage).toString("base64") } : {},
10649
10868
  // A fresh array per item: `Object.assign` puts this on the wire body, and the body is
10650
10869
  // serialized again on every network retry.
10651
10870
  auth_batch: { digests: [...digests] }
@@ -12484,7 +12703,7 @@ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
12484
12703
 
12485
12704
  // src/notes/request-keys.ts
12486
12705
  import { blake3 as blake36 } from "@noble/hashes/blake3";
12487
- import nacl6 from "tweetnacl";
12706
+ import nacl7 from "tweetnacl";
12488
12707
  var BN254_ORDER = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
12489
12708
  var ROOT_SEED_DOMAIN = new TextEncoder().encode("cloak_request_root_v1");
12490
12709
  var ROOT_NK_DOMAIN = new TextEncoder().encode("cloak_request_root_nk_v1");
@@ -12534,7 +12753,7 @@ async function deriveRequestKeys(root, counter) {
12534
12753
  return {
12535
12754
  counter,
12536
12755
  utxoKeypair: { privateKey, publicKey },
12537
- viewingKeypair: { privateKey: vk, publicKey: nacl6.scalarMult.base(vk) }
12756
+ viewingKeypair: { privateKey: vk, publicKey: nacl7.scalarMult.base(vk) }
12538
12757
  };
12539
12758
  }
12540
12759
  async function deriveRequestKeyRange(root, from, count) {
@@ -14035,7 +14254,7 @@ async function loadWeb3() {
14035
14254
  }
14036
14255
 
14037
14256
  // src/bridge/rail-verify.ts
14038
- import nacl7 from "tweetnacl";
14257
+ import nacl8 from "tweetnacl";
14039
14258
  import { sha256 as sha2567 } from "@noble/hashes/sha256";
14040
14259
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
14041
14260
  var b58 = /* @__PURE__ */ (() => {
@@ -14146,7 +14365,7 @@ function verifyQuoteSignature(resp) {
14146
14365
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
14147
14366
  const sig = resp.signature.replace(/^ed25519:/, "");
14148
14367
  try {
14149
- return { valid: nacl7.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
14368
+ return { valid: nacl8.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
14150
14369
  } catch (e) {
14151
14370
  return { valid: false, reason: e instanceof Error ? e.message : String(e) };
14152
14371
  }
@@ -14244,11 +14463,11 @@ function cloakBridgeRail(relayUrl) {
14244
14463
  }
14245
14464
 
14246
14465
  // src/bridge/paymaster-client.ts
14247
- import { getCompiledTransactionMessageDecoder, getInstructionsFromCompiledTransactionMessage } from "@solana/kit";
14466
+ import { getCompiledTransactionMessageDecoder as getCompiledTransactionMessageDecoder2, getInstructionsFromCompiledTransactionMessage } from "@solana/kit";
14248
14467
  import { parseTransferSolInstruction } from "@solana-program/system";
14249
14468
  import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS3, findAssociatedTokenPda as findAssociatedTokenPda3, parseTransferInstruction } from "@solana-program/token";
14250
14469
  async function validatePaymasterTopUpTransaction(tx, expect) {
14251
- const compiledMessage = getCompiledTransactionMessageDecoder().decode(tx.messageBytes);
14470
+ const compiledMessage = getCompiledTransactionMessageDecoder2().decode(tx.messageBytes);
14252
14471
  const ixs = getInstructionsFromCompiledTransactionMessage(compiledMessage);
14253
14472
  if (ixs.length !== 1 && ixs.length !== 2) {
14254
14473
  throw new Error(
@@ -14528,7 +14747,7 @@ async function scanReceivers(rpc, opts, receiverAt, provenance) {
14528
14747
 
14529
14748
  // src/bridge/deposit-core.ts
14530
14749
  import {
14531
- getCompiledTransactionMessageDecoder as getCompiledTransactionMessageDecoder2,
14750
+ getCompiledTransactionMessageDecoder as getCompiledTransactionMessageDecoder3,
14532
14751
  getInstructionsFromCompiledTransactionMessage as getInstructionsFromCompiledTransactionMessage2
14533
14752
  } from "@solana/kit";
14534
14753
  import { getTransferSolInstruction as getTransferSolInstruction2 } from "@solana-program/system";
@@ -14595,7 +14814,7 @@ function makeDepositSigner(params) {
14595
14814
  const out = [];
14596
14815
  for (const tx of transactions) {
14597
14816
  state.measuredSize = transactionBytes(tx).length;
14598
- const compiled = getCompiledTransactionMessageDecoder2().decode(tx.messageBytes);
14817
+ const compiled = getCompiledTransactionMessageDecoder3().decode(tx.messageBytes);
14599
14818
  const loadedAddresses = await resolveLoadedAddresses(rpc, compiled);
14600
14819
  const instructions = getInstructionsFromCompiledTransactionMessage2(compiled, loadedAddresses);
14601
14820
  const transactIx = instructions.find((i) => i.programAddress === programId);
@@ -14912,7 +15131,7 @@ async function withShieldRetries(attempt, hooks = {}) {
14912
15131
  }
14913
15132
 
14914
15133
  // src/index.ts
14915
- var VERSION = "0.2.12";
15134
+ var VERSION = "0.2.14";
14916
15135
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
14917
15136
  export {
14918
15137
  AccountRole,
@@ -14988,6 +15207,7 @@ export {
14988
15207
  VARIABLE_FEE_NUMERATOR,
14989
15208
  VARIABLE_FEE_RATE,
14990
15209
  VERSION,
15210
+ WALLET_ADDED_PROGRAMS,
14991
15211
  WITHDRAW_FEE_BPS,
14992
15212
  WITHDRAW_FIXED_FEE,
14993
15213
  accountMeta,
@@ -15264,6 +15484,7 @@ export {
15264
15484
  verifyQuoteSignature,
15265
15485
  verifyUtxos,
15266
15486
  waitForRoot,
15487
+ walletAuthTransactionMessageBinds,
15267
15488
  withShieldRetries,
15268
15489
  withTiming,
15269
15490
  withdrawFeeFor