@cloak.dev/sdk 0.2.3-staging.f2d7f2a → 0.2.3-staging.fdea6cd

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.cjs CHANGED
@@ -455,7 +455,7 @@ async function deserializeUtxo(bytes) {
455
455
  const blindingBytes = bytes.slice(40, 72);
456
456
  const blinding = bytesToBigint2(blindingBytes);
457
457
  const mintBytes = bytes.slice(72, 104);
458
- const mintAddress = new import_web33.PublicKey(mintBytes);
458
+ const mintAddress = new import_web34.PublicKey(mintBytes);
459
459
  const index = view.getUint32(104, true);
460
460
  const utxo = {
461
461
  amount,
@@ -523,18 +523,18 @@ function selectUtxos(available, targetAmount) {
523
523
  }
524
524
  return selected;
525
525
  }
526
- var import_web33, import_circomlibjs2, import_blake33, FIELD_MODULUS, KEYPAIR_DOMAIN_TAG, UTXO_KEY_DOMAIN, NATIVE_SOL_MINT, poseidonInstance;
526
+ var import_web34, import_circomlibjs2, import_blake33, FIELD_MODULUS, KEYPAIR_DOMAIN_TAG, UTXO_KEY_DOMAIN, NATIVE_SOL_MINT, poseidonInstance;
527
527
  var init_utxo = __esm({
528
528
  "src/notes/utxo.ts"() {
529
529
  "use strict";
530
- import_web33 = require("@solana/web3.js");
530
+ import_web34 = require("@solana/web3.js");
531
531
  import_circomlibjs2 = require("circomlibjs");
532
532
  import_blake33 = require("@noble/hashes/blake3");
533
533
  init_inputs();
534
534
  FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
535
535
  KEYPAIR_DOMAIN_TAG = BigInt("5423839527465210463");
536
536
  UTXO_KEY_DOMAIN = new TextEncoder().encode("cloak_utxo_priv_v1");
537
- NATIVE_SOL_MINT = new import_web33.PublicKey("So11111111111111111111111111111111111111112");
537
+ NATIVE_SOL_MINT = new import_web34.PublicKey("So11111111111111111111111111111111111111112");
538
538
  poseidonInstance = null;
539
539
  }
540
540
  });
@@ -578,9 +578,13 @@ __export(index_exports, {
578
578
  RECIPIENT_DELIVERY_NOTE_BYTES: () => RECIPIENT_DELIVERY_NOTE_BYTES,
579
579
  RECIPIENT_DELIVERY_PLAINTEXT_LEN: () => RECIPIENT_DELIVERY_PLAINTEXT_LEN,
580
580
  RECIPIENT_DELIVERY_TAG_LEN: () => RECIPIENT_DELIVERY_TAG_LEN,
581
+ RELAY_BATCH_AUTH_MAX_ITEMS: () => RELAY_BATCH_AUTH_MAX_ITEMS,
581
582
  RELAY_ORIGIN_ALLOWLIST: () => RELAY_ORIGIN_ALLOWLIST,
583
+ REQUEST_AUTH_BATCH_DOMAIN: () => REQUEST_AUTH_BATCH_DOMAIN,
584
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS: () => REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
582
585
  REQUEST_AUTH_MAX_AGE_SECONDS: () => REQUEST_AUTH_MAX_AGE_SECONDS,
583
586
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS: () => REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
587
+ RelayBatchAuthCoordinator: () => RelayBatchAuthCoordinator,
584
588
  RelayInternalError: () => RelayInternalError,
585
589
  RelayService: () => RelayService,
586
590
  RootNotFoundError: () => RootNotFoundError,
@@ -608,11 +612,13 @@ __export(index_exports, {
608
612
  assessBridgeQuote: () => assessBridgeQuote,
609
613
  bigintToBytes32: () => bigintToBytes32,
610
614
  bigintToHex: () => bigintToHex,
615
+ buildAuthTransactionMessage: () => buildAuthTransactionMessage,
611
616
  buildMerkleTree: () => buildMerkleTree,
612
617
  buildMerkleTreeFromChain: () => buildMerkleTreeFromChain,
613
618
  buildMerkleTreeFromRelay: () => buildMerkleTreeFromRelay,
614
619
  buildRecipientDeliveryNotes: () => buildRecipientDeliveryNotes,
615
620
  buildRelayAuthPreimage: () => buildRelayAuthPreimage,
621
+ buildRelayBatchAuthMessage: () => buildRelayBatchAuthMessage,
616
622
  buildTransactRequestBody: () => buildTransactRequestBody,
617
623
  bytesToHex: () => bytesToHex,
618
624
  calculateFee: () => calculateFee,
@@ -646,6 +652,7 @@ __export(index_exports, {
646
652
  createLogger: () => createLogger,
647
653
  createRecoverableChangeUtxo: () => createRecoverableChangeUtxo,
648
654
  createRecoverableDepositUtxo: () => createRecoverableDepositUtxo,
655
+ createRelayBatchAuthCoordinator: () => createRelayBatchAuthCoordinator,
649
656
  createUtxo: () => createUtxo,
650
657
  createZeroUtxo: () => createZeroUtxo,
651
658
  decryptCompactChainNote: () => decryptCompactChainNote,
@@ -772,6 +779,7 @@ __export(index_exports, {
772
779
  readRent: () => readRent,
773
780
  recipientDeliveryNoteToBase64: () => recipientDeliveryNoteToBase64,
774
781
  registerViewingKey: () => registerViewingKey,
782
+ relayRequestDigestHex: () => relayRequestDigestHex,
775
783
  removePendingDeposit: () => removePendingDeposit,
776
784
  removePendingWithdrawal: () => removePendingWithdrawal,
777
785
  renderAssessment: () => renderAssessment,
@@ -785,10 +793,12 @@ __export(index_exports, {
785
793
  sdkLogger: () => sdkLogger,
786
794
  selectUtxos: () => selectUtxos,
787
795
  sendTransaction: () => sendTransaction,
796
+ serializeAuthTransactionMessage: () => serializeAuthTransactionMessage,
788
797
  serializeNote: () => serializeNote,
789
798
  serializeUtxo: () => serializeUtxo,
790
799
  setCircuitsPath: () => setCircuitsPath,
791
800
  setDebugMode: () => setDebugMode,
801
+ signRelayAuthPayload: () => signRelayAuthPayload,
792
802
  signTransaction: () => signTransaction,
793
803
  splitTo2Limbs: () => splitTo2Limbs,
794
804
  submitTransactToRelay: () => submitTransactToRelay,
@@ -797,6 +807,7 @@ __export(index_exports, {
797
807
  swapWithChange: () => swapWithChange,
798
808
  toComplianceReport: () => toComplianceReport,
799
809
  transact: () => transact,
810
+ transactBatch: () => transactBatch,
800
811
  transfer: () => transfer,
801
812
  truncate: () => truncate,
802
813
  tryDecryptNote: () => tryDecryptNote,
@@ -1380,9 +1391,9 @@ var LocalStorageAdapter = class {
1380
1391
  };
1381
1392
 
1382
1393
  // src/scanning/compliance-keys.ts
1383
- var import_tweetnacl2 = __toESM(require("tweetnacl"), 1);
1394
+ var import_tweetnacl3 = __toESM(require("tweetnacl"), 1);
1384
1395
  var import_blake32 = require("@noble/hashes/blake3");
1385
- var import_sha2 = require("@noble/hashes/sha2");
1396
+ var import_sha22 = require("@noble/hashes/sha2");
1386
1397
  init_inputs();
1387
1398
 
1388
1399
  // src/relay/viewing-key.ts
@@ -1570,6 +1581,276 @@ function connectionRpcEndpoint(connection) {
1570
1581
  return connection?._rpcEndpoint ?? connection?.rpcEndpoint;
1571
1582
  }
1572
1583
 
1584
+ // src/relay/payload.ts
1585
+ var import_sha2 = require("@noble/hashes/sha2");
1586
+ var import_utils = require("@noble/hashes/utils");
1587
+ var import_tweetnacl2 = __toESM(require("tweetnacl"), 1);
1588
+ var import_web33 = require("@solana/web3.js");
1589
+ init_inputs();
1590
+ var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
1591
+ var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
1592
+ var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
1593
+ var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
1594
+ function sha256Hex(text) {
1595
+ return (0, import_utils.bytesToHex)((0, import_sha2.sha256)(new TextEncoder().encode(text)));
1596
+ }
1597
+ function randomNonceUuid() {
1598
+ const webCrypto = globalThis?.crypto;
1599
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
1600
+ const proc = globalThis?.process;
1601
+ const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
1602
+ if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
1603
+ const bytes = randomBytes(16);
1604
+ bytes[6] = bytes[6] & 15 | 64;
1605
+ bytes[8] = bytes[8] & 63 | 128;
1606
+ const hex = (0, import_utils.bytesToHex)(bytes);
1607
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
1608
+ }
1609
+ var TRANSACT_AUTH_FIELDS = [
1610
+ "encrypted_notes",
1611
+ "max_fee",
1612
+ "mint",
1613
+ "proof_bytes",
1614
+ "public_inputs",
1615
+ "recipient",
1616
+ "recipient_delivery_notes",
1617
+ "risk_quote",
1618
+ "sender"
1619
+ ];
1620
+ var TRANSACT_SWAP_AUTH_FIELDS = [
1621
+ "close_timed_out",
1622
+ "dexes",
1623
+ "encrypted_notes",
1624
+ "exclude_dexes",
1625
+ "max_fee",
1626
+ "min_output_amount",
1627
+ "output_mint",
1628
+ "proof_bytes",
1629
+ "public_inputs",
1630
+ "recipient",
1631
+ "recipient_ata",
1632
+ "refund_blinding",
1633
+ "refund_pubkey",
1634
+ "retry_request_id",
1635
+ "risk_quote",
1636
+ "route_retry_attempts",
1637
+ "sender",
1638
+ "slippage_bps",
1639
+ "swap_max_retries"
1640
+ ];
1641
+ var UTF8 = new TextEncoder();
1642
+ function compareKeysBytewise(a, b) {
1643
+ if (a === b) return 0;
1644
+ const ab = UTF8.encode(a);
1645
+ const bb = UTF8.encode(b);
1646
+ const shared = Math.min(ab.length, bb.length);
1647
+ for (let i = 0; i < shared; i++) {
1648
+ if (ab[i] !== bb[i]) return ab[i] - bb[i];
1649
+ }
1650
+ return ab.length - bb.length;
1651
+ }
1652
+ function canonicalJson(value) {
1653
+ if (value === null || value === void 0) return "null";
1654
+ if (typeof value === "boolean") return value ? "true" : "false";
1655
+ if (typeof value === "number") {
1656
+ if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
1657
+ throw new Error(
1658
+ `canonicalJson: refusing to sign the number ${String(value)}. The relay renders numbers with serde_json, which spells non-integer, non-finite and very large values differently from JavaScript, so the two digests would differ and the request would be rejected with an unexplained 401. Send it as a decimal string instead, which is how every amount in this schema travels.`
1659
+ );
1660
+ }
1661
+ return String(value);
1662
+ }
1663
+ if (typeof value === "bigint") return value.toString();
1664
+ if (typeof value === "string") return JSON.stringify(value);
1665
+ if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
1666
+ if (typeof value === "object") {
1667
+ const obj = value;
1668
+ const keys = Object.keys(obj).sort(compareKeysBytewise);
1669
+ return "{" + keys.map((k) => {
1670
+ const v = obj[k];
1671
+ if (typeof v === "function" || typeof v === "symbol") {
1672
+ throw new Error(
1673
+ `canonicalJson: the key "${k}" holds a ${typeof v}, which has no JSON representation. JSON.stringify would drop it from the wire body while it stayed in the signed view, so the relay's digest could never match this one.`
1674
+ );
1675
+ }
1676
+ return `${JSON.stringify(k)}:${canonicalJson(v)}`;
1677
+ }).join(",") + "}";
1678
+ }
1679
+ throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
1680
+ }
1681
+ var FIELDS_WITHOUT_NULL_ENCODING = {
1682
+ slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
1683
+ };
1684
+ function buildAuthRequest(body, sender, fields) {
1685
+ const out = {};
1686
+ for (const k of fields) {
1687
+ if (k === "sender") {
1688
+ out[k] = sender;
1689
+ continue;
1690
+ }
1691
+ const value = body[k];
1692
+ if (value === void 0 || value === null) {
1693
+ const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
1694
+ if (relayDefault) {
1695
+ throw new Error(
1696
+ `Relay request auth: \`${k}\` must be present in the body. It is the one field in this schema that is not optional on the relay side: when it is missing the relay signs its default, ${relayDefault}, while this request would sign null. The two digests differ and the relay answers 401 "Relay request signature does not match the exact request", which points at nothing. Set \`${k}\` explicitly, to the same value the body will carry.`
1697
+ );
1698
+ }
1699
+ out[k] = null;
1700
+ continue;
1701
+ }
1702
+ out[k] = value;
1703
+ }
1704
+ return out;
1705
+ }
1706
+ function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
1707
+ const digest = sha256Hex(canonicalJson(request));
1708
+ return new TextEncoder().encode(
1709
+ `${REQUEST_AUTH_DOMAIN}
1710
+ ${endpoint}
1711
+ ${programId.toBase58()}
1712
+ ${nonce}
1713
+ ${issuedAt}
1714
+ ${digest}`
1715
+ );
1716
+ }
1717
+ function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1718
+ const senderB58 = sender.toBase58();
1719
+ const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
1720
+ const nonce = randomNonceUuid();
1721
+ const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
1722
+ const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
1723
+ return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
1724
+ }
1725
+ function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1726
+ const preimage = buildRelayAuthPreimage(
1727
+ endpoint,
1728
+ programId,
1729
+ body,
1730
+ signer.publicKey,
1731
+ nowSeconds,
1732
+ fields
1733
+ );
1734
+ const signature = import_tweetnacl2.default.sign.detached(preimage.message, signer.secretKey);
1735
+ return {
1736
+ sender: preimage.sender,
1737
+ auth_issued_at: preimage.auth_issued_at,
1738
+ auth_nonce: preimage.auth_nonce,
1739
+ auth_signature: Buffer.from(signature).toString("base64")
1740
+ };
1741
+ }
1742
+ function buildAuthTransactionMessage(sender, digest) {
1743
+ if (digest.length !== 32) throw new Error(`auth transaction digest must be 32 bytes (got ${digest.length})`);
1744
+ const tx = new import_web33.Transaction();
1745
+ tx.add(import_web33.SystemProgram.transfer({ fromPubkey: sender, toPubkey: sender, lamports: 0 }));
1746
+ tx.feePayer = sender;
1747
+ tx.recentBlockhash = new import_web33.PublicKey(digest).toBase58();
1748
+ return tx;
1749
+ }
1750
+ function serializeAuthTransactionMessage(sender, digest) {
1751
+ return Uint8Array.from(buildAuthTransactionMessage(sender, digest).compileMessage().serialize());
1752
+ }
1753
+ async function signRelayAuthPayload(signer, payload) {
1754
+ if (signer instanceof import_web33.Keypair) {
1755
+ return { signature: import_tweetnacl2.default.sign.detached(payload, signer.secretKey), mode: "message" };
1756
+ }
1757
+ if (signer.signMessage) {
1758
+ const signature = await signer.signMessage(payload);
1759
+ assertDetachedSignature(signature, "signMessage");
1760
+ return { signature, mode: "message" };
1761
+ }
1762
+ if (signer.signAuthTransaction) {
1763
+ const digest = (0, import_sha2.sha256)(payload);
1764
+ const signed = await signer.signAuthTransaction(buildAuthTransactionMessage(signer.walletPublicKey, digest));
1765
+ const own = signed.signatures.find((s) => s.publicKey.equals(signer.walletPublicKey))?.signature;
1766
+ if (!own) {
1767
+ throw new Error(
1768
+ "The wallet returned no signature for the Cloak auth transaction. Nothing was submitted."
1769
+ );
1770
+ }
1771
+ const signature = Uint8Array.from(own);
1772
+ assertDetachedSignature(signature, "signTransaction");
1773
+ return { signature, mode: "transaction" };
1774
+ }
1775
+ throw new Error("Relay auth signer has neither signMessage nor signAuthTransaction.");
1776
+ }
1777
+ function assertDetachedSignature(signature, method) {
1778
+ if (!(signature instanceof Uint8Array) || signature.length !== 64) {
1779
+ throw new Error(
1780
+ `The wallet's ${method} did not return a 64-byte ed25519 detached signature (got ${signature instanceof Uint8Array ? `${signature.length} bytes` : typeof signature}). Cloak signs with a raw detached signature over the bytes it hands the wallet; adapters that wrap or re-encode the result cannot be used here.`
1781
+ );
1782
+ }
1783
+ }
1784
+ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_AUTH_MAX_AGE_SECONDS) {
1785
+ const elapsedSeconds = elapsedMs / 1e3;
1786
+ const budget = maxAgeSeconds - RELAY_AUTH_APPROVAL_MARGIN_SECONDS;
1787
+ if (elapsedSeconds <= budget) return;
1788
+ throw new Error(
1789
+ `The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${maxAgeSeconds} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
1790
+ );
1791
+ }
1792
+ function explainRelayAuthRejection(responseText) {
1793
+ const text = String(responseText);
1794
+ const has = (needle) => text.includes(needle);
1795
+ if (has("issued too far in the future")) {
1796
+ return `This computer's clock is more than ${REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS} seconds ahead of the network's, so the request looks like it was signed in the future and is refused before anything else happens. Turn on automatic date and time (or resynchronise the clock) and try again. Nothing was submitted.`;
1797
+ }
1798
+ if (has("signature expired")) {
1799
+ return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
1800
+ }
1801
+ if (has("does not match the exact request")) {
1802
+ return `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
1803
+ }
1804
+ if (has("has no registered viewing key")) {
1805
+ return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
1806
+ }
1807
+ if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
1808
+ return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
1809
+ }
1810
+ if (has("auth_nonce must be a canonical UUID")) {
1811
+ return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
1812
+ }
1813
+ if (has("Relay request signature must be exactly 64 bytes") || has("Invalid relay request signature encoding")) {
1814
+ return `\`auth_signature\` must be the raw 64-byte ed25519 detached signature, base64 encoded. Wallet adapters that wrap or re-encode what \`signMessage\` returns cannot be used here.`;
1815
+ }
1816
+ return null;
1817
+ }
1818
+ async function buildRelayAuthFields(endpoint, programId, body, signers, fields = TRANSACT_AUTH_FIELDS) {
1819
+ if (signers.depositorKeypair) {
1820
+ return signRelayRequest(endpoint, programId, body, signers.depositorKeypair, void 0, fields);
1821
+ }
1822
+ const wallet = signers.relayAuthSigner;
1823
+ if (!wallet) return null;
1824
+ const preimage = buildRelayAuthPreimage(
1825
+ endpoint,
1826
+ programId,
1827
+ body,
1828
+ wallet.walletPublicKey,
1829
+ void 0,
1830
+ fields
1831
+ );
1832
+ const approvalStartedMs = Date.now();
1833
+ const { signature, mode } = await signRelayAuthPayload(wallet, preimage.message);
1834
+ assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
1835
+ return {
1836
+ sender: preimage.sender,
1837
+ auth_issued_at: preimage.auth_issued_at,
1838
+ auth_nonce: preimage.auth_nonce,
1839
+ auth_signature: Buffer.from(signature).toString("base64"),
1840
+ ...mode === "transaction" ? { auth_mode: mode } : {}
1841
+ };
1842
+ }
1843
+ var REQUEST_AUTH_BATCH_DOMAIN = "CLOAK_RELAY_BATCH_AUTH_V1";
1844
+ var REQUEST_AUTH_BATCH_MAX_AGE_SECONDS = 600;
1845
+ var RELAY_BATCH_AUTH_MAX_ITEMS = 64;
1846
+ function relayRequestDigestHex(preimage) {
1847
+ return (0, import_utils.bytesToHex)((0, import_sha2.sha256)(preimage.message));
1848
+ }
1849
+ function buildRelayBatchAuthMessage(programId, issuedAt, digests) {
1850
+ const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId.toBase58(), issuedAt, String(digests.length)];
1851
+ return new TextEncoder().encode([...lines, ...digests].join("\n"));
1852
+ }
1853
+
1573
1854
  // src/scanning/compliance-keys.ts
1574
1855
  var X25519_KEY_LENGTH = 32;
1575
1856
  var DIVERSIFIER_LENGTH = 11;
@@ -1607,7 +1888,7 @@ function deriveViewingKeyFromNk(nk) {
1607
1888
  preimage.set(nk, CHAIN_NOTE_VK_DOMAIN.length);
1608
1889
  const derived = (0, import_blake32.blake3)(preimage);
1609
1890
  const privateKey = clampX25519Secret(derived);
1610
- const publicKey = import_tweetnacl2.default.scalarMult.base(privateKey);
1891
+ const publicKey = import_tweetnacl3.default.scalarMult.base(privateKey);
1611
1892
  return { privateKey, publicKey };
1612
1893
  }
1613
1894
  function deriveDiversifier(nk, commitmentHex, outputIndex) {
@@ -1642,7 +1923,7 @@ function deriveDiversifiedViewingKey(nk, diversifier) {
1642
1923
  preimage.set(diversifier, SK_D_DOMAIN.length + nk.length);
1643
1924
  const derived = (0, import_blake32.blake3)(preimage);
1644
1925
  const privateKey = clampX25519Secret(derived);
1645
- const publicKey = import_tweetnacl2.default.scalarMult.base(privateKey);
1926
+ const publicKey = import_tweetnacl3.default.scalarMult.base(privateKey);
1646
1927
  return { privateKey, publicKey };
1647
1928
  }
1648
1929
  function deriveViewingKeyFromSpendKey(skSpend) {
@@ -1705,19 +1986,19 @@ async function deriveUserCompliancePublicKey(masterCompliancePublicKey, userPubl
1705
1986
  masterCompliancePublicKey,
1706
1987
  userPublicKey
1707
1988
  );
1708
- return import_tweetnacl2.default.scalarMult(factor, masterCompliancePublicKey);
1989
+ return import_tweetnacl3.default.scalarMult(factor, masterCompliancePublicKey);
1709
1990
  }
1710
- function bytesToHex2(bytes) {
1991
+ function bytesToHex3(bytes) {
1711
1992
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1712
1993
  }
1713
1994
  function computeViewingKeyIdentifier(userPubkey, nkHex) {
1714
1995
  const preimage = new TextEncoder().encode(`${userPubkey.toBase58()}${nkHex}`);
1715
- return bytesToHex2((0, import_sha2.sha256)(preimage));
1996
+ return bytesToHex3((0, import_sha22.sha256)(preimage));
1716
1997
  }
1717
1998
  var SIGN_IN_MESSAGE = "Cloak: Sign in\n\nSign this message to securely access your Cloak account.\nThis does NOT authorize any transaction or spend any funds.";
1718
1999
  async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1719
2000
  assert32Bytes(nk, "nk");
1720
- const nkHex = bytesToHex2(nk);
2001
+ const nkHex = bytesToHex3(nk);
1721
2002
  const keyId = computeViewingKeyIdentifier(userPubkey, nkHex);
1722
2003
  const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
1723
2004
  method: "POST",
@@ -1738,8 +2019,11 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1738
2019
  nkHex
1739
2020
  );
1740
2021
  const messageBytes = new TextEncoder().encode(challenge.message);
1741
- const signatureBytes = await signMessage(messageBytes);
1742
- const signature = Buffer.from(signatureBytes).toString("base64");
2022
+ const signed = await signRelayAuthPayload(
2023
+ typeof signMessage === "function" ? { walletPublicKey: userPubkey, signMessage } : signMessage,
2024
+ messageBytes
2025
+ );
2026
+ const signature = Buffer.from(signed.signature).toString("base64");
1743
2027
  const response = await relayFetch(`${relayUrl}/viewing-key/register`, {
1744
2028
  method: "POST",
1745
2029
  headers: { "Content-Type": "application/json" },
@@ -1748,7 +2032,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1748
2032
  viewing_key: nkHex,
1749
2033
  nonce: challenge.nonce,
1750
2034
  identifier: keyId,
1751
- signature
2035
+ signature,
2036
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
1752
2037
  })
1753
2038
  });
1754
2039
  if (!response.ok) {
@@ -1757,7 +2042,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1757
2042
  }
1758
2043
 
1759
2044
  // src/scanning/metadata-encryption.ts
1760
- var import_tweetnacl3 = __toESM(require("tweetnacl"), 1);
2045
+ var import_tweetnacl4 = __toESM(require("tweetnacl"), 1);
1761
2046
  init_inputs();
1762
2047
  var AES_GCM_NONCE_LENGTH = 12;
1763
2048
  var AES_GCM_TAG_LENGTH = 16;
@@ -1855,8 +2140,8 @@ async function aesGcmDecrypt(ciphertext, keyBytes, nonce) {
1855
2140
  }
1856
2141
  async function encryptForRecipient(plaintext, recipientPublicKey) {
1857
2142
  assert32Bytes2(recipientPublicKey, "recipientPublicKey");
1858
- const ephemeral = import_tweetnacl3.default.box.keyPair();
1859
- const sharedSecret = import_tweetnacl3.default.scalarMult(ephemeral.secretKey, recipientPublicKey);
2143
+ const ephemeral = import_tweetnacl4.default.box.keyPair();
2144
+ const sharedSecret = import_tweetnacl4.default.scalarMult(ephemeral.secretKey, recipientPublicKey);
1860
2145
  const nonce = randomBytes(AES_GCM_NONCE_LENGTH);
1861
2146
  const ciphertext = await aesGcmEncrypt(plaintext, sharedSecret, nonce);
1862
2147
  return {
@@ -1915,7 +2200,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
1915
2200
  const plaintext = new TextEncoder().encode(JSON.stringify(metadata));
1916
2201
  const basePoint = new Uint8Array(32);
1917
2202
  basePoint[0] = 9;
1918
- const viewingKeyPublic = import_tweetnacl3.default.scalarMult(viewingKeyPrivate, basePoint);
2203
+ const viewingKeyPublic = import_tweetnacl4.default.scalarMult(viewingKeyPrivate, basePoint);
1919
2204
  const [userPayload, compliancePayload] = await Promise.all([
1920
2205
  encryptForRecipient(plaintext, viewingKeyPublic),
1921
2206
  encryptForRecipient(plaintext, viewingKeyPublic)
@@ -1934,7 +2219,7 @@ async function decryptTransactionMetadata(encrypted, viewKeySecret) {
1934
2219
  const payload = decodePayload(encrypted);
1935
2220
  const ephemeralPk = hexToBytes(payload.ephemeral_pk);
1936
2221
  assert32Bytes2(ephemeralPk, "ephemeral public key");
1937
- const sharedSecret = import_tweetnacl3.default.scalarMult(viewKeySecret, ephemeralPk);
2222
+ const sharedSecret = import_tweetnacl4.default.scalarMult(viewKeySecret, ephemeralPk);
1938
2223
  return decryptWithSharedSecret(payload, sharedSecret);
1939
2224
  }
1940
2225
  async function decryptComplianceMetadataWithMasterKey(encrypted, masterCompliancePrivateKey, masterCompliancePublicKey, userPublicKey) {
@@ -1947,8 +2232,8 @@ async function decryptComplianceMetadataWithMasterKey(encrypted, masterComplianc
1947
2232
  masterCompliancePublicKey,
1948
2233
  userPublicKey
1949
2234
  );
1950
- const scaledEphemeral = import_tweetnacl3.default.scalarMult(userFactor, ephemeralPk);
1951
- const sharedSecret = import_tweetnacl3.default.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
2235
+ const scaledEphemeral = import_tweetnacl4.default.scalarMult(userFactor, ephemeralPk);
2236
+ const sharedSecret = import_tweetnacl4.default.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1952
2237
  return decryptWithSharedSecret(payload, sharedSecret);
1953
2238
  }
1954
2239
 
@@ -2885,23 +3170,23 @@ function formatErrorForLogging(error) {
2885
3170
  init_utxo();
2886
3171
 
2887
3172
  // src/program/pda.ts
2888
- var import_web34 = require("@solana/web3.js");
3173
+ var import_web35 = require("@solana/web3.js");
2889
3174
  init_utxo();
2890
3175
  function getShieldPoolPDAs(programId, mint = NATIVE_SOL_MINT) {
2891
3176
  const pid = programId || CLOAK_PROGRAM_ID;
2892
- const [pool] = import_web34.PublicKey.findProgramAddressSync(
3177
+ const [pool] = import_web35.PublicKey.findProgramAddressSync(
2893
3178
  [Buffer.from("pool"), mint.toBuffer()],
2894
3179
  pid
2895
3180
  );
2896
- const [merkleTree] = import_web34.PublicKey.findProgramAddressSync(
3181
+ const [merkleTree] = import_web35.PublicKey.findProgramAddressSync(
2897
3182
  [Buffer.from("merkle_tree"), mint.toBuffer()],
2898
3183
  pid
2899
3184
  );
2900
- const [treasury] = import_web34.PublicKey.findProgramAddressSync(
3185
+ const [treasury] = import_web35.PublicKey.findProgramAddressSync(
2901
3186
  [Buffer.from("treasury"), mint.toBuffer()],
2902
3187
  pid
2903
3188
  );
2904
- const [vaultAuthority] = import_web34.PublicKey.findProgramAddressSync(
3189
+ const [vaultAuthority] = import_web35.PublicKey.findProgramAddressSync(
2905
3190
  [Buffer.from("vault_authority"), mint.toBuffer()],
2906
3191
  pid
2907
3192
  );
@@ -2917,7 +3202,7 @@ function getNullifierPDA(poolPubkey, nullifier, programId) {
2917
3202
  if (nullifier.length !== 32) {
2918
3203
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2919
3204
  }
2920
- return import_web34.PublicKey.findProgramAddressSync(
3205
+ return import_web35.PublicKey.findProgramAddressSync(
2921
3206
  [Buffer.from("nullifier"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2922
3207
  pid
2923
3208
  );
@@ -2927,25 +3212,25 @@ function getSwapStatePDA(poolPubkey, nullifier, programId) {
2927
3212
  if (nullifier.length !== 32) {
2928
3213
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2929
3214
  }
2930
- return import_web34.PublicKey.findProgramAddressSync(
3215
+ return import_web35.PublicKey.findProgramAddressSync(
2931
3216
  [Buffer.from("swap_state"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2932
3217
  pid
2933
3218
  );
2934
3219
  }
2935
3220
  function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
2936
3221
  const pid = programId || CLOAK_PROGRAM_ID;
2937
- return import_web34.PublicKey.findProgramAddressSync(
3222
+ return import_web35.PublicKey.findProgramAddressSync(
2938
3223
  [Buffer.from("pool_authority"), mint.toBuffer()],
2939
3224
  pid
2940
3225
  );
2941
3226
  }
2942
3227
  function getDeliveryRegistryPDA(programId) {
2943
3228
  const pid = programId || CLOAK_PROGRAM_ID;
2944
- return import_web34.PublicKey.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
3229
+ return import_web35.PublicKey.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
2945
3230
  }
2946
3231
  function getChainNoteRegistryPDA(programId) {
2947
3232
  const pid = programId || CLOAK_PROGRAM_ID;
2948
- return import_web34.PublicKey.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
3233
+ return import_web35.PublicKey.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
2949
3234
  }
2950
3235
 
2951
3236
  // src/flows/verify-utxos.ts
@@ -3276,8 +3561,9 @@ function truncate(str, len = 20) {
3276
3561
  var sdkLogger = createLogger("cloak::sdk");
3277
3562
 
3278
3563
  // src/relay/relay-service.ts
3279
- var import_sha22 = require("@noble/hashes/sha2");
3564
+ var import_sha23 = require("@noble/hashes/sha2");
3280
3565
  init_inputs();
3566
+ var import_web36 = require("@solana/web3.js");
3281
3567
  var RelayService = class {
3282
3568
  /**
3283
3569
  * Create a new Relay Service client
@@ -3593,8 +3879,11 @@ var RelayService = class {
3593
3879
  userPubkey,
3594
3880
  viewingKey
3595
3881
  );
3596
- const signatureBytes = await signMessage(new TextEncoder().encode(challenge.message));
3597
- const signature = this.bytesToBase64(signatureBytes);
3882
+ const signed = await signRelayAuthPayload(
3883
+ typeof signMessage === "function" ? { walletPublicKey: new import_web36.PublicKey(userPubkey), signMessage } : signMessage,
3884
+ new TextEncoder().encode(challenge.message)
3885
+ );
3886
+ const signature = this.bytesToBase64(signed.signature);
3598
3887
  const response = await relayFetch(`${this.baseUrl}/viewing-key/register`, {
3599
3888
  method: "POST",
3600
3889
  headers: { "Content-Type": "application/json" },
@@ -3603,7 +3892,8 @@ var RelayService = class {
3603
3892
  viewing_key: viewingKey,
3604
3893
  nonce: challenge.nonce,
3605
3894
  identifier,
3606
- signature
3895
+ signature,
3896
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
3607
3897
  })
3608
3898
  });
3609
3899
  if (!response.ok) {
@@ -3641,7 +3931,7 @@ var RelayService = class {
3641
3931
  }
3642
3932
  computeViewingKeyIdentifier(userPubkey, viewingKeyHex) {
3643
3933
  const preimage = new TextEncoder().encode(`${userPubkey}${viewingKeyHex}`);
3644
- const hash = (0, import_sha22.sha256)(preimage);
3934
+ const hash = (0, import_sha23.sha256)(preimage);
3645
3935
  return Array.from(hash).map((b) => b.toString(16).padStart(2, "0")).join("");
3646
3936
  }
3647
3937
  };
@@ -3759,10 +4049,10 @@ function encodeNoteSimple(note) {
3759
4049
  }
3760
4050
 
3761
4051
  // src/wallet/adapter.ts
3762
- var import_web35 = require("@solana/web3.js");
4052
+ var import_web37 = require("@solana/web3.js");
3763
4053
  init_types();
3764
4054
  function validateWalletConnected(wallet) {
3765
- if (wallet instanceof import_web35.Keypair) {
4055
+ if (wallet instanceof import_web37.Keypair) {
3766
4056
  return;
3767
4057
  }
3768
4058
  if (!wallet.publicKey) {
@@ -3774,7 +4064,7 @@ function validateWalletConnected(wallet) {
3774
4064
  }
3775
4065
  }
3776
4066
  function getPublicKey(wallet) {
3777
- if (wallet instanceof import_web35.Keypair) {
4067
+ if (wallet instanceof import_web37.Keypair) {
3778
4068
  return wallet.publicKey;
3779
4069
  }
3780
4070
  if (!wallet.publicKey) {
@@ -3788,7 +4078,7 @@ function getPublicKey(wallet) {
3788
4078
  }
3789
4079
  async function sendTransaction(transaction, wallet, connection, options) {
3790
4080
  assertAllowedRpcConnection(connection);
3791
- if (wallet instanceof import_web35.Keypair) {
4081
+ if (wallet instanceof import_web37.Keypair) {
3792
4082
  return await connection.sendTransaction(transaction, [wallet], options);
3793
4083
  }
3794
4084
  if (wallet.sendTransaction) {
@@ -3805,7 +4095,7 @@ async function sendTransaction(transaction, wallet, connection, options) {
3805
4095
  }
3806
4096
  }
3807
4097
  async function signTransaction(transaction, wallet) {
3808
- if (wallet instanceof import_web35.Keypair) {
4098
+ if (wallet instanceof import_web37.Keypair) {
3809
4099
  transaction.sign(wallet);
3810
4100
  return transaction;
3811
4101
  }
@@ -3833,7 +4123,7 @@ function keypairToAdapter(keypair) {
3833
4123
  }
3834
4124
 
3835
4125
  // src/program/instructions.ts
3836
- var import_web36 = require("@solana/web3.js");
4126
+ var import_web38 = require("@solana/web3.js");
3837
4127
  function createDepositInstruction(params) {
3838
4128
  if (params.commitment.length !== 32) {
3839
4129
  throw new Error(
@@ -3855,7 +4145,7 @@ function createDepositInstruction(params) {
3855
4145
  data.set(discriminant, 0);
3856
4146
  data.set(amountBytes, 1);
3857
4147
  data.set(params.commitment, 9);
3858
- return new import_web36.TransactionInstruction({
4148
+ return new import_web38.TransactionInstruction({
3859
4149
  programId: params.programId,
3860
4150
  keys: [
3861
4151
  // Account 0: Payer (signer, writable) - pays for transaction
@@ -3863,7 +4153,7 @@ function createDepositInstruction(params) {
3863
4153
  // Account 1: Pool (writable) - receives SOL
3864
4154
  { pubkey: params.pool, isSigner: false, isWritable: true },
3865
4155
  // Account 2: System Program (readonly) - for transfers
3866
- { pubkey: import_web36.SystemProgram.programId, isSigner: false, isWritable: false },
4156
+ { pubkey: import_web38.SystemProgram.programId, isSigner: false, isWritable: false },
3867
4157
  // Account 3: Merkle Tree (writable) - stores on-chain Merkle tree
3868
4158
  { pubkey: params.merkleTree, isSigner: false, isWritable: true }
3869
4159
  ],
@@ -3871,16 +4161,16 @@ function createDepositInstruction(params) {
3871
4161
  });
3872
4162
  }
3873
4163
  function validateDepositParams(params) {
3874
- if (!(params.programId instanceof import_web36.PublicKey)) {
4164
+ if (!(params.programId instanceof import_web38.PublicKey)) {
3875
4165
  throw new Error("programId must be a PublicKey");
3876
4166
  }
3877
- if (!(params.payer instanceof import_web36.PublicKey)) {
4167
+ if (!(params.payer instanceof import_web38.PublicKey)) {
3878
4168
  throw new Error("payer must be a PublicKey");
3879
4169
  }
3880
- if (!(params.pool instanceof import_web36.PublicKey)) {
4170
+ if (!(params.pool instanceof import_web38.PublicKey)) {
3881
4171
  throw new Error("pool must be a PublicKey");
3882
4172
  }
3883
- if (!(params.merkleTree instanceof import_web36.PublicKey)) {
4173
+ if (!(params.merkleTree instanceof import_web38.PublicKey)) {
3884
4174
  throw new Error("merkleTree must be a PublicKey");
3885
4175
  }
3886
4176
  if (typeof params.amount !== "number" || params.amount <= 0) {
@@ -3979,6 +4269,23 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
3979
4269
  const finalRoot = root || rpcRoot;
3980
4270
  return { nextIndex, root: finalRoot, subtrees };
3981
4271
  }
4272
+ function nearTipProofUndecidableLevels(leafIndex, nextIndex, height = MERKLE_TREE_HEIGHT) {
4273
+ if (!Number.isInteger(leafIndex) || !Number.isInteger(nextIndex) || !Number.isInteger(height)) {
4274
+ throw new Error(`nearTipProofUndecidableLevels: integers required (leafIndex=${leafIndex}, nextIndex=${nextIndex}, height=${height})`);
4275
+ }
4276
+ if (leafIndex < 0 || leafIndex >= nextIndex) {
4277
+ throw new Error(`Leaf index ${leafIndex} is not below next_index ${nextIndex}`);
4278
+ }
4279
+ const levels = [];
4280
+ for (let level = 0; level < height; level++) {
4281
+ const width = 2 ** level;
4282
+ const ancestor = Math.floor(leafIndex / width);
4283
+ if (ancestor % 2 === 1 && (ancestor + 1) * width < nextIndex) {
4284
+ levels.push(level);
4285
+ }
4286
+ }
4287
+ return levels;
4288
+ }
3982
4289
  async function computeProofFromChain(connection, merkleTreePDA, leafIndex, forceConfirmed = false) {
3983
4290
  assertAllowedRpcConnection(connection);
3984
4291
  await ensureZeroValues();
@@ -4011,7 +4318,12 @@ async function computeProofFromChain(connection, merkleTreePDA, leafIndex, force
4011
4318
  }
4012
4319
  index = Math.floor(index / 2);
4013
4320
  }
4014
- return { pathElements, pathIndices, root };
4321
+ return {
4322
+ pathElements,
4323
+ pathIndices,
4324
+ root,
4325
+ undecidableLevels: nearTipProofUndecidableLevels(leafIndex, nextIndex)
4326
+ };
4015
4327
  }
4016
4328
  async function computeProofForLatestDeposit(connection, merkleTreePDA) {
4017
4329
  assertAllowedRpcConnection(connection);
@@ -4022,7 +4334,7 @@ async function computeProofForLatestDeposit(connection, merkleTreePDA) {
4022
4334
  }
4023
4335
  const leafIndex = nextIndex - 1;
4024
4336
  const proof = await computeProofInternal(leafIndex, nextIndex, subtrees);
4025
- return { ...proof, root, leafIndex };
4337
+ return { ...proof, root, leafIndex, undecidableLevels: [] };
4026
4338
  }
4027
4339
  async function computeProofInternal(leafIndex, _nextIndex, subtrees) {
4028
4340
  const pathElements = [];
@@ -4221,7 +4533,7 @@ async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4221
4533
  }
4222
4534
 
4223
4535
  // src/relay/client.ts
4224
- var import_web37 = require("@solana/web3.js");
4536
+ var import_web39 = require("@solana/web3.js");
4225
4537
  var import_bs58 = __toESM(require("bs58"), 1);
4226
4538
 
4227
4539
  // src/notes/refund-leaf.ts
@@ -4330,6 +4642,9 @@ function isBrowserLike() {
4330
4642
  return typeof globalThis !== "undefined" && (typeof globalThis.window !== "undefined" || typeof globalThis.document !== "undefined");
4331
4643
  }
4332
4644
 
4645
+ // src/config/transaction-version.ts
4646
+ var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
4647
+
4333
4648
  // src/relay/client.ts
4334
4649
  var bs58 = import_bs58.default.default || import_bs58.default;
4335
4650
  var TRANSACT_TAG = 0;
@@ -4338,7 +4653,7 @@ var CLOSE_SWAP_STATE_TAG = 13;
4338
4653
  var CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN = 40;
4339
4654
  var CLOSE_SWAP_STATE_PHASE1_WIRE_LEN = 1 + CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN;
4340
4655
  var CLOSE_SWAP_STATE_COMMITMENT_END = 1 + 32;
4341
- var NATIVE_SOL_MINT2 = new import_web37.PublicKey("So11111111111111111111111111111111111111112");
4656
+ var NATIVE_SOL_MINT2 = new import_web39.PublicKey("So11111111111111111111111111111111111111112");
4342
4657
  var PROOF_LEN = 256;
4343
4658
  var PUBLIC_INPUTS_LEN = 264;
4344
4659
  var COMMITMENTS_OFFSET = 168;
@@ -4541,7 +4856,7 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
4541
4856
  }
4542
4857
  const signature = signatures[i];
4543
4858
  const tx = await connection.getParsedTransaction(signature, {
4544
- maxSupportedTransactionVersion: 0,
4859
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION,
4545
4860
  commitment: "confirmed"
4546
4861
  });
4547
4862
  if (!tx || tx.meta?.err) continue;
@@ -4627,7 +4942,7 @@ async function preflightCheck(relayUrl, rootHex) {
4627
4942
  }
4628
4943
 
4629
4944
  // src/flows/transact.ts
4630
- var import_web39 = require("@solana/web3.js");
4945
+ var import_web311 = require("@solana/web3.js");
4631
4946
  var import_spl_token = require("@solana/spl-token");
4632
4947
  var snarkjs = __toESM(require("snarkjs"), 1);
4633
4948
  init_utxo();
@@ -4855,7 +5170,7 @@ function chainNoteFromBase64(base64) {
4855
5170
  }
4856
5171
 
4857
5172
  // src/notes/delivery-note.ts
4858
- var import_tweetnacl4 = __toESM(require("tweetnacl"), 1);
5173
+ var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
4859
5174
  var RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN = 32;
4860
5175
  var RECIPIENT_DELIVERY_NONCE_LEN = 24;
4861
5176
  var RECIPIENT_DELIVERY_PLAINTEXT_LEN = 40;
@@ -4906,10 +5221,10 @@ function encodeRecipientDeliveryNote(note, recipientViewingPublicKey) {
4906
5221
  const plaintext = new Uint8Array(RECIPIENT_DELIVERY_PLAINTEXT_LEN);
4907
5222
  writeU64LE2(plaintext, 0, note.amount);
4908
5223
  writeU256BE2(plaintext, 8, note.blinding);
4909
- const ephemeral = import_tweetnacl4.default.box.keyPair();
4910
- const shared = import_tweetnacl4.default.box.before(recipientViewingPublicKey, ephemeral.secretKey);
4911
- const nonce = import_tweetnacl4.default.randomBytes(import_tweetnacl4.default.secretbox.nonceLength);
4912
- const ciphertext = import_tweetnacl4.default.secretbox(plaintext, nonce, shared);
5224
+ const ephemeral = import_tweetnacl5.default.box.keyPair();
5225
+ const shared = import_tweetnacl5.default.box.before(recipientViewingPublicKey, ephemeral.secretKey);
5226
+ const nonce = import_tweetnacl5.default.randomBytes(import_tweetnacl5.default.secretbox.nonceLength);
5227
+ const ciphertext = import_tweetnacl5.default.secretbox(plaintext, nonce, shared);
4913
5228
  if (ciphertext.length !== RECIPIENT_DELIVERY_CIPHERTEXT_LEN) {
4914
5229
  throw new Error(
4915
5230
  `delivery ciphertext must be ${RECIPIENT_DELIVERY_CIPHERTEXT_LEN} bytes, got ${ciphertext.length}`
@@ -4935,8 +5250,8 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4935
5250
  const ciphertext = envelope.slice(
4936
5251
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
4937
5252
  );
4938
- const shared = import_tweetnacl4.default.box.before(ephemeralPk, viewingSecretKey);
4939
- const plaintext = import_tweetnacl4.default.secretbox.open(ciphertext, nonce, shared);
5253
+ const shared = import_tweetnacl5.default.box.before(ephemeralPk, viewingSecretKey);
5254
+ const plaintext = import_tweetnacl5.default.secretbox.open(ciphertext, nonce, shared);
4940
5255
  if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
4941
5256
  return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
4942
5257
  } catch {
@@ -4994,7 +5309,7 @@ function parseDeliveryCarrierMemo(data) {
4994
5309
 
4995
5310
  // src/notes/swap-refund.ts
4996
5311
  var import_blake34 = require("@noble/hashes/blake3");
4997
- var import_web38 = require("@solana/web3.js");
5312
+ var import_web310 = require("@solana/web3.js");
4998
5313
  var import_bs582 = __toESM(require("bs58"), 1);
4999
5314
  init_utxo();
5000
5315
  init_inputs();
@@ -5141,7 +5456,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5141
5456
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5142
5457
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5143
5458
  const programIdBase58 = programId.toBase58();
5144
- const [pool] = import_web38.PublicKey.findProgramAddressSync(
5459
+ const [pool] = import_web310.PublicKey.findProgramAddressSync(
5145
5460
  [Buffer.from("pool"), poolMint.toBuffer()],
5146
5461
  programId
5147
5462
  );
@@ -5175,7 +5490,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5175
5490
  try {
5176
5491
  return await connection.getTransaction(signature, {
5177
5492
  commitment: "confirmed",
5178
- maxSupportedTransactionVersion: 0
5493
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
5179
5494
  });
5180
5495
  } catch {
5181
5496
  return null;
@@ -5192,7 +5507,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5192
5507
  if (data[0] !== TRANSACT_SWAP_TAG2 || data.length < MIN_TRANSACT_SWAP_LEN) continue;
5193
5508
  const nullifier = data.slice(NULLIFIER_0_OFFSET, NULLIFIER_0_OFFSET + 32);
5194
5509
  if (nullifier.length !== 32) continue;
5195
- const [swapState] = import_web38.PublicKey.findProgramAddressSync(
5510
+ const [swapState] = import_web310.PublicKey.findProgramAddressSync(
5196
5511
  [Buffer.from("swap_state"), pool.toBuffer(), Buffer.from(nullifier)],
5197
5512
  programId
5198
5513
  );
@@ -5348,303 +5663,80 @@ function saltToBytes2(noteSalt) {
5348
5663
  let v = noteSalt;
5349
5664
  for (let i = 31; i >= 0; i--) {
5350
5665
  out[i] = Number(v & 0xffn);
5351
- v >>= 8n;
5352
- }
5353
- return out;
5354
- }
5355
- function toFieldSecret3(bytes) {
5356
- let value = 0n;
5357
- for (let i = 0; i < 32; i++) value = value << 8n | BigInt(bytes[i]);
5358
- const reduced = value % (BN254_MODULUS >> 4n);
5359
- return reduced === 0n ? 1n : reduced;
5360
- }
5361
- function randomChangeNoteSalt() {
5362
- const bytes = randomBytes(12);
5363
- let v = 0n;
5364
- for (const b of bytes) v = v << 8n | BigInt(b);
5365
- return v === 0n ? 1n : v;
5366
- }
5367
- function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
5368
- if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5369
- throw new Error("viewingKeyNk must be 32 bytes");
5370
- }
5371
- if (!Number.isInteger(outputIndex) || outputIndex < 0 || outputIndex > MAX_OUTPUT_INDEX) {
5372
- throw new Error(`outputIndex must be 0..${MAX_OUTPUT_INDEX}`);
5373
- }
5374
- const salt = saltToBytes2(noteSalt);
5375
- const preimage = new Uint8Array(
5376
- CHANGE_NOTE_DOMAIN.length + viewingKeyNk.length + salt.length + 1 + CHANGE_BLINDING_INFO.length
5377
- );
5378
- let off = 0;
5379
- preimage.set(CHANGE_NOTE_DOMAIN, off);
5380
- off += CHANGE_NOTE_DOMAIN.length;
5381
- preimage.set(viewingKeyNk, off);
5382
- off += viewingKeyNk.length;
5383
- preimage.set(salt, off);
5384
- off += salt.length;
5385
- preimage[off] = outputIndex;
5386
- off += 1;
5387
- preimage.set(CHANGE_BLINDING_INFO, off);
5388
- return toFieldSecret3((0, import_blake36.blake3)(preimage));
5389
- }
5390
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5391
- if (typeof amount !== "bigint" || amount <= 0n) {
5392
- throw new Error("amount must be a positive bigint");
5393
- }
5394
- const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5395
- const utxo = { amount, keypair, blinding, mintAddress };
5396
- utxo.commitment = await computeCommitment2(utxo);
5397
- return { utxo, noteSalt };
5398
- }
5399
- function normalizeCommitment2(value) {
5400
- if (typeof value === "bigint") return value;
5401
- if (typeof value !== "string") return null;
5402
- const clean = value.startsWith("0x") ? value.slice(2) : value;
5403
- if (!/^[0-9a-fA-F]{1,64}$/.test(clean)) return null;
5404
- return BigInt("0x" + clean);
5405
- }
5406
- async function matchChangeNote(params) {
5407
- const { viewingKeyNk, noteSalt, amount, keypair, mintAddress, outputIndex, outputCommitments } = params;
5408
- if (typeof amount !== "bigint" || amount <= 0n) return null;
5409
- if (!keypair || typeof keypair.publicKey !== "bigint" || keypair.publicKey === 0n) return null;
5410
- let blinding;
5411
- try {
5412
- blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5413
- } catch {
5414
- return null;
5415
- }
5416
- const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
5417
- const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
5418
- if (!published.some((value) => value === candidate)) return null;
5419
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
5420
- }
5421
-
5422
- // src/flows/transact.ts
5423
- var import_circomlibjs4 = require("circomlibjs");
5424
- var import_tweetnacl6 = __toESM(require("tweetnacl"), 1);
5425
-
5426
- // src/relay/payload.ts
5427
- var import_sha23 = require("@noble/hashes/sha2");
5428
- var import_utils = require("@noble/hashes/utils");
5429
- var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
5430
- init_inputs();
5431
- var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
5432
- var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
5433
- var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
5434
- var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
5435
- function sha256Hex(text) {
5436
- return (0, import_utils.bytesToHex)((0, import_sha23.sha256)(new TextEncoder().encode(text)));
5437
- }
5438
- function randomNonceUuid() {
5439
- const webCrypto = globalThis?.crypto;
5440
- if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
5441
- const proc = globalThis?.process;
5442
- const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
5443
- if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
5444
- const bytes = randomBytes(16);
5445
- bytes[6] = bytes[6] & 15 | 64;
5446
- bytes[8] = bytes[8] & 63 | 128;
5447
- const hex = (0, import_utils.bytesToHex)(bytes);
5448
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
5449
- }
5450
- var TRANSACT_AUTH_FIELDS = [
5451
- "encrypted_notes",
5452
- "max_fee",
5453
- "mint",
5454
- "proof_bytes",
5455
- "public_inputs",
5456
- "recipient",
5457
- "recipient_delivery_notes",
5458
- "risk_quote",
5459
- "sender"
5460
- ];
5461
- var TRANSACT_SWAP_AUTH_FIELDS = [
5462
- "close_timed_out",
5463
- "dexes",
5464
- "encrypted_notes",
5465
- "exclude_dexes",
5466
- "max_fee",
5467
- "min_output_amount",
5468
- "output_mint",
5469
- "proof_bytes",
5470
- "public_inputs",
5471
- "recipient",
5472
- "recipient_ata",
5473
- "refund_blinding",
5474
- "refund_pubkey",
5475
- "retry_request_id",
5476
- "risk_quote",
5477
- "route_retry_attempts",
5478
- "sender",
5479
- "slippage_bps",
5480
- "swap_max_retries"
5481
- ];
5482
- var UTF8 = new TextEncoder();
5483
- function compareKeysBytewise(a, b) {
5484
- if (a === b) return 0;
5485
- const ab = UTF8.encode(a);
5486
- const bb = UTF8.encode(b);
5487
- const shared = Math.min(ab.length, bb.length);
5488
- for (let i = 0; i < shared; i++) {
5489
- if (ab[i] !== bb[i]) return ab[i] - bb[i];
5490
- }
5491
- return ab.length - bb.length;
5492
- }
5493
- function canonicalJson(value) {
5494
- if (value === null || value === void 0) return "null";
5495
- if (typeof value === "boolean") return value ? "true" : "false";
5496
- if (typeof value === "number") {
5497
- if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
5498
- throw new Error(
5499
- `canonicalJson: refusing to sign the number ${String(value)}. The relay renders numbers with serde_json, which spells non-integer, non-finite and very large values differently from JavaScript, so the two digests would differ and the request would be rejected with an unexplained 401. Send it as a decimal string instead, which is how every amount in this schema travels.`
5500
- );
5501
- }
5502
- return String(value);
5503
- }
5504
- if (typeof value === "bigint") return value.toString();
5505
- if (typeof value === "string") return JSON.stringify(value);
5506
- if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
5507
- if (typeof value === "object") {
5508
- const obj = value;
5509
- const keys = Object.keys(obj).sort(compareKeysBytewise);
5510
- return "{" + keys.map((k) => {
5511
- const v = obj[k];
5512
- if (typeof v === "function" || typeof v === "symbol") {
5513
- throw new Error(
5514
- `canonicalJson: the key "${k}" holds a ${typeof v}, which has no JSON representation. JSON.stringify would drop it from the wire body while it stayed in the signed view, so the relay's digest could never match this one.`
5515
- );
5516
- }
5517
- return `${JSON.stringify(k)}:${canonicalJson(v)}`;
5518
- }).join(",") + "}";
5519
- }
5520
- throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
5521
- }
5522
- var FIELDS_WITHOUT_NULL_ENCODING = {
5523
- slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
5524
- };
5525
- function buildAuthRequest(body, sender, fields) {
5526
- const out = {};
5527
- for (const k of fields) {
5528
- if (k === "sender") {
5529
- out[k] = sender;
5530
- continue;
5531
- }
5532
- const value = body[k];
5533
- if (value === void 0 || value === null) {
5534
- const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
5535
- if (relayDefault) {
5536
- throw new Error(
5537
- `Relay request auth: \`${k}\` must be present in the body. It is the one field in this schema that is not optional on the relay side: when it is missing the relay signs its default, ${relayDefault}, while this request would sign null. The two digests differ and the relay answers 401 "Relay request signature does not match the exact request", which points at nothing. Set \`${k}\` explicitly, to the same value the body will carry.`
5538
- );
5539
- }
5540
- out[k] = null;
5541
- continue;
5542
- }
5543
- out[k] = value;
5666
+ v >>= 8n;
5544
5667
  }
5545
5668
  return out;
5546
5669
  }
5547
- function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
5548
- const digest = sha256Hex(canonicalJson(request));
5549
- return new TextEncoder().encode(
5550
- `${REQUEST_AUTH_DOMAIN}
5551
- ${endpoint}
5552
- ${programId.toBase58()}
5553
- ${nonce}
5554
- ${issuedAt}
5555
- ${digest}`
5556
- );
5557
- }
5558
- function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
5559
- const senderB58 = sender.toBase58();
5560
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
5561
- const nonce = randomNonceUuid();
5562
- const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
5563
- const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
5564
- return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
5565
- }
5566
- function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
5567
- const preimage = buildRelayAuthPreimage(
5568
- endpoint,
5569
- programId,
5570
- body,
5571
- signer.publicKey,
5572
- nowSeconds,
5573
- fields
5574
- );
5575
- const signature = import_tweetnacl5.default.sign.detached(preimage.message, signer.secretKey);
5576
- return {
5577
- sender: preimage.sender,
5578
- auth_issued_at: preimage.auth_issued_at,
5579
- auth_nonce: preimage.auth_nonce,
5580
- auth_signature: Buffer.from(signature).toString("base64")
5581
- };
5670
+ function toFieldSecret3(bytes) {
5671
+ let value = 0n;
5672
+ for (let i = 0; i < 32; i++) value = value << 8n | BigInt(bytes[i]);
5673
+ const reduced = value % (BN254_MODULUS >> 4n);
5674
+ return reduced === 0n ? 1n : reduced;
5582
5675
  }
5583
- function assertApprovalWithinFreshnessWindow(elapsedMs) {
5584
- const elapsedSeconds = elapsedMs / 1e3;
5585
- const budget = REQUEST_AUTH_MAX_AGE_SECONDS - RELAY_AUTH_APPROVAL_MARGIN_SECONDS;
5586
- if (elapsedSeconds <= budget) return;
5587
- throw new Error(
5588
- `The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
5589
- );
5676
+ function randomChangeNoteSalt() {
5677
+ const bytes = randomBytes(12);
5678
+ let v = 0n;
5679
+ for (const b of bytes) v = v << 8n | BigInt(b);
5680
+ return v === 0n ? 1n : v;
5590
5681
  }
5591
- function explainRelayAuthRejection(responseText) {
5592
- const text = String(responseText);
5593
- const has = (needle) => text.includes(needle);
5594
- if (has("issued too far in the future")) {
5595
- return `This computer's clock is more than ${REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS} seconds ahead of the network's, so the request looks like it was signed in the future and is refused before anything else happens. Turn on automatic date and time (or resynchronise the clock) and try again. Nothing was submitted.`;
5596
- }
5597
- if (has("signature expired")) {
5598
- return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
5599
- }
5600
- if (has("does not match the exact request")) {
5601
- return `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
5602
- }
5603
- if (has("has no registered viewing key")) {
5604
- return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
5605
- }
5606
- if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
5607
- return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
5608
- }
5609
- if (has("auth_nonce must be a canonical UUID")) {
5610
- return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
5682
+ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
5683
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5684
+ throw new Error("viewingKeyNk must be 32 bytes");
5611
5685
  }
5612
- if (has("Relay request signature must be exactly 64 bytes") || has("Invalid relay request signature encoding")) {
5613
- return `\`auth_signature\` must be the raw 64-byte ed25519 detached signature, base64 encoded. Wallet adapters that wrap or re-encode what \`signMessage\` returns cannot be used here.`;
5686
+ if (!Number.isInteger(outputIndex) || outputIndex < 0 || outputIndex > MAX_OUTPUT_INDEX) {
5687
+ throw new Error(`outputIndex must be 0..${MAX_OUTPUT_INDEX}`);
5614
5688
  }
5615
- return null;
5689
+ const salt = saltToBytes2(noteSalt);
5690
+ const preimage = new Uint8Array(
5691
+ CHANGE_NOTE_DOMAIN.length + viewingKeyNk.length + salt.length + 1 + CHANGE_BLINDING_INFO.length
5692
+ );
5693
+ let off = 0;
5694
+ preimage.set(CHANGE_NOTE_DOMAIN, off);
5695
+ off += CHANGE_NOTE_DOMAIN.length;
5696
+ preimage.set(viewingKeyNk, off);
5697
+ off += viewingKeyNk.length;
5698
+ preimage.set(salt, off);
5699
+ off += salt.length;
5700
+ preimage[off] = outputIndex;
5701
+ off += 1;
5702
+ preimage.set(CHANGE_BLINDING_INFO, off);
5703
+ return toFieldSecret3((0, import_blake36.blake3)(preimage));
5616
5704
  }
5617
- async function buildRelayAuthFields(endpoint, programId, body, signers, fields = TRANSACT_AUTH_FIELDS) {
5618
- if (signers.depositorKeypair) {
5619
- return signRelayRequest(endpoint, programId, body, signers.depositorKeypair, void 0, fields);
5705
+ async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5706
+ if (typeof amount !== "bigint" || amount <= 0n) {
5707
+ throw new Error("amount must be a positive bigint");
5620
5708
  }
5621
- const wallet = signers.relayAuthSigner;
5622
- if (!wallet) return null;
5623
- const preimage = buildRelayAuthPreimage(
5624
- endpoint,
5625
- programId,
5626
- body,
5627
- wallet.walletPublicKey,
5628
- void 0,
5629
- fields
5630
- );
5631
- const approvalStartedMs = Date.now();
5632
- const signature = await wallet.signMessage(preimage.message);
5633
- assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
5634
- if (!(signature instanceof Uint8Array) || signature.length !== 64) {
5635
- throw new Error(
5636
- `The wallet's signMessage did not return a 64-byte ed25519 detached signature (got ${signature instanceof Uint8Array ? `${signature.length} bytes` : typeof signature}). Cloak signs with a raw detached signature over the bytes it hands the wallet; adapters that wrap or re-encode the result cannot be used here. Pass depositorKeypair instead, or use an adapter whose signMessage returns the raw signature.`
5637
- );
5709
+ const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5710
+ const utxo = { amount, keypair, blinding, mintAddress };
5711
+ utxo.commitment = await computeCommitment2(utxo);
5712
+ return { utxo, noteSalt };
5713
+ }
5714
+ function normalizeCommitment2(value) {
5715
+ if (typeof value === "bigint") return value;
5716
+ if (typeof value !== "string") return null;
5717
+ const clean = value.startsWith("0x") ? value.slice(2) : value;
5718
+ if (!/^[0-9a-fA-F]{1,64}$/.test(clean)) return null;
5719
+ return BigInt("0x" + clean);
5720
+ }
5721
+ async function matchChangeNote(params) {
5722
+ const { viewingKeyNk, noteSalt, amount, keypair, mintAddress, outputIndex, outputCommitments } = params;
5723
+ if (typeof amount !== "bigint" || amount <= 0n) return null;
5724
+ if (!keypair || typeof keypair.publicKey !== "bigint" || keypair.publicKey === 0n) return null;
5725
+ let blinding;
5726
+ try {
5727
+ blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5728
+ } catch {
5729
+ return null;
5638
5730
  }
5639
- return {
5640
- sender: preimage.sender,
5641
- auth_issued_at: preimage.auth_issued_at,
5642
- auth_nonce: preimage.auth_nonce,
5643
- auth_signature: Buffer.from(signature).toString("base64")
5644
- };
5731
+ const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
5732
+ const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
5733
+ if (!published.some((value) => value === candidate)) return null;
5734
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
5645
5735
  }
5646
5736
 
5647
5737
  // src/flows/transact.ts
5738
+ var import_circomlibjs4 = require("circomlibjs");
5739
+ var import_tweetnacl6 = __toESM(require("tweetnacl"), 1);
5648
5740
  init_inputs();
5649
5741
 
5650
5742
  // src/proving/artifacts.ts
@@ -5922,6 +6014,7 @@ async function resolveTransactionCircuitFiles() {
5922
6014
  }
5923
6015
  var _transactPaddingSaltCounter = 0;
5924
6016
  var _registeredViewingKeys = /* @__PURE__ */ new Set();
6017
+ var _viewingKeyRegistrationsInFlight = /* @__PURE__ */ new Map();
5925
6018
  var _resolvedAltAccountsCache = /* @__PURE__ */ new Map();
5926
6019
  var _relayMerkleDisabledMints = /* @__PURE__ */ new Set();
5927
6020
  var _relayMerkleFallbackNotifiedMints = /* @__PURE__ */ new Set();
@@ -6046,7 +6139,7 @@ async function fetchSupplementalAltFromRelay(relayUrl, params) {
6046
6139
  throw new Error("Supplemental ALT response is missing a 'table' address");
6047
6140
  }
6048
6141
  try {
6049
- return new import_web39.PublicKey(table);
6142
+ return new import_web311.PublicKey(table);
6050
6143
  } catch {
6051
6144
  throw new Error(`Supplemental ALT response 'table' is not a valid public key: ${table}`);
6052
6145
  }
@@ -6114,7 +6207,7 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
6114
6207
  const fetched = await Promise.all(
6115
6208
  altAddresses.map(async (addr) => {
6116
6209
  try {
6117
- const pubkey = new import_web39.PublicKey(addr);
6210
+ const pubkey = new import_web311.PublicKey(addr);
6118
6211
  const result = await connection.getAddressLookupTable(pubkey);
6119
6212
  return result.value ?? null;
6120
6213
  } catch {
@@ -6204,7 +6297,7 @@ function calculateConfiguredProtocolFee(amount, config) {
6204
6297
  return total;
6205
6298
  }
6206
6299
  async function readLiveProtocolFee(connection, programId, mint, amount, requireSwapOpen = false) {
6207
- const [poolConfigPda] = import_web39.PublicKey.findProgramAddressSync(
6300
+ const [poolConfigPda] = import_web311.PublicKey.findProgramAddressSync(
6208
6301
  [Buffer.from("pool_config"), mint.toBuffer()],
6209
6302
  programId
6210
6303
  );
@@ -6326,6 +6419,26 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6326
6419
  if (_registeredViewingKeys.has(cacheKey)) {
6327
6420
  return;
6328
6421
  }
6422
+ const inFlight = _viewingKeyRegistrationsInFlight.get(cacheKey);
6423
+ if (inFlight) {
6424
+ return inFlight;
6425
+ }
6426
+ const registration = registerViewingKeyOnce(
6427
+ relayUrl,
6428
+ userPubkey,
6429
+ viewingKeyHex,
6430
+ cacheKey,
6431
+ options,
6432
+ onProgress
6433
+ );
6434
+ _viewingKeyRegistrationsInFlight.set(cacheKey, registration);
6435
+ try {
6436
+ await registration;
6437
+ } finally {
6438
+ _viewingKeyRegistrationsInFlight.delete(cacheKey);
6439
+ }
6440
+ }
6441
+ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cacheKey, options, onProgress) {
6329
6442
  const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
6330
6443
  method: "POST",
6331
6444
  headers: { "Content-Type": "application/json" },
@@ -6346,17 +6459,27 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6346
6459
  viewingKeyHex
6347
6460
  );
6348
6461
  let signatureBase64;
6462
+ let authMode = "message";
6463
+ const messageBytes = new TextEncoder().encode(challenge.message);
6349
6464
  if (options.signMessage) {
6350
- const messageBytes = new TextEncoder().encode(challenge.message);
6351
6465
  const sig = await options.signMessage(messageBytes);
6352
6466
  signatureBase64 = Buffer.from(sig).toString("base64");
6353
6467
  } else if (options.depositorKeypair) {
6354
- const messageBytes = new TextEncoder().encode(challenge.message);
6355
6468
  const sig = import_tweetnacl6.default.sign.detached(messageBytes, options.depositorKeypair.secretKey);
6356
6469
  signatureBase64 = Buffer.from(sig).toString("base64");
6470
+ } else if (options.signAuthTransaction) {
6471
+ onProgress?.(
6472
+ "Approve the viewing-key registration in your wallet. It shows as a 0 SOL transfer to yourself and is never sent to the network."
6473
+ );
6474
+ const signed = await signRelayAuthPayload(
6475
+ { walletPublicKey: userPubkey, signAuthTransaction: options.signAuthTransaction },
6476
+ messageBytes
6477
+ );
6478
+ signatureBase64 = Buffer.from(signed.signature).toString("base64");
6479
+ authMode = signed.mode;
6357
6480
  } else {
6358
6481
  throw new Error(
6359
- "Viewing key registration is mandatory: signMessage (wallet) or depositorKeypair is required."
6482
+ "Viewing key registration is mandatory: signMessage or signAuthTransaction (wallet) or depositorKeypair is required."
6360
6483
  );
6361
6484
  }
6362
6485
  onProgress?.("Registering viewing key...");
@@ -6367,7 +6490,8 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6367
6490
  user_pubkey: userPubkey.toBase58(),
6368
6491
  viewing_key: viewingKeyHex,
6369
6492
  nonce: challenge.nonce,
6370
- signature: signatureBase64
6493
+ signature: signatureBase64,
6494
+ ...authMode === "transaction" ? { auth_mode: authMode } : {}
6371
6495
  })
6372
6496
  });
6373
6497
  if (!response.ok) {
@@ -6461,7 +6585,7 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6461
6585
  var TRANSACT_DISCRIMINATOR = 0;
6462
6586
  var RANGE_QUOTE_TAG_DEPOSIT = 1;
6463
6587
  function deriveRiskNoncePDA(programId, nonce) {
6464
- return import_web39.PublicKey.findProgramAddressSync(
6588
+ return import_web311.PublicKey.findProgramAddressSync(
6465
6589
  [Buffer.from("risk_nonce"), Buffer.from(nonce)],
6466
6590
  programId
6467
6591
  );
@@ -6480,7 +6604,7 @@ function extractDepositNonceFromEd25519Ix(ix) {
6480
6604
  }
6481
6605
  }
6482
6606
  function deriveNullifierPDA(programId, poolPDA, nullifier) {
6483
- return import_web39.PublicKey.findProgramAddressSync(
6607
+ return import_web311.PublicKey.findProgramAddressSync(
6484
6608
  [Buffer.from("nullifier"), poolPDA.toBuffer(), Buffer.from(nullifier)],
6485
6609
  programId
6486
6610
  );
@@ -6513,7 +6637,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6513
6637
  }
6514
6638
  if (!isDepositData) {
6515
6639
  data[offset++] = 3;
6516
- data.set((relayer ?? import_web39.PublicKey.default).toBytes(), offset);
6640
+ data.set((relayer ?? import_web311.PublicKey.default).toBytes(), offset);
6517
6641
  offset += 32;
6518
6642
  writeBigUInt64LE(data, relayerFee ?? BigInt(0), offset);
6519
6643
  offset += 8;
@@ -6543,7 +6667,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6543
6667
  // 4. nullifier PDA 0 (writable)
6544
6668
  { pubkey: nullifierPDA1, isSigner: false, isWritable: true },
6545
6669
  // 5. nullifier PDA 1 (writable)
6546
- { pubkey: import_web39.SystemProgram.programId, isSigner: false, isWritable: false }
6670
+ { pubkey: import_web311.SystemProgram.programId, isSigner: false, isWritable: false }
6547
6671
  // 6. system_program
6548
6672
  ];
6549
6673
  if (splAccounts) {
@@ -6552,34 +6676,34 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6552
6676
  accounts.push({ pubkey: splAccounts.tokenProgram, isSigner: false, isWritable: false });
6553
6677
  if (splAccounts.payerAta) {
6554
6678
  if (enableRiskCheck) {
6555
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6679
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6556
6680
  }
6557
6681
  accounts.push({ pubkey: splAccounts.payerAta, isSigner: false, isWritable: true });
6558
6682
  if (riskNonce) {
6559
6683
  accounts.push({ pubkey: riskNonce, isSigner: false, isWritable: true });
6560
6684
  }
6561
6685
  } else if (enableRiskCheck && !recipient) {
6562
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6686
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6563
6687
  }
6564
6688
  } else {
6565
6689
  if (recipient) {
6566
6690
  accounts.push({ pubkey: recipient, isSigner: false, isWritable: true });
6567
6691
  if (enableRiskCheck) {
6568
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6692
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6569
6693
  }
6570
6694
  } else if (enableRiskCheck) {
6571
6695
  if (publicAmountForAccounts === BigInt(0)) {
6572
6696
  accounts.push({ pubkey: payer, isSigner: true, isWritable: false });
6573
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6697
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6574
6698
  } else {
6575
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6699
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6576
6700
  if (riskNonce) {
6577
6701
  accounts.push({ pubkey: riskNonce, isSigner: false, isWritable: true });
6578
6702
  }
6579
6703
  }
6580
6704
  }
6581
6705
  }
6582
- return new import_web39.TransactionInstruction({
6706
+ return new import_web311.TransactionInstruction({
6583
6707
  programId,
6584
6708
  keys: accounts,
6585
6709
  data
@@ -6588,10 +6712,10 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6588
6712
  var PACKET_LIMIT_BYTES = 1232;
6589
6713
  function getCommonALTAddresses() {
6590
6714
  return [
6591
- import_web39.SystemProgram.programId,
6592
- import_web39.SYSVAR_SLOT_HASHES_PUBKEY,
6593
- import_web39.SYSVAR_INSTRUCTIONS_PUBKEY,
6594
- import_web39.ComputeBudgetProgram.programId
6715
+ import_web311.SystemProgram.programId,
6716
+ import_web311.SYSVAR_SLOT_HASHES_PUBKEY,
6717
+ import_web311.SYSVAR_INSTRUCTIONS_PUBKEY,
6718
+ import_web311.ComputeBudgetProgram.programId
6595
6719
  ];
6596
6720
  }
6597
6721
  function dedupePubkeys(addresses) {
@@ -6642,12 +6766,12 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
6642
6766
  try {
6643
6767
  const slot = await connection.getSlot("finalized");
6644
6768
  const altPayerPubkey = externalFeePayer ? await externalFeePayer.getPayerPubkey() : depositor.publicKey;
6645
- const [createIx, altAddress] = import_web39.AddressLookupTableProgram.createLookupTable({
6769
+ const [createIx, altAddress] = import_web311.AddressLookupTableProgram.createLookupTable({
6646
6770
  authority: depositor.publicKey,
6647
6771
  payer: altPayerPubkey,
6648
6772
  recentSlot: slot
6649
6773
  });
6650
- const extendIx = import_web39.AddressLookupTableProgram.extendLookupTable({
6774
+ const extendIx = import_web311.AddressLookupTableProgram.extendLookupTable({
6651
6775
  payer: altPayerPubkey,
6652
6776
  authority: depositor.publicKey,
6653
6777
  lookupTable: altAddress,
@@ -6666,12 +6790,12 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
6666
6790
  allowSupplementalAlt
6667
6791
  );
6668
6792
  } else {
6669
- const tx = new import_web39.Transaction().add(createIx).add(extendIx);
6793
+ const tx = new import_web311.Transaction().add(createIx).add(extendIx);
6670
6794
  const { blockhash } = await connection.getLatestBlockhash();
6671
6795
  tx.recentBlockhash = blockhash;
6672
6796
  tx.feePayer = depositor.publicKey;
6673
6797
  if (depositor.keypair) {
6674
- await (0, import_web39.sendAndConfirmTransaction)(connection, tx, [depositor.keypair], { commitment: "confirmed" });
6798
+ await (0, import_web311.sendAndConfirmTransaction)(connection, tx, [depositor.keypair], { commitment: "confirmed" });
6675
6799
  } else if (depositor.signTransaction) {
6676
6800
  const signedTx = await depositor.signTransaction(tx);
6677
6801
  const sig = await connection.sendRawTransaction(signedTx.serialize());
@@ -6710,7 +6834,7 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
6710
6834
  var SOLANA_PACKET_DATA_SIZE = 1232;
6711
6835
  function estimateV0TransactionSize(payerKey, recentBlockhash, instructions, addressLookupTableAccounts) {
6712
6836
  try {
6713
- const messageV0 = new import_web39.TransactionMessage({
6837
+ const messageV0 = new import_web311.TransactionMessage({
6714
6838
  payerKey,
6715
6839
  recentBlockhash,
6716
6840
  instructions
@@ -6779,7 +6903,7 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6779
6903
  const { blockhash: quoteBlockhash } = await connection.getLatestBlockhash();
6780
6904
  const measure = (instrs, alts) => {
6781
6905
  try {
6782
- const message = new import_web39.TransactionMessage({
6906
+ const message = new import_web311.TransactionMessage({
6783
6907
  payerKey: externalFeePayerPubkey,
6784
6908
  recentBlockhash: quoteBlockhash,
6785
6909
  instructions: instrs
@@ -6837,12 +6961,12 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6837
6961
  pre = measure(instructions, addressLookupTableAccounts);
6838
6962
  }
6839
6963
  failIfOverLimit(pre.size, pre.error);
6840
- const quoteMessage = new import_web39.TransactionMessage({
6964
+ const quoteMessage = new import_web311.TransactionMessage({
6841
6965
  payerKey: externalFeePayerPubkey,
6842
6966
  recentBlockhash: quoteBlockhash,
6843
6967
  instructions
6844
6968
  }).compileToV0Message(addressLookupTableAccounts ?? []);
6845
- const quoteTxBase64 = Buffer.from(new import_web39.VersionedTransaction(quoteMessage).serialize()).toString("base64");
6969
+ const quoteTxBase64 = Buffer.from(new import_web311.VersionedTransaction(quoteMessage).serialize()).toString("base64");
6846
6970
  const paymentInstruction = await externalFeePayer.getPaymentInstruction(quoteTxBase64);
6847
6971
  const finalInstructions = [...instructions, paymentInstruction];
6848
6972
  let post = measure(finalInstructions, addressLookupTableAccounts);
@@ -6853,12 +6977,12 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6853
6977
  failIfOverLimit(post.size, post.error);
6854
6978
  onProgress?.("Building final transaction...");
6855
6979
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
6856
- const finalMessage = new import_web39.TransactionMessage({
6980
+ const finalMessage = new import_web311.TransactionMessage({
6857
6981
  payerKey: externalFeePayerPubkey,
6858
6982
  recentBlockhash: blockhash,
6859
6983
  instructions: finalInstructions
6860
6984
  }).compileToV0Message(addressLookupTableAccounts ?? []);
6861
- const finalTx = new import_web39.VersionedTransaction(finalMessage);
6985
+ const finalTx = new import_web311.VersionedTransaction(finalMessage);
6862
6986
  onProgress?.("Waiting for wallet signature...");
6863
6987
  const partiallySignedTx = await depositor.signTransaction(finalTx);
6864
6988
  const partiallySignedBase64 = Buffer.from(partiallySignedTx.serialize()).toString("base64");
@@ -7079,8 +7203,8 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7079
7203
  baseInstructions.splice(riskQuoteIx ? 1 : 0, 0, ...topUpInstructions);
7080
7204
  }
7081
7205
  }
7082
- const cuLimitIx = import_web39.ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 });
7083
- const cuPriceIx = import_web39.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1e5 });
7206
+ const cuLimitIx = import_web311.ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 });
7207
+ const cuPriceIx = import_web311.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1e5 });
7084
7208
  const fullInstructions = [...baseInstructions, cuLimitIx, cuPriceIx, transactIx];
7085
7209
  const compactInstructions = [...baseInstructions, cuLimitIx, transactIx];
7086
7210
  const minimalInstructions = [...baseInstructions, cuLimitIx, transactIx];
@@ -7192,12 +7316,12 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7192
7316
  }
7193
7317
  let transportAttempt = 0;
7194
7318
  while (true) {
7195
- const messageV0 = new import_web39.TransactionMessage({
7319
+ const messageV0 = new import_web311.TransactionMessage({
7196
7320
  payerKey: depositor.publicKey,
7197
7321
  recentBlockhash: blockhash,
7198
7322
  instructions: ixs
7199
7323
  }).compileToV0Message(addressLookupTableAccounts);
7200
- const versionedTx = new import_web39.VersionedTransaction(messageV0);
7324
+ const versionedTx = new import_web311.VersionedTransaction(messageV0);
7201
7325
  if (onTransactProofBuilt) {
7202
7326
  await onTransactProofBuilt();
7203
7327
  }
@@ -7327,7 +7451,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7327
7451
  let legacyTransportAttempt = 0;
7328
7452
  while (true) {
7329
7453
  try {
7330
- const tx = new import_web39.Transaction();
7454
+ const tx = new import_web311.Transaction();
7331
7455
  for (const ix of instructions) {
7332
7456
  tx.add(ix);
7333
7457
  }
@@ -7335,7 +7459,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7335
7459
  tx.feePayer = depositor.publicKey;
7336
7460
  if (depositor.keypair) {
7337
7461
  onProgress?.("Signing and sending transaction...");
7338
- signature = await (0, import_web39.sendAndConfirmTransaction)(
7462
+ signature = await (0, import_web311.sendAndConfirmTransaction)(
7339
7463
  connection,
7340
7464
  tx,
7341
7465
  [depositor.keypair],
@@ -7551,7 +7675,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
7551
7675
  const messageArr = hexToBytes2(messageHex);
7552
7676
  let signerPubkey;
7553
7677
  try {
7554
- signerPubkey = new import_web39.PublicKey(signerB58);
7678
+ signerPubkey = new import_web311.PublicKey(signerB58);
7555
7679
  } catch {
7556
7680
  throw new Error("Invalid risk quote response: signer_pubkey is not a public key");
7557
7681
  }
@@ -7575,7 +7699,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
7575
7699
  const signature = new Uint8Array(signatureBuf);
7576
7700
  const message = new Uint8Array(messageArr);
7577
7701
  const publicKey = new Uint8Array(publicKeyBytes);
7578
- const instruction = import_web39.Ed25519Program.createInstructionWithPublicKey({
7702
+ const instruction = import_web311.Ed25519Program.createInstructionWithPublicKey({
7579
7703
  publicKey,
7580
7704
  message,
7581
7705
  signature
@@ -7652,18 +7776,22 @@ function planRelayAuth(options) {
7652
7776
  const walletPublicKey = resolveUserWallet(options);
7653
7777
  if (options.depositorKeypair) return { kind: "keypair" };
7654
7778
  const signMessage = options.signMessage;
7779
+ const signAuthTransaction = options.signAuthTransaction;
7655
7780
  if (walletPublicKey && signMessage) return { kind: "wallet", signer: { walletPublicKey, signMessage } };
7656
- if (!walletPublicKey && !signMessage) return { kind: "none" };
7781
+ if (walletPublicKey && signAuthTransaction) {
7782
+ return { kind: "wallet", signer: { walletPublicKey, signAuthTransaction } };
7783
+ }
7784
+ if (!walletPublicKey && !signMessage && !signAuthTransaction) return { kind: "none" };
7657
7785
  return {
7658
7786
  kind: "incomplete",
7659
- detail: signMessage ? "`signMessage` was provided but no wallet public key, so the request has no sender to authenticate as. Add `walletPublicKey` (or `depositorPublicKey`)." : "a wallet public key was provided but no `signMessage`, so nothing can sign. Add `signMessage` from the same wallet adapter."
7787
+ detail: signMessage || signAuthTransaction ? "a signer was provided but no wallet public key, so the request has no sender to authenticate as. Add `walletPublicKey` (or `depositorPublicKey`)." : "a wallet public key was provided but no `signMessage` and no `signAuthTransaction`, so nothing can sign. Add `signMessage` from the wallet adapter, or `signAuthTransaction` (its `signTransaction`) for a wallet that cannot sign messages."
7660
7788
  };
7661
7789
  }
7662
7790
  function assertRelayAuthAvailable(plan, flow) {
7663
7791
  if (plan.kind === "keypair" || plan.kind === "wallet") return;
7664
7792
  const cause = plan.kind === "none" ? "no signer was provided." : `the signer provided cannot produce one: ${plan.detail}`;
7665
7793
  throw new Error(
7666
- `Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local Keypair) or \`signMessage\` together with \`walletPublicKey\` (a browser wallet adapter). The sender must be the end user's own wallet. Checked before proof generation, so nothing has been computed or submitted yet.`
7794
+ `Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local Keypair), or \`signMessage\` (a browser wallet adapter) or \`signAuthTransaction\` (a hardware wallet that cannot sign messages) together with \`walletPublicKey\`. The sender must be the end user's own wallet. Checked up front, so nothing has been computed or submitted yet.`
7667
7795
  );
7668
7796
  }
7669
7797
  async function submitTransactToRelay(args) {
@@ -7681,12 +7809,12 @@ async function submitTransactToRelay(args) {
7681
7809
  const doFetch = args.fetchImpl ?? fetch;
7682
7810
  const maxNetworkRetries = args.maxNetworkRetries ?? relayNetworkRetries();
7683
7811
  const requestTimeoutMs = args.requestTimeoutMs ?? relayRequestTimeoutMs();
7684
- if (!depositorKeypair && args.relayAuthSigner) {
7812
+ if (!depositorKeypair && args.relayAuthSigner && !args.relayAuthBatch) {
7685
7813
  onProgress?.(
7686
7814
  "Approve the request in your wallet. This signs the request for the relay, not a transaction, and it must be approved within a few minutes to stay valid."
7687
7815
  );
7688
7816
  }
7689
- const authFields = await buildRelayAuthFields("/transact", programId, requestBody, {
7817
+ const authFields = args.relayAuthBatch ? await args.relayAuthBatch.authorize("/transact", programId, requestBody, TRANSACT_AUTH_FIELDS) : await buildRelayAuthFields("/transact", programId, requestBody, {
7690
7818
  depositorKeypair,
7691
7819
  relayAuthSigner: args.relayAuthSigner
7692
7820
  });
@@ -8139,6 +8267,29 @@ async function transact(params, options) {
8139
8267
  "Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
8140
8268
  );
8141
8269
  }
8270
+ if (needsTreeForProof && treeState) {
8271
+ const tip = treeState.nextIndex;
8272
+ const unprovable = paddedInputs.filter((utxo) => {
8273
+ if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
8274
+ if (merkleTree && utxo.index < merkleTree.length) return false;
8275
+ if (utxo.index >= tip) return false;
8276
+ const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
8277
+ return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
8278
+ });
8279
+ if (unprovable.length > 0) {
8280
+ onProgress?.(
8281
+ `On-chain frontier can no longer prove leaf ${unprovable.map((u) => u.index).join(", ")} (a later leaf overwrote a frontier level on its path); rebuilding the full tree from chain...`
8282
+ );
8283
+ forceChainIndexing = true;
8284
+ try {
8285
+ merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, mint);
8286
+ } catch (e) {
8287
+ onProgress?.(
8288
+ `Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
8289
+ );
8290
+ }
8291
+ }
8292
+ }
8142
8293
  const merkleProofs = [];
8143
8294
  let resolvedRootHex = treeState?.root ?? "0";
8144
8295
  let proofRootHex = null;
@@ -8443,11 +8594,14 @@ async function transact(params, options) {
8443
8594
  }
8444
8595
  let proof;
8445
8596
  let publicSignals;
8597
+ const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
8446
8598
  try {
8447
8599
  const result = await generateTransactionProof(circuitInputs, onProofProgress);
8448
8600
  proof = result.proof;
8449
8601
  publicSignals = result.publicSignals;
8602
+ releaseProofSlot?.();
8450
8603
  } catch (proofError) {
8604
+ releaseProofSlot?.();
8451
8605
  const errorMsg = proofError?.message || String(proofError);
8452
8606
  if ((errorMsg.includes("ForceEqual") || errorMsg.includes("Assert Failed")) && submissionAttempts < maxRootRetries) {
8453
8607
  onProgress?.(`Merkle proof error (stale sibling data), will regenerate with fresh tree...`);
@@ -8760,6 +8914,7 @@ async function transact(params, options) {
8760
8914
  // point where they reach the relay submission instead of stopping at viewing-key
8761
8915
  // registration. The keypair still wins when both are present.
8762
8916
  relayAuthSigner: relayAuthPlan.kind === "wallet" ? relayAuthPlan.signer : void 0,
8917
+ relayAuthBatch: options.relayAuthBatch,
8763
8918
  settlement: {
8764
8919
  connection,
8765
8920
  programId,
@@ -8805,7 +8960,7 @@ async function transact(params, options) {
8805
8960
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
8806
8961
  );
8807
8962
  try {
8808
- const [merkleTreePda] = import_web39.PublicKey.findProgramAddressSync(
8963
+ const [merkleTreePda] = import_web311.PublicKey.findProgramAddressSync(
8809
8964
  [Buffer.from("merkle_tree"), mint.toBuffer()],
8810
8965
  programId
8811
8966
  );
@@ -9419,6 +9574,29 @@ async function swapUtxo(params, options) {
9419
9574
  "Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
9420
9575
  );
9421
9576
  }
9577
+ if (needsTreeForProof && merkleState) {
9578
+ const tip = merkleState.nextIndex;
9579
+ const unprovable = paddedInputs.filter((utxo) => {
9580
+ if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
9581
+ if (merkleTree && utxo.index < merkleTree.length) return false;
9582
+ if (utxo.index >= tip) return false;
9583
+ const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
9584
+ return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
9585
+ });
9586
+ if (unprovable.length > 0) {
9587
+ onProgress?.(
9588
+ `On-chain frontier can no longer prove leaf ${unprovable.map((u) => u.index).join(", ")} (a later leaf overwrote a frontier level on its path); rebuilding the full tree from chain...`
9589
+ );
9590
+ forceChainIndexing = true;
9591
+ try {
9592
+ merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, NATIVE_SOL_MINT);
9593
+ } catch (e) {
9594
+ onProgress?.(
9595
+ `Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
9596
+ );
9597
+ }
9598
+ }
9599
+ }
9422
9600
  const merkleProofs = [];
9423
9601
  let resolvedRootHex = merkleState?.root ?? "0";
9424
9602
  let proofRootHex = null;
@@ -9793,7 +9971,7 @@ async function swapUtxo(params, options) {
9793
9971
  }
9794
9972
  if (options.onSwapStatePredicted && inputNullifiers.length > 0) {
9795
9973
  const nBytes = bigintToBytes323(inputNullifiers[0]);
9796
- const [ssp] = import_web39.PublicKey.findProgramAddressSync(
9974
+ const [ssp] = import_web311.PublicKey.findProgramAddressSync(
9797
9975
  [Buffer.from("swap_state"), pdas.pool.toBuffer(), Buffer.from(nBytes)],
9798
9976
  programId
9799
9977
  );
@@ -10215,9 +10393,275 @@ function cleanupStalePendingOperations(maxAgeMs = 24 * 60 * 60 * 1e3) {
10215
10393
  // src/index.ts
10216
10394
  init_utxo();
10217
10395
 
10396
+ // src/relay/batch-auth.ts
10397
+ var import_web312 = require("@solana/web3.js");
10398
+ var RelayBatchAuthCoordinator = class {
10399
+ constructor(options) {
10400
+ this.proofSlotsInUse = 0;
10401
+ this.proofQueue = [];
10402
+ this.items = [];
10403
+ this.signing = false;
10404
+ this.slotsInUse = 0;
10405
+ this.ready = [];
10406
+ this.waves = 0;
10407
+ if (!Number.isInteger(options.items) || options.items < 1) {
10408
+ throw new Error(`A batch needs at least one item (got ${options.items}).`);
10409
+ }
10410
+ if (options.items > RELAY_BATCH_AUTH_MAX_ITEMS) {
10411
+ throw new Error(
10412
+ `A batch may cover at most ${RELAY_BATCH_AUTH_MAX_ITEMS} requests (got ${options.items}); the relay refuses longer digest lists. Chunk the payout. The practical bound is lower still: each spend appends two roots to the on-chain ring of 100, so a batch proved against one root evicts it by itself before 50 items.`
10413
+ );
10414
+ }
10415
+ const concurrency = options.submitConcurrency ?? 3;
10416
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
10417
+ throw new Error(`submitConcurrency must be a positive integer (got ${concurrency}).`);
10418
+ }
10419
+ this.signer = options.signer;
10420
+ this.sender = options.signer instanceof import_web312.Keypair ? options.signer.publicKey : options.signer.walletPublicKey;
10421
+ this.expectedItems = options.items;
10422
+ this.submitConcurrency = concurrency;
10423
+ const proofConcurrency = options.proofConcurrency ?? 2;
10424
+ if (!Number.isInteger(proofConcurrency) || proofConcurrency < 1) {
10425
+ throw new Error(`proofConcurrency must be a positive integer (got ${proofConcurrency}).`);
10426
+ }
10427
+ this.proofConcurrency = proofConcurrency;
10428
+ this.onProgress = options.onProgress;
10429
+ }
10430
+ /** The wallet that signs and is every item's authenticated `sender`. */
10431
+ get walletPublicKey() {
10432
+ return this.sender;
10433
+ }
10434
+ /** How many times the signer has been asked so far: one per wave. */
10435
+ get approvals() {
10436
+ return this.waves;
10437
+ }
10438
+ /** Where every item is right now. For progress UIs and for diagnosing a batch that never signs. */
10439
+ snapshot() {
10440
+ const count = (state) => this.items.filter((i) => i.state === state).length;
10441
+ return {
10442
+ building: count("building"),
10443
+ waiting: count("waiting"),
10444
+ submitting: count("submitting"),
10445
+ done: count("done"),
10446
+ proving: this.proofSlotsInUse,
10447
+ proofQueue: this.proofQueue.length,
10448
+ registered: this.items.length,
10449
+ expected: this.expectedItems
10450
+ };
10451
+ }
10452
+ /** Register one item. Throws past `items`: the wave condition would never be reachable. */
10453
+ item() {
10454
+ if (this.items.length >= this.expectedItems) {
10455
+ throw new Error(
10456
+ `This batch was created for ${this.expectedItems} item(s) and all of them are registered.`
10457
+ );
10458
+ }
10459
+ const item = { state: "building", waiting: null, holdsSlot: false };
10460
+ this.items.push(item);
10461
+ return {
10462
+ proofSlot: () => this.acquireProofSlot(),
10463
+ authorize: (endpoint, programId, body, fields) => this.authorize(item, endpoint, programId, body, fields),
10464
+ finish: () => this.finish(item)
10465
+ };
10466
+ }
10467
+ acquireProofSlot() {
10468
+ return new Promise((resolve) => {
10469
+ const grant = () => {
10470
+ this.proofSlotsInUse += 1;
10471
+ let released = false;
10472
+ resolve(() => {
10473
+ if (released) return;
10474
+ released = true;
10475
+ this.proofSlotsInUse -= 1;
10476
+ const next = this.proofQueue.shift();
10477
+ if (next) next();
10478
+ });
10479
+ };
10480
+ if (this.proofSlotsInUse < this.proofConcurrency) grant();
10481
+ else this.proofQueue.push(grant);
10482
+ });
10483
+ }
10484
+ authorize(item, endpoint, programId, body, fields) {
10485
+ if (item.state === "done") {
10486
+ return Promise.reject(new Error("This batch item already finished; it cannot authorize."));
10487
+ }
10488
+ if (item.state === "waiting") {
10489
+ return Promise.reject(new Error("This batch item is already waiting for a signature."));
10490
+ }
10491
+ this.releaseSlot(item);
10492
+ return new Promise((resolve, reject) => {
10493
+ item.state = "waiting";
10494
+ item.waiting = { endpoint, programId, body, fields, resolve, reject };
10495
+ this.maybeSign();
10496
+ });
10497
+ }
10498
+ finish(item) {
10499
+ if (item.state === "done") return;
10500
+ if (item.state === "waiting" && item.waiting) {
10501
+ item.waiting.reject(new Error("Batch item finished before it was signed."));
10502
+ item.waiting = null;
10503
+ }
10504
+ this.releaseSlot(item);
10505
+ item.state = "done";
10506
+ this.maybeSign();
10507
+ this.pump();
10508
+ }
10509
+ releaseSlot(item) {
10510
+ if (!item.holdsSlot) return;
10511
+ item.holdsSlot = false;
10512
+ this.slotsInUse -= 1;
10513
+ }
10514
+ /** Sign when every registered item is either waiting here or finished, and nothing is building. */
10515
+ maybeSign() {
10516
+ if (this.signing) return;
10517
+ if (this.items.length < this.expectedItems) return;
10518
+ if (this.items.some((item) => item.state === "building" || item.state === "submitting")) return;
10519
+ const wave = this.items.filter((item) => item.state === "waiting");
10520
+ if (wave.length === 0) return;
10521
+ this.signing = true;
10522
+ void this.signWave(wave).finally(() => {
10523
+ this.signing = false;
10524
+ this.maybeSign();
10525
+ });
10526
+ }
10527
+ async signWave(wave) {
10528
+ const waiting = wave.map((item) => item.waiting);
10529
+ try {
10530
+ const programId = waiting[0].programId;
10531
+ for (const w of waiting) {
10532
+ if (!w.programId.equals(programId)) {
10533
+ throw new Error("Every item of a batch must target the same program id.");
10534
+ }
10535
+ }
10536
+ const nowSeconds = Math.floor(Date.now() / 1e3);
10537
+ const preimages = waiting.map(
10538
+ (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10539
+ );
10540
+ const digests = preimages.map(relayRequestDigestHex);
10541
+ const issuedAt = preimages[0].auth_issued_at;
10542
+ const message = buildRelayBatchAuthMessage(programId, issuedAt, digests);
10543
+ this.waves += 1;
10544
+ if (!(this.signer instanceof import_web312.Keypair)) {
10545
+ const asTransaction = !this.signer.signMessage;
10546
+ this.onProgress?.(
10547
+ `Approve ${waiting.length} request(s) in your wallet` + (this.waves > 1 ? ` (approval ${this.waves}, for the rows that had to re-prove)` : "") + (asTransaction ? `. Your wallet shows this as a 0 SOL transfer to yourself: it is how a wallet that cannot sign messages authorizes the requests for the relay, and it is never sent to the network. Approve it on the device within a few minutes.` : `. This signs the requests for the relay, not a transaction, and must be approved within a few minutes to stay valid.`)
10548
+ );
10549
+ }
10550
+ const approvalStartedMs = Date.now();
10551
+ const { signature, mode } = await signRelayAuthPayload(this.signer, message);
10552
+ if (!(this.signer instanceof import_web312.Keypair)) {
10553
+ assertApprovalWithinFreshnessWindow(
10554
+ Date.now() - approvalStartedMs,
10555
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS
10556
+ );
10557
+ }
10558
+ const signatureB64 = Buffer.from(signature).toString("base64");
10559
+ wave.forEach((item, i) => {
10560
+ const preimage = preimages[i];
10561
+ this.ready.push({
10562
+ item,
10563
+ fields: {
10564
+ sender: preimage.sender,
10565
+ auth_issued_at: preimage.auth_issued_at,
10566
+ auth_nonce: preimage.auth_nonce,
10567
+ auth_signature: signatureB64,
10568
+ ...mode === "transaction" ? { auth_mode: mode } : {},
10569
+ // A fresh array per item: `Object.assign` puts this on the wire body, and the body is
10570
+ // serialized again on every network retry.
10571
+ auth_batch: { digests: [...digests] }
10572
+ }
10573
+ });
10574
+ });
10575
+ this.pump();
10576
+ } catch (error) {
10577
+ for (const item of wave) {
10578
+ const w = item.waiting;
10579
+ item.waiting = null;
10580
+ item.state = "done";
10581
+ w?.reject(error);
10582
+ }
10583
+ }
10584
+ }
10585
+ /** Release signed items to submit, `submitConcurrency` at a time, in signing order. */
10586
+ pump() {
10587
+ while (this.ready.length > 0 && this.slotsInUse < this.submitConcurrency) {
10588
+ const next = this.ready.shift();
10589
+ const w = next.item.waiting;
10590
+ next.item.waiting = null;
10591
+ if (next.item.state !== "waiting" || !w) continue;
10592
+ next.item.state = "submitting";
10593
+ next.item.holdsSlot = true;
10594
+ this.slotsInUse += 1;
10595
+ w.resolve(next.fields);
10596
+ }
10597
+ }
10598
+ };
10599
+ function createRelayBatchAuthCoordinator(options) {
10600
+ return new RelayBatchAuthCoordinator(options);
10601
+ }
10602
+
10603
+ // src/flows/transact-batch.ts
10604
+ async function transactBatch(items, options) {
10605
+ if (items.length === 0) {
10606
+ return { results: [], approvals: 0 };
10607
+ }
10608
+ if (items.length > RELAY_BATCH_AUTH_MAX_ITEMS) {
10609
+ throw new Error(
10610
+ `transactBatch accepts at most ${RELAY_BATCH_AUTH_MAX_ITEMS} items per call (got ${items.length}). Chunk the payout; see RELAY_BATCH_AUTH_MAX_ITEMS for why the practical bound is lower.`
10611
+ );
10612
+ }
10613
+ if (!options.relayUrl) {
10614
+ throw new Error("transactBatch requires relayUrl: batch approval is a relay authentication scheme.");
10615
+ }
10616
+ const { proofConcurrency, submitConcurrency, ...shared } = options;
10617
+ const signer = shared.depositorKeypair ? shared.depositorKeypair : (() => {
10618
+ const wallet = shared.walletPublicKey ?? shared.depositorPublicKey;
10619
+ if (!wallet) return null;
10620
+ if (shared.signMessage) return { walletPublicKey: wallet, signMessage: shared.signMessage };
10621
+ if (shared.signAuthTransaction) {
10622
+ return { walletPublicKey: wallet, signAuthTransaction: shared.signAuthTransaction };
10623
+ }
10624
+ return null;
10625
+ })();
10626
+ if (!signer) {
10627
+ throw new Error(
10628
+ "transactBatch requires an authenticated sender: pass `depositorKeypair` (a local Keypair), or `walletPublicKey` with `signMessage` (a browser wallet adapter) or `signAuthTransaction` (a hardware wallet). Checked up front, so nothing has been computed or submitted yet."
10629
+ );
10630
+ }
10631
+ const coordinator = createRelayBatchAuthCoordinator({
10632
+ signer,
10633
+ items: items.length,
10634
+ proofConcurrency,
10635
+ submitConcurrency,
10636
+ onProgress: shared.onProgress
10637
+ });
10638
+ const handles = items.map(() => coordinator.item());
10639
+ const results = new Array(items.length);
10640
+ const runOne = async (index) => {
10641
+ const item = items[index];
10642
+ const handle = handles[index];
10643
+ const label = `[batch ${index + 1}/${items.length}]`;
10644
+ try {
10645
+ const value = await transact(item.params, {
10646
+ ...shared,
10647
+ ...item.options,
10648
+ relayAuthBatch: handle,
10649
+ onProgress: shared.onProgress ? (status) => shared.onProgress?.(`${label} ${status}`) : void 0
10650
+ });
10651
+ results[index] = { status: "fulfilled", value };
10652
+ } catch (reason) {
10653
+ results[index] = { status: "rejected", reason };
10654
+ } finally {
10655
+ handle.finish();
10656
+ }
10657
+ };
10658
+ await Promise.all(items.map((_, index) => runOne(index)));
10659
+ return { results, approvals: coordinator.approvals };
10660
+ }
10661
+
10218
10662
  // src/scanning/scan.ts
10219
10663
  var import_bs583 = __toESM(require("bs58"), 1);
10220
- var import_web310 = require("@solana/web3.js");
10664
+ var import_web313 = require("@solana/web3.js");
10221
10665
  var import_spl_token2 = require("@solana/spl-token");
10222
10666
  init_inputs();
10223
10667
  init_utxo();
@@ -10306,7 +10750,7 @@ function parseSwapOutputMint(data) {
10306
10750
  const mintBytes = data.slice(SWAP_OUTPUT_MINT_OFFSET, end);
10307
10751
  if (mintBytes.every((byte) => byte === 0)) return void 0;
10308
10752
  try {
10309
- return new import_web310.PublicKey(mintBytes).toBase58();
10753
+ return new import_web313.PublicKey(mintBytes).toBase58();
10310
10754
  } catch {
10311
10755
  return void 0;
10312
10756
  }
@@ -10396,7 +10840,7 @@ function parseSwapRecipientAta(data) {
10396
10840
  const recipientAtaBytes = data.slice(recipientAtaStart, recipientAtaEnd);
10397
10841
  if (recipientAtaBytes.every((byte) => byte === 0)) return void 0;
10398
10842
  try {
10399
- return new import_web310.PublicKey(recipientAtaBytes).toBase58();
10843
+ return new import_web313.PublicKey(recipientAtaBytes).toBase58();
10400
10844
  } catch {
10401
10845
  return void 0;
10402
10846
  }
@@ -10558,7 +11002,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
10558
11002
  let rpcCalls = 0;
10559
11003
  const candidates = Array.from(swapCtxByCommitment.keys());
10560
11004
  if (candidates.length === 0) return { records, rpcCalls };
10561
- const [registry] = import_web310.PublicKey.findProgramAddressSync(
11005
+ const [registry] = import_web313.PublicKey.findProgramAddressSync(
10562
11006
  [Buffer.from("cloak_chain_note_registry")],
10563
11007
  programId
10564
11008
  );
@@ -10589,7 +11033,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
10589
11033
  tx = await withRpcRetry(
10590
11034
  () => connection.getTransaction(si.signature, {
10591
11035
  commitment: "confirmed",
10592
- maxSupportedTransactionVersion: 0
11036
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10593
11037
  })
10594
11038
  );
10595
11039
  } catch {
@@ -10690,7 +11134,7 @@ async function scanRecipientDeliveryNotes(opts) {
10690
11134
  tx = await withRpcRetry(
10691
11135
  () => connection.getTransaction(si.signature, {
10692
11136
  commitment: "confirmed",
10693
- maxSupportedTransactionVersion: 0
11137
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10694
11138
  })
10695
11139
  );
10696
11140
  } catch {
@@ -10861,7 +11305,7 @@ async function scanTransactions(opts) {
10861
11305
  return await withRpcRetry(
10862
11306
  () => connection.getTransaction(sigInfo.signature, {
10863
11307
  commitment: "confirmed",
10864
- maxSupportedTransactionVersion: 0
11308
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10865
11309
  })
10866
11310
  );
10867
11311
  } catch {
@@ -10961,8 +11405,8 @@ async function scanTransactions(opts) {
10961
11405
  if (onChainAta) {
10962
11406
  try {
10963
11407
  const expectedAta = (0, import_spl_token2.getAssociatedTokenAddressSync)(
10964
- new import_web310.PublicKey(asset.mint),
10965
- new import_web310.PublicKey(walletPublicKey)
11408
+ new import_web313.PublicKey(asset.mint),
11409
+ new import_web313.PublicKey(walletPublicKey)
10966
11410
  ).toBase58();
10967
11411
  if (onChainAta === expectedAta) {
10968
11412
  isOurs = true;
@@ -11176,7 +11620,7 @@ async function scanTransactions(opts) {
11176
11620
  // deposit — that is the public deposit amount. A deposit that also merged inputs
11177
11621
  // carries a larger output 0 and is not recoverable from public data alone.
11178
11622
  amount: grossAmount,
11179
- mintAddress: new import_web310.PublicKey(asset.mint),
11623
+ mintAddress: new import_web313.PublicKey(asset.mint),
11180
11624
  outputCommitments: ixCtx.outputCommitments ?? []
11181
11625
  });
11182
11626
  if (recoveredDeposit) {
@@ -11202,7 +11646,7 @@ async function scanTransactions(opts) {
11202
11646
  noteSalt: compactNote.noteSalt,
11203
11647
  amount: compactNote.outAmount0,
11204
11648
  keypair: { privateKey: 0n, publicKey: compactNote.outPubkey0 },
11205
- mintAddress: new import_web310.PublicKey(asset.mint),
11649
+ mintAddress: new import_web313.PublicKey(asset.mint),
11206
11650
  outputIndex: 0,
11207
11651
  // v4 describes output 0, which is where change lands
11208
11652
  outputCommitments: ixCtx.outputCommitments ?? []
@@ -11395,7 +11839,7 @@ function formatComplianceCsv(report) {
11395
11839
  }
11396
11840
 
11397
11841
  // src/wallet/utxo-wallet.ts
11398
- var import_web311 = require("@solana/web3.js");
11842
+ var import_web314 = require("@solana/web3.js");
11399
11843
  init_utxo();
11400
11844
  var UtxoWallet = class _UtxoWallet {
11401
11845
  constructor(viewingKey) {
@@ -11608,7 +12052,7 @@ var UtxoWallet = class _UtxoWallet {
11608
12052
  data.viewingKey ? new Uint8Array(data.viewingKey) : void 0
11609
12053
  );
11610
12054
  for (const w of data.wallets) {
11611
- const mint = new import_web311.PublicKey(w.mint);
12055
+ const mint = new import_web314.PublicKey(w.mint);
11612
12056
  for (const u of w.utxos) {
11613
12057
  wallet.addUtxo({
11614
12058
  amount: BigInt(u.amount),
@@ -11900,7 +12344,7 @@ function cloakBridgeRail(relayUrl) {
11900
12344
  }
11901
12345
 
11902
12346
  // src/bridge/paymaster-client.ts
11903
- var import_web312 = require("@solana/web3.js");
12347
+ var import_web315 = require("@solana/web3.js");
11904
12348
  var import_spl_token3 = require("@solana/spl-token");
11905
12349
  function validatePaymasterTopUpTransaction(tx, expect) {
11906
12350
  const ixs = tx.instructions;
@@ -11910,12 +12354,12 @@ function validatePaymasterTopUpTransaction(tx, expect) {
11910
12354
  );
11911
12355
  }
11912
12356
  const ix0 = ixs[0];
11913
- if (!ix0.programId.equals(import_web312.SystemProgram.programId)) {
12357
+ if (!ix0.programId.equals(import_web315.SystemProgram.programId)) {
11914
12358
  throw new Error(
11915
12359
  `paymaster top-up instruction 0 is owned by ${ix0.programId.toBase58()}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
11916
12360
  );
11917
12361
  }
11918
- const transfer2 = import_web312.SystemInstruction.decodeTransfer(ix0);
12362
+ const transfer2 = import_web315.SystemInstruction.decodeTransfer(ix0);
11919
12363
  if (!transfer2.toPubkey.equals(expect.recipient)) {
11920
12364
  throw new Error(
11921
12365
  `paymaster top-up sends SOL to ${transfer2.toPubkey.toBase58()}, which is not our recipient ${expect.recipient.toBase58()} \u2014 refusing to sign a transaction that funds a key we do not control`
@@ -11994,10 +12438,10 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
11994
12438
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
11995
12439
  );
11996
12440
  }
11997
- const feeMint = new import_web312.PublicKey(prepared.fee_mint);
11998
- const paymentAddress = new import_web312.PublicKey(prepared.payment_address);
12441
+ const feeMint = new import_web315.PublicKey(prepared.fee_mint);
12442
+ const paymentAddress = new import_web315.PublicKey(prepared.payment_address);
11999
12443
  const feeTokenAmount = BigInt(prepared.fee_token_amount);
12000
- const tx = import_web312.Transaction.from(Buffer.from(prepared.transaction, "base64"));
12444
+ const tx = import_web315.Transaction.from(Buffer.from(prepared.transaction, "base64"));
12001
12445
  validatePaymasterTopUpTransaction(tx, {
12002
12446
  recipient: receiver.publicKey,
12003
12447
  maxGrantLamports: grantLamports,
@@ -12016,7 +12460,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12016
12460
  });
12017
12461
  const cosigned = await parseBridgeResponse2(cosignRes, "paymaster cosign");
12018
12462
  return {
12019
- transaction: import_web312.Transaction.from(Buffer.from(cosigned.transaction, "base64")),
12463
+ transaction: import_web315.Transaction.from(Buffer.from(cosigned.transaction, "base64")),
12020
12464
  feeTokenAmount,
12021
12465
  feeMint: prepared.fee_mint,
12022
12466
  paymentAddress: prepared.payment_address
@@ -12024,7 +12468,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12024
12468
  }
12025
12469
 
12026
12470
  // src/bridge/derive.ts
12027
- var import_web313 = require("@solana/web3.js");
12471
+ var import_web316 = require("@solana/web3.js");
12028
12472
  var import_hmac = require("@noble/hashes/hmac");
12029
12473
  var import_sha512 = require("@noble/hashes/sha512");
12030
12474
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
@@ -12039,11 +12483,11 @@ function deriveBridgeReceiver(nk, index) {
12039
12483
  );
12040
12484
  }
12041
12485
  const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12042
- return import_web313.Keypair.fromSeed(h.slice(0, 32));
12486
+ return import_web316.Keypair.fromSeed(h.slice(0, 32));
12043
12487
  }
12044
12488
 
12045
12489
  // src/bridge/discover.ts
12046
- var import_web314 = require("@solana/web3.js");
12490
+ var import_web317 = require("@solana/web3.js");
12047
12491
  var import_spl_token4 = require("@solana/spl-token");
12048
12492
  function describeError(err) {
12049
12493
  return err instanceof Error ? err.message : String(err);
@@ -12065,7 +12509,7 @@ async function listBridgeDeposits(conn, nk, opts) {
12065
12509
  try {
12066
12510
  tokenBalance = BigInt((await conn.getTokenAccountBalance(tokenAccount)).value.amount);
12067
12511
  } catch (err) {
12068
- if (!(err instanceof import_web314.SolanaJSONRPCError && /could not find account/i.test(err.message))) {
12512
+ if (!(err instanceof import_web317.SolanaJSONRPCError && /could not find account/i.test(err.message))) {
12069
12513
  throw err;
12070
12514
  }
12071
12515
  }
@@ -12080,7 +12524,9 @@ async function listBridgeDeposits(conn, nk, opts) {
12080
12524
  const sigs = await conn.getSignaturesForAddress(receiver, { limit: 20 });
12081
12525
  for (const s of sigs) {
12082
12526
  if (s.err) continue;
12083
- const tx = await conn.getTransaction(s.signature, { maxSupportedTransactionVersion: 0 });
12527
+ const tx = await conn.getTransaction(s.signature, {
12528
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
12529
+ });
12084
12530
  const keys = tx?.transaction.message.getAccountKeys({
12085
12531
  accountKeysFromLookups: tx.meta?.loadedAddresses
12086
12532
  });
@@ -12120,18 +12566,18 @@ async function listBridgeDeposits(conn, nk, opts) {
12120
12566
  }
12121
12567
 
12122
12568
  // src/bridge/deposit-core.ts
12123
- var import_web316 = require("@solana/web3.js");
12569
+ var import_web319 = require("@solana/web3.js");
12124
12570
  var import_tweetnacl8 = __toESM(require("tweetnacl"), 1);
12125
12571
  init_utxo();
12126
12572
 
12127
12573
  // src/bridge/funder.ts
12128
- var import_web315 = require("@solana/web3.js");
12574
+ var import_web318 = require("@solana/web3.js");
12129
12575
  var import_spl_token5 = require("@solana/spl-token");
12130
12576
  var MAINNET_RENT_0 = 890880;
12131
12577
  var MAINNET_RENT_1 = 897840;
12132
12578
  var FEE_BUDGET = 13e4;
12133
12579
  var CLEANUP_FEE_BUDGET = 5e3;
12134
- var pda = (seeds, programId) => import_web315.PublicKey.findProgramAddressSync(seeds.map((s) => Buffer.from(s)), programId)[0];
12580
+ var pda = (seeds, programId) => import_web318.PublicKey.findProgramAddressSync(seeds.map((s) => Buffer.from(s)), programId)[0];
12135
12581
  function deriveFundingTargets(d) {
12136
12582
  const pool = pda([Buffer.from("pool"), d.mint.toBuffer()], d.programId);
12137
12583
  return {
@@ -12192,15 +12638,15 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
12192
12638
  if (heldByR >= grantR) {
12193
12639
  log(` R already holds ${heldByR} (>= ${grantR}) \u2014 no top-up needed`);
12194
12640
  } else {
12195
- await (0, import_web316.sendAndConfirmTransaction)(conn, new import_web316.Transaction().add(
12196
- import_web316.SystemProgram.transfer({ fromPubkey: funder.publicKey, toPubkey: R.publicKey, lamports: grantR - heldByR })
12641
+ await (0, import_web319.sendAndConfirmTransaction)(conn, new import_web319.Transaction().add(
12642
+ import_web319.SystemProgram.transfer({ fromPubkey: funder.publicKey, toPubkey: R.publicKey, lamports: grantR - heldByR })
12197
12643
  ), [funder]);
12198
12644
  log(` funder topped R up by ${grantR - heldByR} to ${grantR}${grantOverride !== void 0 ? " (OVERRIDDEN for a deliberate test)" : " \u2014 floor + deposit fee + cleanup fee, no rent"}`);
12199
12645
  }
12200
12646
  let measuredSize = -1;
12201
12647
  let fundedAccounts = [];
12202
12648
  const signTransaction2 = async (tx) => {
12203
- if (tx instanceof import_web316.VersionedTransaction) {
12649
+ if (tx instanceof import_web319.VersionedTransaction) {
12204
12650
  measuredSize = tx.serialize().length;
12205
12651
  const alts = await Promise.all(
12206
12652
  tx.message.addressTableLookups.map(async (l) => (await conn.getAddressLookupTable(l.accountKey)).value)
@@ -12219,13 +12665,13 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
12219
12665
  address: t.a.toBase58(),
12220
12666
  lamportsSent: Math.max(0, t.need - (infos[i]?.lamports ?? 0))
12221
12667
  }));
12222
- const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [import_web316.SystemProgram.transfer({
12668
+ const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [import_web319.SystemProgram.transfer({
12223
12669
  fromPubkey: funder.publicKey,
12224
12670
  toPubkey: t.a,
12225
12671
  lamports: t.need - (infos[i]?.lamports ?? 0)
12226
12672
  })]);
12227
12673
  if (ixs.length) {
12228
- const sig = await (0, import_web316.sendAndConfirmTransaction)(conn, new import_web316.Transaction().add(...ixs), [funder]);
12674
+ const sig = await (0, import_web319.sendAndConfirmTransaction)(conn, new import_web319.Transaction().add(...ixs), [funder]);
12229
12675
  log(` seam: funded ${ixs.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
12230
12676
  }
12231
12677
  tx.sign([R]);
@@ -12281,9 +12727,9 @@ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log,
12281
12727
  }
12282
12728
 
12283
12729
  // src/bridge/cleanup.ts
12284
- var import_web317 = require("@solana/web3.js");
12730
+ var import_web320 = require("@solana/web3.js");
12285
12731
  var import_spl_token6 = require("@solana/spl-token");
12286
- var DEFAULT_MINT = new import_web317.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
12732
+ var DEFAULT_MINT = new import_web320.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
12287
12733
  async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_MINT) {
12288
12734
  assertAllowedRpcConnection(conn);
12289
12735
  const rAta = (0, import_spl_token6.getAssociatedTokenAddressSync)(mint, R.publicKey);
@@ -12329,7 +12775,7 @@ async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_
12329
12775
  destination = destAta.toBase58();
12330
12776
  }
12331
12777
  ixs.push((0, import_spl_token6.createCloseAccountInstruction)(rAta, R.publicKey, R.publicKey));
12332
- const signature = await (0, import_web317.sendAndConfirmTransaction)(conn, new import_web317.Transaction().add(...ixs), [R], {
12778
+ const signature = await (0, import_web320.sendAndConfirmTransaction)(conn, new import_web320.Transaction().add(...ixs), [R], {
12333
12779
  commitment: "confirmed"
12334
12780
  });
12335
12781
  const after = await conn.getBalance(R.publicKey);
@@ -12497,9 +12943,13 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12497
12943
  RECIPIENT_DELIVERY_NOTE_BYTES,
12498
12944
  RECIPIENT_DELIVERY_PLAINTEXT_LEN,
12499
12945
  RECIPIENT_DELIVERY_TAG_LEN,
12946
+ RELAY_BATCH_AUTH_MAX_ITEMS,
12500
12947
  RELAY_ORIGIN_ALLOWLIST,
12948
+ REQUEST_AUTH_BATCH_DOMAIN,
12949
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
12501
12950
  REQUEST_AUTH_MAX_AGE_SECONDS,
12502
12951
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
12952
+ RelayBatchAuthCoordinator,
12503
12953
  RelayInternalError,
12504
12954
  RelayService,
12505
12955
  RootNotFoundError,
@@ -12527,11 +12977,13 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12527
12977
  assessBridgeQuote,
12528
12978
  bigintToBytes32,
12529
12979
  bigintToHex,
12980
+ buildAuthTransactionMessage,
12530
12981
  buildMerkleTree,
12531
12982
  buildMerkleTreeFromChain,
12532
12983
  buildMerkleTreeFromRelay,
12533
12984
  buildRecipientDeliveryNotes,
12534
12985
  buildRelayAuthPreimage,
12986
+ buildRelayBatchAuthMessage,
12535
12987
  buildTransactRequestBody,
12536
12988
  bytesToHex,
12537
12989
  calculateFee,
@@ -12565,6 +13017,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12565
13017
  createLogger,
12566
13018
  createRecoverableChangeUtxo,
12567
13019
  createRecoverableDepositUtxo,
13020
+ createRelayBatchAuthCoordinator,
12568
13021
  createUtxo,
12569
13022
  createZeroUtxo,
12570
13023
  decryptCompactChainNote,
@@ -12691,6 +13144,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12691
13144
  readRent,
12692
13145
  recipientDeliveryNoteToBase64,
12693
13146
  registerViewingKey,
13147
+ relayRequestDigestHex,
12694
13148
  removePendingDeposit,
12695
13149
  removePendingWithdrawal,
12696
13150
  renderAssessment,
@@ -12704,10 +13158,12 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12704
13158
  sdkLogger,
12705
13159
  selectUtxos,
12706
13160
  sendTransaction,
13161
+ serializeAuthTransactionMessage,
12707
13162
  serializeNote,
12708
13163
  serializeUtxo,
12709
13164
  setCircuitsPath,
12710
13165
  setDebugMode,
13166
+ signRelayAuthPayload,
12711
13167
  signTransaction,
12712
13168
  splitTo2Limbs,
12713
13169
  submitTransactToRelay,
@@ -12716,6 +13172,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12716
13172
  swapWithChange,
12717
13173
  toComplianceReport,
12718
13174
  transact,
13175
+ transactBatch,
12719
13176
  transfer,
12720
13177
  truncate,
12721
13178
  tryDecryptNote,