@cloak.dev/sdk 0.2.3 → 0.2.4-staging.d6e0e6c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -577,9 +577,9 @@ var LocalStorageAdapter = class {
577
577
  };
578
578
 
579
579
  // src/scanning/compliance-keys.ts
580
- import nacl2 from "tweetnacl";
580
+ import nacl3 from "tweetnacl";
581
581
  import { blake3 as blake32 } from "@noble/hashes/blake3";
582
- import { sha256 } from "@noble/hashes/sha2";
582
+ import { sha256 as sha2562 } from "@noble/hashes/sha2";
583
583
 
584
584
  // src/relay/viewing-key.ts
585
585
  var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
@@ -621,7 +621,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
621
621
 
622
622
  // src/config/relay.ts
623
623
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
624
- var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
624
+ var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
625
625
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
626
626
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
627
627
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -766,6 +766,275 @@ function connectionRpcEndpoint(connection) {
766
766
  return connection?._rpcEndpoint ?? connection?.rpcEndpoint;
767
767
  }
768
768
 
769
+ // src/relay/payload.ts
770
+ import { sha256 } from "@noble/hashes/sha2";
771
+ import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils";
772
+ import nacl2 from "tweetnacl";
773
+ import { Keypair, PublicKey as PublicKey3, SystemProgram, Transaction } from "@solana/web3.js";
774
+ var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
775
+ var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
776
+ var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
777
+ var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
778
+ function sha256Hex(text) {
779
+ return bytesToHex2(sha256(new TextEncoder().encode(text)));
780
+ }
781
+ function randomNonceUuid() {
782
+ const webCrypto = globalThis?.crypto;
783
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
784
+ const proc = globalThis?.process;
785
+ const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
786
+ if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
787
+ const bytes = randomBytes(16);
788
+ bytes[6] = bytes[6] & 15 | 64;
789
+ bytes[8] = bytes[8] & 63 | 128;
790
+ const hex = bytesToHex2(bytes);
791
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
792
+ }
793
+ var TRANSACT_AUTH_FIELDS = [
794
+ "encrypted_notes",
795
+ "max_fee",
796
+ "mint",
797
+ "proof_bytes",
798
+ "public_inputs",
799
+ "recipient",
800
+ "recipient_delivery_notes",
801
+ "risk_quote",
802
+ "sender"
803
+ ];
804
+ var TRANSACT_SWAP_AUTH_FIELDS = [
805
+ "close_timed_out",
806
+ "dexes",
807
+ "encrypted_notes",
808
+ "exclude_dexes",
809
+ "max_fee",
810
+ "min_output_amount",
811
+ "output_mint",
812
+ "proof_bytes",
813
+ "public_inputs",
814
+ "recipient",
815
+ "recipient_ata",
816
+ "refund_blinding",
817
+ "refund_pubkey",
818
+ "retry_request_id",
819
+ "risk_quote",
820
+ "route_retry_attempts",
821
+ "sender",
822
+ "slippage_bps",
823
+ "swap_max_retries"
824
+ ];
825
+ var UTF8 = new TextEncoder();
826
+ function compareKeysBytewise(a, b) {
827
+ if (a === b) return 0;
828
+ const ab = UTF8.encode(a);
829
+ const bb = UTF8.encode(b);
830
+ const shared = Math.min(ab.length, bb.length);
831
+ for (let i = 0; i < shared; i++) {
832
+ if (ab[i] !== bb[i]) return ab[i] - bb[i];
833
+ }
834
+ return ab.length - bb.length;
835
+ }
836
+ function canonicalJson(value) {
837
+ if (value === null || value === void 0) return "null";
838
+ if (typeof value === "boolean") return value ? "true" : "false";
839
+ if (typeof value === "number") {
840
+ if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
841
+ throw new Error(
842
+ `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.`
843
+ );
844
+ }
845
+ return String(value);
846
+ }
847
+ if (typeof value === "bigint") return value.toString();
848
+ if (typeof value === "string") return JSON.stringify(value);
849
+ if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
850
+ if (typeof value === "object") {
851
+ const obj = value;
852
+ const keys = Object.keys(obj).sort(compareKeysBytewise);
853
+ return "{" + keys.map((k) => {
854
+ const v = obj[k];
855
+ if (typeof v === "function" || typeof v === "symbol") {
856
+ throw new Error(
857
+ `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.`
858
+ );
859
+ }
860
+ return `${JSON.stringify(k)}:${canonicalJson(v)}`;
861
+ }).join(",") + "}";
862
+ }
863
+ throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
864
+ }
865
+ var FIELDS_WITHOUT_NULL_ENCODING = {
866
+ slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
867
+ };
868
+ function buildAuthRequest(body, sender, fields) {
869
+ const out = {};
870
+ for (const k of fields) {
871
+ if (k === "sender") {
872
+ out[k] = sender;
873
+ continue;
874
+ }
875
+ const value = body[k];
876
+ if (value === void 0 || value === null) {
877
+ const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
878
+ if (relayDefault) {
879
+ throw new Error(
880
+ `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.`
881
+ );
882
+ }
883
+ out[k] = null;
884
+ continue;
885
+ }
886
+ out[k] = value;
887
+ }
888
+ return out;
889
+ }
890
+ function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
891
+ const digest = sha256Hex(canonicalJson(request));
892
+ return new TextEncoder().encode(
893
+ `${REQUEST_AUTH_DOMAIN}
894
+ ${endpoint}
895
+ ${programId.toBase58()}
896
+ ${nonce}
897
+ ${issuedAt}
898
+ ${digest}`
899
+ );
900
+ }
901
+ function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
902
+ const senderB58 = sender.toBase58();
903
+ const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
904
+ const nonce = randomNonceUuid();
905
+ const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
906
+ const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
907
+ return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
908
+ }
909
+ function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
910
+ const preimage = buildRelayAuthPreimage(
911
+ endpoint,
912
+ programId,
913
+ body,
914
+ signer.publicKey,
915
+ nowSeconds,
916
+ fields
917
+ );
918
+ const signature = nacl2.sign.detached(preimage.message, signer.secretKey);
919
+ return {
920
+ sender: preimage.sender,
921
+ auth_issued_at: preimage.auth_issued_at,
922
+ auth_nonce: preimage.auth_nonce,
923
+ auth_signature: Buffer.from(signature).toString("base64")
924
+ };
925
+ }
926
+ function buildAuthTransactionMessage(sender, digest) {
927
+ if (digest.length !== 32) throw new Error(`auth transaction digest must be 32 bytes (got ${digest.length})`);
928
+ const tx = new Transaction();
929
+ tx.add(SystemProgram.transfer({ fromPubkey: sender, toPubkey: sender, lamports: 0 }));
930
+ tx.feePayer = sender;
931
+ tx.recentBlockhash = new PublicKey3(digest).toBase58();
932
+ return tx;
933
+ }
934
+ function serializeAuthTransactionMessage(sender, digest) {
935
+ return Uint8Array.from(buildAuthTransactionMessage(sender, digest).compileMessage().serialize());
936
+ }
937
+ async function signRelayAuthPayload(signer, payload) {
938
+ if (signer instanceof Keypair) {
939
+ return { signature: nacl2.sign.detached(payload, signer.secretKey), mode: "message" };
940
+ }
941
+ if (signer.signMessage) {
942
+ const signature = await signer.signMessage(payload);
943
+ assertDetachedSignature(signature, "signMessage");
944
+ return { signature, mode: "message" };
945
+ }
946
+ if (signer.signAuthTransaction) {
947
+ const digest = sha256(payload);
948
+ const signed = await signer.signAuthTransaction(buildAuthTransactionMessage(signer.walletPublicKey, digest));
949
+ const own = signed.signatures.find((s) => s.publicKey.equals(signer.walletPublicKey))?.signature;
950
+ if (!own) {
951
+ throw new Error(
952
+ "The wallet returned no signature for the Cloak auth transaction. Nothing was submitted."
953
+ );
954
+ }
955
+ const signature = Uint8Array.from(own);
956
+ assertDetachedSignature(signature, "signTransaction");
957
+ return { signature, mode: "transaction" };
958
+ }
959
+ throw new Error("Relay auth signer has neither signMessage nor signAuthTransaction.");
960
+ }
961
+ function assertDetachedSignature(signature, method) {
962
+ if (!(signature instanceof Uint8Array) || signature.length !== 64) {
963
+ throw new Error(
964
+ `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.`
965
+ );
966
+ }
967
+ }
968
+ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_AUTH_MAX_AGE_SECONDS) {
969
+ const elapsedSeconds = elapsedMs / 1e3;
970
+ const budget = maxAgeSeconds - RELAY_AUTH_APPROVAL_MARGIN_SECONDS;
971
+ if (elapsedSeconds <= budget) return;
972
+ throw new Error(
973
+ `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.`
974
+ );
975
+ }
976
+ function explainRelayAuthRejection(responseText) {
977
+ const text = String(responseText);
978
+ const has = (needle) => text.includes(needle);
979
+ if (has("issued too far in the future")) {
980
+ 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.`;
981
+ }
982
+ if (has("signature expired")) {
983
+ 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.`;
984
+ }
985
+ if (has("does not match the exact request")) {
986
+ 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\`.`;
987
+ }
988
+ if (has("has no registered viewing key")) {
989
+ 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.`;
990
+ }
991
+ if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
992
+ return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
993
+ }
994
+ if (has("auth_nonce must be a canonical UUID")) {
995
+ return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
996
+ }
997
+ if (has("Relay request signature must be exactly 64 bytes") || has("Invalid relay request signature encoding")) {
998
+ 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.`;
999
+ }
1000
+ return null;
1001
+ }
1002
+ async function buildRelayAuthFields(endpoint, programId, body, signers, fields = TRANSACT_AUTH_FIELDS) {
1003
+ if (signers.depositorKeypair) {
1004
+ return signRelayRequest(endpoint, programId, body, signers.depositorKeypair, void 0, fields);
1005
+ }
1006
+ const wallet = signers.relayAuthSigner;
1007
+ if (!wallet) return null;
1008
+ const preimage = buildRelayAuthPreimage(
1009
+ endpoint,
1010
+ programId,
1011
+ body,
1012
+ wallet.walletPublicKey,
1013
+ void 0,
1014
+ fields
1015
+ );
1016
+ const approvalStartedMs = Date.now();
1017
+ const { signature, mode } = await signRelayAuthPayload(wallet, preimage.message);
1018
+ assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
1019
+ return {
1020
+ sender: preimage.sender,
1021
+ auth_issued_at: preimage.auth_issued_at,
1022
+ auth_nonce: preimage.auth_nonce,
1023
+ auth_signature: Buffer.from(signature).toString("base64"),
1024
+ ...mode === "transaction" ? { auth_mode: mode } : {}
1025
+ };
1026
+ }
1027
+ var REQUEST_AUTH_BATCH_DOMAIN = "CLOAK_RELAY_BATCH_AUTH_V1";
1028
+ var REQUEST_AUTH_BATCH_MAX_AGE_SECONDS = 600;
1029
+ var RELAY_BATCH_AUTH_MAX_ITEMS = 64;
1030
+ function relayRequestDigestHex(preimage) {
1031
+ return bytesToHex2(sha256(preimage.message));
1032
+ }
1033
+ function buildRelayBatchAuthMessage(programId, issuedAt, digests) {
1034
+ const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId.toBase58(), issuedAt, String(digests.length)];
1035
+ return new TextEncoder().encode([...lines, ...digests].join("\n"));
1036
+ }
1037
+
769
1038
  // src/scanning/compliance-keys.ts
770
1039
  var X25519_KEY_LENGTH = 32;
771
1040
  var DIVERSIFIER_LENGTH = 11;
@@ -803,7 +1072,7 @@ function deriveViewingKeyFromNk(nk) {
803
1072
  preimage.set(nk, CHAIN_NOTE_VK_DOMAIN.length);
804
1073
  const derived = blake32(preimage);
805
1074
  const privateKey = clampX25519Secret(derived);
806
- const publicKey = nacl2.scalarMult.base(privateKey);
1075
+ const publicKey = nacl3.scalarMult.base(privateKey);
807
1076
  return { privateKey, publicKey };
808
1077
  }
809
1078
  function deriveDiversifier(nk, commitmentHex, outputIndex) {
@@ -838,7 +1107,7 @@ function deriveDiversifiedViewingKey(nk, diversifier) {
838
1107
  preimage.set(diversifier, SK_D_DOMAIN.length + nk.length);
839
1108
  const derived = blake32(preimage);
840
1109
  const privateKey = clampX25519Secret(derived);
841
- const publicKey = nacl2.scalarMult.base(privateKey);
1110
+ const publicKey = nacl3.scalarMult.base(privateKey);
842
1111
  return { privateKey, publicKey };
843
1112
  }
844
1113
  function deriveViewingKeyFromSpendKey(skSpend) {
@@ -901,19 +1170,19 @@ async function deriveUserCompliancePublicKey(masterCompliancePublicKey, userPubl
901
1170
  masterCompliancePublicKey,
902
1171
  userPublicKey
903
1172
  );
904
- return nacl2.scalarMult(factor, masterCompliancePublicKey);
1173
+ return nacl3.scalarMult(factor, masterCompliancePublicKey);
905
1174
  }
906
- function bytesToHex2(bytes) {
1175
+ function bytesToHex3(bytes) {
907
1176
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
908
1177
  }
909
1178
  function computeViewingKeyIdentifier(userPubkey, nkHex) {
910
1179
  const preimage = new TextEncoder().encode(`${userPubkey.toBase58()}${nkHex}`);
911
- return bytesToHex2(sha256(preimage));
1180
+ return bytesToHex3(sha2562(preimage));
912
1181
  }
913
1182
  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.";
914
1183
  async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
915
1184
  assert32Bytes(nk, "nk");
916
- const nkHex = bytesToHex2(nk);
1185
+ const nkHex = bytesToHex3(nk);
917
1186
  const keyId = computeViewingKeyIdentifier(userPubkey, nkHex);
918
1187
  const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
919
1188
  method: "POST",
@@ -934,8 +1203,11 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
934
1203
  nkHex
935
1204
  );
936
1205
  const messageBytes = new TextEncoder().encode(challenge.message);
937
- const signatureBytes = await signMessage(messageBytes);
938
- const signature = Buffer.from(signatureBytes).toString("base64");
1206
+ const signed = await signRelayAuthPayload(
1207
+ typeof signMessage === "function" ? { walletPublicKey: userPubkey, signMessage } : signMessage,
1208
+ messageBytes
1209
+ );
1210
+ const signature = Buffer.from(signed.signature).toString("base64");
939
1211
  const response = await relayFetch(`${relayUrl}/viewing-key/register`, {
940
1212
  method: "POST",
941
1213
  headers: { "Content-Type": "application/json" },
@@ -944,7 +1216,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
944
1216
  viewing_key: nkHex,
945
1217
  nonce: challenge.nonce,
946
1218
  identifier: keyId,
947
- signature
1219
+ signature,
1220
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
948
1221
  })
949
1222
  });
950
1223
  if (!response.ok) {
@@ -953,7 +1226,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
953
1226
  }
954
1227
 
955
1228
  // src/scanning/metadata-encryption.ts
956
- import nacl3 from "tweetnacl";
1229
+ import nacl4 from "tweetnacl";
957
1230
  var AES_GCM_NONCE_LENGTH = 12;
958
1231
  var AES_GCM_TAG_LENGTH = 16;
959
1232
  var X25519_KEY_LENGTH2 = 32;
@@ -1050,8 +1323,8 @@ async function aesGcmDecrypt(ciphertext, keyBytes, nonce) {
1050
1323
  }
1051
1324
  async function encryptForRecipient(plaintext, recipientPublicKey) {
1052
1325
  assert32Bytes2(recipientPublicKey, "recipientPublicKey");
1053
- const ephemeral = nacl3.box.keyPair();
1054
- const sharedSecret = nacl3.scalarMult(ephemeral.secretKey, recipientPublicKey);
1326
+ const ephemeral = nacl4.box.keyPair();
1327
+ const sharedSecret = nacl4.scalarMult(ephemeral.secretKey, recipientPublicKey);
1055
1328
  const nonce = randomBytes(AES_GCM_NONCE_LENGTH);
1056
1329
  const ciphertext = await aesGcmEncrypt(plaintext, sharedSecret, nonce);
1057
1330
  return {
@@ -1110,7 +1383,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
1110
1383
  const plaintext = new TextEncoder().encode(JSON.stringify(metadata));
1111
1384
  const basePoint = new Uint8Array(32);
1112
1385
  basePoint[0] = 9;
1113
- const viewingKeyPublic = nacl3.scalarMult(viewingKeyPrivate, basePoint);
1386
+ const viewingKeyPublic = nacl4.scalarMult(viewingKeyPrivate, basePoint);
1114
1387
  const [userPayload, compliancePayload] = await Promise.all([
1115
1388
  encryptForRecipient(plaintext, viewingKeyPublic),
1116
1389
  encryptForRecipient(plaintext, viewingKeyPublic)
@@ -1129,7 +1402,7 @@ async function decryptTransactionMetadata(encrypted, viewKeySecret) {
1129
1402
  const payload = decodePayload(encrypted);
1130
1403
  const ephemeralPk = hexToBytes(payload.ephemeral_pk);
1131
1404
  assert32Bytes2(ephemeralPk, "ephemeral public key");
1132
- const sharedSecret = nacl3.scalarMult(viewKeySecret, ephemeralPk);
1405
+ const sharedSecret = nacl4.scalarMult(viewKeySecret, ephemeralPk);
1133
1406
  return decryptWithSharedSecret(payload, sharedSecret);
1134
1407
  }
1135
1408
  async function decryptComplianceMetadataWithMasterKey(encrypted, masterCompliancePrivateKey, masterCompliancePublicKey, userPublicKey) {
@@ -1142,8 +1415,8 @@ async function decryptComplianceMetadataWithMasterKey(encrypted, masterComplianc
1142
1415
  masterCompliancePublicKey,
1143
1416
  userPublicKey
1144
1417
  );
1145
- const scaledEphemeral = nacl3.scalarMult(userFactor, ephemeralPk);
1146
- const sharedSecret = nacl3.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1418
+ const scaledEphemeral = nacl4.scalarMult(userFactor, ephemeralPk);
1419
+ const sharedSecret = nacl4.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1147
1420
  return decryptWithSharedSecret(payload, sharedSecret);
1148
1421
  }
1149
1422
 
@@ -2073,22 +2346,22 @@ function formatErrorForLogging(error) {
2073
2346
  }
2074
2347
 
2075
2348
  // src/program/pda.ts
2076
- import { PublicKey as PublicKey3 } from "@solana/web3.js";
2349
+ import { PublicKey as PublicKey4 } from "@solana/web3.js";
2077
2350
  function getShieldPoolPDAs(programId, mint = NATIVE_SOL_MINT) {
2078
2351
  const pid = programId || CLOAK_PROGRAM_ID;
2079
- const [pool] = PublicKey3.findProgramAddressSync(
2352
+ const [pool] = PublicKey4.findProgramAddressSync(
2080
2353
  [Buffer.from("pool"), mint.toBuffer()],
2081
2354
  pid
2082
2355
  );
2083
- const [merkleTree] = PublicKey3.findProgramAddressSync(
2356
+ const [merkleTree] = PublicKey4.findProgramAddressSync(
2084
2357
  [Buffer.from("merkle_tree"), mint.toBuffer()],
2085
2358
  pid
2086
2359
  );
2087
- const [treasury] = PublicKey3.findProgramAddressSync(
2360
+ const [treasury] = PublicKey4.findProgramAddressSync(
2088
2361
  [Buffer.from("treasury"), mint.toBuffer()],
2089
2362
  pid
2090
2363
  );
2091
- const [vaultAuthority] = PublicKey3.findProgramAddressSync(
2364
+ const [vaultAuthority] = PublicKey4.findProgramAddressSync(
2092
2365
  [Buffer.from("vault_authority"), mint.toBuffer()],
2093
2366
  pid
2094
2367
  );
@@ -2104,7 +2377,7 @@ function getNullifierPDA(poolPubkey, nullifier, programId) {
2104
2377
  if (nullifier.length !== 32) {
2105
2378
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2106
2379
  }
2107
- return PublicKey3.findProgramAddressSync(
2380
+ return PublicKey4.findProgramAddressSync(
2108
2381
  [Buffer.from("nullifier"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2109
2382
  pid
2110
2383
  );
@@ -2114,25 +2387,25 @@ function getSwapStatePDA(poolPubkey, nullifier, programId) {
2114
2387
  if (nullifier.length !== 32) {
2115
2388
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2116
2389
  }
2117
- return PublicKey3.findProgramAddressSync(
2390
+ return PublicKey4.findProgramAddressSync(
2118
2391
  [Buffer.from("swap_state"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2119
2392
  pid
2120
2393
  );
2121
2394
  }
2122
2395
  function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
2123
2396
  const pid = programId || CLOAK_PROGRAM_ID;
2124
- return PublicKey3.findProgramAddressSync(
2397
+ return PublicKey4.findProgramAddressSync(
2125
2398
  [Buffer.from("pool_authority"), mint.toBuffer()],
2126
2399
  pid
2127
2400
  );
2128
2401
  }
2129
2402
  function getDeliveryRegistryPDA(programId) {
2130
2403
  const pid = programId || CLOAK_PROGRAM_ID;
2131
- return PublicKey3.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
2404
+ return PublicKey4.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
2132
2405
  }
2133
2406
  function getChainNoteRegistryPDA(programId) {
2134
2407
  const pid = programId || CLOAK_PROGRAM_ID;
2135
- return PublicKey3.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
2408
+ return PublicKey4.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
2136
2409
  }
2137
2410
 
2138
2411
  // src/flows/verify-utxos.ts
@@ -2150,8 +2423,8 @@ async function verifyUtxos(utxos, connection, programId, commitment = "confirmed
2150
2423
  const nullifierHex = nullifierBig.toString(16).padStart(64, "0");
2151
2424
  const nullifierBytes = Buffer.from(nullifierHex, "hex");
2152
2425
  const { pool } = getShieldPoolPDAs(programId, utxo.mintAddress);
2153
- const [pda] = getNullifierPDA(pool, nullifierBytes, programId);
2154
- checkable.push({ utxo, pda });
2426
+ const [pda2] = getNullifierPDA(pool, nullifierBytes, programId);
2427
+ checkable.push({ utxo, pda: pda2 });
2155
2428
  } catch {
2156
2429
  skipped.push(utxo);
2157
2430
  }
@@ -2221,8 +2494,8 @@ function deriveInputNullifierPdas(programId, mint, inputNullifiers) {
2221
2494
  const pdas = [];
2222
2495
  for (const nullifier of inputNullifiers) {
2223
2496
  if (nullifier === BigInt(0)) continue;
2224
- const [pda] = getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
2225
- pdas.push(pda);
2497
+ const [pda2] = getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
2498
+ pdas.push(pda2);
2226
2499
  }
2227
2500
  return pdas;
2228
2501
  }
@@ -2463,7 +2736,8 @@ function truncate(str, len = 20) {
2463
2736
  var sdkLogger = createLogger("cloak::sdk");
2464
2737
 
2465
2738
  // src/relay/relay-service.ts
2466
- import { sha256 as sha2562 } from "@noble/hashes/sha2";
2739
+ import { sha256 as sha2563 } from "@noble/hashes/sha2";
2740
+ import { PublicKey as PublicKey5 } from "@solana/web3.js";
2467
2741
  var RelayService = class {
2468
2742
  /**
2469
2743
  * Create a new Relay Service client
@@ -2779,8 +3053,11 @@ var RelayService = class {
2779
3053
  userPubkey,
2780
3054
  viewingKey
2781
3055
  );
2782
- const signatureBytes = await signMessage(new TextEncoder().encode(challenge.message));
2783
- const signature = this.bytesToBase64(signatureBytes);
3056
+ const signed = await signRelayAuthPayload(
3057
+ typeof signMessage === "function" ? { walletPublicKey: new PublicKey5(userPubkey), signMessage } : signMessage,
3058
+ new TextEncoder().encode(challenge.message)
3059
+ );
3060
+ const signature = this.bytesToBase64(signed.signature);
2784
3061
  const response = await relayFetch(`${this.baseUrl}/viewing-key/register`, {
2785
3062
  method: "POST",
2786
3063
  headers: { "Content-Type": "application/json" },
@@ -2789,7 +3066,8 @@ var RelayService = class {
2789
3066
  viewing_key: viewingKey,
2790
3067
  nonce: challenge.nonce,
2791
3068
  identifier,
2792
- signature
3069
+ signature,
3070
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
2793
3071
  })
2794
3072
  });
2795
3073
  if (!response.ok) {
@@ -2827,7 +3105,7 @@ var RelayService = class {
2827
3105
  }
2828
3106
  computeViewingKeyIdentifier(userPubkey, viewingKeyHex) {
2829
3107
  const preimage = new TextEncoder().encode(`${userPubkey}${viewingKeyHex}`);
2830
- const hash = sha2562(preimage);
3108
+ const hash = sha2563(preimage);
2831
3109
  return Array.from(hash).map((b) => b.toString(16).padStart(2, "0")).join("");
2832
3110
  }
2833
3111
  };
@@ -2945,10 +3223,10 @@ function encodeNoteSimple(note) {
2945
3223
 
2946
3224
  // src/wallet/adapter.ts
2947
3225
  import {
2948
- Keypair
3226
+ Keypair as Keypair2
2949
3227
  } from "@solana/web3.js";
2950
3228
  function validateWalletConnected(wallet) {
2951
- if (wallet instanceof Keypair) {
3229
+ if (wallet instanceof Keypair2) {
2952
3230
  return;
2953
3231
  }
2954
3232
  if (!wallet.publicKey) {
@@ -2960,7 +3238,7 @@ function validateWalletConnected(wallet) {
2960
3238
  }
2961
3239
  }
2962
3240
  function getPublicKey(wallet) {
2963
- if (wallet instanceof Keypair) {
3241
+ if (wallet instanceof Keypair2) {
2964
3242
  return wallet.publicKey;
2965
3243
  }
2966
3244
  if (!wallet.publicKey) {
@@ -2974,7 +3252,7 @@ function getPublicKey(wallet) {
2974
3252
  }
2975
3253
  async function sendTransaction(transaction, wallet, connection, options) {
2976
3254
  assertAllowedRpcConnection(connection);
2977
- if (wallet instanceof Keypair) {
3255
+ if (wallet instanceof Keypair2) {
2978
3256
  return await connection.sendTransaction(transaction, [wallet], options);
2979
3257
  }
2980
3258
  if (wallet.sendTransaction) {
@@ -2991,7 +3269,7 @@ async function sendTransaction(transaction, wallet, connection, options) {
2991
3269
  }
2992
3270
  }
2993
3271
  async function signTransaction(transaction, wallet) {
2994
- if (wallet instanceof Keypair) {
3272
+ if (wallet instanceof Keypair2) {
2995
3273
  transaction.sign(wallet);
2996
3274
  return transaction;
2997
3275
  }
@@ -3020,8 +3298,8 @@ function keypairToAdapter(keypair) {
3020
3298
 
3021
3299
  // src/program/instructions.ts
3022
3300
  import {
3023
- PublicKey as PublicKey5,
3024
- SystemProgram,
3301
+ PublicKey as PublicKey7,
3302
+ SystemProgram as SystemProgram2,
3025
3303
  TransactionInstruction
3026
3304
  } from "@solana/web3.js";
3027
3305
  function createDepositInstruction(params) {
@@ -3053,7 +3331,7 @@ function createDepositInstruction(params) {
3053
3331
  // Account 1: Pool (writable) - receives SOL
3054
3332
  { pubkey: params.pool, isSigner: false, isWritable: true },
3055
3333
  // Account 2: System Program (readonly) - for transfers
3056
- { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
3334
+ { pubkey: SystemProgram2.programId, isSigner: false, isWritable: false },
3057
3335
  // Account 3: Merkle Tree (writable) - stores on-chain Merkle tree
3058
3336
  { pubkey: params.merkleTree, isSigner: false, isWritable: true }
3059
3337
  ],
@@ -3061,16 +3339,16 @@ function createDepositInstruction(params) {
3061
3339
  });
3062
3340
  }
3063
3341
  function validateDepositParams(params) {
3064
- if (!(params.programId instanceof PublicKey5)) {
3342
+ if (!(params.programId instanceof PublicKey7)) {
3065
3343
  throw new Error("programId must be a PublicKey");
3066
3344
  }
3067
- if (!(params.payer instanceof PublicKey5)) {
3345
+ if (!(params.payer instanceof PublicKey7)) {
3068
3346
  throw new Error("payer must be a PublicKey");
3069
3347
  }
3070
- if (!(params.pool instanceof PublicKey5)) {
3348
+ if (!(params.pool instanceof PublicKey7)) {
3071
3349
  throw new Error("pool must be a PublicKey");
3072
3350
  }
3073
- if (!(params.merkleTree instanceof PublicKey5)) {
3351
+ if (!(params.merkleTree instanceof PublicKey7)) {
3074
3352
  throw new Error("merkleTree must be a PublicKey");
3075
3353
  }
3076
3354
  if (typeof params.amount !== "number" || params.amount <= 0) {
@@ -3168,6 +3446,23 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
3168
3446
  const finalRoot = root || rpcRoot;
3169
3447
  return { nextIndex, root: finalRoot, subtrees };
3170
3448
  }
3449
+ function nearTipProofUndecidableLevels(leafIndex, nextIndex, height = MERKLE_TREE_HEIGHT) {
3450
+ if (!Number.isInteger(leafIndex) || !Number.isInteger(nextIndex) || !Number.isInteger(height)) {
3451
+ throw new Error(`nearTipProofUndecidableLevels: integers required (leafIndex=${leafIndex}, nextIndex=${nextIndex}, height=${height})`);
3452
+ }
3453
+ if (leafIndex < 0 || leafIndex >= nextIndex) {
3454
+ throw new Error(`Leaf index ${leafIndex} is not below next_index ${nextIndex}`);
3455
+ }
3456
+ const levels = [];
3457
+ for (let level = 0; level < height; level++) {
3458
+ const width = 2 ** level;
3459
+ const ancestor = Math.floor(leafIndex / width);
3460
+ if (ancestor % 2 === 1 && (ancestor + 1) * width < nextIndex) {
3461
+ levels.push(level);
3462
+ }
3463
+ }
3464
+ return levels;
3465
+ }
3171
3466
  async function computeProofFromChain(connection, merkleTreePDA, leafIndex, forceConfirmed = false) {
3172
3467
  assertAllowedRpcConnection(connection);
3173
3468
  await ensureZeroValues();
@@ -3200,7 +3495,12 @@ async function computeProofFromChain(connection, merkleTreePDA, leafIndex, force
3200
3495
  }
3201
3496
  index = Math.floor(index / 2);
3202
3497
  }
3203
- return { pathElements, pathIndices, root };
3498
+ return {
3499
+ pathElements,
3500
+ pathIndices,
3501
+ root,
3502
+ undecidableLevels: nearTipProofUndecidableLevels(leafIndex, nextIndex)
3503
+ };
3204
3504
  }
3205
3505
  async function computeProofForLatestDeposit(connection, merkleTreePDA) {
3206
3506
  assertAllowedRpcConnection(connection);
@@ -3211,7 +3511,7 @@ async function computeProofForLatestDeposit(connection, merkleTreePDA) {
3211
3511
  }
3212
3512
  const leafIndex = nextIndex - 1;
3213
3513
  const proof = await computeProofInternal(leafIndex, nextIndex, subtrees);
3214
- return { ...proof, root, leafIndex };
3514
+ return { ...proof, root, leafIndex, undecidableLevels: [] };
3215
3515
  }
3216
3516
  async function computeProofInternal(leafIndex, _nextIndex, subtrees) {
3217
3517
  const pathElements = [];
@@ -3410,7 +3710,7 @@ async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
3410
3710
  }
3411
3711
 
3412
3712
  // src/relay/client.ts
3413
- import { PublicKey as PublicKey6 } from "@solana/web3.js";
3713
+ import { PublicKey as PublicKey8 } from "@solana/web3.js";
3414
3714
  import _bs58 from "bs58";
3415
3715
 
3416
3716
  // src/notes/refund-leaf.ts
@@ -3519,6 +3819,9 @@ function isBrowserLike() {
3519
3819
  return typeof globalThis !== "undefined" && (typeof globalThis.window !== "undefined" || typeof globalThis.document !== "undefined");
3520
3820
  }
3521
3821
 
3822
+ // src/config/transaction-version.ts
3823
+ var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
3824
+
3522
3825
  // src/relay/client.ts
3523
3826
  var bs58 = _bs58.default || _bs58;
3524
3827
  var TRANSACT_TAG = 0;
@@ -3527,7 +3830,7 @@ var CLOSE_SWAP_STATE_TAG = 13;
3527
3830
  var CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN = 40;
3528
3831
  var CLOSE_SWAP_STATE_PHASE1_WIRE_LEN = 1 + CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN;
3529
3832
  var CLOSE_SWAP_STATE_COMMITMENT_END = 1 + 32;
3530
- var NATIVE_SOL_MINT2 = new PublicKey6("So11111111111111111111111111111111111111112");
3833
+ var NATIVE_SOL_MINT2 = new PublicKey8("So11111111111111111111111111111111111111112");
3531
3834
  var PROOF_LEN = 256;
3532
3835
  var PUBLIC_INPUTS_LEN = 264;
3533
3836
  var COMMITMENTS_OFFSET = 168;
@@ -3543,7 +3846,7 @@ async function fetchWithRetry(url, options = {}) {
3543
3846
  const {
3544
3847
  timeoutMs = DEFAULT_TIMEOUT_MS,
3545
3848
  maxRetries = DEFAULT_MAX_RETRIES,
3546
- retryDelayMs = 1e3
3849
+ retryDelayMs: retryDelayMs2 = 1e3
3547
3850
  } = options;
3548
3851
  assertAllowedRelayOrigin(url);
3549
3852
  let lastError = null;
@@ -3567,7 +3870,7 @@ async function fetchWithRetry(url, options = {}) {
3567
3870
  `Relay request failed after ${attempt + 1} attempts: ${lastError.message}`
3568
3871
  );
3569
3872
  }
3570
- const delay = retryDelayMs * Math.pow(2, attempt) + Math.random() * 500;
3873
+ const delay = retryDelayMs2 * Math.pow(2, attempt) + Math.random() * 500;
3571
3874
  await new Promise((resolve) => setTimeout(resolve, delay));
3572
3875
  }
3573
3876
  }
@@ -3730,7 +4033,7 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
3730
4033
  }
3731
4034
  const signature = signatures[i];
3732
4035
  const tx = await connection.getParsedTransaction(signature, {
3733
- maxSupportedTransactionVersion: 0,
4036
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION,
3734
4037
  commitment: "confirmed"
3735
4038
  });
3736
4039
  if (!tx || tx.meta?.err) continue;
@@ -3817,11 +4120,11 @@ async function preflightCheck(relayUrl, rootHex) {
3817
4120
 
3818
4121
  // src/flows/transact.ts
3819
4122
  import {
3820
- PublicKey as PublicKey8,
3821
- Transaction as Transaction2,
4123
+ PublicKey as PublicKey10,
4124
+ Transaction as Transaction3,
3822
4125
  TransactionInstruction as TransactionInstruction2,
3823
4126
  sendAndConfirmTransaction,
3824
- SystemProgram as SystemProgram2,
4127
+ SystemProgram as SystemProgram3,
3825
4128
  ComputeBudgetProgram,
3826
4129
  SYSVAR_INSTRUCTIONS_PUBKEY,
3827
4130
  SYSVAR_SLOT_HASHES_PUBKEY,
@@ -4060,7 +4363,7 @@ function chainNoteFromBase64(base64) {
4060
4363
  }
4061
4364
 
4062
4365
  // src/notes/delivery-note.ts
4063
- import nacl4 from "tweetnacl";
4366
+ import nacl5 from "tweetnacl";
4064
4367
  var RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN = 32;
4065
4368
  var RECIPIENT_DELIVERY_NONCE_LEN = 24;
4066
4369
  var RECIPIENT_DELIVERY_PLAINTEXT_LEN = 40;
@@ -4111,10 +4414,10 @@ function encodeRecipientDeliveryNote(note, recipientViewingPublicKey) {
4111
4414
  const plaintext = new Uint8Array(RECIPIENT_DELIVERY_PLAINTEXT_LEN);
4112
4415
  writeU64LE2(plaintext, 0, note.amount);
4113
4416
  writeU256BE2(plaintext, 8, note.blinding);
4114
- const ephemeral = nacl4.box.keyPair();
4115
- const shared = nacl4.box.before(recipientViewingPublicKey, ephemeral.secretKey);
4116
- const nonce = nacl4.randomBytes(nacl4.secretbox.nonceLength);
4117
- const ciphertext = nacl4.secretbox(plaintext, nonce, shared);
4417
+ const ephemeral = nacl5.box.keyPair();
4418
+ const shared = nacl5.box.before(recipientViewingPublicKey, ephemeral.secretKey);
4419
+ const nonce = nacl5.randomBytes(nacl5.secretbox.nonceLength);
4420
+ const ciphertext = nacl5.secretbox(plaintext, nonce, shared);
4118
4421
  if (ciphertext.length !== RECIPIENT_DELIVERY_CIPHERTEXT_LEN) {
4119
4422
  throw new Error(
4120
4423
  `delivery ciphertext must be ${RECIPIENT_DELIVERY_CIPHERTEXT_LEN} bytes, got ${ciphertext.length}`
@@ -4140,8 +4443,8 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4140
4443
  const ciphertext = envelope.slice(
4141
4444
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
4142
4445
  );
4143
- const shared = nacl4.box.before(ephemeralPk, viewingSecretKey);
4144
- const plaintext = nacl4.secretbox.open(ciphertext, nonce, shared);
4446
+ const shared = nacl5.box.before(ephemeralPk, viewingSecretKey);
4447
+ const plaintext = nacl5.secretbox.open(ciphertext, nonce, shared);
4145
4448
  if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
4146
4449
  return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
4147
4450
  } catch {
@@ -4199,7 +4502,7 @@ function parseDeliveryCarrierMemo(data) {
4199
4502
 
4200
4503
  // src/notes/swap-refund.ts
4201
4504
  import { blake3 as blake33 } from "@noble/hashes/blake3";
4202
- import { PublicKey as PublicKey7 } from "@solana/web3.js";
4505
+ import { PublicKey as PublicKey9 } from "@solana/web3.js";
4203
4506
  import _bs582 from "bs58";
4204
4507
  var bs582 = _bs582.default || _bs582;
4205
4508
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
@@ -4344,7 +4647,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
4344
4647
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
4345
4648
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
4346
4649
  const programIdBase58 = programId.toBase58();
4347
- const [pool] = PublicKey7.findProgramAddressSync(
4650
+ const [pool] = PublicKey9.findProgramAddressSync(
4348
4651
  [Buffer.from("pool"), poolMint.toBuffer()],
4349
4652
  programId
4350
4653
  );
@@ -4378,7 +4681,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
4378
4681
  try {
4379
4682
  return await connection.getTransaction(signature, {
4380
4683
  commitment: "confirmed",
4381
- maxSupportedTransactionVersion: 0
4684
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
4382
4685
  });
4383
4686
  } catch {
4384
4687
  return null;
@@ -4395,7 +4698,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
4395
4698
  if (data[0] !== TRANSACT_SWAP_TAG2 || data.length < MIN_TRANSACT_SWAP_LEN) continue;
4396
4699
  const nullifier = data.slice(NULLIFIER_0_OFFSET, NULLIFIER_0_OFFSET + 32);
4397
4700
  if (nullifier.length !== 32) continue;
4398
- const [swapState] = PublicKey7.findProgramAddressSync(
4701
+ const [swapState] = PublicKey9.findProgramAddressSync(
4399
4702
  [Buffer.from("swap_state"), pool.toBuffer(), Buffer.from(nullifier)],
4400
4703
  programId
4401
4704
  );
@@ -4622,226 +4925,6 @@ async function matchChangeNote(params) {
4622
4925
  import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
4623
4926
  import nacl6 from "tweetnacl";
4624
4927
 
4625
- // src/relay/payload.ts
4626
- import { sha256 as sha2563 } from "@noble/hashes/sha2";
4627
- import { bytesToHex as bytesToHex3 } from "@noble/hashes/utils";
4628
- import nacl5 from "tweetnacl";
4629
- var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
4630
- var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
4631
- var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
4632
- var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
4633
- function sha256Hex(text) {
4634
- return bytesToHex3(sha2563(new TextEncoder().encode(text)));
4635
- }
4636
- function randomNonceUuid() {
4637
- const webCrypto = globalThis?.crypto;
4638
- if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
4639
- const proc = globalThis?.process;
4640
- const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
4641
- if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
4642
- const bytes = randomBytes(16);
4643
- bytes[6] = bytes[6] & 15 | 64;
4644
- bytes[8] = bytes[8] & 63 | 128;
4645
- const hex = bytesToHex3(bytes);
4646
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
4647
- }
4648
- var TRANSACT_AUTH_FIELDS = [
4649
- "encrypted_notes",
4650
- "max_fee",
4651
- "mint",
4652
- "proof_bytes",
4653
- "public_inputs",
4654
- "recipient",
4655
- "recipient_delivery_notes",
4656
- "risk_quote",
4657
- "sender"
4658
- ];
4659
- var TRANSACT_SWAP_AUTH_FIELDS = [
4660
- "close_timed_out",
4661
- "dexes",
4662
- "encrypted_notes",
4663
- "exclude_dexes",
4664
- "max_fee",
4665
- "min_output_amount",
4666
- "output_mint",
4667
- "proof_bytes",
4668
- "public_inputs",
4669
- "recipient",
4670
- "recipient_ata",
4671
- "refund_blinding",
4672
- "refund_pubkey",
4673
- "retry_request_id",
4674
- "risk_quote",
4675
- "route_retry_attempts",
4676
- "sender",
4677
- "slippage_bps",
4678
- "swap_max_retries"
4679
- ];
4680
- var UTF8 = new TextEncoder();
4681
- function compareKeysBytewise(a, b) {
4682
- if (a === b) return 0;
4683
- const ab = UTF8.encode(a);
4684
- const bb = UTF8.encode(b);
4685
- const shared = Math.min(ab.length, bb.length);
4686
- for (let i = 0; i < shared; i++) {
4687
- if (ab[i] !== bb[i]) return ab[i] - bb[i];
4688
- }
4689
- return ab.length - bb.length;
4690
- }
4691
- function canonicalJson(value) {
4692
- if (value === null || value === void 0) return "null";
4693
- if (typeof value === "boolean") return value ? "true" : "false";
4694
- if (typeof value === "number") {
4695
- if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
4696
- throw new Error(
4697
- `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.`
4698
- );
4699
- }
4700
- return String(value);
4701
- }
4702
- if (typeof value === "bigint") return value.toString();
4703
- if (typeof value === "string") return JSON.stringify(value);
4704
- if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
4705
- if (typeof value === "object") {
4706
- const obj = value;
4707
- const keys = Object.keys(obj).sort(compareKeysBytewise);
4708
- return "{" + keys.map((k) => {
4709
- const v = obj[k];
4710
- if (typeof v === "function" || typeof v === "symbol") {
4711
- throw new Error(
4712
- `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.`
4713
- );
4714
- }
4715
- return `${JSON.stringify(k)}:${canonicalJson(v)}`;
4716
- }).join(",") + "}";
4717
- }
4718
- throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
4719
- }
4720
- var FIELDS_WITHOUT_NULL_ENCODING = {
4721
- slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
4722
- };
4723
- function buildAuthRequest(body, sender, fields) {
4724
- const out = {};
4725
- for (const k of fields) {
4726
- if (k === "sender") {
4727
- out[k] = sender;
4728
- continue;
4729
- }
4730
- const value = body[k];
4731
- if (value === void 0 || value === null) {
4732
- const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
4733
- if (relayDefault) {
4734
- throw new Error(
4735
- `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.`
4736
- );
4737
- }
4738
- out[k] = null;
4739
- continue;
4740
- }
4741
- out[k] = value;
4742
- }
4743
- return out;
4744
- }
4745
- function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
4746
- const digest = sha256Hex(canonicalJson(request));
4747
- return new TextEncoder().encode(
4748
- `${REQUEST_AUTH_DOMAIN}
4749
- ${endpoint}
4750
- ${programId.toBase58()}
4751
- ${nonce}
4752
- ${issuedAt}
4753
- ${digest}`
4754
- );
4755
- }
4756
- function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
4757
- const senderB58 = sender.toBase58();
4758
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
4759
- const nonce = randomNonceUuid();
4760
- const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
4761
- const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
4762
- return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
4763
- }
4764
- function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
4765
- const preimage = buildRelayAuthPreimage(
4766
- endpoint,
4767
- programId,
4768
- body,
4769
- signer.publicKey,
4770
- nowSeconds,
4771
- fields
4772
- );
4773
- const signature = nacl5.sign.detached(preimage.message, signer.secretKey);
4774
- return {
4775
- sender: preimage.sender,
4776
- auth_issued_at: preimage.auth_issued_at,
4777
- auth_nonce: preimage.auth_nonce,
4778
- auth_signature: Buffer.from(signature).toString("base64")
4779
- };
4780
- }
4781
- function assertApprovalWithinFreshnessWindow(elapsedMs) {
4782
- const elapsedSeconds = elapsedMs / 1e3;
4783
- const budget = REQUEST_AUTH_MAX_AGE_SECONDS - RELAY_AUTH_APPROVAL_MARGIN_SECONDS;
4784
- if (elapsedSeconds <= budget) return;
4785
- throw new Error(
4786
- `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.`
4787
- );
4788
- }
4789
- function explainRelayAuthRejection(responseText) {
4790
- const text = String(responseText);
4791
- const has = (needle) => text.includes(needle);
4792
- if (has("issued too far in the future")) {
4793
- 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.`;
4794
- }
4795
- if (has("signature expired")) {
4796
- 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.`;
4797
- }
4798
- if (has("does not match the exact request")) {
4799
- 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\`.`;
4800
- }
4801
- if (has("has no registered viewing key")) {
4802
- 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.`;
4803
- }
4804
- if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
4805
- return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
4806
- }
4807
- if (has("auth_nonce must be a canonical UUID")) {
4808
- return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
4809
- }
4810
- if (has("Relay request signature must be exactly 64 bytes") || has("Invalid relay request signature encoding")) {
4811
- 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.`;
4812
- }
4813
- return null;
4814
- }
4815
- async function buildRelayAuthFields(endpoint, programId, body, signers, fields = TRANSACT_AUTH_FIELDS) {
4816
- if (signers.depositorKeypair) {
4817
- return signRelayRequest(endpoint, programId, body, signers.depositorKeypair, void 0, fields);
4818
- }
4819
- const wallet = signers.relayAuthSigner;
4820
- if (!wallet) return null;
4821
- const preimage = buildRelayAuthPreimage(
4822
- endpoint,
4823
- programId,
4824
- body,
4825
- wallet.walletPublicKey,
4826
- void 0,
4827
- fields
4828
- );
4829
- const approvalStartedMs = Date.now();
4830
- const signature = await wallet.signMessage(preimage.message);
4831
- assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
4832
- if (!(signature instanceof Uint8Array) || signature.length !== 64) {
4833
- throw new Error(
4834
- `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.`
4835
- );
4836
- }
4837
- return {
4838
- sender: preimage.sender,
4839
- auth_issued_at: preimage.auth_issued_at,
4840
- auth_nonce: preimage.auth_nonce,
4841
- auth_signature: Buffer.from(signature).toString("base64")
4842
- };
4843
- }
4844
-
4845
4928
  // src/proving/artifacts.ts
4846
4929
  import { sha256 as sha2564 } from "@noble/hashes/sha2";
4847
4930
 
@@ -5117,6 +5200,7 @@ async function resolveTransactionCircuitFiles() {
5117
5200
  }
5118
5201
  var _transactPaddingSaltCounter = 0;
5119
5202
  var _registeredViewingKeys = /* @__PURE__ */ new Set();
5203
+ var _viewingKeyRegistrationsInFlight = /* @__PURE__ */ new Map();
5120
5204
  var _resolvedAltAccountsCache = /* @__PURE__ */ new Map();
5121
5205
  var _relayMerkleDisabledMints = /* @__PURE__ */ new Set();
5122
5206
  var _relayMerkleFallbackNotifiedMints = /* @__PURE__ */ new Set();
@@ -5241,7 +5325,7 @@ async function fetchSupplementalAltFromRelay(relayUrl, params) {
5241
5325
  throw new Error("Supplemental ALT response is missing a 'table' address");
5242
5326
  }
5243
5327
  try {
5244
- return new PublicKey8(table);
5328
+ return new PublicKey10(table);
5245
5329
  } catch {
5246
5330
  throw new Error(`Supplemental ALT response 'table' is not a valid public key: ${table}`);
5247
5331
  }
@@ -5309,7 +5393,7 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
5309
5393
  const fetched = await Promise.all(
5310
5394
  altAddresses.map(async (addr) => {
5311
5395
  try {
5312
- const pubkey = new PublicKey8(addr);
5396
+ const pubkey = new PublicKey10(addr);
5313
5397
  const result = await connection.getAddressLookupTable(pubkey);
5314
5398
  return result.value ?? null;
5315
5399
  } catch {
@@ -5399,7 +5483,7 @@ function calculateConfiguredProtocolFee(amount, config) {
5399
5483
  return total;
5400
5484
  }
5401
5485
  async function readLiveProtocolFee(connection, programId, mint, amount, requireSwapOpen = false) {
5402
- const [poolConfigPda] = PublicKey8.findProgramAddressSync(
5486
+ const [poolConfigPda] = PublicKey10.findProgramAddressSync(
5403
5487
  [Buffer.from("pool_config"), mint.toBuffer()],
5404
5488
  programId
5405
5489
  );
@@ -5521,6 +5605,26 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5521
5605
  if (_registeredViewingKeys.has(cacheKey)) {
5522
5606
  return;
5523
5607
  }
5608
+ const inFlight = _viewingKeyRegistrationsInFlight.get(cacheKey);
5609
+ if (inFlight) {
5610
+ return inFlight;
5611
+ }
5612
+ const registration = registerViewingKeyOnce(
5613
+ relayUrl,
5614
+ userPubkey,
5615
+ viewingKeyHex,
5616
+ cacheKey,
5617
+ options,
5618
+ onProgress
5619
+ );
5620
+ _viewingKeyRegistrationsInFlight.set(cacheKey, registration);
5621
+ try {
5622
+ await registration;
5623
+ } finally {
5624
+ _viewingKeyRegistrationsInFlight.delete(cacheKey);
5625
+ }
5626
+ }
5627
+ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cacheKey, options, onProgress) {
5524
5628
  const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
5525
5629
  method: "POST",
5526
5630
  headers: { "Content-Type": "application/json" },
@@ -5541,17 +5645,27 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5541
5645
  viewingKeyHex
5542
5646
  );
5543
5647
  let signatureBase64;
5648
+ let authMode = "message";
5649
+ const messageBytes = new TextEncoder().encode(challenge.message);
5544
5650
  if (options.signMessage) {
5545
- const messageBytes = new TextEncoder().encode(challenge.message);
5546
5651
  const sig = await options.signMessage(messageBytes);
5547
5652
  signatureBase64 = Buffer.from(sig).toString("base64");
5548
5653
  } else if (options.depositorKeypair) {
5549
- const messageBytes = new TextEncoder().encode(challenge.message);
5550
5654
  const sig = nacl6.sign.detached(messageBytes, options.depositorKeypair.secretKey);
5551
5655
  signatureBase64 = Buffer.from(sig).toString("base64");
5656
+ } else if (options.signAuthTransaction) {
5657
+ onProgress?.(
5658
+ "Approve the viewing-key registration in your wallet. It shows as a 0 SOL transfer to yourself and is never sent to the network."
5659
+ );
5660
+ const signed = await signRelayAuthPayload(
5661
+ { walletPublicKey: userPubkey, signAuthTransaction: options.signAuthTransaction },
5662
+ messageBytes
5663
+ );
5664
+ signatureBase64 = Buffer.from(signed.signature).toString("base64");
5665
+ authMode = signed.mode;
5552
5666
  } else {
5553
5667
  throw new Error(
5554
- "Viewing key registration is mandatory: signMessage (wallet) or depositorKeypair is required."
5668
+ "Viewing key registration is mandatory: signMessage or signAuthTransaction (wallet) or depositorKeypair is required."
5555
5669
  );
5556
5670
  }
5557
5671
  onProgress?.("Registering viewing key...");
@@ -5562,7 +5676,8 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5562
5676
  user_pubkey: userPubkey.toBase58(),
5563
5677
  viewing_key: viewingKeyHex,
5564
5678
  nonce: challenge.nonce,
5565
- signature: signatureBase64
5679
+ signature: signatureBase64,
5680
+ ...authMode === "transaction" ? { auth_mode: authMode } : {}
5566
5681
  })
5567
5682
  });
5568
5683
  if (!response.ok) {
@@ -5656,7 +5771,7 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
5656
5771
  var TRANSACT_DISCRIMINATOR = 0;
5657
5772
  var RANGE_QUOTE_TAG_DEPOSIT = 1;
5658
5773
  function deriveRiskNoncePDA(programId, nonce) {
5659
- return PublicKey8.findProgramAddressSync(
5774
+ return PublicKey10.findProgramAddressSync(
5660
5775
  [Buffer.from("risk_nonce"), Buffer.from(nonce)],
5661
5776
  programId
5662
5777
  );
@@ -5675,7 +5790,7 @@ function extractDepositNonceFromEd25519Ix(ix) {
5675
5790
  }
5676
5791
  }
5677
5792
  function deriveNullifierPDA(programId, poolPDA, nullifier) {
5678
- return PublicKey8.findProgramAddressSync(
5793
+ return PublicKey10.findProgramAddressSync(
5679
5794
  [Buffer.from("nullifier"), poolPDA.toBuffer(), Buffer.from(nullifier)],
5680
5795
  programId
5681
5796
  );
@@ -5708,7 +5823,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
5708
5823
  }
5709
5824
  if (!isDepositData) {
5710
5825
  data[offset++] = 3;
5711
- data.set((relayer ?? PublicKey8.default).toBytes(), offset);
5826
+ data.set((relayer ?? PublicKey10.default).toBytes(), offset);
5712
5827
  offset += 32;
5713
5828
  writeBigUInt64LE(data, relayerFee ?? BigInt(0), offset);
5714
5829
  offset += 8;
@@ -5738,7 +5853,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
5738
5853
  // 4. nullifier PDA 0 (writable)
5739
5854
  { pubkey: nullifierPDA1, isSigner: false, isWritable: true },
5740
5855
  // 5. nullifier PDA 1 (writable)
5741
- { pubkey: SystemProgram2.programId, isSigner: false, isWritable: false }
5856
+ { pubkey: SystemProgram3.programId, isSigner: false, isWritable: false }
5742
5857
  // 6. system_program
5743
5858
  ];
5744
5859
  if (splAccounts) {
@@ -5783,7 +5898,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
5783
5898
  var PACKET_LIMIT_BYTES = 1232;
5784
5899
  function getCommonALTAddresses() {
5785
5900
  return [
5786
- SystemProgram2.programId,
5901
+ SystemProgram3.programId,
5787
5902
  SYSVAR_SLOT_HASHES_PUBKEY,
5788
5903
  SYSVAR_INSTRUCTIONS_PUBKEY,
5789
5904
  ComputeBudgetProgram.programId
@@ -5861,7 +5976,7 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
5861
5976
  allowSupplementalAlt
5862
5977
  );
5863
5978
  } else {
5864
- const tx = new Transaction2().add(createIx).add(extendIx);
5979
+ const tx = new Transaction3().add(createIx).add(extendIx);
5865
5980
  const { blockhash } = await connection.getLatestBlockhash();
5866
5981
  tx.recentBlockhash = blockhash;
5867
5982
  tx.feePayer = depositor.publicKey;
@@ -6522,7 +6637,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
6522
6637
  let legacyTransportAttempt = 0;
6523
6638
  while (true) {
6524
6639
  try {
6525
- const tx = new Transaction2();
6640
+ const tx = new Transaction3();
6526
6641
  for (const ix of instructions) {
6527
6642
  tx.add(ix);
6528
6643
  }
@@ -6746,7 +6861,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
6746
6861
  const messageArr = hexToBytes2(messageHex);
6747
6862
  let signerPubkey;
6748
6863
  try {
6749
- signerPubkey = new PublicKey8(signerB58);
6864
+ signerPubkey = new PublicKey10(signerB58);
6750
6865
  } catch {
6751
6866
  throw new Error("Invalid risk quote response: signer_pubkey is not a public key");
6752
6867
  }
@@ -6847,18 +6962,22 @@ function planRelayAuth(options) {
6847
6962
  const walletPublicKey = resolveUserWallet(options);
6848
6963
  if (options.depositorKeypair) return { kind: "keypair" };
6849
6964
  const signMessage = options.signMessage;
6965
+ const signAuthTransaction = options.signAuthTransaction;
6850
6966
  if (walletPublicKey && signMessage) return { kind: "wallet", signer: { walletPublicKey, signMessage } };
6851
- if (!walletPublicKey && !signMessage) return { kind: "none" };
6967
+ if (walletPublicKey && signAuthTransaction) {
6968
+ return { kind: "wallet", signer: { walletPublicKey, signAuthTransaction } };
6969
+ }
6970
+ if (!walletPublicKey && !signMessage && !signAuthTransaction) return { kind: "none" };
6852
6971
  return {
6853
6972
  kind: "incomplete",
6854
- 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."
6973
+ 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."
6855
6974
  };
6856
6975
  }
6857
6976
  function assertRelayAuthAvailable(plan, flow) {
6858
6977
  if (plan.kind === "keypair" || plan.kind === "wallet") return;
6859
6978
  const cause = plan.kind === "none" ? "no signer was provided." : `the signer provided cannot produce one: ${plan.detail}`;
6860
6979
  throw new Error(
6861
- `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.`
6980
+ `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.`
6862
6981
  );
6863
6982
  }
6864
6983
  async function submitTransactToRelay(args) {
@@ -6876,12 +6995,12 @@ async function submitTransactToRelay(args) {
6876
6995
  const doFetch = args.fetchImpl ?? fetch;
6877
6996
  const maxNetworkRetries = args.maxNetworkRetries ?? relayNetworkRetries();
6878
6997
  const requestTimeoutMs = args.requestTimeoutMs ?? relayRequestTimeoutMs();
6879
- if (!depositorKeypair && args.relayAuthSigner) {
6998
+ if (!depositorKeypair && args.relayAuthSigner && !args.relayAuthBatch) {
6880
6999
  onProgress?.(
6881
7000
  "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."
6882
7001
  );
6883
7002
  }
6884
- const authFields = await buildRelayAuthFields("/transact", programId, requestBody, {
7003
+ const authFields = args.relayAuthBatch ? await args.relayAuthBatch.authorize("/transact", programId, requestBody, TRANSACT_AUTH_FIELDS) : await buildRelayAuthFields("/transact", programId, requestBody, {
6885
7004
  depositorKeypair,
6886
7005
  relayAuthSigner: args.relayAuthSigner
6887
7006
  });
@@ -7077,7 +7196,7 @@ async function transact(params, options) {
7077
7196
  // names is refused.
7078
7197
  maxRootRetries = 40,
7079
7198
  // Increased to handle prolonged relay sync recovery under high concurrency
7080
- retryDelayMs = 500,
7199
+ retryDelayMs: retryDelayMs2 = 500,
7081
7200
  // Start with short delay, will exponentially back off
7082
7201
  riskOracleQueue,
7083
7202
  riskQuoteUrl: riskQuoteUrlOption,
@@ -7334,6 +7453,29 @@ async function transact(params, options) {
7334
7453
  "Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
7335
7454
  );
7336
7455
  }
7456
+ if (needsTreeForProof && treeState) {
7457
+ const tip = treeState.nextIndex;
7458
+ const unprovable = paddedInputs.filter((utxo) => {
7459
+ if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
7460
+ if (merkleTree && utxo.index < merkleTree.length) return false;
7461
+ if (utxo.index >= tip) return false;
7462
+ const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
7463
+ return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
7464
+ });
7465
+ if (unprovable.length > 0) {
7466
+ onProgress?.(
7467
+ `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...`
7468
+ );
7469
+ forceChainIndexing = true;
7470
+ try {
7471
+ merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, mint);
7472
+ } catch (e) {
7473
+ onProgress?.(
7474
+ `Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
7475
+ );
7476
+ }
7477
+ }
7478
+ }
7337
7479
  const merkleProofs = [];
7338
7480
  let resolvedRootHex = treeState?.root ?? "0";
7339
7481
  let proofRootHex = null;
@@ -7499,7 +7641,7 @@ async function transact(params, options) {
7499
7641
  while (submissionAttempts <= maxRootRetries) {
7500
7642
  const isRetry = submissionAttempts > 0;
7501
7643
  if (isRetry) {
7502
- const exponentialDelay = Math.min(retryDelayMs * Math.pow(1.5, submissionAttempts - 1), 5e3);
7644
+ const exponentialDelay = Math.min(retryDelayMs2 * Math.pow(1.5, submissionAttempts - 1), 5e3);
7503
7645
  const jitter = Math.random() * 500;
7504
7646
  const totalDelay = Math.floor(exponentialDelay + jitter);
7505
7647
  await sleep2(totalDelay);
@@ -7638,11 +7780,14 @@ async function transact(params, options) {
7638
7780
  }
7639
7781
  let proof;
7640
7782
  let publicSignals;
7783
+ const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
7641
7784
  try {
7642
7785
  const result = await generateTransactionProof(circuitInputs, onProofProgress);
7643
7786
  proof = result.proof;
7644
7787
  publicSignals = result.publicSignals;
7788
+ releaseProofSlot?.();
7645
7789
  } catch (proofError) {
7790
+ releaseProofSlot?.();
7646
7791
  const errorMsg = proofError?.message || String(proofError);
7647
7792
  if ((errorMsg.includes("ForceEqual") || errorMsg.includes("Assert Failed")) && submissionAttempts < maxRootRetries) {
7648
7793
  onProgress?.(`Merkle proof error (stale sibling data), will regenerate with fresh tree...`);
@@ -7662,7 +7807,7 @@ async function transact(params, options) {
7662
7807
  }
7663
7808
  treeState = null;
7664
7809
  useSiblingInfo = false;
7665
- const waitMs = Math.min(retryDelayMs * Math.pow(2, Math.min(submissionAttempts, 4)), 5e3);
7810
+ const waitMs = Math.min(retryDelayMs2 * Math.pow(2, Math.min(submissionAttempts, 4)), 5e3);
7666
7811
  if (waitMs > 0) {
7667
7812
  onProgress?.(`Waiting ${waitMs}ms for relay sync before retry...`);
7668
7813
  await new Promise((r) => setTimeout(r, waitMs));
@@ -7955,6 +8100,7 @@ async function transact(params, options) {
7955
8100
  // point where they reach the relay submission instead of stopping at viewing-key
7956
8101
  // registration. The keypair still wins when both are present.
7957
8102
  relayAuthSigner: relayAuthPlan.kind === "wallet" ? relayAuthPlan.signer : void 0,
8103
+ relayAuthBatch: options.relayAuthBatch,
7958
8104
  settlement: {
7959
8105
  connection,
7960
8106
  programId,
@@ -8000,7 +8146,7 @@ async function transact(params, options) {
8000
8146
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
8001
8147
  );
8002
8148
  try {
8003
- const [merkleTreePda] = PublicKey8.findProgramAddressSync(
8149
+ const [merkleTreePda] = PublicKey10.findProgramAddressSync(
8004
8150
  [Buffer.from("merkle_tree"), mint.toBuffer()],
8005
8151
  programId
8006
8152
  );
@@ -8356,7 +8502,7 @@ async function swapUtxo(params, options) {
8356
8502
  riskQuoteUrl: riskQuoteUrlOption,
8357
8503
  maxRootRetries = 40,
8358
8504
  // Increased to handle prolonged relay sync recovery under high concurrency
8359
- retryDelayMs = 500,
8505
+ retryDelayMs: retryDelayMs2 = 500,
8360
8506
  // Start with short delay, will exponentially back off
8361
8507
  useUniqueNullifiers,
8362
8508
  useChainRootForProof = true
@@ -8614,6 +8760,29 @@ async function swapUtxo(params, options) {
8614
8760
  "Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
8615
8761
  );
8616
8762
  }
8763
+ if (needsTreeForProof && merkleState) {
8764
+ const tip = merkleState.nextIndex;
8765
+ const unprovable = paddedInputs.filter((utxo) => {
8766
+ if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
8767
+ if (merkleTree && utxo.index < merkleTree.length) return false;
8768
+ if (utxo.index >= tip) return false;
8769
+ const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
8770
+ return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
8771
+ });
8772
+ if (unprovable.length > 0) {
8773
+ onProgress?.(
8774
+ `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...`
8775
+ );
8776
+ forceChainIndexing = true;
8777
+ try {
8778
+ merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, NATIVE_SOL_MINT);
8779
+ } catch (e) {
8780
+ onProgress?.(
8781
+ `Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
8782
+ );
8783
+ }
8784
+ }
8785
+ }
8617
8786
  const merkleProofs = [];
8618
8787
  let resolvedRootHex = merkleState?.root ?? "0";
8619
8788
  let proofRootHex = null;
@@ -8767,7 +8936,7 @@ async function swapUtxo(params, options) {
8767
8936
  let walletApprovals = 0;
8768
8937
  for (let attempt = 0; attempt <= maxRootRetries; attempt++) {
8769
8938
  if (attempt > 0) {
8770
- const exponentialDelay = Math.min(retryDelayMs * Math.pow(1.5, attempt - 1), 5e3);
8939
+ const exponentialDelay = Math.min(retryDelayMs2 * Math.pow(1.5, attempt - 1), 5e3);
8771
8940
  const jitter = Math.random() * 500;
8772
8941
  const totalDelay = Math.floor(exponentialDelay + jitter);
8773
8942
  await sleep2(totalDelay);
@@ -8905,7 +9074,7 @@ async function swapUtxo(params, options) {
8905
9074
  }
8906
9075
  merkleState = null;
8907
9076
  useSiblingInfo = false;
8908
- const waitMs = Math.min(retryDelayMs * Math.pow(2, Math.min(attempt, 4)), 5e3);
9077
+ const waitMs = Math.min(retryDelayMs2 * Math.pow(2, Math.min(attempt, 4)), 5e3);
8909
9078
  if (waitMs > 0) {
8910
9079
  onProgress?.(`Waiting ${waitMs}ms for relay sync before retry...`);
8911
9080
  await new Promise((r) => setTimeout(r, waitMs));
@@ -8988,7 +9157,7 @@ async function swapUtxo(params, options) {
8988
9157
  }
8989
9158
  if (options.onSwapStatePredicted && inputNullifiers.length > 0) {
8990
9159
  const nBytes = bigintToBytes322(inputNullifiers[0]);
8991
- const [ssp] = PublicKey8.findProgramAddressSync(
9160
+ const [ssp] = PublicKey10.findProgramAddressSync(
8992
9161
  [Buffer.from("swap_state"), pdas.pool.toBuffer(), Buffer.from(nBytes)],
8993
9162
  programId
8994
9163
  );
@@ -9407,32 +9576,298 @@ function cleanupStalePendingOperations(maxAgeMs = 24 * 60 * 60 * 1e3) {
9407
9576
  return { removedDeposits, removedWithdrawals };
9408
9577
  }
9409
9578
 
9410
- // src/scanning/scan.ts
9411
- import _bs583 from "bs58";
9412
- import {
9413
- PublicKey as PublicKey9
9414
- } from "@solana/web3.js";
9415
- import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync2 } from "@solana/spl-token";
9416
- var bs583 = _bs583.default || _bs583;
9417
- var TRANSACT_TAG2 = 0;
9418
- var TRANSACT_SWAP_TAG3 = 1;
9419
- var PROOF_LEN3 = 256;
9420
- var PUBLIC_INPUTS_LEN3 = 264;
9421
- var SWAP_PARAMS_LEN = 72;
9422
- var CHAIN_NOTES_OFFSET_TRANSACT = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3;
9423
- var CHAIN_NOTES_OFFSET_TRANSACT_SWAP = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3 + SWAP_PARAMS_LEN;
9424
- var PUBLIC_INPUTS_OFFSET = 1 + PROOF_LEN3;
9425
- var SWAP_OUTPUT_MINT_OFFSET = CHAIN_NOTES_OFFSET_TRANSACT;
9426
- var TOKEN_PROGRAM_ID2 = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
9427
- var SOL_MINT = "So11111111111111111111111111111111111111112";
9428
- var USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
9429
- var USDT_MINT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
9430
- var PUBLIC_AMOUNT_OFFSET = 32;
9431
- var EXT_DATA_HASH_OFFSET = 40;
9432
- var OUTPUT_COMMITMENT_0_OFFSET = 168;
9433
- var OUTPUT_COMMITMENT_1_OFFSET = 200;
9434
- var CHAIN_NOTE_HASH_OFFSET = 232;
9435
- var RPC_RETRY_MAX_ATTEMPTS = 6;
9579
+ // src/relay/batch-auth.ts
9580
+ import { Keypair as Keypair4 } from "@solana/web3.js";
9581
+ var RelayBatchAuthCoordinator = class {
9582
+ constructor(options) {
9583
+ this.proofSlotsInUse = 0;
9584
+ this.proofQueue = [];
9585
+ this.items = [];
9586
+ this.signing = false;
9587
+ this.slotsInUse = 0;
9588
+ this.ready = [];
9589
+ this.waves = 0;
9590
+ if (!Number.isInteger(options.items) || options.items < 1) {
9591
+ throw new Error(`A batch needs at least one item (got ${options.items}).`);
9592
+ }
9593
+ if (options.items > RELAY_BATCH_AUTH_MAX_ITEMS) {
9594
+ throw new Error(
9595
+ `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.`
9596
+ );
9597
+ }
9598
+ const concurrency = options.submitConcurrency ?? 3;
9599
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
9600
+ throw new Error(`submitConcurrency must be a positive integer (got ${concurrency}).`);
9601
+ }
9602
+ this.signer = options.signer;
9603
+ this.sender = options.signer instanceof Keypair4 ? options.signer.publicKey : options.signer.walletPublicKey;
9604
+ this.expectedItems = options.items;
9605
+ this.submitConcurrency = concurrency;
9606
+ const proofConcurrency = options.proofConcurrency ?? 2;
9607
+ if (!Number.isInteger(proofConcurrency) || proofConcurrency < 1) {
9608
+ throw new Error(`proofConcurrency must be a positive integer (got ${proofConcurrency}).`);
9609
+ }
9610
+ this.proofConcurrency = proofConcurrency;
9611
+ this.onProgress = options.onProgress;
9612
+ }
9613
+ /** The wallet that signs and is every item's authenticated `sender`. */
9614
+ get walletPublicKey() {
9615
+ return this.sender;
9616
+ }
9617
+ /** How many times the signer has been asked so far: one per wave. */
9618
+ get approvals() {
9619
+ return this.waves;
9620
+ }
9621
+ /** Where every item is right now. For progress UIs and for diagnosing a batch that never signs. */
9622
+ snapshot() {
9623
+ const count = (state) => this.items.filter((i) => i.state === state).length;
9624
+ return {
9625
+ building: count("building"),
9626
+ waiting: count("waiting"),
9627
+ submitting: count("submitting"),
9628
+ done: count("done"),
9629
+ proving: this.proofSlotsInUse,
9630
+ proofQueue: this.proofQueue.length,
9631
+ registered: this.items.length,
9632
+ expected: this.expectedItems
9633
+ };
9634
+ }
9635
+ /** Register one item. Throws past `items`: the wave condition would never be reachable. */
9636
+ item() {
9637
+ if (this.items.length >= this.expectedItems) {
9638
+ throw new Error(
9639
+ `This batch was created for ${this.expectedItems} item(s) and all of them are registered.`
9640
+ );
9641
+ }
9642
+ const item = { state: "building", waiting: null, holdsSlot: false };
9643
+ this.items.push(item);
9644
+ return {
9645
+ proofSlot: () => this.acquireProofSlot(),
9646
+ authorize: (endpoint, programId, body, fields) => this.authorize(item, endpoint, programId, body, fields),
9647
+ finish: () => this.finish(item)
9648
+ };
9649
+ }
9650
+ acquireProofSlot() {
9651
+ return new Promise((resolve) => {
9652
+ const grant = () => {
9653
+ this.proofSlotsInUse += 1;
9654
+ let released = false;
9655
+ resolve(() => {
9656
+ if (released) return;
9657
+ released = true;
9658
+ this.proofSlotsInUse -= 1;
9659
+ const next = this.proofQueue.shift();
9660
+ if (next) next();
9661
+ });
9662
+ };
9663
+ if (this.proofSlotsInUse < this.proofConcurrency) grant();
9664
+ else this.proofQueue.push(grant);
9665
+ });
9666
+ }
9667
+ authorize(item, endpoint, programId, body, fields) {
9668
+ if (item.state === "done") {
9669
+ return Promise.reject(new Error("This batch item already finished; it cannot authorize."));
9670
+ }
9671
+ if (item.state === "waiting") {
9672
+ return Promise.reject(new Error("This batch item is already waiting for a signature."));
9673
+ }
9674
+ this.releaseSlot(item);
9675
+ return new Promise((resolve, reject) => {
9676
+ item.state = "waiting";
9677
+ item.waiting = { endpoint, programId, body, fields, resolve, reject };
9678
+ this.maybeSign();
9679
+ });
9680
+ }
9681
+ finish(item) {
9682
+ if (item.state === "done") return;
9683
+ if (item.state === "waiting" && item.waiting) {
9684
+ item.waiting.reject(new Error("Batch item finished before it was signed."));
9685
+ item.waiting = null;
9686
+ }
9687
+ this.releaseSlot(item);
9688
+ item.state = "done";
9689
+ this.maybeSign();
9690
+ this.pump();
9691
+ }
9692
+ releaseSlot(item) {
9693
+ if (!item.holdsSlot) return;
9694
+ item.holdsSlot = false;
9695
+ this.slotsInUse -= 1;
9696
+ }
9697
+ /** Sign when every registered item is either waiting here or finished, and nothing is building. */
9698
+ maybeSign() {
9699
+ if (this.signing) return;
9700
+ if (this.items.length < this.expectedItems) return;
9701
+ if (this.items.some((item) => item.state === "building" || item.state === "submitting")) return;
9702
+ const wave = this.items.filter((item) => item.state === "waiting");
9703
+ if (wave.length === 0) return;
9704
+ this.signing = true;
9705
+ void this.signWave(wave).finally(() => {
9706
+ this.signing = false;
9707
+ this.maybeSign();
9708
+ });
9709
+ }
9710
+ async signWave(wave) {
9711
+ const waiting = wave.map((item) => item.waiting);
9712
+ try {
9713
+ const programId = waiting[0].programId;
9714
+ for (const w of waiting) {
9715
+ if (!w.programId.equals(programId)) {
9716
+ throw new Error("Every item of a batch must target the same program id.");
9717
+ }
9718
+ }
9719
+ const nowSeconds = Math.floor(Date.now() / 1e3);
9720
+ const preimages = waiting.map(
9721
+ (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
9722
+ );
9723
+ const digests = preimages.map(relayRequestDigestHex);
9724
+ const issuedAt = preimages[0].auth_issued_at;
9725
+ const message = buildRelayBatchAuthMessage(programId, issuedAt, digests);
9726
+ this.waves += 1;
9727
+ if (!(this.signer instanceof Keypair4)) {
9728
+ const asTransaction = !this.signer.signMessage;
9729
+ this.onProgress?.(
9730
+ `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.`)
9731
+ );
9732
+ }
9733
+ const approvalStartedMs = Date.now();
9734
+ const { signature, mode } = await signRelayAuthPayload(this.signer, message);
9735
+ if (!(this.signer instanceof Keypair4)) {
9736
+ assertApprovalWithinFreshnessWindow(
9737
+ Date.now() - approvalStartedMs,
9738
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS
9739
+ );
9740
+ }
9741
+ const signatureB64 = Buffer.from(signature).toString("base64");
9742
+ wave.forEach((item, i) => {
9743
+ const preimage = preimages[i];
9744
+ this.ready.push({
9745
+ item,
9746
+ fields: {
9747
+ sender: preimage.sender,
9748
+ auth_issued_at: preimage.auth_issued_at,
9749
+ auth_nonce: preimage.auth_nonce,
9750
+ auth_signature: signatureB64,
9751
+ ...mode === "transaction" ? { auth_mode: mode } : {},
9752
+ // A fresh array per item: `Object.assign` puts this on the wire body, and the body is
9753
+ // serialized again on every network retry.
9754
+ auth_batch: { digests: [...digests] }
9755
+ }
9756
+ });
9757
+ });
9758
+ this.pump();
9759
+ } catch (error) {
9760
+ for (const item of wave) {
9761
+ const w = item.waiting;
9762
+ item.waiting = null;
9763
+ item.state = "done";
9764
+ w?.reject(error);
9765
+ }
9766
+ }
9767
+ }
9768
+ /** Release signed items to submit, `submitConcurrency` at a time, in signing order. */
9769
+ pump() {
9770
+ while (this.ready.length > 0 && this.slotsInUse < this.submitConcurrency) {
9771
+ const next = this.ready.shift();
9772
+ const w = next.item.waiting;
9773
+ next.item.waiting = null;
9774
+ if (next.item.state !== "waiting" || !w) continue;
9775
+ next.item.state = "submitting";
9776
+ next.item.holdsSlot = true;
9777
+ this.slotsInUse += 1;
9778
+ w.resolve(next.fields);
9779
+ }
9780
+ }
9781
+ };
9782
+ function createRelayBatchAuthCoordinator(options) {
9783
+ return new RelayBatchAuthCoordinator(options);
9784
+ }
9785
+
9786
+ // src/flows/transact-batch.ts
9787
+ async function transactBatch(items, options) {
9788
+ if (items.length === 0) {
9789
+ return { results: [], approvals: 0 };
9790
+ }
9791
+ if (items.length > RELAY_BATCH_AUTH_MAX_ITEMS) {
9792
+ throw new Error(
9793
+ `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.`
9794
+ );
9795
+ }
9796
+ if (!options.relayUrl) {
9797
+ throw new Error("transactBatch requires relayUrl: batch approval is a relay authentication scheme.");
9798
+ }
9799
+ const { proofConcurrency, submitConcurrency, ...shared } = options;
9800
+ const signer = shared.depositorKeypair ? shared.depositorKeypair : (() => {
9801
+ const wallet = shared.walletPublicKey ?? shared.depositorPublicKey;
9802
+ if (!wallet) return null;
9803
+ if (shared.signMessage) return { walletPublicKey: wallet, signMessage: shared.signMessage };
9804
+ if (shared.signAuthTransaction) {
9805
+ return { walletPublicKey: wallet, signAuthTransaction: shared.signAuthTransaction };
9806
+ }
9807
+ return null;
9808
+ })();
9809
+ if (!signer) {
9810
+ throw new Error(
9811
+ "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."
9812
+ );
9813
+ }
9814
+ const coordinator = createRelayBatchAuthCoordinator({
9815
+ signer,
9816
+ items: items.length,
9817
+ proofConcurrency,
9818
+ submitConcurrency,
9819
+ onProgress: shared.onProgress
9820
+ });
9821
+ const handles = items.map(() => coordinator.item());
9822
+ const results = new Array(items.length);
9823
+ const runOne = async (index) => {
9824
+ const item = items[index];
9825
+ const handle = handles[index];
9826
+ const label = `[batch ${index + 1}/${items.length}]`;
9827
+ try {
9828
+ const value = await transact(item.params, {
9829
+ ...shared,
9830
+ ...item.options,
9831
+ relayAuthBatch: handle,
9832
+ onProgress: shared.onProgress ? (status) => shared.onProgress?.(`${label} ${status}`) : void 0
9833
+ });
9834
+ results[index] = { status: "fulfilled", value };
9835
+ } catch (reason) {
9836
+ results[index] = { status: "rejected", reason };
9837
+ } finally {
9838
+ handle.finish();
9839
+ }
9840
+ };
9841
+ await Promise.all(items.map((_, index) => runOne(index)));
9842
+ return { results, approvals: coordinator.approvals };
9843
+ }
9844
+
9845
+ // src/scanning/scan.ts
9846
+ import _bs583 from "bs58";
9847
+ import {
9848
+ PublicKey as PublicKey12
9849
+ } from "@solana/web3.js";
9850
+ import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync2 } from "@solana/spl-token";
9851
+ var bs583 = _bs583.default || _bs583;
9852
+ var TRANSACT_TAG2 = 0;
9853
+ var TRANSACT_SWAP_TAG3 = 1;
9854
+ var PROOF_LEN3 = 256;
9855
+ var PUBLIC_INPUTS_LEN3 = 264;
9856
+ var SWAP_PARAMS_LEN = 72;
9857
+ var CHAIN_NOTES_OFFSET_TRANSACT = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3;
9858
+ var CHAIN_NOTES_OFFSET_TRANSACT_SWAP = 1 + PROOF_LEN3 + PUBLIC_INPUTS_LEN3 + SWAP_PARAMS_LEN;
9859
+ var PUBLIC_INPUTS_OFFSET = 1 + PROOF_LEN3;
9860
+ var SWAP_OUTPUT_MINT_OFFSET = CHAIN_NOTES_OFFSET_TRANSACT;
9861
+ var TOKEN_PROGRAM_ID2 = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
9862
+ var SOL_MINT = "So11111111111111111111111111111111111111112";
9863
+ var USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
9864
+ var USDT_MINT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
9865
+ var PUBLIC_AMOUNT_OFFSET = 32;
9866
+ var EXT_DATA_HASH_OFFSET = 40;
9867
+ var OUTPUT_COMMITMENT_0_OFFSET = 168;
9868
+ var OUTPUT_COMMITMENT_1_OFFSET = 200;
9869
+ var CHAIN_NOTE_HASH_OFFSET = 232;
9870
+ var RPC_RETRY_MAX_ATTEMPTS = 6;
9436
9871
  var RPC_RETRY_BASE_DELAY_MS = 300;
9437
9872
  var SIGNATURE_PAGE_SIZE = 250;
9438
9873
  function isRetryableRpcError(error) {
@@ -9498,7 +9933,7 @@ function parseSwapOutputMint(data) {
9498
9933
  const mintBytes = data.slice(SWAP_OUTPUT_MINT_OFFSET, end);
9499
9934
  if (mintBytes.every((byte) => byte === 0)) return void 0;
9500
9935
  try {
9501
- return new PublicKey9(mintBytes).toBase58();
9936
+ return new PublicKey12(mintBytes).toBase58();
9502
9937
  } catch {
9503
9938
  return void 0;
9504
9939
  }
@@ -9588,7 +10023,7 @@ function parseSwapRecipientAta(data) {
9588
10023
  const recipientAtaBytes = data.slice(recipientAtaStart, recipientAtaEnd);
9589
10024
  if (recipientAtaBytes.every((byte) => byte === 0)) return void 0;
9590
10025
  try {
9591
- return new PublicKey9(recipientAtaBytes).toBase58();
10026
+ return new PublicKey12(recipientAtaBytes).toBase58();
9592
10027
  } catch {
9593
10028
  return void 0;
9594
10029
  }
@@ -9750,7 +10185,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
9750
10185
  let rpcCalls = 0;
9751
10186
  const candidates = Array.from(swapCtxByCommitment.keys());
9752
10187
  if (candidates.length === 0) return { records, rpcCalls };
9753
- const [registry] = PublicKey9.findProgramAddressSync(
10188
+ const [registry] = PublicKey12.findProgramAddressSync(
9754
10189
  [Buffer.from("cloak_chain_note_registry")],
9755
10190
  programId
9756
10191
  );
@@ -9781,7 +10216,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
9781
10216
  tx = await withRpcRetry(
9782
10217
  () => connection.getTransaction(si.signature, {
9783
10218
  commitment: "confirmed",
9784
- maxSupportedTransactionVersion: 0
10219
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
9785
10220
  })
9786
10221
  );
9787
10222
  } catch {
@@ -9882,7 +10317,7 @@ async function scanRecipientDeliveryNotes(opts) {
9882
10317
  tx = await withRpcRetry(
9883
10318
  () => connection.getTransaction(si.signature, {
9884
10319
  commitment: "confirmed",
9885
- maxSupportedTransactionVersion: 0
10320
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
9886
10321
  })
9887
10322
  );
9888
10323
  } catch {
@@ -10053,7 +10488,7 @@ async function scanTransactions(opts) {
10053
10488
  return await withRpcRetry(
10054
10489
  () => connection.getTransaction(sigInfo.signature, {
10055
10490
  commitment: "confirmed",
10056
- maxSupportedTransactionVersion: 0
10491
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10057
10492
  })
10058
10493
  );
10059
10494
  } catch {
@@ -10153,8 +10588,8 @@ async function scanTransactions(opts) {
10153
10588
  if (onChainAta) {
10154
10589
  try {
10155
10590
  const expectedAta = getAssociatedTokenAddressSync2(
10156
- new PublicKey9(asset.mint),
10157
- new PublicKey9(walletPublicKey)
10591
+ new PublicKey12(asset.mint),
10592
+ new PublicKey12(walletPublicKey)
10158
10593
  ).toBase58();
10159
10594
  if (onChainAta === expectedAta) {
10160
10595
  isOurs = true;
@@ -10368,7 +10803,7 @@ async function scanTransactions(opts) {
10368
10803
  // deposit — that is the public deposit amount. A deposit that also merged inputs
10369
10804
  // carries a larger output 0 and is not recoverable from public data alone.
10370
10805
  amount: grossAmount,
10371
- mintAddress: new PublicKey9(asset.mint),
10806
+ mintAddress: new PublicKey12(asset.mint),
10372
10807
  outputCommitments: ixCtx.outputCommitments ?? []
10373
10808
  });
10374
10809
  if (recoveredDeposit) {
@@ -10394,7 +10829,7 @@ async function scanTransactions(opts) {
10394
10829
  noteSalt: compactNote.noteSalt,
10395
10830
  amount: compactNote.outAmount0,
10396
10831
  keypair: { privateKey: 0n, publicKey: compactNote.outPubkey0 },
10397
- mintAddress: new PublicKey9(asset.mint),
10832
+ mintAddress: new PublicKey12(asset.mint),
10398
10833
  outputIndex: 0,
10399
10834
  // v4 describes output 0, which is where change lands
10400
10835
  outputCommitments: ixCtx.outputCommitments ?? []
@@ -10587,7 +11022,7 @@ function formatComplianceCsv(report) {
10587
11022
  }
10588
11023
 
10589
11024
  // src/wallet/utxo-wallet.ts
10590
- import { PublicKey as PublicKey10 } from "@solana/web3.js";
11025
+ import { PublicKey as PublicKey13 } from "@solana/web3.js";
10591
11026
  var UtxoWallet = class _UtxoWallet {
10592
11027
  constructor(viewingKey) {
10593
11028
  this.wallets = /* @__PURE__ */ new Map();
@@ -10799,7 +11234,7 @@ var UtxoWallet = class _UtxoWallet {
10799
11234
  data.viewingKey ? new Uint8Array(data.viewingKey) : void 0
10800
11235
  );
10801
11236
  for (const w of data.wallets) {
10802
- const mint = new PublicKey10(w.mint);
11237
+ const mint = new PublicKey13(w.mint);
10803
11238
  for (const u of w.utxos) {
10804
11239
  wallet.addUtxo({
10805
11240
  amount: BigInt(u.amount),
@@ -10881,12 +11316,801 @@ var SimpleWallet = class {
10881
11316
  }
10882
11317
  };
10883
11318
 
11319
+ // src/bridge/rail-verify.ts
11320
+ import nacl7 from "tweetnacl";
11321
+ import { sha256 as sha2565 } from "@noble/hashes/sha256";
11322
+ var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
11323
+ var b58 = /* @__PURE__ */ (() => {
11324
+ const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
11325
+ return {
11326
+ decode(s) {
11327
+ let n = 0n;
11328
+ for (const c of s) {
11329
+ const i = A.indexOf(c);
11330
+ if (i < 0) throw new Error("bad base58");
11331
+ n = n * 58n + BigInt(i);
11332
+ }
11333
+ const bytes = [];
11334
+ while (n > 0n) {
11335
+ bytes.unshift(Number(n & 255n));
11336
+ n >>= 8n;
11337
+ }
11338
+ for (const c of s) {
11339
+ if (c === "1") bytes.unshift(0);
11340
+ else break;
11341
+ }
11342
+ return Uint8Array.from(bytes);
11343
+ },
11344
+ encode(b) {
11345
+ let n = 0n;
11346
+ for (const x of b) n = n * 256n + BigInt(x);
11347
+ let s = "";
11348
+ while (n > 0n) {
11349
+ s = A[Number(n % 58n)] + s;
11350
+ n /= 58n;
11351
+ }
11352
+ for (const x of b) {
11353
+ if (x === 0) s = "1" + s;
11354
+ else break;
11355
+ }
11356
+ return s;
11357
+ }
11358
+ };
11359
+ })();
11360
+ function stable(v) {
11361
+ if (v === null || typeof v !== "object") return JSON.stringify(v) ?? "null";
11362
+ if (Array.isArray(v)) return `[${v.map(stable).join(",")}]`;
11363
+ const o = v;
11364
+ const parts = Object.keys(o).sort().filter((k) => o[k] !== void 0).map((k) => `${JSON.stringify(k)}:${stable(o[k])}`);
11365
+ return `{${parts.join(",")}}`;
11366
+ }
11367
+ function signedRequest(r) {
11368
+ const q = r.quoteRequest ?? {};
11369
+ return {
11370
+ dry: q.dry,
11371
+ swapType: q.swapType,
11372
+ slippageTolerance: q.slippageTolerance,
11373
+ originAsset: q.originAsset,
11374
+ depositType: q.depositType,
11375
+ destinationAsset: q.destinationAsset,
11376
+ amount: q.amount,
11377
+ refundTo: q.refundTo,
11378
+ refundType: q.refundType,
11379
+ recipient: q.recipient,
11380
+ recipientType: q.recipientType,
11381
+ deadline: q.deadline,
11382
+ quoteWaitingTimeMs: q.quoteWaitingTimeMs || void 0,
11383
+ referral: q.referral || void 0,
11384
+ virtualChainRecipient: q.virtualChainRecipient || void 0,
11385
+ virtualChainRefundRecipient: q.virtualChainRefundRecipient || void 0,
11386
+ customRecipientMsg: q.customRecipientMsg || void 0
11387
+ // Deliberately unsigned by the rail: sessionId, connectedWallets, correlationId, appFees,
11388
+ // partnerId, userAccountId, depositMode. APP FEES ARE NOT AUTHENTICATED — never display a fee
11389
+ // caption as if the signature vouched for it.
11390
+ };
11391
+ }
11392
+ function signedQuote(r) {
11393
+ const q = r.quote ?? {};
11394
+ const base = {
11395
+ amountIn: q.amountIn,
11396
+ amountInFormatted: q.amountInFormatted,
11397
+ amountInUsd: q.amountInUsd,
11398
+ minAmountIn: q.minAmountIn,
11399
+ amountOut: q.amountOut,
11400
+ amountOutFormatted: q.amountOutFormatted,
11401
+ amountOutUsd: q.amountOutUsd,
11402
+ minAmountOut: q.minAmountOut
11403
+ };
11404
+ if (r.quoteRequest?.dry) return base;
11405
+ return {
11406
+ ...base,
11407
+ depositAddress: q.depositAddress || void 0,
11408
+ // <- the field that makes substitution detectable
11409
+ depositMemo: q.depositMemo || void 0,
11410
+ deadline: q.deadline || void 0,
11411
+ // <- a real, SIGNED expiry
11412
+ timeWhenInactive: q.timeWhenInactive || void 0,
11413
+ timeEstimate: q.timeEstimate || void 0,
11414
+ virtualChainRecipient: q.virtualChainRecipient || void 0,
11415
+ virtualChainRefundRecipient: q.virtualChainRefundRecipient || void 0,
11416
+ customRecipientMsg: q.customRecipientMsg || void 0,
11417
+ refundFee: q.refundFee || void 0,
11418
+ withdrawFee: q.withdrawFee || void 0
11419
+ };
11420
+ }
11421
+ function canonicalPayloadString(resp) {
11422
+ return stable({ ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp });
11423
+ }
11424
+ function verifyQuoteSignature(resp) {
11425
+ if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
11426
+ const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
11427
+ const digest = sha2565(new TextEncoder().encode(stable(payload)));
11428
+ const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
11429
+ const sig = resp.signature.replace(/^ed25519:/, "");
11430
+ try {
11431
+ return { valid: nacl7.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
11432
+ } catch (e) {
11433
+ return { valid: false, reason: e instanceof Error ? e.message : String(e) };
11434
+ }
11435
+ }
11436
+
11437
+ // src/bridge/rails.ts
11438
+ async function parseBridgeResponse(res, what) {
11439
+ let body;
11440
+ try {
11441
+ body = await res.json();
11442
+ } catch {
11443
+ throw new Error(`${what} failed: ${res.status} ${res.statusText} (response body was not JSON)`);
11444
+ }
11445
+ if (!res.ok) {
11446
+ const b = body ?? {};
11447
+ throw new Error(
11448
+ `${what} failed: ${b.message ?? res.statusText} (${b.code ?? res.status}${b.retryable ? ", retryable" : ""})`
11449
+ );
11450
+ }
11451
+ return body;
11452
+ }
11453
+ function toAttestation(raw) {
11454
+ if (raw.kind === "ed25519") {
11455
+ return { kind: "ed25519", verified: raw.verified ?? false, signer: raw.signer ?? "" };
11456
+ }
11457
+ return { kind: "none", checks: raw.checks ?? [], note: raw.note ?? "" };
11458
+ }
11459
+ async function fetchBridgeQuote(relayUrl, req) {
11460
+ const body = {
11461
+ recipient: req.recipient,
11462
+ origin_chain: req.originChain,
11463
+ amount_base_units: req.amountBaseUnits.toString(),
11464
+ allocate: req.allocate ?? false
11465
+ };
11466
+ if (req.refundTo !== void 0) body.refund_to = req.refundTo;
11467
+ if (req.rails !== void 0) body.rails = req.rails;
11468
+ const res = await relayFetch(`${relayUrl}/bridge/quote`, {
11469
+ method: "POST",
11470
+ headers: { "Content-Type": "application/json" },
11471
+ body: JSON.stringify(body)
11472
+ });
11473
+ const raw = await parseBridgeResponse(res, "bridge quote");
11474
+ const options = [];
11475
+ const unavailable = (raw.unavailable ?? []).map((p) => ({
11476
+ rail: p.rail,
11477
+ reason: p.reason
11478
+ }));
11479
+ for (const opt of raw.options) {
11480
+ const attestation = toAttestation(opt.attestation);
11481
+ if (attestation.kind === "ed25519") {
11482
+ const verdict = opt.rail_response ? verifyQuoteSignature(opt.rail_response) : { valid: false, reason: "no rail_response to verify against" };
11483
+ if (!verdict.valid) {
11484
+ unavailable.push({
11485
+ rail: opt.rail,
11486
+ reason: `deposit address failed independent signature verification, refusing to display it (${verdict.reason ?? "signature did not verify"})`
11487
+ });
11488
+ continue;
11489
+ }
11490
+ }
11491
+ options.push({
11492
+ rail: opt.rail,
11493
+ refunds: opt.refunds,
11494
+ addressLifetime: opt.address_lifetime,
11495
+ amountOut: BigInt(opt.amount_out),
11496
+ minAmountOut: BigInt(opt.min_amount_out),
11497
+ timeEstimateSeconds: opt.time_estimate_s,
11498
+ expiresAt: opt.expires_at,
11499
+ depositAddress: opt.deposit_address,
11500
+ attestation
11501
+ });
11502
+ }
11503
+ return { options, unavailable };
11504
+ }
11505
+ var STATUS_STATES = [
11506
+ "pending",
11507
+ "delivered",
11508
+ "refunded",
11509
+ "expired",
11510
+ "unknown"
11511
+ ];
11512
+ async function fetchBridgeStatus(relayUrl, depositAddress, rail) {
11513
+ const qs = new URLSearchParams({ deposit_address: depositAddress, rail });
11514
+ const res = await relayFetch(`${relayUrl}/bridge/status?${qs.toString()}`);
11515
+ const raw = await parseBridgeResponse(res, "bridge status");
11516
+ const state = STATUS_STATES.includes(raw.state ?? "") ? raw.state : "unknown";
11517
+ return { rail: raw.rail ?? rail, state, detail: raw.detail ?? "" };
11518
+ }
11519
+ function cloakBridgeRail(relayUrl) {
11520
+ assertAllowedRelayOrigin(relayUrl);
11521
+ return {
11522
+ id: "cloak-bridge",
11523
+ quote: (req) => fetchBridgeQuote(relayUrl, req),
11524
+ status: (depositAddress, rail) => fetchBridgeStatus(relayUrl, depositAddress, rail)
11525
+ };
11526
+ }
11527
+
11528
+ // src/bridge/paymaster-client.ts
11529
+ import {
11530
+ PublicKey as PublicKey14,
11531
+ SystemInstruction,
11532
+ SystemProgram as SystemProgram4,
11533
+ Transaction as Transaction4
11534
+ } from "@solana/web3.js";
11535
+ import { TOKEN_PROGRAM_ID as TOKEN_PROGRAM_ID3, decodeTransferInstruction, getAssociatedTokenAddressSync as getAssociatedTokenAddressSync3 } from "@solana/spl-token";
11536
+ function validatePaymasterTopUpTransaction(tx, expect) {
11537
+ const ixs = tx.instructions;
11538
+ if (ixs.length !== 1 && ixs.length !== 2) {
11539
+ throw new Error(
11540
+ `paymaster top-up must be exactly 1 or 2 instructions, got ${ixs.length} \u2014 refusing to sign a transaction whose shape does not match the documented top-up contract`
11541
+ );
11542
+ }
11543
+ const ix0 = ixs[0];
11544
+ if (!ix0.programId.equals(SystemProgram4.programId)) {
11545
+ throw new Error(
11546
+ `paymaster top-up instruction 0 is owned by ${ix0.programId.toBase58()}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
11547
+ );
11548
+ }
11549
+ const transfer2 = SystemInstruction.decodeTransfer(ix0);
11550
+ if (!transfer2.toPubkey.equals(expect.recipient)) {
11551
+ throw new Error(
11552
+ `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`
11553
+ );
11554
+ }
11555
+ if (BigInt(transfer2.lamports) > expect.maxGrantLamports) {
11556
+ throw new Error(
11557
+ `paymaster top-up grants ${transfer2.lamports} lamports, more than the ${expect.maxGrantLamports} we asked for \u2014 refusing a transaction that funds beyond our own request`
11558
+ );
11559
+ }
11560
+ if (ixs.length === 1) return;
11561
+ const ix1 = ixs[1];
11562
+ if (!ix1.programId.equals(TOKEN_PROGRAM_ID3)) {
11563
+ throw new Error(
11564
+ `paymaster top-up instruction 1 is owned by ${ix1.programId.toBase58()}, not the SPL Token program \u2014 refusing to sign an unrecognised second instruction`
11565
+ );
11566
+ }
11567
+ const spl = decodeTransferInstruction(ix1, TOKEN_PROGRAM_ID3);
11568
+ const authority = spl.keys.owner.pubkey;
11569
+ if (!authority.equals(expect.recipient)) {
11570
+ throw new Error(
11571
+ `paymaster top-up's fee transfer is authorised by ${authority.toBase58()}, not our recipient ${expect.recipient.toBase58()} \u2014 refusing to sign away tokens from an account we do not control`
11572
+ );
11573
+ }
11574
+ const expectedDestination = getAssociatedTokenAddressSync3(
11575
+ expect.feeMint,
11576
+ expect.paymentAddress,
11577
+ false
11578
+ );
11579
+ const destination = spl.keys.destination.pubkey;
11580
+ if (!destination.equals(expectedDestination)) {
11581
+ throw new Error(
11582
+ `paymaster top-up's fee transfer is addressed to ${destination.toBase58()}, not the paymaster's own payment ATA ${expectedDestination.toBase58()} \u2014 refusing to sign a payment to an unverified destination`
11583
+ );
11584
+ }
11585
+ const paidAmount = BigInt(spl.data.amount);
11586
+ if (paidAmount !== expect.feeTokenAmount) {
11587
+ throw new Error(
11588
+ `paymaster top-up's fee amount is ${paidAmount}, not the ${expect.feeTokenAmount} Kora quoted at prepare time \u2014 refusing to sign a payment that does not match the quote`
11589
+ );
11590
+ }
11591
+ }
11592
+ async function parseBridgeResponse2(res, what) {
11593
+ let body;
11594
+ try {
11595
+ body = await res.json();
11596
+ } catch {
11597
+ throw new Error(`${what} failed: ${res.status} ${res.statusText} (response body was not JSON)`);
11598
+ }
11599
+ if (!res.ok) {
11600
+ const b = body ?? {};
11601
+ throw new Error(
11602
+ `${what} failed: ${b.message ?? res.statusText} (${b.code ?? res.status}${b.retryable ? ", retryable" : ""})`
11603
+ );
11604
+ }
11605
+ return body;
11606
+ }
11607
+ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
11608
+ assertAllowedRelayOrigin(relayUrl);
11609
+ if (grantLamports <= 0n || grantLamports > BigInt(Number.MAX_SAFE_INTEGER)) {
11610
+ throw new Error(
11611
+ `grantLamports must be a positive value representable as a JS number, got ${grantLamports}`
11612
+ );
11613
+ }
11614
+ const prepareRes = await relayFetch(`${relayUrl}/bridge/paymaster/prepare`, {
11615
+ method: "POST",
11616
+ headers: { "Content-Type": "application/json" },
11617
+ body: JSON.stringify({
11618
+ recipient: receiver.publicKey.toBase58(),
11619
+ grant_lamports: Number(grantLamports)
11620
+ })
11621
+ });
11622
+ const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
11623
+ if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
11624
+ throw new Error(
11625
+ "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
11626
+ );
11627
+ }
11628
+ const feeMint = new PublicKey14(prepared.fee_mint);
11629
+ const paymentAddress = new PublicKey14(prepared.payment_address);
11630
+ const feeTokenAmount = BigInt(prepared.fee_token_amount);
11631
+ const tx = Transaction4.from(Buffer.from(prepared.transaction, "base64"));
11632
+ validatePaymasterTopUpTransaction(tx, {
11633
+ recipient: receiver.publicKey,
11634
+ maxGrantLamports: grantLamports,
11635
+ feeMint,
11636
+ feeTokenAmount,
11637
+ paymentAddress
11638
+ });
11639
+ tx.partialSign(receiver);
11640
+ const cosignRes = await relayFetch(`${relayUrl}/bridge/paymaster/cosign`, {
11641
+ method: "POST",
11642
+ headers: { "Content-Type": "application/json" },
11643
+ body: JSON.stringify({
11644
+ transaction: tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString("base64"),
11645
+ voucher: prepared.voucher
11646
+ })
11647
+ });
11648
+ const cosigned = await parseBridgeResponse2(cosignRes, "paymaster cosign");
11649
+ return {
11650
+ transaction: Transaction4.from(Buffer.from(cosigned.transaction, "base64")),
11651
+ feeTokenAmount,
11652
+ feeMint: prepared.fee_mint,
11653
+ paymentAddress: prepared.payment_address
11654
+ };
11655
+ }
11656
+
11657
+ // src/bridge/derive.ts
11658
+ import { Keypair as Keypair6 } from "@solana/web3.js";
11659
+ import { hmac } from "@noble/hashes/hmac";
11660
+ import { sha512 } from "@noble/hashes/sha512";
11661
+ var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
11662
+ var MAX_RECEIVER_INDEX = 1e4;
11663
+ function deriveBridgeReceiver(nk, index) {
11664
+ if (!Number.isInteger(index) || index < 0) {
11665
+ throw new Error(`index must be a non-negative integer, got ${index}`);
11666
+ }
11667
+ if (index > MAX_RECEIVER_INDEX) {
11668
+ throw new Error(
11669
+ `index ${index} exceeds MAX_RECEIVER_INDEX (${MAX_RECEIVER_INDEX}). Indices must be a small sequential counter \u2014 discovery derives 0\u2026N and reads each on chain, so a timestamp index is unreachable by any scan and the deposit would be invisible to every device but this one.`
11670
+ );
11671
+ }
11672
+ const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
11673
+ return Keypair6.fromSeed(h.slice(0, 32));
11674
+ }
11675
+
11676
+ // src/bridge/discover.ts
11677
+ import { SolanaJSONRPCError } from "@solana/web3.js";
11678
+ import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync4 } from "@solana/spl-token";
11679
+ function describeError(err) {
11680
+ return err instanceof Error ? err.message : String(err);
11681
+ }
11682
+ async function listBridgeDeposits(conn, nk, opts) {
11683
+ const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
11684
+ const stopAfterUnused = opts.stopAfterUnused ?? 5;
11685
+ const out = [];
11686
+ let consecutiveUnused = 0;
11687
+ for (let index = 0; index < scanDepth; index++) {
11688
+ const kp = deriveBridgeReceiver(nk, index);
11689
+ const receiver = kp.publicKey;
11690
+ const tokenAccount = getAssociatedTokenAddressSync4(opts.mint, receiver, false);
11691
+ try {
11692
+ const [recvInfo, ataInfo] = await conn.getMultipleAccountsInfo([receiver, tokenAccount]);
11693
+ const lamports = recvInfo?.lamports ?? 0;
11694
+ let tokenBalance = 0n;
11695
+ if (ataInfo) {
11696
+ try {
11697
+ tokenBalance = BigInt((await conn.getTokenAccountBalance(tokenAccount)).value.amount);
11698
+ } catch (err) {
11699
+ if (!(err instanceof SolanaJSONRPCError && /could not find account/i.test(err.message))) {
11700
+ throw err;
11701
+ }
11702
+ }
11703
+ }
11704
+ if (lamports === 0 && !ataInfo) {
11705
+ consecutiveUnused++;
11706
+ if (consecutiveUnused >= stopAfterUnused) break;
11707
+ continue;
11708
+ }
11709
+ consecutiveUnused = 0;
11710
+ const shieldSignatures = [];
11711
+ const sigs = await conn.getSignaturesForAddress(receiver, { limit: 20 });
11712
+ for (const s of sigs) {
11713
+ if (s.err) continue;
11714
+ const tx = await conn.getTransaction(s.signature, {
11715
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
11716
+ });
11717
+ const keys = tx?.transaction.message.getAccountKeys({
11718
+ accountKeysFromLookups: tx.meta?.loadedAddresses
11719
+ });
11720
+ if (keys && [...Array(keys.length).keys()].some((i) => keys.get(i)?.equals(opts.programId))) {
11721
+ shieldSignatures.push(s.signature);
11722
+ }
11723
+ }
11724
+ const shieldSignature = shieldSignatures[0];
11725
+ const indexReused = shieldSignatures.length > 1;
11726
+ let state;
11727
+ if (tokenBalance > 0n) state = shieldSignature ? "needs-cleanup" : "arrived";
11728
+ else if (shieldSignature) state = ataInfo ? "needs-cleanup" : "complete";
11729
+ else state = "awaiting";
11730
+ out.push({
11731
+ index,
11732
+ receiver,
11733
+ tokenAccount,
11734
+ state,
11735
+ tokenBalance,
11736
+ lamports,
11737
+ shieldSignature,
11738
+ ...indexReused ? { indexReused, shieldSignatures } : {}
11739
+ });
11740
+ } catch (err) {
11741
+ out.push({
11742
+ index,
11743
+ receiver,
11744
+ tokenAccount,
11745
+ state: "unknown",
11746
+ tokenBalance: 0n,
11747
+ lamports: 0,
11748
+ error: describeError(err)
11749
+ });
11750
+ }
11751
+ }
11752
+ return out;
11753
+ }
11754
+
11755
+ // src/bridge/deposit-core.ts
11756
+ import {
11757
+ SystemProgram as SystemProgram5,
11758
+ Transaction as Transaction5,
11759
+ VersionedTransaction as VersionedTransaction2,
11760
+ sendAndConfirmTransaction as sendAndConfirmTransaction2
11761
+ } from "@solana/web3.js";
11762
+ import nacl8 from "tweetnacl";
11763
+
11764
+ // src/bridge/funder.ts
11765
+ import { PublicKey as PublicKey16 } from "@solana/web3.js";
11766
+ import { getAssociatedTokenAddressSync as getAssociatedTokenAddressSync5 } from "@solana/spl-token";
11767
+ var MAINNET_RENT_0 = 890880;
11768
+ var MAINNET_RENT_1 = 897840;
11769
+ var FEE_BUDGET = 13e4;
11770
+ var CLEANUP_FEE_BUDGET = 5e3;
11771
+ var pda = (seeds, programId) => PublicKey16.findProgramAddressSync(seeds.map((s) => Buffer.from(s)), programId)[0];
11772
+ function deriveFundingTargets(d) {
11773
+ const pool = pda([Buffer.from("pool"), d.mint.toBuffer()], d.programId);
11774
+ return {
11775
+ pool,
11776
+ // program: NullifierAccount::derive_pda_with_pool -> [b"nullifier", pool, nullifier]
11777
+ nullifier0: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[0]], d.programId),
11778
+ nullifier1: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[1]], d.programId),
11779
+ // relay: derive_risk_nonce_pda -> [b"risk_nonce", bind0]
11780
+ riskNonce: pda([Buffer.from("risk_nonce"), d.bind0], d.programId),
11781
+ depositorAta: getAssociatedTokenAddressSync5(d.mint, d.depositor, false)
11782
+ };
11783
+ }
11784
+ async function readRent(conn) {
11785
+ const [zero, one] = await Promise.all([
11786
+ conn.getMinimumBalanceForRentExemption(0),
11787
+ conn.getMinimumBalanceForRentExemption(1)
11788
+ ]);
11789
+ return { zero, one };
11790
+ }
11791
+
11792
+ // src/bridge/deposit-core.ts
11793
+ var DepositError = class extends Error {
11794
+ constructor(message, fundedAccounts, measuredTxSize) {
11795
+ super(message);
11796
+ this.fundedAccounts = fundedAccounts;
11797
+ this.measuredTxSize = measuredTxSize;
11798
+ this.name = "DepositError";
11799
+ }
11800
+ };
11801
+ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log, grantOverride, opts) {
11802
+ if (!opts.noteSpendKey || opts.noteSpendKey.length !== 32) {
11803
+ throw new Error(
11804
+ "opts.noteSpendKey (32 bytes) is required. It derives the note's spending key, and a note whose key is not derived from something you can reproduce is unspendable forever. Pass the same Cloak seed you derived the receiving address from."
11805
+ );
11806
+ }
11807
+ if (!opts.relayUrl) {
11808
+ throw new Error(
11809
+ "opts.relayUrl is required. There is no default: a missing relay used to resolve silently to the local stack, which is how a live run built a deposit against infrastructure that only existed on someone's laptop. Say which relay, every call."
11810
+ );
11811
+ }
11812
+ if (!opts.programId) {
11813
+ throw new Error(
11814
+ "opts.programId is required. There is no default: this is the exact field a live mainnet run once inherited from this module's local-stack constant, built a deposit against a program that does not exist on mainnet, and failed hunting a merkle tree that was never there."
11815
+ );
11816
+ }
11817
+ if (!opts.mint) {
11818
+ throw new Error(
11819
+ "opts.mint is required. There is no default: a deposit built for the wrong mint produces a note for an asset that never arrived at R, and there is nothing to silently fall back to."
11820
+ );
11821
+ }
11822
+ assertAllowedRpcConnection(conn);
11823
+ const relayUrl = opts.relayUrl;
11824
+ const programId = opts.programId;
11825
+ const mint = opts.mint;
11826
+ setCircuitsPath(resolveCircuitsBase());
11827
+ const grantR = grantOverride ?? MAINNET_RENT_0 + FEE_BUDGET + CLEANUP_FEE_BUDGET;
11828
+ const heldByR = await conn.getBalance(R.publicKey);
11829
+ if (heldByR >= grantR) {
11830
+ log(` R already holds ${heldByR} (>= ${grantR}) \u2014 no top-up needed`);
11831
+ } else {
11832
+ await sendAndConfirmTransaction2(conn, new Transaction5().add(
11833
+ SystemProgram5.transfer({ fromPubkey: funder.publicKey, toPubkey: R.publicKey, lamports: grantR - heldByR })
11834
+ ), [funder]);
11835
+ 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"}`);
11836
+ }
11837
+ let measuredSize = -1;
11838
+ let fundedAccounts = [];
11839
+ const signTransaction2 = async (tx) => {
11840
+ if (tx instanceof VersionedTransaction2) {
11841
+ measuredSize = tx.serialize().length;
11842
+ const alts = await Promise.all(
11843
+ tx.message.addressTableLookups.map(async (l) => (await conn.getAddressLookupTable(l.accountKey)).value)
11844
+ );
11845
+ const keys = tx.message.getAccountKeys({ addressLookupTableAccounts: alts });
11846
+ const ix = tx.message.compiledInstructions.find((i) => keys.get(i.programIdIndex).equals(programId));
11847
+ const at = (n) => keys.get(ix.accountKeyIndexes[n]);
11848
+ const targets = [
11849
+ { a: at(12), need: MAINNET_RENT_0, name: "risk_nonce" },
11850
+ { a: at(4), need: MAINNET_RENT_1, name: "nullifier_0" },
11851
+ { a: at(5), need: MAINNET_RENT_1, name: "nullifier_1" }
11852
+ ];
11853
+ const infos = await conn.getMultipleAccountsInfo(targets.map((t) => t.a));
11854
+ fundedAccounts = targets.map((t, i) => ({
11855
+ name: t.name,
11856
+ address: t.a.toBase58(),
11857
+ lamportsSent: Math.max(0, t.need - (infos[i]?.lamports ?? 0))
11858
+ }));
11859
+ const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [SystemProgram5.transfer({
11860
+ fromPubkey: funder.publicKey,
11861
+ toPubkey: t.a,
11862
+ lamports: t.need - (infos[i]?.lamports ?? 0)
11863
+ })]);
11864
+ if (ixs.length) {
11865
+ const sig = await sendAndConfirmTransaction2(conn, new Transaction5().add(...ixs), [funder]);
11866
+ log(` seam: funded ${ixs.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
11867
+ }
11868
+ tx.sign([R]);
11869
+ return tx;
11870
+ }
11871
+ tx.partialSign(R);
11872
+ return tx;
11873
+ };
11874
+ const signMessage = async (m) => nacl8.sign.detached(m, R.secretKey);
11875
+ const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
11876
+ const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
11877
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
11878
+ const zeroInput = await createZeroUtxo(mint);
11879
+ const rBefore = await conn.getBalance(R.publicKey);
11880
+ let result;
11881
+ try {
11882
+ result = await transact(
11883
+ { inputUtxos: [zeroInput], outputUtxos: [utxo], externalAmount: amount, depositor: R.publicKey },
11884
+ {
11885
+ connection: conn,
11886
+ programId,
11887
+ relayUrl,
11888
+ // NO depositorKeypair: the SDK branches `if (keypair) … else if (signTransaction)`
11889
+ // (transact.ts:2786, :2936), so passing one silently skips the funding seam.
11890
+ depositorPublicKey: R.publicKey,
11891
+ walletPublicKey: R.publicKey,
11892
+ signTransaction: signTransaction2,
11893
+ signMessage,
11894
+ chainNoteViewingKeyNk: nk,
11895
+ chainNoteSalt: noteSalt,
11896
+ relaySupplementalAlt: true,
11897
+ onProgress: (s) => log(` \xB7 ${s}`)
11898
+ }
11899
+ );
11900
+ } catch (e) {
11901
+ const msg = e instanceof Error ? e.message : String(e);
11902
+ throw new DepositError(msg, fundedAccounts, measuredSize);
11903
+ }
11904
+ const rAfter = await conn.getBalance(R.publicKey);
11905
+ const noteIndex = result.outputUtxos[0].index;
11906
+ if (noteIndex === void 0) throw new Error("deposit landed but the note has no index \u2014 it cannot be discovered later");
11907
+ return {
11908
+ signature: result.signature,
11909
+ noteIndex,
11910
+ amount: result.outputUtxos[0].amount,
11911
+ txSize: measuredSize,
11912
+ rBefore,
11913
+ rAfter,
11914
+ rentExempt: rAfter >= MAINNET_RENT_0,
11915
+ inputNullifiers: result.inputNullifiers,
11916
+ fundedAccounts
11917
+ };
11918
+ }
11919
+
11920
+ // src/bridge/cleanup.ts
11921
+ import {
11922
+ PublicKey as PublicKey18,
11923
+ Transaction as Transaction6,
11924
+ sendAndConfirmTransaction as sendAndConfirmTransaction3
11925
+ } from "@solana/web3.js";
11926
+ import {
11927
+ getAssociatedTokenAddressSync as getAssociatedTokenAddressSync6,
11928
+ createCloseAccountInstruction,
11929
+ createTransferInstruction,
11930
+ createAssociatedTokenAccountIdempotentInstruction,
11931
+ getMinimumBalanceForRentExemptAccount
11932
+ } from "@solana/spl-token";
11933
+ var DEFAULT_MINT = new PublicKey18("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
11934
+ async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_MINT) {
11935
+ assertAllowedRpcConnection(conn);
11936
+ const rAta = getAssociatedTokenAddressSync6(mint, R.publicKey);
11937
+ const info = await conn.getAccountInfo(rAta);
11938
+ if (!info) {
11939
+ return {
11940
+ closed: false,
11941
+ dustSwept: 0n,
11942
+ rentReturned: 0,
11943
+ destination: null,
11944
+ signature: null,
11945
+ note: "no token account \u2014 nothing to recover"
11946
+ };
11947
+ }
11948
+ const bal = BigInt((await conn.getTokenAccountBalance(rAta)).value.amount);
11949
+ const rentHeld = info.lamports;
11950
+ const before = await conn.getBalance(R.publicKey);
11951
+ const ixs = [];
11952
+ let destination = null;
11953
+ if (bal > 0n && !dustDestination) {
11954
+ return {
11955
+ closed: false,
11956
+ dustSwept: 0n,
11957
+ rentReturned: 0,
11958
+ destination: null,
11959
+ signature: null,
11960
+ note: `dusted with ${bal} base units after the deposit; leaving the account open and ${rentHeld.toLocaleString()} lamports of rent unrecovered, because sweeping it would publish a link from this deposit to whoever receives it`
11961
+ };
11962
+ }
11963
+ if (bal > 0n && dustDestination) {
11964
+ const destAta = getAssociatedTokenAddressSync6(mint, dustDestination);
11965
+ const destInfo = await conn.getAccountInfo(destAta);
11966
+ if (!destInfo) {
11967
+ const ataRent = await getMinimumBalanceForRentExemptAccount(conn);
11968
+ if (before < ataRent + CLEANUP_FEE_BUDGET) {
11969
+ throw new Error(
11970
+ `dustDestination ${dustDestination.toBase58()} has no token account for mint ${mint.toBase58()}, and creating one costs ${ataRent} lamports of rent that R does not have: R holds ${before}, which deposit-core.ts reserved only for this transaction's own fee (CLEANUP_FEE_BUDGET = ${CLEANUP_FEE_BUDGET} in funder.ts), not for a fresh account's rent. Fund R with at least ${ataRent + CLEANUP_FEE_BUDGET - before} more lamports first, or choose a destination that already has a token account for this mint.`
11971
+ );
11972
+ }
11973
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(R.publicKey, destAta, dustDestination, mint));
11974
+ }
11975
+ ixs.push(createTransferInstruction(rAta, destAta, R.publicKey, bal));
11976
+ destination = destAta.toBase58();
11977
+ }
11978
+ ixs.push(createCloseAccountInstruction(rAta, R.publicKey, R.publicKey));
11979
+ const signature = await sendAndConfirmTransaction3(conn, new Transaction6().add(...ixs), [R], {
11980
+ commitment: "confirmed"
11981
+ });
11982
+ const after = await conn.getBalance(R.publicKey);
11983
+ const gone = await conn.getAccountInfo(rAta) === null;
11984
+ return {
11985
+ closed: gone,
11986
+ dustSwept: bal,
11987
+ rentReturned: after - before,
11988
+ destination,
11989
+ signature,
11990
+ note: bal > 0n ? `swept ${bal} base units of dust to the caller-chosen destination and closed, in one transaction \u2014 note this publishes a link from the deposit to that destination` : `closed cleanly, nothing to sweep`
11991
+ };
11992
+ }
11993
+
11994
+ // src/bridge/quote.ts
11995
+ var MIN_DEPOSIT_SPL_BASE_UNITS = 1000000n;
11996
+ var WITHDRAW_FIXED_FEE = 450000n;
11997
+ var WITHDRAW_FEE_BPS = 30n;
11998
+ function withdrawFeeAt(amount, fixedFee, feeBps) {
11999
+ return fixedFee + amount * feeBps / 10000n;
12000
+ }
12001
+ var MAX_FEE_FRACTION = 0.063;
12002
+ var FIXED_ROUND_TRIP = 903000n;
12003
+ var ECONOMIC_MINIMUM = FIXED_ROUND_TRIP * 1000000n / BigInt(Math.round((MAX_FEE_FRACTION - 3e-3) * 1e6));
12004
+ function withdrawFeeFor(amount) {
12005
+ return withdrawFeeAt(amount, WITHDRAW_FIXED_FEE, WITHDRAW_FEE_BPS);
12006
+ }
12007
+ function assessBridgeQuote(q) {
12008
+ if (q.sent < 0n) {
12009
+ throw new Error(`assessBridgeQuote: sent must not be negative (got ${q.sent}).`);
12010
+ }
12011
+ if (q.arrivesMin > q.sent) {
12012
+ throw new Error(
12013
+ `assessBridgeQuote: arrivesMin (${q.arrivesMin}) exceeds sent (${q.sent}) \u2014 no rail returns more than it was given, so this input did not come from a real quote.`
12014
+ );
12015
+ }
12016
+ const shieldedMinRaw = q.arrivesMin - q.paymasterFee;
12017
+ const shieldedTargetRaw = q.arrivesTarget - q.paymasterFee;
12018
+ const shieldedMin = shieldedMinRaw > 0n ? shieldedMinRaw : 0n;
12019
+ const shieldedTarget = shieldedTargetRaw > 0n ? shieldedTargetRaw : 0n;
12020
+ const viable = shieldedMinRaw >= MIN_DEPOSIT_SPL_BASE_UNITS;
12021
+ const economic = q.sent >= ECONOMIC_MINIMUM;
12022
+ const withdrawFee = shieldedMin > 0n ? withdrawFeeAt(shieldedMin, q.liveWithdrawFixedFee ?? WITHDRAW_FIXED_FEE, q.liveWithdrawFeeBps ?? WITHDRAW_FEE_BPS) : 0n;
12023
+ const roundTripCost = q.sent - (shieldedMin > withdrawFee ? shieldedMin - withdrawFee : 0n);
12024
+ const roundTripFraction = q.sent > 0n ? Number(roundTripCost) / Number(q.sent) : 0;
12025
+ const reasons = [];
12026
+ if (!viable) {
12027
+ const short = MIN_DEPOSIT_SPL_BASE_UNITS - shieldedMinRaw;
12028
+ reasons.push(
12029
+ (shieldedMinRaw <= 0n ? `The ${fmt(q.paymasterFee)} paymaster fee alone is ${shieldedMinRaw < 0n ? `${fmt(-shieldedMinRaw)} more than` : "all of"} the ${fmt(q.arrivesMin)} the rail guarantees, so nothing would be left to shield.` : `Only ${fmt(shieldedMinRaw)} would be left to shield after the ${fmt(q.paymasterFee)} paymaster fee.`) + ` The program's minimum deposit is ${fmt(MIN_DEPOSIT_SPL_BASE_UNITS)}. Send at least ${fmt(q.sent + short)} to clear it.`
12030
+ );
12031
+ }
12032
+ if (viable && !economic) {
12033
+ reasons.push(
12034
+ `This works, but ${fmt(roundTripCost)} of ${fmt(q.sent)} goes to fees (${(roundTripFraction * 100).toFixed(0)}%). The costs are almost all fixed, so bridging ${fmt(ECONOMIC_MINIMUM)} or more spreads them much further.`
12035
+ );
12036
+ }
12037
+ return {
12038
+ ...q,
12039
+ shieldedMin,
12040
+ shieldedTarget,
12041
+ viable,
12042
+ economic,
12043
+ withdrawFee,
12044
+ roundTripCost,
12045
+ roundTripFraction,
12046
+ reasons
12047
+ };
12048
+ }
12049
+ var fmt = (v) => `${(Number(v) / 1e6).toFixed(6)} USDC`;
12050
+ function renderAssessment(a) {
12051
+ const L = [];
12052
+ L.push(` you send ${fmt(a.sent)}`);
12053
+ L.push(` arrives at least ${fmt(a.arrivesMin)} (target ${fmt(a.arrivesTarget)}, not a promise)`);
12054
+ L.push(` paymaster fee ${fmt(a.paymasterFee)} buys the receiver its SOL, so your wallet stays off chain`);
12055
+ L.push(` SHIELDED ${fmt(a.shieldedMin)} at least \u2014 this is what you end up with`);
12056
+ L.push(` to withdraw later ${fmt(a.withdrawFee)} the program's fee, whenever you take it out`);
12057
+ for (const r of a.reasons) L.push(`
12058
+ ${a.viable ? "NOTE" : "REFUSED"}: ${r}`);
12059
+ return L.join("\n");
12060
+ }
12061
+
12062
+ // src/bridge/retry.ts
12063
+ var TERMINAL_FAILURE = /DepositTooSmall|minimum is 1\.000000|insufficient|holds only|below the program|kora wants|over the .* ceiling/i;
12064
+ function isTerminalFailure(message) {
12065
+ return TERMINAL_FAILURE.test(message);
12066
+ }
12067
+ function classifyPostFailure(attempted, after) {
12068
+ if (after === null) return "unknown";
12069
+ if (after === 0n) return "landed";
12070
+ if (after >= attempted) return "did-not-land";
12071
+ return "unknown";
12072
+ }
12073
+ function mayRetry(verdict, message) {
12074
+ return verdict === "did-not-land" && !isTerminalFailure(message);
12075
+ }
12076
+ function retryDelayMs(attempt) {
12077
+ return 15e3 * Math.max(0, attempt - 1);
12078
+ }
12079
+ var DoNotRetry = class extends Error {
12080
+ constructor(message) {
12081
+ super(message);
12082
+ this.name = "DoNotRetry";
12083
+ }
12084
+ };
12085
+ async function withShieldRetries(attempt, hooks = {}) {
12086
+ const attempts = hooks.attempts ?? 3;
12087
+ const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
12088
+ let last = "";
12089
+ for (let n = 1; n <= attempts; n++) {
12090
+ if (n > 1) {
12091
+ const delay = retryDelayMs(n);
12092
+ hooks.onRetry?.(n, delay, last);
12093
+ await sleep4(delay);
12094
+ }
12095
+ try {
12096
+ return await attempt(n);
12097
+ } catch (e) {
12098
+ if (e instanceof DoNotRetry) throw e;
12099
+ last = e instanceof Error ? e.message : String(e);
12100
+ if (isTerminalFailure(last) || n === attempts) throw e;
12101
+ }
12102
+ }
12103
+ throw new Error("unreachable");
12104
+ }
12105
+
10884
12106
  // src/index.ts
10885
- var VERSION = "0.2.3";
12107
+ var VERSION = "0.2.4";
10886
12108
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
10887
12109
  export {
12110
+ BRIDGE_ESCROW_LABEL,
10888
12111
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
10889
12112
  CHAIN_NOTE_SALT_BITS,
12113
+ CLEANUP_FEE_BUDGET,
10890
12114
  CLOAK_PRODUCTION_RELAY_URL,
10891
12115
  CLOAK_PROGRAM_ID,
10892
12116
  CloakError,
@@ -10894,25 +12118,38 @@ export {
10894
12118
  DEFAULT_TRANSACTION_CIRCUITS_URL,
10895
12119
  DELIVERY_MEMO_TAG,
10896
12120
  DELIVERY_REGISTRY_SEED,
12121
+ DepositError,
12122
+ DoNotRetry,
12123
+ ECONOMIC_MINIMUM,
10897
12124
  EXPECTED_CIRCUIT_HASHES,
12125
+ FEE_BUDGET,
10898
12126
  FIXED_FEE_LAMPORTS,
10899
12127
  InsecureRandomnessError,
10900
12128
  LAMPORTS_PER_SOL,
10901
12129
  LocalStorageAdapter,
12130
+ MAINNET_RENT_0,
12131
+ MAINNET_RENT_1,
12132
+ MAX_RECEIVER_INDEX,
10902
12133
  MERKLE_TREE_HEIGHT2 as MERKLE_TREE_HEIGHT,
10903
12134
  MIN_DEPOSIT_LAMPORTS,
12135
+ MIN_DEPOSIT_SPL_BASE_UNITS,
10904
12136
  MemoryStorageAdapter,
10905
12137
  MerkleTree,
10906
12138
  NATIVE_SOL_MINT,
12139
+ ONECLICK_PUBKEY_B58,
10907
12140
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
10908
12141
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
10909
12142
  RECIPIENT_DELIVERY_NONCE_LEN,
10910
12143
  RECIPIENT_DELIVERY_NOTE_BYTES,
10911
12144
  RECIPIENT_DELIVERY_PLAINTEXT_LEN,
10912
12145
  RECIPIENT_DELIVERY_TAG_LEN,
12146
+ RELAY_BATCH_AUTH_MAX_ITEMS,
10913
12147
  RELAY_ORIGIN_ALLOWLIST,
12148
+ REQUEST_AUTH_BATCH_DOMAIN,
12149
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
10914
12150
  REQUEST_AUTH_MAX_AGE_SECONDS,
10915
12151
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
12152
+ RelayBatchAuthCoordinator,
10916
12153
  RelayInternalError,
10917
12154
  RelayService,
10918
12155
  RootNotFoundError,
@@ -10922,6 +12159,7 @@ export {
10922
12159
  SettlementVerificationError,
10923
12160
  ShieldPoolErrors,
10924
12161
  SimpleWallet,
12162
+ TERMINAL_FAILURE,
10925
12163
  TRANSACTION_CIRCUITS_VERSION,
10926
12164
  TRANSACT_AUTH_FIELDS,
10927
12165
  TRANSACT_SWAP_AUTH_FIELDS,
@@ -10931,16 +12169,21 @@ export {
10931
12169
  VARIABLE_FEE_NUMERATOR,
10932
12170
  VARIABLE_FEE_RATE,
10933
12171
  VERSION,
12172
+ WITHDRAW_FEE_BPS,
12173
+ WITHDRAW_FIXED_FEE,
10934
12174
  assertDirectSubmissionLanded,
10935
12175
  assertInputMints,
10936
12176
  assertTransactionCircuitIntegrity,
12177
+ assessBridgeQuote,
10937
12178
  bigintToBytes32,
10938
12179
  bigintToHex,
12180
+ buildAuthTransactionMessage,
10939
12181
  buildMerkleTree,
10940
12182
  buildMerkleTreeFromChain,
10941
12183
  buildMerkleTreeFromRelay,
10942
12184
  buildRecipientDeliveryNotes,
10943
12185
  buildRelayAuthPreimage,
12186
+ buildRelayBatchAuthMessage,
10944
12187
  buildTransactRequestBody,
10945
12188
  bytesToHex,
10946
12189
  calculateFee,
@@ -10948,12 +12191,16 @@ export {
10948
12191
  calculateRelayFee,
10949
12192
  canRebuildMerkleTreeFromChain,
10950
12193
  canonicalJson,
12194
+ canonicalPayloadString,
10951
12195
  chainNoteFromBase64,
10952
12196
  chainNoteToBase64,
12197
+ classifyPostFailure,
10953
12198
  classifyRelayError,
12199
+ cleanupReceivingAddress,
10954
12200
  cleanupStalePendingOperations,
10955
12201
  clearPendingDeposits,
10956
12202
  clearPendingWithdrawals,
12203
+ cloakBridgeRail,
10957
12204
  computeChainNoteHash,
10958
12205
  computeExtDataHash,
10959
12206
  computeMerkleRoot,
@@ -10970,15 +12217,19 @@ export {
10970
12217
  createLogger,
10971
12218
  createRecoverableChangeUtxo,
10972
12219
  createRecoverableDepositUtxo,
12220
+ createRelayBatchAuthCoordinator,
10973
12221
  createUtxo,
10974
12222
  createZeroUtxo,
10975
12223
  decryptCompactChainNote,
10976
12224
  decryptComplianceMetadataWithMasterKey,
10977
12225
  decryptTransactionMetadata,
12226
+ depositFromDerivedKey,
12227
+ deriveBridgeReceiver,
10978
12228
  deriveChangeNoteBlinding,
10979
12229
  deriveDepositNoteSecrets,
10980
12230
  deriveDiversifiedViewingKey,
10981
12231
  deriveDiversifier,
12232
+ deriveFundingTargets,
10982
12233
  deriveInputNullifierPdas,
10983
12234
  derivePublicKey,
10984
12235
  deriveSpendKey,
@@ -11017,6 +12268,7 @@ export {
11017
12268
  formatErrorForLogging,
11018
12269
  formatSol,
11019
12270
  fullWithdraw,
12271
+ fundReceiverViaPaymaster,
11020
12272
  generateCloakKeys,
11021
12273
  generateCommitmentAsync,
11022
12274
  generateMasterSeed,
@@ -11052,18 +12304,21 @@ export {
11052
12304
  isReactNative,
11053
12305
  isRootNotFoundError,
11054
12306
  isSubmissionOutcomeUnknownResponse,
12307
+ isTerminalFailure,
11055
12308
  isValidHex,
11056
12309
  isValidRpcUrl,
11057
12310
  isValidSolanaAddress,
11058
12311
  isWithdrawAmountSufficient,
11059
12312
  isWithdrawable,
11060
12313
  keypairToAdapter,
12314
+ listBridgeDeposits,
11061
12315
  loadPendingDeposits,
11062
12316
  loadPendingWithdrawals,
11063
12317
  loadVerifiedCircuitArtifacts,
11064
12318
  matchChangeNote,
11065
12319
  matchDepositNote,
11066
12320
  matchSwapRefundLeaf,
12321
+ mayRetry,
11067
12322
  openRecipientDeliveryNote,
11068
12323
  parseAmount,
11069
12324
  parseDeliveryCarrierMemo,
@@ -11086,11 +12341,15 @@ export {
11086
12341
  randomDepositNoteSalt,
11087
12342
  randomFieldElement,
11088
12343
  readMerkleTreeState,
12344
+ readRent,
11089
12345
  recipientDeliveryNoteToBase64,
11090
12346
  registerViewingKey,
12347
+ relayRequestDigestHex,
11091
12348
  removePendingDeposit,
11092
12349
  removePendingWithdrawal,
12350
+ renderAssessment,
11093
12351
  resolveCircuitsBase,
12352
+ retryDelayMs,
11094
12353
  savePendingDeposit,
11095
12354
  savePendingWithdrawal,
11096
12355
  scanNotesForWallet,
@@ -11099,10 +12358,12 @@ export {
11099
12358
  sdkLogger,
11100
12359
  selectUtxos,
11101
12360
  sendTransaction,
12361
+ serializeAuthTransactionMessage,
11102
12362
  serializeNote,
11103
12363
  serializeUtxo,
11104
12364
  setCircuitsPath,
11105
12365
  setDebugMode,
12366
+ signRelayAuthPayload,
11106
12367
  signTransaction,
11107
12368
  splitTo2Limbs,
11108
12369
  submitTransactToRelay,
@@ -11111,6 +12372,7 @@ export {
11111
12372
  swapWithChange,
11112
12373
  toComplianceReport,
11113
12374
  transact,
12375
+ transactBatch,
11114
12376
  transfer,
11115
12377
  truncate,
11116
12378
  tryDecryptNote,
@@ -11123,13 +12385,17 @@ export {
11123
12385
  validateDepositParams,
11124
12386
  validateNote,
11125
12387
  validateOutputsSum,
12388
+ validatePaymasterTopUpTransaction,
11126
12389
  validateRoot,
11127
12390
  validateTransfers,
11128
12391
  validateWalletConnected,
11129
12392
  validateWithdrawableNote,
11130
12393
  verifyAllCircuits,
11131
12394
  verifyCircuitIntegrity,
12395
+ verifyQuoteSignature,
11132
12396
  verifyUtxos,
11133
12397
  waitForRoot,
11134
- withTiming
12398
+ withShieldRetries,
12399
+ withTiming,
12400
+ withdrawFeeFor
11135
12401
  };