@cloak.dev/sdk 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -455,7 +455,7 @@ async function deserializeUtxo(bytes) {
455
455
  const blindingBytes = bytes.slice(40, 72);
456
456
  const blinding = bytesToBigint2(blindingBytes);
457
457
  const mintBytes = bytes.slice(72, 104);
458
- const mintAddress = new import_web33.PublicKey(mintBytes);
458
+ const mintAddress = new import_web34.PublicKey(mintBytes);
459
459
  const index = view.getUint32(104, true);
460
460
  const utxo = {
461
461
  amount,
@@ -523,18 +523,18 @@ function selectUtxos(available, targetAmount) {
523
523
  }
524
524
  return selected;
525
525
  }
526
- var import_web33, import_circomlibjs2, import_blake33, FIELD_MODULUS, KEYPAIR_DOMAIN_TAG, UTXO_KEY_DOMAIN, NATIVE_SOL_MINT, poseidonInstance;
526
+ var import_web34, import_circomlibjs2, import_blake33, FIELD_MODULUS, KEYPAIR_DOMAIN_TAG, UTXO_KEY_DOMAIN, NATIVE_SOL_MINT, poseidonInstance;
527
527
  var init_utxo = __esm({
528
528
  "src/notes/utxo.ts"() {
529
529
  "use strict";
530
- import_web33 = require("@solana/web3.js");
530
+ import_web34 = require("@solana/web3.js");
531
531
  import_circomlibjs2 = require("circomlibjs");
532
532
  import_blake33 = require("@noble/hashes/blake3");
533
533
  init_inputs();
534
534
  FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
535
535
  KEYPAIR_DOMAIN_TAG = BigInt("5423839527465210463");
536
536
  UTXO_KEY_DOMAIN = new TextEncoder().encode("cloak_utxo_priv_v1");
537
- NATIVE_SOL_MINT = new import_web33.PublicKey("So11111111111111111111111111111111111111112");
537
+ NATIVE_SOL_MINT = new import_web34.PublicKey("So11111111111111111111111111111111111111112");
538
538
  poseidonInstance = null;
539
539
  }
540
540
  });
@@ -542,8 +542,10 @@ var init_utxo = __esm({
542
542
  // src/index.ts
543
543
  var index_exports = {};
544
544
  __export(index_exports, {
545
+ BRIDGE_ESCROW_LABEL: () => BRIDGE_ESCROW_LABEL,
545
546
  BUILD_ALLOWS_LOCAL_ENDPOINTS: () => BUILD_ALLOWS_LOCAL_ENDPOINTS,
546
547
  CHAIN_NOTE_SALT_BITS: () => CHAIN_NOTE_SALT_BITS,
548
+ CLEANUP_FEE_BUDGET: () => CLEANUP_FEE_BUDGET,
547
549
  CLOAK_PRODUCTION_RELAY_URL: () => CLOAK_PRODUCTION_RELAY_URL,
548
550
  CLOAK_PROGRAM_ID: () => CLOAK_PROGRAM_ID,
549
551
  CloakError: () => CloakError,
@@ -551,25 +553,38 @@ __export(index_exports, {
551
553
  DEFAULT_TRANSACTION_CIRCUITS_URL: () => DEFAULT_TRANSACTION_CIRCUITS_URL,
552
554
  DELIVERY_MEMO_TAG: () => DELIVERY_MEMO_TAG,
553
555
  DELIVERY_REGISTRY_SEED: () => DELIVERY_REGISTRY_SEED,
556
+ DepositError: () => DepositError,
557
+ DoNotRetry: () => DoNotRetry,
558
+ ECONOMIC_MINIMUM: () => ECONOMIC_MINIMUM,
554
559
  EXPECTED_CIRCUIT_HASHES: () => EXPECTED_CIRCUIT_HASHES,
560
+ FEE_BUDGET: () => FEE_BUDGET,
555
561
  FIXED_FEE_LAMPORTS: () => FIXED_FEE_LAMPORTS,
556
562
  InsecureRandomnessError: () => InsecureRandomnessError,
557
563
  LAMPORTS_PER_SOL: () => LAMPORTS_PER_SOL,
558
564
  LocalStorageAdapter: () => LocalStorageAdapter,
565
+ MAINNET_RENT_0: () => MAINNET_RENT_0,
566
+ MAINNET_RENT_1: () => MAINNET_RENT_1,
567
+ MAX_RECEIVER_INDEX: () => MAX_RECEIVER_INDEX,
559
568
  MERKLE_TREE_HEIGHT: () => MERKLE_TREE_HEIGHT2,
560
569
  MIN_DEPOSIT_LAMPORTS: () => MIN_DEPOSIT_LAMPORTS,
570
+ MIN_DEPOSIT_SPL_BASE_UNITS: () => MIN_DEPOSIT_SPL_BASE_UNITS,
561
571
  MemoryStorageAdapter: () => MemoryStorageAdapter,
562
572
  MerkleTree: () => MerkleTree,
563
573
  NATIVE_SOL_MINT: () => NATIVE_SOL_MINT,
574
+ ONECLICK_PUBKEY_B58: () => ONECLICK_PUBKEY_B58,
564
575
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN: () => RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
565
576
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN: () => RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
566
577
  RECIPIENT_DELIVERY_NONCE_LEN: () => RECIPIENT_DELIVERY_NONCE_LEN,
567
578
  RECIPIENT_DELIVERY_NOTE_BYTES: () => RECIPIENT_DELIVERY_NOTE_BYTES,
568
579
  RECIPIENT_DELIVERY_PLAINTEXT_LEN: () => RECIPIENT_DELIVERY_PLAINTEXT_LEN,
569
580
  RECIPIENT_DELIVERY_TAG_LEN: () => RECIPIENT_DELIVERY_TAG_LEN,
581
+ RELAY_BATCH_AUTH_MAX_ITEMS: () => RELAY_BATCH_AUTH_MAX_ITEMS,
570
582
  RELAY_ORIGIN_ALLOWLIST: () => RELAY_ORIGIN_ALLOWLIST,
583
+ REQUEST_AUTH_BATCH_DOMAIN: () => REQUEST_AUTH_BATCH_DOMAIN,
584
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS: () => REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
571
585
  REQUEST_AUTH_MAX_AGE_SECONDS: () => REQUEST_AUTH_MAX_AGE_SECONDS,
572
586
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS: () => REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
587
+ RelayBatchAuthCoordinator: () => RelayBatchAuthCoordinator,
573
588
  RelayInternalError: () => RelayInternalError,
574
589
  RelayService: () => RelayService,
575
590
  RootNotFoundError: () => RootNotFoundError,
@@ -579,6 +594,7 @@ __export(index_exports, {
579
594
  SettlementVerificationError: () => SettlementVerificationError,
580
595
  ShieldPoolErrors: () => ShieldPoolErrors,
581
596
  SimpleWallet: () => SimpleWallet,
597
+ TERMINAL_FAILURE: () => TERMINAL_FAILURE,
582
598
  TRANSACTION_CIRCUITS_VERSION: () => TRANSACTION_CIRCUITS_VERSION,
583
599
  TRANSACT_AUTH_FIELDS: () => TRANSACT_AUTH_FIELDS,
584
600
  TRANSACT_SWAP_AUTH_FIELDS: () => TRANSACT_SWAP_AUTH_FIELDS,
@@ -588,16 +604,21 @@ __export(index_exports, {
588
604
  VARIABLE_FEE_NUMERATOR: () => VARIABLE_FEE_NUMERATOR,
589
605
  VARIABLE_FEE_RATE: () => VARIABLE_FEE_RATE,
590
606
  VERSION: () => VERSION,
607
+ WITHDRAW_FEE_BPS: () => WITHDRAW_FEE_BPS,
608
+ WITHDRAW_FIXED_FEE: () => WITHDRAW_FIXED_FEE,
591
609
  assertDirectSubmissionLanded: () => assertDirectSubmissionLanded,
592
610
  assertInputMints: () => assertInputMints,
593
611
  assertTransactionCircuitIntegrity: () => assertTransactionCircuitIntegrity,
612
+ assessBridgeQuote: () => assessBridgeQuote,
594
613
  bigintToBytes32: () => bigintToBytes32,
595
614
  bigintToHex: () => bigintToHex,
615
+ buildAuthTransactionMessage: () => buildAuthTransactionMessage,
596
616
  buildMerkleTree: () => buildMerkleTree,
597
617
  buildMerkleTreeFromChain: () => buildMerkleTreeFromChain,
598
618
  buildMerkleTreeFromRelay: () => buildMerkleTreeFromRelay,
599
619
  buildRecipientDeliveryNotes: () => buildRecipientDeliveryNotes,
600
620
  buildRelayAuthPreimage: () => buildRelayAuthPreimage,
621
+ buildRelayBatchAuthMessage: () => buildRelayBatchAuthMessage,
601
622
  buildTransactRequestBody: () => buildTransactRequestBody,
602
623
  bytesToHex: () => bytesToHex,
603
624
  calculateFee: () => calculateFee,
@@ -605,12 +626,16 @@ __export(index_exports, {
605
626
  calculateRelayFee: () => calculateRelayFee,
606
627
  canRebuildMerkleTreeFromChain: () => canRebuildMerkleTreeFromChain,
607
628
  canonicalJson: () => canonicalJson,
629
+ canonicalPayloadString: () => canonicalPayloadString,
608
630
  chainNoteFromBase64: () => chainNoteFromBase64,
609
631
  chainNoteToBase64: () => chainNoteToBase64,
632
+ classifyPostFailure: () => classifyPostFailure,
610
633
  classifyRelayError: () => classifyRelayError,
634
+ cleanupReceivingAddress: () => cleanupReceivingAddress,
611
635
  cleanupStalePendingOperations: () => cleanupStalePendingOperations,
612
636
  clearPendingDeposits: () => clearPendingDeposits,
613
637
  clearPendingWithdrawals: () => clearPendingWithdrawals,
638
+ cloakBridgeRail: () => cloakBridgeRail,
614
639
  computeChainNoteHash: () => computeChainNoteHash,
615
640
  computeExtDataHash: () => computeExtDataHash,
616
641
  computeMerkleRoot: () => computeMerkleRoot,
@@ -627,15 +652,19 @@ __export(index_exports, {
627
652
  createLogger: () => createLogger,
628
653
  createRecoverableChangeUtxo: () => createRecoverableChangeUtxo,
629
654
  createRecoverableDepositUtxo: () => createRecoverableDepositUtxo,
655
+ createRelayBatchAuthCoordinator: () => createRelayBatchAuthCoordinator,
630
656
  createUtxo: () => createUtxo,
631
657
  createZeroUtxo: () => createZeroUtxo,
632
658
  decryptCompactChainNote: () => decryptCompactChainNote,
633
659
  decryptComplianceMetadataWithMasterKey: () => decryptComplianceMetadataWithMasterKey,
634
660
  decryptTransactionMetadata: () => decryptTransactionMetadata,
661
+ depositFromDerivedKey: () => depositFromDerivedKey,
662
+ deriveBridgeReceiver: () => deriveBridgeReceiver,
635
663
  deriveChangeNoteBlinding: () => deriveChangeNoteBlinding,
636
664
  deriveDepositNoteSecrets: () => deriveDepositNoteSecrets,
637
665
  deriveDiversifiedViewingKey: () => deriveDiversifiedViewingKey,
638
666
  deriveDiversifier: () => deriveDiversifier,
667
+ deriveFundingTargets: () => deriveFundingTargets,
639
668
  deriveInputNullifierPdas: () => deriveInputNullifierPdas,
640
669
  derivePublicKey: () => derivePublicKey,
641
670
  deriveSpendKey: () => deriveSpendKey,
@@ -674,6 +703,7 @@ __export(index_exports, {
674
703
  formatErrorForLogging: () => formatErrorForLogging,
675
704
  formatSol: () => formatSol,
676
705
  fullWithdraw: () => fullWithdraw,
706
+ fundReceiverViaPaymaster: () => fundReceiverViaPaymaster,
677
707
  generateCloakKeys: () => generateCloakKeys,
678
708
  generateCommitmentAsync: () => generateCommitmentAsync,
679
709
  generateMasterSeed: () => generateMasterSeed,
@@ -709,18 +739,21 @@ __export(index_exports, {
709
739
  isReactNative: () => isReactNative,
710
740
  isRootNotFoundError: () => isRootNotFoundError,
711
741
  isSubmissionOutcomeUnknownResponse: () => isSubmissionOutcomeUnknownResponse,
742
+ isTerminalFailure: () => isTerminalFailure,
712
743
  isValidHex: () => isValidHex,
713
744
  isValidRpcUrl: () => isValidRpcUrl,
714
745
  isValidSolanaAddress: () => isValidSolanaAddress,
715
746
  isWithdrawAmountSufficient: () => isWithdrawAmountSufficient,
716
747
  isWithdrawable: () => isWithdrawable,
717
748
  keypairToAdapter: () => keypairToAdapter,
749
+ listBridgeDeposits: () => listBridgeDeposits,
718
750
  loadPendingDeposits: () => loadPendingDeposits,
719
751
  loadPendingWithdrawals: () => loadPendingWithdrawals,
720
752
  loadVerifiedCircuitArtifacts: () => loadVerifiedCircuitArtifacts,
721
753
  matchChangeNote: () => matchChangeNote,
722
754
  matchDepositNote: () => matchDepositNote,
723
755
  matchSwapRefundLeaf: () => matchSwapRefundLeaf,
756
+ mayRetry: () => mayRetry,
724
757
  openRecipientDeliveryNote: () => openRecipientDeliveryNote,
725
758
  parseAmount: () => parseAmount,
726
759
  parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
@@ -743,11 +776,15 @@ __export(index_exports, {
743
776
  randomDepositNoteSalt: () => randomDepositNoteSalt,
744
777
  randomFieldElement: () => randomFieldElement,
745
778
  readMerkleTreeState: () => readMerkleTreeState,
779
+ readRent: () => readRent,
746
780
  recipientDeliveryNoteToBase64: () => recipientDeliveryNoteToBase64,
747
781
  registerViewingKey: () => registerViewingKey,
782
+ relayRequestDigestHex: () => relayRequestDigestHex,
748
783
  removePendingDeposit: () => removePendingDeposit,
749
784
  removePendingWithdrawal: () => removePendingWithdrawal,
785
+ renderAssessment: () => renderAssessment,
750
786
  resolveCircuitsBase: () => resolveCircuitsBase,
787
+ retryDelayMs: () => retryDelayMs,
751
788
  savePendingDeposit: () => savePendingDeposit,
752
789
  savePendingWithdrawal: () => savePendingWithdrawal,
753
790
  scanNotesForWallet: () => scanNotesForWallet,
@@ -756,10 +793,12 @@ __export(index_exports, {
756
793
  sdkLogger: () => sdkLogger,
757
794
  selectUtxos: () => selectUtxos,
758
795
  sendTransaction: () => sendTransaction,
796
+ serializeAuthTransactionMessage: () => serializeAuthTransactionMessage,
759
797
  serializeNote: () => serializeNote,
760
798
  serializeUtxo: () => serializeUtxo,
761
799
  setCircuitsPath: () => setCircuitsPath,
762
800
  setDebugMode: () => setDebugMode,
801
+ signRelayAuthPayload: () => signRelayAuthPayload,
763
802
  signTransaction: () => signTransaction,
764
803
  splitTo2Limbs: () => splitTo2Limbs,
765
804
  submitTransactToRelay: () => submitTransactToRelay,
@@ -768,6 +807,7 @@ __export(index_exports, {
768
807
  swapWithChange: () => swapWithChange,
769
808
  toComplianceReport: () => toComplianceReport,
770
809
  transact: () => transact,
810
+ transactBatch: () => transactBatch,
771
811
  transfer: () => transfer,
772
812
  truncate: () => truncate,
773
813
  tryDecryptNote: () => tryDecryptNote,
@@ -780,15 +820,19 @@ __export(index_exports, {
780
820
  validateDepositParams: () => validateDepositParams,
781
821
  validateNote: () => validateNote,
782
822
  validateOutputsSum: () => validateOutputsSum,
823
+ validatePaymasterTopUpTransaction: () => validatePaymasterTopUpTransaction,
783
824
  validateRoot: () => validateRoot,
784
825
  validateTransfers: () => validateTransfers,
785
826
  validateWalletConnected: () => validateWalletConnected,
786
827
  validateWithdrawableNote: () => validateWithdrawableNote,
787
828
  verifyAllCircuits: () => verifyAllCircuits,
788
829
  verifyCircuitIntegrity: () => verifyCircuitIntegrity,
830
+ verifyQuoteSignature: () => verifyQuoteSignature,
789
831
  verifyUtxos: () => verifyUtxos,
790
832
  waitForRoot: () => waitForRoot,
791
- withTiming: () => withTiming
833
+ withShieldRetries: () => withShieldRetries,
834
+ withTiming: () => withTiming,
835
+ withdrawFeeFor: () => withdrawFeeFor
792
836
  });
793
837
  module.exports = __toCommonJS(index_exports);
794
838
 
@@ -1347,9 +1391,9 @@ var LocalStorageAdapter = class {
1347
1391
  };
1348
1392
 
1349
1393
  // src/scanning/compliance-keys.ts
1350
- var import_tweetnacl2 = __toESM(require("tweetnacl"), 1);
1394
+ var import_tweetnacl3 = __toESM(require("tweetnacl"), 1);
1351
1395
  var import_blake32 = require("@noble/hashes/blake3");
1352
- var import_sha2 = require("@noble/hashes/sha2");
1396
+ var import_sha22 = require("@noble/hashes/sha2");
1353
1397
  init_inputs();
1354
1398
 
1355
1399
  // src/relay/viewing-key.ts
@@ -1537,6 +1581,276 @@ function connectionRpcEndpoint(connection) {
1537
1581
  return connection?._rpcEndpoint ?? connection?.rpcEndpoint;
1538
1582
  }
1539
1583
 
1584
+ // src/relay/payload.ts
1585
+ var import_sha2 = require("@noble/hashes/sha2");
1586
+ var import_utils = require("@noble/hashes/utils");
1587
+ var import_tweetnacl2 = __toESM(require("tweetnacl"), 1);
1588
+ var import_web33 = require("@solana/web3.js");
1589
+ init_inputs();
1590
+ var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
1591
+ var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
1592
+ var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
1593
+ var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
1594
+ function sha256Hex(text) {
1595
+ return (0, import_utils.bytesToHex)((0, import_sha2.sha256)(new TextEncoder().encode(text)));
1596
+ }
1597
+ function randomNonceUuid() {
1598
+ const webCrypto = globalThis?.crypto;
1599
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
1600
+ const proc = globalThis?.process;
1601
+ const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
1602
+ if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
1603
+ const bytes = randomBytes(16);
1604
+ bytes[6] = bytes[6] & 15 | 64;
1605
+ bytes[8] = bytes[8] & 63 | 128;
1606
+ const hex = (0, import_utils.bytesToHex)(bytes);
1607
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
1608
+ }
1609
+ var TRANSACT_AUTH_FIELDS = [
1610
+ "encrypted_notes",
1611
+ "max_fee",
1612
+ "mint",
1613
+ "proof_bytes",
1614
+ "public_inputs",
1615
+ "recipient",
1616
+ "recipient_delivery_notes",
1617
+ "risk_quote",
1618
+ "sender"
1619
+ ];
1620
+ var TRANSACT_SWAP_AUTH_FIELDS = [
1621
+ "close_timed_out",
1622
+ "dexes",
1623
+ "encrypted_notes",
1624
+ "exclude_dexes",
1625
+ "max_fee",
1626
+ "min_output_amount",
1627
+ "output_mint",
1628
+ "proof_bytes",
1629
+ "public_inputs",
1630
+ "recipient",
1631
+ "recipient_ata",
1632
+ "refund_blinding",
1633
+ "refund_pubkey",
1634
+ "retry_request_id",
1635
+ "risk_quote",
1636
+ "route_retry_attempts",
1637
+ "sender",
1638
+ "slippage_bps",
1639
+ "swap_max_retries"
1640
+ ];
1641
+ var UTF8 = new TextEncoder();
1642
+ function compareKeysBytewise(a, b) {
1643
+ if (a === b) return 0;
1644
+ const ab = UTF8.encode(a);
1645
+ const bb = UTF8.encode(b);
1646
+ const shared = Math.min(ab.length, bb.length);
1647
+ for (let i = 0; i < shared; i++) {
1648
+ if (ab[i] !== bb[i]) return ab[i] - bb[i];
1649
+ }
1650
+ return ab.length - bb.length;
1651
+ }
1652
+ function canonicalJson(value) {
1653
+ if (value === null || value === void 0) return "null";
1654
+ if (typeof value === "boolean") return value ? "true" : "false";
1655
+ if (typeof value === "number") {
1656
+ if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
1657
+ throw new Error(
1658
+ `canonicalJson: refusing to sign the number ${String(value)}. The relay renders numbers with serde_json, which spells non-integer, non-finite and very large values differently from JavaScript, so the two digests would differ and the request would be rejected with an unexplained 401. Send it as a decimal string instead, which is how every amount in this schema travels.`
1659
+ );
1660
+ }
1661
+ return String(value);
1662
+ }
1663
+ if (typeof value === "bigint") return value.toString();
1664
+ if (typeof value === "string") return JSON.stringify(value);
1665
+ if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
1666
+ if (typeof value === "object") {
1667
+ const obj = value;
1668
+ const keys = Object.keys(obj).sort(compareKeysBytewise);
1669
+ return "{" + keys.map((k) => {
1670
+ const v = obj[k];
1671
+ if (typeof v === "function" || typeof v === "symbol") {
1672
+ throw new Error(
1673
+ `canonicalJson: the key "${k}" holds a ${typeof v}, which has no JSON representation. JSON.stringify would drop it from the wire body while it stayed in the signed view, so the relay's digest could never match this one.`
1674
+ );
1675
+ }
1676
+ return `${JSON.stringify(k)}:${canonicalJson(v)}`;
1677
+ }).join(",") + "}";
1678
+ }
1679
+ throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
1680
+ }
1681
+ var FIELDS_WITHOUT_NULL_ENCODING = {
1682
+ slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
1683
+ };
1684
+ function buildAuthRequest(body, sender, fields) {
1685
+ const out = {};
1686
+ for (const k of fields) {
1687
+ if (k === "sender") {
1688
+ out[k] = sender;
1689
+ continue;
1690
+ }
1691
+ const value = body[k];
1692
+ if (value === void 0 || value === null) {
1693
+ const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
1694
+ if (relayDefault) {
1695
+ throw new Error(
1696
+ `Relay request auth: \`${k}\` must be present in the body. It is the one field in this schema that is not optional on the relay side: when it is missing the relay signs its default, ${relayDefault}, while this request would sign null. The two digests differ and the relay answers 401 "Relay request signature does not match the exact request", which points at nothing. Set \`${k}\` explicitly, to the same value the body will carry.`
1697
+ );
1698
+ }
1699
+ out[k] = null;
1700
+ continue;
1701
+ }
1702
+ out[k] = value;
1703
+ }
1704
+ return out;
1705
+ }
1706
+ function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
1707
+ const digest = sha256Hex(canonicalJson(request));
1708
+ return new TextEncoder().encode(
1709
+ `${REQUEST_AUTH_DOMAIN}
1710
+ ${endpoint}
1711
+ ${programId.toBase58()}
1712
+ ${nonce}
1713
+ ${issuedAt}
1714
+ ${digest}`
1715
+ );
1716
+ }
1717
+ function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1718
+ const senderB58 = sender.toBase58();
1719
+ const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
1720
+ const nonce = randomNonceUuid();
1721
+ const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
1722
+ const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
1723
+ return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
1724
+ }
1725
+ function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1726
+ const preimage = buildRelayAuthPreimage(
1727
+ endpoint,
1728
+ programId,
1729
+ body,
1730
+ signer.publicKey,
1731
+ nowSeconds,
1732
+ fields
1733
+ );
1734
+ const signature = import_tweetnacl2.default.sign.detached(preimage.message, signer.secretKey);
1735
+ return {
1736
+ sender: preimage.sender,
1737
+ auth_issued_at: preimage.auth_issued_at,
1738
+ auth_nonce: preimage.auth_nonce,
1739
+ auth_signature: Buffer.from(signature).toString("base64")
1740
+ };
1741
+ }
1742
+ function buildAuthTransactionMessage(sender, digest) {
1743
+ if (digest.length !== 32) throw new Error(`auth transaction digest must be 32 bytes (got ${digest.length})`);
1744
+ const tx = new import_web33.Transaction();
1745
+ tx.add(import_web33.SystemProgram.transfer({ fromPubkey: sender, toPubkey: sender, lamports: 0 }));
1746
+ tx.feePayer = sender;
1747
+ tx.recentBlockhash = new import_web33.PublicKey(digest).toBase58();
1748
+ return tx;
1749
+ }
1750
+ function serializeAuthTransactionMessage(sender, digest) {
1751
+ return Uint8Array.from(buildAuthTransactionMessage(sender, digest).compileMessage().serialize());
1752
+ }
1753
+ async function signRelayAuthPayload(signer, payload) {
1754
+ if (signer instanceof import_web33.Keypair) {
1755
+ return { signature: import_tweetnacl2.default.sign.detached(payload, signer.secretKey), mode: "message" };
1756
+ }
1757
+ if (signer.signMessage) {
1758
+ const signature = await signer.signMessage(payload);
1759
+ assertDetachedSignature(signature, "signMessage");
1760
+ return { signature, mode: "message" };
1761
+ }
1762
+ if (signer.signAuthTransaction) {
1763
+ const digest = (0, import_sha2.sha256)(payload);
1764
+ const signed = await signer.signAuthTransaction(buildAuthTransactionMessage(signer.walletPublicKey, digest));
1765
+ const own = signed.signatures.find((s) => s.publicKey.equals(signer.walletPublicKey))?.signature;
1766
+ if (!own) {
1767
+ throw new Error(
1768
+ "The wallet returned no signature for the Cloak auth transaction. Nothing was submitted."
1769
+ );
1770
+ }
1771
+ const signature = Uint8Array.from(own);
1772
+ assertDetachedSignature(signature, "signTransaction");
1773
+ return { signature, mode: "transaction" };
1774
+ }
1775
+ throw new Error("Relay auth signer has neither signMessage nor signAuthTransaction.");
1776
+ }
1777
+ function assertDetachedSignature(signature, method) {
1778
+ if (!(signature instanceof Uint8Array) || signature.length !== 64) {
1779
+ throw new Error(
1780
+ `The wallet's ${method} did not return a 64-byte ed25519 detached signature (got ${signature instanceof Uint8Array ? `${signature.length} bytes` : typeof signature}). Cloak signs with a raw detached signature over the bytes it hands the wallet; adapters that wrap or re-encode the result cannot be used here.`
1781
+ );
1782
+ }
1783
+ }
1784
+ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_AUTH_MAX_AGE_SECONDS) {
1785
+ const elapsedSeconds = elapsedMs / 1e3;
1786
+ const budget = maxAgeSeconds - RELAY_AUTH_APPROVAL_MARGIN_SECONDS;
1787
+ if (elapsedSeconds <= budget) return;
1788
+ throw new Error(
1789
+ `The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${maxAgeSeconds} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
1790
+ );
1791
+ }
1792
+ function explainRelayAuthRejection(responseText) {
1793
+ const text = String(responseText);
1794
+ const has = (needle) => text.includes(needle);
1795
+ if (has("issued too far in the future")) {
1796
+ return `This computer's clock is more than ${REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS} seconds ahead of the network's, so the request looks like it was signed in the future and is refused before anything else happens. Turn on automatic date and time (or resynchronise the clock) and try again. Nothing was submitted.`;
1797
+ }
1798
+ if (has("signature expired")) {
1799
+ return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
1800
+ }
1801
+ if (has("does not match the exact request")) {
1802
+ return `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
1803
+ }
1804
+ if (has("has no registered viewing key")) {
1805
+ return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
1806
+ }
1807
+ if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
1808
+ return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
1809
+ }
1810
+ if (has("auth_nonce must be a canonical UUID")) {
1811
+ return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
1812
+ }
1813
+ if (has("Relay request signature must be exactly 64 bytes") || has("Invalid relay request signature encoding")) {
1814
+ return `\`auth_signature\` must be the raw 64-byte ed25519 detached signature, base64 encoded. Wallet adapters that wrap or re-encode what \`signMessage\` returns cannot be used here.`;
1815
+ }
1816
+ return null;
1817
+ }
1818
+ async function buildRelayAuthFields(endpoint, programId, body, signers, fields = TRANSACT_AUTH_FIELDS) {
1819
+ if (signers.depositorKeypair) {
1820
+ return signRelayRequest(endpoint, programId, body, signers.depositorKeypair, void 0, fields);
1821
+ }
1822
+ const wallet = signers.relayAuthSigner;
1823
+ if (!wallet) return null;
1824
+ const preimage = buildRelayAuthPreimage(
1825
+ endpoint,
1826
+ programId,
1827
+ body,
1828
+ wallet.walletPublicKey,
1829
+ void 0,
1830
+ fields
1831
+ );
1832
+ const approvalStartedMs = Date.now();
1833
+ const { signature, mode } = await signRelayAuthPayload(wallet, preimage.message);
1834
+ assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
1835
+ return {
1836
+ sender: preimage.sender,
1837
+ auth_issued_at: preimage.auth_issued_at,
1838
+ auth_nonce: preimage.auth_nonce,
1839
+ auth_signature: Buffer.from(signature).toString("base64"),
1840
+ ...mode === "transaction" ? { auth_mode: mode } : {}
1841
+ };
1842
+ }
1843
+ var REQUEST_AUTH_BATCH_DOMAIN = "CLOAK_RELAY_BATCH_AUTH_V1";
1844
+ var REQUEST_AUTH_BATCH_MAX_AGE_SECONDS = 600;
1845
+ var RELAY_BATCH_AUTH_MAX_ITEMS = 64;
1846
+ function relayRequestDigestHex(preimage) {
1847
+ return (0, import_utils.bytesToHex)((0, import_sha2.sha256)(preimage.message));
1848
+ }
1849
+ function buildRelayBatchAuthMessage(programId, issuedAt, digests) {
1850
+ const lines = [REQUEST_AUTH_BATCH_DOMAIN, programId.toBase58(), issuedAt, String(digests.length)];
1851
+ return new TextEncoder().encode([...lines, ...digests].join("\n"));
1852
+ }
1853
+
1540
1854
  // src/scanning/compliance-keys.ts
1541
1855
  var X25519_KEY_LENGTH = 32;
1542
1856
  var DIVERSIFIER_LENGTH = 11;
@@ -1574,7 +1888,7 @@ function deriveViewingKeyFromNk(nk) {
1574
1888
  preimage.set(nk, CHAIN_NOTE_VK_DOMAIN.length);
1575
1889
  const derived = (0, import_blake32.blake3)(preimage);
1576
1890
  const privateKey = clampX25519Secret(derived);
1577
- const publicKey = import_tweetnacl2.default.scalarMult.base(privateKey);
1891
+ const publicKey = import_tweetnacl3.default.scalarMult.base(privateKey);
1578
1892
  return { privateKey, publicKey };
1579
1893
  }
1580
1894
  function deriveDiversifier(nk, commitmentHex, outputIndex) {
@@ -1609,7 +1923,7 @@ function deriveDiversifiedViewingKey(nk, diversifier) {
1609
1923
  preimage.set(diversifier, SK_D_DOMAIN.length + nk.length);
1610
1924
  const derived = (0, import_blake32.blake3)(preimage);
1611
1925
  const privateKey = clampX25519Secret(derived);
1612
- const publicKey = import_tweetnacl2.default.scalarMult.base(privateKey);
1926
+ const publicKey = import_tweetnacl3.default.scalarMult.base(privateKey);
1613
1927
  return { privateKey, publicKey };
1614
1928
  }
1615
1929
  function deriveViewingKeyFromSpendKey(skSpend) {
@@ -1672,19 +1986,19 @@ async function deriveUserCompliancePublicKey(masterCompliancePublicKey, userPubl
1672
1986
  masterCompliancePublicKey,
1673
1987
  userPublicKey
1674
1988
  );
1675
- return import_tweetnacl2.default.scalarMult(factor, masterCompliancePublicKey);
1989
+ return import_tweetnacl3.default.scalarMult(factor, masterCompliancePublicKey);
1676
1990
  }
1677
- function bytesToHex2(bytes) {
1991
+ function bytesToHex3(bytes) {
1678
1992
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1679
1993
  }
1680
1994
  function computeViewingKeyIdentifier(userPubkey, nkHex) {
1681
1995
  const preimage = new TextEncoder().encode(`${userPubkey.toBase58()}${nkHex}`);
1682
- return bytesToHex2((0, import_sha2.sha256)(preimage));
1996
+ return bytesToHex3((0, import_sha22.sha256)(preimage));
1683
1997
  }
1684
1998
  var SIGN_IN_MESSAGE = "Cloak: Sign in\n\nSign this message to securely access your Cloak account.\nThis does NOT authorize any transaction or spend any funds.";
1685
1999
  async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1686
2000
  assert32Bytes(nk, "nk");
1687
- const nkHex = bytesToHex2(nk);
2001
+ const nkHex = bytesToHex3(nk);
1688
2002
  const keyId = computeViewingKeyIdentifier(userPubkey, nkHex);
1689
2003
  const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
1690
2004
  method: "POST",
@@ -1705,8 +2019,11 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1705
2019
  nkHex
1706
2020
  );
1707
2021
  const messageBytes = new TextEncoder().encode(challenge.message);
1708
- const signatureBytes = await signMessage(messageBytes);
1709
- const signature = Buffer.from(signatureBytes).toString("base64");
2022
+ const signed = await signRelayAuthPayload(
2023
+ typeof signMessage === "function" ? { walletPublicKey: userPubkey, signMessage } : signMessage,
2024
+ messageBytes
2025
+ );
2026
+ const signature = Buffer.from(signed.signature).toString("base64");
1710
2027
  const response = await relayFetch(`${relayUrl}/viewing-key/register`, {
1711
2028
  method: "POST",
1712
2029
  headers: { "Content-Type": "application/json" },
@@ -1715,7 +2032,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1715
2032
  viewing_key: nkHex,
1716
2033
  nonce: challenge.nonce,
1717
2034
  identifier: keyId,
1718
- signature
2035
+ signature,
2036
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
1719
2037
  })
1720
2038
  });
1721
2039
  if (!response.ok) {
@@ -1724,7 +2042,7 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1724
2042
  }
1725
2043
 
1726
2044
  // src/scanning/metadata-encryption.ts
1727
- var import_tweetnacl3 = __toESM(require("tweetnacl"), 1);
2045
+ var import_tweetnacl4 = __toESM(require("tweetnacl"), 1);
1728
2046
  init_inputs();
1729
2047
  var AES_GCM_NONCE_LENGTH = 12;
1730
2048
  var AES_GCM_TAG_LENGTH = 16;
@@ -1822,8 +2140,8 @@ async function aesGcmDecrypt(ciphertext, keyBytes, nonce) {
1822
2140
  }
1823
2141
  async function encryptForRecipient(plaintext, recipientPublicKey) {
1824
2142
  assert32Bytes2(recipientPublicKey, "recipientPublicKey");
1825
- const ephemeral = import_tweetnacl3.default.box.keyPair();
1826
- const sharedSecret = import_tweetnacl3.default.scalarMult(ephemeral.secretKey, recipientPublicKey);
2143
+ const ephemeral = import_tweetnacl4.default.box.keyPair();
2144
+ const sharedSecret = import_tweetnacl4.default.scalarMult(ephemeral.secretKey, recipientPublicKey);
1827
2145
  const nonce = randomBytes(AES_GCM_NONCE_LENGTH);
1828
2146
  const ciphertext = await aesGcmEncrypt(plaintext, sharedSecret, nonce);
1829
2147
  return {
@@ -1882,7 +2200,7 @@ async function encryptTransactionMetadataBundle(metadata, viewingKeyPrivate, use
1882
2200
  const plaintext = new TextEncoder().encode(JSON.stringify(metadata));
1883
2201
  const basePoint = new Uint8Array(32);
1884
2202
  basePoint[0] = 9;
1885
- const viewingKeyPublic = import_tweetnacl3.default.scalarMult(viewingKeyPrivate, basePoint);
2203
+ const viewingKeyPublic = import_tweetnacl4.default.scalarMult(viewingKeyPrivate, basePoint);
1886
2204
  const [userPayload, compliancePayload] = await Promise.all([
1887
2205
  encryptForRecipient(plaintext, viewingKeyPublic),
1888
2206
  encryptForRecipient(plaintext, viewingKeyPublic)
@@ -1901,7 +2219,7 @@ async function decryptTransactionMetadata(encrypted, viewKeySecret) {
1901
2219
  const payload = decodePayload(encrypted);
1902
2220
  const ephemeralPk = hexToBytes(payload.ephemeral_pk);
1903
2221
  assert32Bytes2(ephemeralPk, "ephemeral public key");
1904
- const sharedSecret = import_tweetnacl3.default.scalarMult(viewKeySecret, ephemeralPk);
2222
+ const sharedSecret = import_tweetnacl4.default.scalarMult(viewKeySecret, ephemeralPk);
1905
2223
  return decryptWithSharedSecret(payload, sharedSecret);
1906
2224
  }
1907
2225
  async function decryptComplianceMetadataWithMasterKey(encrypted, masterCompliancePrivateKey, masterCompliancePublicKey, userPublicKey) {
@@ -1914,8 +2232,8 @@ async function decryptComplianceMetadataWithMasterKey(encrypted, masterComplianc
1914
2232
  masterCompliancePublicKey,
1915
2233
  userPublicKey
1916
2234
  );
1917
- const scaledEphemeral = import_tweetnacl3.default.scalarMult(userFactor, ephemeralPk);
1918
- const sharedSecret = import_tweetnacl3.default.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
2235
+ const scaledEphemeral = import_tweetnacl4.default.scalarMult(userFactor, ephemeralPk);
2236
+ const sharedSecret = import_tweetnacl4.default.scalarMult(masterCompliancePrivateKey, scaledEphemeral);
1919
2237
  return decryptWithSharedSecret(payload, sharedSecret);
1920
2238
  }
1921
2239
 
@@ -2852,23 +3170,23 @@ function formatErrorForLogging(error) {
2852
3170
  init_utxo();
2853
3171
 
2854
3172
  // src/program/pda.ts
2855
- var import_web34 = require("@solana/web3.js");
3173
+ var import_web35 = require("@solana/web3.js");
2856
3174
  init_utxo();
2857
3175
  function getShieldPoolPDAs(programId, mint = NATIVE_SOL_MINT) {
2858
3176
  const pid = programId || CLOAK_PROGRAM_ID;
2859
- const [pool] = import_web34.PublicKey.findProgramAddressSync(
3177
+ const [pool] = import_web35.PublicKey.findProgramAddressSync(
2860
3178
  [Buffer.from("pool"), mint.toBuffer()],
2861
3179
  pid
2862
3180
  );
2863
- const [merkleTree] = import_web34.PublicKey.findProgramAddressSync(
3181
+ const [merkleTree] = import_web35.PublicKey.findProgramAddressSync(
2864
3182
  [Buffer.from("merkle_tree"), mint.toBuffer()],
2865
3183
  pid
2866
3184
  );
2867
- const [treasury] = import_web34.PublicKey.findProgramAddressSync(
3185
+ const [treasury] = import_web35.PublicKey.findProgramAddressSync(
2868
3186
  [Buffer.from("treasury"), mint.toBuffer()],
2869
3187
  pid
2870
3188
  );
2871
- const [vaultAuthority] = import_web34.PublicKey.findProgramAddressSync(
3189
+ const [vaultAuthority] = import_web35.PublicKey.findProgramAddressSync(
2872
3190
  [Buffer.from("vault_authority"), mint.toBuffer()],
2873
3191
  pid
2874
3192
  );
@@ -2884,7 +3202,7 @@ function getNullifierPDA(poolPubkey, nullifier, programId) {
2884
3202
  if (nullifier.length !== 32) {
2885
3203
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2886
3204
  }
2887
- return import_web34.PublicKey.findProgramAddressSync(
3205
+ return import_web35.PublicKey.findProgramAddressSync(
2888
3206
  [Buffer.from("nullifier"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2889
3207
  pid
2890
3208
  );
@@ -2894,25 +3212,25 @@ function getSwapStatePDA(poolPubkey, nullifier, programId) {
2894
3212
  if (nullifier.length !== 32) {
2895
3213
  throw new Error(`Nullifier must be 32 bytes, got ${nullifier.length}`);
2896
3214
  }
2897
- return import_web34.PublicKey.findProgramAddressSync(
3215
+ return import_web35.PublicKey.findProgramAddressSync(
2898
3216
  [Buffer.from("swap_state"), poolPubkey.toBuffer(), Buffer.from(nullifier)],
2899
3217
  pid
2900
3218
  );
2901
3219
  }
2902
3220
  function getPoolAuthorityConfigPDA(mint = NATIVE_SOL_MINT, programId) {
2903
3221
  const pid = programId || CLOAK_PROGRAM_ID;
2904
- return import_web34.PublicKey.findProgramAddressSync(
3222
+ return import_web35.PublicKey.findProgramAddressSync(
2905
3223
  [Buffer.from("pool_authority"), mint.toBuffer()],
2906
3224
  pid
2907
3225
  );
2908
3226
  }
2909
3227
  function getDeliveryRegistryPDA(programId) {
2910
3228
  const pid = programId || CLOAK_PROGRAM_ID;
2911
- return import_web34.PublicKey.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
3229
+ return import_web35.PublicKey.findProgramAddressSync([Buffer.from("cloak_delivery_registry")], pid)[0];
2912
3230
  }
2913
3231
  function getChainNoteRegistryPDA(programId) {
2914
3232
  const pid = programId || CLOAK_PROGRAM_ID;
2915
- return import_web34.PublicKey.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
3233
+ return import_web35.PublicKey.findProgramAddressSync([Buffer.from("cloak_chain_note_registry")], pid)[0];
2916
3234
  }
2917
3235
 
2918
3236
  // src/flows/verify-utxos.ts
@@ -2930,8 +3248,8 @@ async function verifyUtxos(utxos, connection, programId, commitment = "confirmed
2930
3248
  const nullifierHex = nullifierBig.toString(16).padStart(64, "0");
2931
3249
  const nullifierBytes = Buffer.from(nullifierHex, "hex");
2932
3250
  const { pool } = getShieldPoolPDAs(programId, utxo.mintAddress);
2933
- const [pda] = getNullifierPDA(pool, nullifierBytes, programId);
2934
- checkable.push({ utxo, pda });
3251
+ const [pda2] = getNullifierPDA(pool, nullifierBytes, programId);
3252
+ checkable.push({ utxo, pda: pda2 });
2935
3253
  } catch {
2936
3254
  skipped.push(utxo);
2937
3255
  }
@@ -3001,8 +3319,8 @@ function deriveInputNullifierPdas(programId, mint, inputNullifiers) {
3001
3319
  const pdas = [];
3002
3320
  for (const nullifier of inputNullifiers) {
3003
3321
  if (nullifier === BigInt(0)) continue;
3004
- const [pda] = getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
3005
- pdas.push(pda);
3322
+ const [pda2] = getNullifierPDA(pool, bigintToBytes324(nullifier), programId);
3323
+ pdas.push(pda2);
3006
3324
  }
3007
3325
  return pdas;
3008
3326
  }
@@ -3243,8 +3561,9 @@ function truncate(str, len = 20) {
3243
3561
  var sdkLogger = createLogger("cloak::sdk");
3244
3562
 
3245
3563
  // src/relay/relay-service.ts
3246
- var import_sha22 = require("@noble/hashes/sha2");
3564
+ var import_sha23 = require("@noble/hashes/sha2");
3247
3565
  init_inputs();
3566
+ var import_web36 = require("@solana/web3.js");
3248
3567
  var RelayService = class {
3249
3568
  /**
3250
3569
  * Create a new Relay Service client
@@ -3560,8 +3879,11 @@ var RelayService = class {
3560
3879
  userPubkey,
3561
3880
  viewingKey
3562
3881
  );
3563
- const signatureBytes = await signMessage(new TextEncoder().encode(challenge.message));
3564
- const signature = this.bytesToBase64(signatureBytes);
3882
+ const signed = await signRelayAuthPayload(
3883
+ typeof signMessage === "function" ? { walletPublicKey: new import_web36.PublicKey(userPubkey), signMessage } : signMessage,
3884
+ new TextEncoder().encode(challenge.message)
3885
+ );
3886
+ const signature = this.bytesToBase64(signed.signature);
3565
3887
  const response = await relayFetch(`${this.baseUrl}/viewing-key/register`, {
3566
3888
  method: "POST",
3567
3889
  headers: { "Content-Type": "application/json" },
@@ -3570,7 +3892,8 @@ var RelayService = class {
3570
3892
  viewing_key: viewingKey,
3571
3893
  nonce: challenge.nonce,
3572
3894
  identifier,
3573
- signature
3895
+ signature,
3896
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
3574
3897
  })
3575
3898
  });
3576
3899
  if (!response.ok) {
@@ -3608,7 +3931,7 @@ var RelayService = class {
3608
3931
  }
3609
3932
  computeViewingKeyIdentifier(userPubkey, viewingKeyHex) {
3610
3933
  const preimage = new TextEncoder().encode(`${userPubkey}${viewingKeyHex}`);
3611
- const hash = (0, import_sha22.sha256)(preimage);
3934
+ const hash = (0, import_sha23.sha256)(preimage);
3612
3935
  return Array.from(hash).map((b) => b.toString(16).padStart(2, "0")).join("");
3613
3936
  }
3614
3937
  };
@@ -3726,10 +4049,10 @@ function encodeNoteSimple(note) {
3726
4049
  }
3727
4050
 
3728
4051
  // src/wallet/adapter.ts
3729
- var import_web35 = require("@solana/web3.js");
4052
+ var import_web37 = require("@solana/web3.js");
3730
4053
  init_types();
3731
4054
  function validateWalletConnected(wallet) {
3732
- if (wallet instanceof import_web35.Keypair) {
4055
+ if (wallet instanceof import_web37.Keypair) {
3733
4056
  return;
3734
4057
  }
3735
4058
  if (!wallet.publicKey) {
@@ -3741,7 +4064,7 @@ function validateWalletConnected(wallet) {
3741
4064
  }
3742
4065
  }
3743
4066
  function getPublicKey(wallet) {
3744
- if (wallet instanceof import_web35.Keypair) {
4067
+ if (wallet instanceof import_web37.Keypair) {
3745
4068
  return wallet.publicKey;
3746
4069
  }
3747
4070
  if (!wallet.publicKey) {
@@ -3755,7 +4078,7 @@ function getPublicKey(wallet) {
3755
4078
  }
3756
4079
  async function sendTransaction(transaction, wallet, connection, options) {
3757
4080
  assertAllowedRpcConnection(connection);
3758
- if (wallet instanceof import_web35.Keypair) {
4081
+ if (wallet instanceof import_web37.Keypair) {
3759
4082
  return await connection.sendTransaction(transaction, [wallet], options);
3760
4083
  }
3761
4084
  if (wallet.sendTransaction) {
@@ -3772,7 +4095,7 @@ async function sendTransaction(transaction, wallet, connection, options) {
3772
4095
  }
3773
4096
  }
3774
4097
  async function signTransaction(transaction, wallet) {
3775
- if (wallet instanceof import_web35.Keypair) {
4098
+ if (wallet instanceof import_web37.Keypair) {
3776
4099
  transaction.sign(wallet);
3777
4100
  return transaction;
3778
4101
  }
@@ -3800,7 +4123,7 @@ function keypairToAdapter(keypair) {
3800
4123
  }
3801
4124
 
3802
4125
  // src/program/instructions.ts
3803
- var import_web36 = require("@solana/web3.js");
4126
+ var import_web38 = require("@solana/web3.js");
3804
4127
  function createDepositInstruction(params) {
3805
4128
  if (params.commitment.length !== 32) {
3806
4129
  throw new Error(
@@ -3822,7 +4145,7 @@ function createDepositInstruction(params) {
3822
4145
  data.set(discriminant, 0);
3823
4146
  data.set(amountBytes, 1);
3824
4147
  data.set(params.commitment, 9);
3825
- return new import_web36.TransactionInstruction({
4148
+ return new import_web38.TransactionInstruction({
3826
4149
  programId: params.programId,
3827
4150
  keys: [
3828
4151
  // Account 0: Payer (signer, writable) - pays for transaction
@@ -3830,7 +4153,7 @@ function createDepositInstruction(params) {
3830
4153
  // Account 1: Pool (writable) - receives SOL
3831
4154
  { pubkey: params.pool, isSigner: false, isWritable: true },
3832
4155
  // Account 2: System Program (readonly) - for transfers
3833
- { pubkey: import_web36.SystemProgram.programId, isSigner: false, isWritable: false },
4156
+ { pubkey: import_web38.SystemProgram.programId, isSigner: false, isWritable: false },
3834
4157
  // Account 3: Merkle Tree (writable) - stores on-chain Merkle tree
3835
4158
  { pubkey: params.merkleTree, isSigner: false, isWritable: true }
3836
4159
  ],
@@ -3838,16 +4161,16 @@ function createDepositInstruction(params) {
3838
4161
  });
3839
4162
  }
3840
4163
  function validateDepositParams(params) {
3841
- if (!(params.programId instanceof import_web36.PublicKey)) {
4164
+ if (!(params.programId instanceof import_web38.PublicKey)) {
3842
4165
  throw new Error("programId must be a PublicKey");
3843
4166
  }
3844
- if (!(params.payer instanceof import_web36.PublicKey)) {
4167
+ if (!(params.payer instanceof import_web38.PublicKey)) {
3845
4168
  throw new Error("payer must be a PublicKey");
3846
4169
  }
3847
- if (!(params.pool instanceof import_web36.PublicKey)) {
4170
+ if (!(params.pool instanceof import_web38.PublicKey)) {
3848
4171
  throw new Error("pool must be a PublicKey");
3849
4172
  }
3850
- if (!(params.merkleTree instanceof import_web36.PublicKey)) {
4173
+ if (!(params.merkleTree instanceof import_web38.PublicKey)) {
3851
4174
  throw new Error("merkleTree must be a PublicKey");
3852
4175
  }
3853
4176
  if (typeof params.amount !== "number" || params.amount <= 0) {
@@ -3946,6 +4269,23 @@ async function readMerkleTreeState(connection, merkleTreePDA, forceConfirmed = f
3946
4269
  const finalRoot = root || rpcRoot;
3947
4270
  return { nextIndex, root: finalRoot, subtrees };
3948
4271
  }
4272
+ function nearTipProofUndecidableLevels(leafIndex, nextIndex, height = MERKLE_TREE_HEIGHT) {
4273
+ if (!Number.isInteger(leafIndex) || !Number.isInteger(nextIndex) || !Number.isInteger(height)) {
4274
+ throw new Error(`nearTipProofUndecidableLevels: integers required (leafIndex=${leafIndex}, nextIndex=${nextIndex}, height=${height})`);
4275
+ }
4276
+ if (leafIndex < 0 || leafIndex >= nextIndex) {
4277
+ throw new Error(`Leaf index ${leafIndex} is not below next_index ${nextIndex}`);
4278
+ }
4279
+ const levels = [];
4280
+ for (let level = 0; level < height; level++) {
4281
+ const width = 2 ** level;
4282
+ const ancestor = Math.floor(leafIndex / width);
4283
+ if (ancestor % 2 === 1 && (ancestor + 1) * width < nextIndex) {
4284
+ levels.push(level);
4285
+ }
4286
+ }
4287
+ return levels;
4288
+ }
3949
4289
  async function computeProofFromChain(connection, merkleTreePDA, leafIndex, forceConfirmed = false) {
3950
4290
  assertAllowedRpcConnection(connection);
3951
4291
  await ensureZeroValues();
@@ -3978,7 +4318,12 @@ async function computeProofFromChain(connection, merkleTreePDA, leafIndex, force
3978
4318
  }
3979
4319
  index = Math.floor(index / 2);
3980
4320
  }
3981
- return { pathElements, pathIndices, root };
4321
+ return {
4322
+ pathElements,
4323
+ pathIndices,
4324
+ root,
4325
+ undecidableLevels: nearTipProofUndecidableLevels(leafIndex, nextIndex)
4326
+ };
3982
4327
  }
3983
4328
  async function computeProofForLatestDeposit(connection, merkleTreePDA) {
3984
4329
  assertAllowedRpcConnection(connection);
@@ -3989,7 +4334,7 @@ async function computeProofForLatestDeposit(connection, merkleTreePDA) {
3989
4334
  }
3990
4335
  const leafIndex = nextIndex - 1;
3991
4336
  const proof = await computeProofInternal(leafIndex, nextIndex, subtrees);
3992
- return { ...proof, root, leafIndex };
4337
+ return { ...proof, root, leafIndex, undecidableLevels: [] };
3993
4338
  }
3994
4339
  async function computeProofInternal(leafIndex, _nextIndex, subtrees) {
3995
4340
  const pathElements = [];
@@ -4188,7 +4533,7 @@ async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4188
4533
  }
4189
4534
 
4190
4535
  // src/relay/client.ts
4191
- var import_web37 = require("@solana/web3.js");
4536
+ var import_web39 = require("@solana/web3.js");
4192
4537
  var import_bs58 = __toESM(require("bs58"), 1);
4193
4538
 
4194
4539
  // src/notes/refund-leaf.ts
@@ -4297,6 +4642,9 @@ function isBrowserLike() {
4297
4642
  return typeof globalThis !== "undefined" && (typeof globalThis.window !== "undefined" || typeof globalThis.document !== "undefined");
4298
4643
  }
4299
4644
 
4645
+ // src/config/transaction-version.ts
4646
+ var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
4647
+
4300
4648
  // src/relay/client.ts
4301
4649
  var bs58 = import_bs58.default.default || import_bs58.default;
4302
4650
  var TRANSACT_TAG = 0;
@@ -4305,7 +4653,7 @@ var CLOSE_SWAP_STATE_TAG = 13;
4305
4653
  var CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN = 40;
4306
4654
  var CLOSE_SWAP_STATE_PHASE1_WIRE_LEN = 1 + CLOSE_SWAP_STATE_PHASE1_PAYLOAD_LEN;
4307
4655
  var CLOSE_SWAP_STATE_COMMITMENT_END = 1 + 32;
4308
- var NATIVE_SOL_MINT2 = new import_web37.PublicKey("So11111111111111111111111111111111111111112");
4656
+ var NATIVE_SOL_MINT2 = new import_web39.PublicKey("So11111111111111111111111111111111111111112");
4309
4657
  var PROOF_LEN = 256;
4310
4658
  var PUBLIC_INPUTS_LEN = 264;
4311
4659
  var COMMITMENTS_OFFSET = 168;
@@ -4321,7 +4669,7 @@ async function fetchWithRetry(url, options = {}) {
4321
4669
  const {
4322
4670
  timeoutMs = DEFAULT_TIMEOUT_MS,
4323
4671
  maxRetries = DEFAULT_MAX_RETRIES,
4324
- retryDelayMs = 1e3
4672
+ retryDelayMs: retryDelayMs2 = 1e3
4325
4673
  } = options;
4326
4674
  assertAllowedRelayOrigin(url);
4327
4675
  let lastError = null;
@@ -4345,7 +4693,7 @@ async function fetchWithRetry(url, options = {}) {
4345
4693
  `Relay request failed after ${attempt + 1} attempts: ${lastError.message}`
4346
4694
  );
4347
4695
  }
4348
- const delay = retryDelayMs * Math.pow(2, attempt) + Math.random() * 500;
4696
+ const delay = retryDelayMs2 * Math.pow(2, attempt) + Math.random() * 500;
4349
4697
  await new Promise((resolve) => setTimeout(resolve, delay));
4350
4698
  }
4351
4699
  }
@@ -4508,7 +4856,7 @@ async function buildMerkleTreeFromChain(connection, programId, merkleTree, onPro
4508
4856
  }
4509
4857
  const signature = signatures[i];
4510
4858
  const tx = await connection.getParsedTransaction(signature, {
4511
- maxSupportedTransactionVersion: 0,
4859
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION,
4512
4860
  commitment: "confirmed"
4513
4861
  });
4514
4862
  if (!tx || tx.meta?.err) continue;
@@ -4594,7 +4942,7 @@ async function preflightCheck(relayUrl, rootHex) {
4594
4942
  }
4595
4943
 
4596
4944
  // src/flows/transact.ts
4597
- var import_web39 = require("@solana/web3.js");
4945
+ var import_web311 = require("@solana/web3.js");
4598
4946
  var import_spl_token = require("@solana/spl-token");
4599
4947
  var snarkjs = __toESM(require("snarkjs"), 1);
4600
4948
  init_utxo();
@@ -4822,7 +5170,7 @@ function chainNoteFromBase64(base64) {
4822
5170
  }
4823
5171
 
4824
5172
  // src/notes/delivery-note.ts
4825
- var import_tweetnacl4 = __toESM(require("tweetnacl"), 1);
5173
+ var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
4826
5174
  var RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN = 32;
4827
5175
  var RECIPIENT_DELIVERY_NONCE_LEN = 24;
4828
5176
  var RECIPIENT_DELIVERY_PLAINTEXT_LEN = 40;
@@ -4873,10 +5221,10 @@ function encodeRecipientDeliveryNote(note, recipientViewingPublicKey) {
4873
5221
  const plaintext = new Uint8Array(RECIPIENT_DELIVERY_PLAINTEXT_LEN);
4874
5222
  writeU64LE2(plaintext, 0, note.amount);
4875
5223
  writeU256BE2(plaintext, 8, note.blinding);
4876
- const ephemeral = import_tweetnacl4.default.box.keyPair();
4877
- const shared = import_tweetnacl4.default.box.before(recipientViewingPublicKey, ephemeral.secretKey);
4878
- const nonce = import_tweetnacl4.default.randomBytes(import_tweetnacl4.default.secretbox.nonceLength);
4879
- const ciphertext = import_tweetnacl4.default.secretbox(plaintext, nonce, shared);
5224
+ const ephemeral = import_tweetnacl5.default.box.keyPair();
5225
+ const shared = import_tweetnacl5.default.box.before(recipientViewingPublicKey, ephemeral.secretKey);
5226
+ const nonce = import_tweetnacl5.default.randomBytes(import_tweetnacl5.default.secretbox.nonceLength);
5227
+ const ciphertext = import_tweetnacl5.default.secretbox(plaintext, nonce, shared);
4880
5228
  if (ciphertext.length !== RECIPIENT_DELIVERY_CIPHERTEXT_LEN) {
4881
5229
  throw new Error(
4882
5230
  `delivery ciphertext must be ${RECIPIENT_DELIVERY_CIPHERTEXT_LEN} bytes, got ${ciphertext.length}`
@@ -4902,8 +5250,8 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4902
5250
  const ciphertext = envelope.slice(
4903
5251
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
4904
5252
  );
4905
- const shared = import_tweetnacl4.default.box.before(ephemeralPk, viewingSecretKey);
4906
- const plaintext = import_tweetnacl4.default.secretbox.open(ciphertext, nonce, shared);
5253
+ const shared = import_tweetnacl5.default.box.before(ephemeralPk, viewingSecretKey);
5254
+ const plaintext = import_tweetnacl5.default.secretbox.open(ciphertext, nonce, shared);
4907
5255
  if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
4908
5256
  return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
4909
5257
  } catch {
@@ -4961,7 +5309,7 @@ function parseDeliveryCarrierMemo(data) {
4961
5309
 
4962
5310
  // src/notes/swap-refund.ts
4963
5311
  var import_blake34 = require("@noble/hashes/blake3");
4964
- var import_web38 = require("@solana/web3.js");
5312
+ var import_web310 = require("@solana/web3.js");
4965
5313
  var import_bs582 = __toESM(require("bs58"), 1);
4966
5314
  init_utxo();
4967
5315
  init_inputs();
@@ -5108,7 +5456,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5108
5456
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5109
5457
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5110
5458
  const programIdBase58 = programId.toBase58();
5111
- const [pool] = import_web38.PublicKey.findProgramAddressSync(
5459
+ const [pool] = import_web310.PublicKey.findProgramAddressSync(
5112
5460
  [Buffer.from("pool"), poolMint.toBuffer()],
5113
5461
  programId
5114
5462
  );
@@ -5142,7 +5490,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5142
5490
  try {
5143
5491
  return await connection.getTransaction(signature, {
5144
5492
  commitment: "confirmed",
5145
- maxSupportedTransactionVersion: 0
5493
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
5146
5494
  });
5147
5495
  } catch {
5148
5496
  return null;
@@ -5159,7 +5507,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5159
5507
  if (data[0] !== TRANSACT_SWAP_TAG2 || data.length < MIN_TRANSACT_SWAP_LEN) continue;
5160
5508
  const nullifier = data.slice(NULLIFIER_0_OFFSET, NULLIFIER_0_OFFSET + 32);
5161
5509
  if (nullifier.length !== 32) continue;
5162
- const [swapState] = import_web38.PublicKey.findProgramAddressSync(
5510
+ const [swapState] = import_web310.PublicKey.findProgramAddressSync(
5163
5511
  [Buffer.from("swap_state"), pool.toBuffer(), Buffer.from(nullifier)],
5164
5512
  programId
5165
5513
  );
@@ -5389,229 +5737,6 @@ async function matchChangeNote(params) {
5389
5737
  // src/flows/transact.ts
5390
5738
  var import_circomlibjs4 = require("circomlibjs");
5391
5739
  var import_tweetnacl6 = __toESM(require("tweetnacl"), 1);
5392
-
5393
- // src/relay/payload.ts
5394
- var import_sha23 = require("@noble/hashes/sha2");
5395
- var import_utils = require("@noble/hashes/utils");
5396
- var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
5397
- init_inputs();
5398
- var REQUEST_AUTH_DOMAIN = "CLOAK_RELAY_REQUEST_AUTH_V1";
5399
- var REQUEST_AUTH_MAX_AGE_SECONDS = 300;
5400
- var REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
5401
- var RELAY_AUTH_APPROVAL_MARGIN_SECONDS = 15;
5402
- function sha256Hex(text) {
5403
- return (0, import_utils.bytesToHex)((0, import_sha23.sha256)(new TextEncoder().encode(text)));
5404
- }
5405
- function randomNonceUuid() {
5406
- const webCrypto = globalThis?.crypto;
5407
- if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
5408
- const proc = globalThis?.process;
5409
- const nodeCrypto = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule("node:crypto") : void 0;
5410
- if (typeof nodeCrypto?.randomUUID === "function") return nodeCrypto.randomUUID();
5411
- const bytes = randomBytes(16);
5412
- bytes[6] = bytes[6] & 15 | 64;
5413
- bytes[8] = bytes[8] & 63 | 128;
5414
- const hex = (0, import_utils.bytesToHex)(bytes);
5415
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
5416
- }
5417
- var TRANSACT_AUTH_FIELDS = [
5418
- "encrypted_notes",
5419
- "max_fee",
5420
- "mint",
5421
- "proof_bytes",
5422
- "public_inputs",
5423
- "recipient",
5424
- "recipient_delivery_notes",
5425
- "risk_quote",
5426
- "sender"
5427
- ];
5428
- var TRANSACT_SWAP_AUTH_FIELDS = [
5429
- "close_timed_out",
5430
- "dexes",
5431
- "encrypted_notes",
5432
- "exclude_dexes",
5433
- "max_fee",
5434
- "min_output_amount",
5435
- "output_mint",
5436
- "proof_bytes",
5437
- "public_inputs",
5438
- "recipient",
5439
- "recipient_ata",
5440
- "refund_blinding",
5441
- "refund_pubkey",
5442
- "retry_request_id",
5443
- "risk_quote",
5444
- "route_retry_attempts",
5445
- "sender",
5446
- "slippage_bps",
5447
- "swap_max_retries"
5448
- ];
5449
- var UTF8 = new TextEncoder();
5450
- function compareKeysBytewise(a, b) {
5451
- if (a === b) return 0;
5452
- const ab = UTF8.encode(a);
5453
- const bb = UTF8.encode(b);
5454
- const shared = Math.min(ab.length, bb.length);
5455
- for (let i = 0; i < shared; i++) {
5456
- if (ab[i] !== bb[i]) return ab[i] - bb[i];
5457
- }
5458
- return ab.length - bb.length;
5459
- }
5460
- function canonicalJson(value) {
5461
- if (value === null || value === void 0) return "null";
5462
- if (typeof value === "boolean") return value ? "true" : "false";
5463
- if (typeof value === "number") {
5464
- if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
5465
- throw new Error(
5466
- `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.`
5467
- );
5468
- }
5469
- return String(value);
5470
- }
5471
- if (typeof value === "bigint") return value.toString();
5472
- if (typeof value === "string") return JSON.stringify(value);
5473
- if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
5474
- if (typeof value === "object") {
5475
- const obj = value;
5476
- const keys = Object.keys(obj).sort(compareKeysBytewise);
5477
- return "{" + keys.map((k) => {
5478
- const v = obj[k];
5479
- if (typeof v === "function" || typeof v === "symbol") {
5480
- throw new Error(
5481
- `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.`
5482
- );
5483
- }
5484
- return `${JSON.stringify(k)}:${canonicalJson(v)}`;
5485
- }).join(",") + "}";
5486
- }
5487
- throw new Error(`canonicalJson: unsupported value of type ${typeof value}`);
5488
- }
5489
- var FIELDS_WITHOUT_NULL_ENCODING = {
5490
- slippage_bps: "500 (`default_slippage_bps` in api/transact_swap.rs)"
5491
- };
5492
- function buildAuthRequest(body, sender, fields) {
5493
- const out = {};
5494
- for (const k of fields) {
5495
- if (k === "sender") {
5496
- out[k] = sender;
5497
- continue;
5498
- }
5499
- const value = body[k];
5500
- if (value === void 0 || value === null) {
5501
- const relayDefault = FIELDS_WITHOUT_NULL_ENCODING[k];
5502
- if (relayDefault) {
5503
- throw new Error(
5504
- `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.`
5505
- );
5506
- }
5507
- out[k] = null;
5508
- continue;
5509
- }
5510
- out[k] = value;
5511
- }
5512
- return out;
5513
- }
5514
- function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
5515
- const digest = sha256Hex(canonicalJson(request));
5516
- return new TextEncoder().encode(
5517
- `${REQUEST_AUTH_DOMAIN}
5518
- ${endpoint}
5519
- ${programId.toBase58()}
5520
- ${nonce}
5521
- ${issuedAt}
5522
- ${digest}`
5523
- );
5524
- }
5525
- function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
5526
- const senderB58 = sender.toBase58();
5527
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
5528
- const nonce = randomNonceUuid();
5529
- const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
5530
- const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
5531
- return { sender: senderB58, auth_issued_at: issuedAt, auth_nonce: nonce, message };
5532
- }
5533
- function signRelayRequest(endpoint, programId, body, signer, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
5534
- const preimage = buildRelayAuthPreimage(
5535
- endpoint,
5536
- programId,
5537
- body,
5538
- signer.publicKey,
5539
- nowSeconds,
5540
- fields
5541
- );
5542
- const signature = import_tweetnacl5.default.sign.detached(preimage.message, signer.secretKey);
5543
- return {
5544
- sender: preimage.sender,
5545
- auth_issued_at: preimage.auth_issued_at,
5546
- auth_nonce: preimage.auth_nonce,
5547
- auth_signature: Buffer.from(signature).toString("base64")
5548
- };
5549
- }
5550
- function assertApprovalWithinFreshnessWindow(elapsedMs) {
5551
- const elapsedSeconds = elapsedMs / 1e3;
5552
- const budget = REQUEST_AUTH_MAX_AGE_SECONDS - RELAY_AUTH_APPROVAL_MARGIN_SECONDS;
5553
- if (elapsedSeconds <= budget) return;
5554
- throw new Error(
5555
- `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.`
5556
- );
5557
- }
5558
- function explainRelayAuthRejection(responseText) {
5559
- const text = String(responseText);
5560
- const has = (needle) => text.includes(needle);
5561
- if (has("issued too far in the future")) {
5562
- 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.`;
5563
- }
5564
- if (has("signature expired")) {
5565
- 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.`;
5566
- }
5567
- if (has("does not match the exact request")) {
5568
- 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\`.`;
5569
- }
5570
- if (has("has no registered viewing key")) {
5571
- 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.`;
5572
- }
5573
- if (has("Authenticated sender is required") || has("auth_issued_at is required") || has("auth_nonce is required") || has("auth_signature is required")) {
5574
- return `The request reached the relay without its authentication fields. Pass \`depositorKeypair\`, or \`signMessage\` together with \`walletPublicKey\`, so the request can be signed.`;
5575
- }
5576
- if (has("auth_nonce must be a canonical UUID")) {
5577
- return `\`auth_nonce\` must be a canonical lowercase UUID. Reuse the one from the preimage.`;
5578
- }
5579
- if (has("Relay request signature must be exactly 64 bytes") || has("Invalid relay request signature encoding")) {
5580
- 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.`;
5581
- }
5582
- return null;
5583
- }
5584
- async function buildRelayAuthFields(endpoint, programId, body, signers, fields = TRANSACT_AUTH_FIELDS) {
5585
- if (signers.depositorKeypair) {
5586
- return signRelayRequest(endpoint, programId, body, signers.depositorKeypair, void 0, fields);
5587
- }
5588
- const wallet = signers.relayAuthSigner;
5589
- if (!wallet) return null;
5590
- const preimage = buildRelayAuthPreimage(
5591
- endpoint,
5592
- programId,
5593
- body,
5594
- wallet.walletPublicKey,
5595
- void 0,
5596
- fields
5597
- );
5598
- const approvalStartedMs = Date.now();
5599
- const signature = await wallet.signMessage(preimage.message);
5600
- assertApprovalWithinFreshnessWindow(Date.now() - approvalStartedMs);
5601
- if (!(signature instanceof Uint8Array) || signature.length !== 64) {
5602
- throw new Error(
5603
- `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.`
5604
- );
5605
- }
5606
- return {
5607
- sender: preimage.sender,
5608
- auth_issued_at: preimage.auth_issued_at,
5609
- auth_nonce: preimage.auth_nonce,
5610
- auth_signature: Buffer.from(signature).toString("base64")
5611
- };
5612
- }
5613
-
5614
- // src/flows/transact.ts
5615
5740
  init_inputs();
5616
5741
 
5617
5742
  // src/proving/artifacts.ts
@@ -5889,6 +6014,7 @@ async function resolveTransactionCircuitFiles() {
5889
6014
  }
5890
6015
  var _transactPaddingSaltCounter = 0;
5891
6016
  var _registeredViewingKeys = /* @__PURE__ */ new Set();
6017
+ var _viewingKeyRegistrationsInFlight = /* @__PURE__ */ new Map();
5892
6018
  var _resolvedAltAccountsCache = /* @__PURE__ */ new Map();
5893
6019
  var _relayMerkleDisabledMints = /* @__PURE__ */ new Set();
5894
6020
  var _relayMerkleFallbackNotifiedMints = /* @__PURE__ */ new Set();
@@ -6013,7 +6139,7 @@ async function fetchSupplementalAltFromRelay(relayUrl, params) {
6013
6139
  throw new Error("Supplemental ALT response is missing a 'table' address");
6014
6140
  }
6015
6141
  try {
6016
- return new import_web39.PublicKey(table);
6142
+ return new import_web311.PublicKey(table);
6017
6143
  } catch {
6018
6144
  throw new Error(`Supplemental ALT response 'table' is not a valid public key: ${table}`);
6019
6145
  }
@@ -6081,7 +6207,7 @@ async function resolveAddressLookupTableAccounts(connection, relayUrl, altAddres
6081
6207
  const fetched = await Promise.all(
6082
6208
  altAddresses.map(async (addr) => {
6083
6209
  try {
6084
- const pubkey = new import_web39.PublicKey(addr);
6210
+ const pubkey = new import_web311.PublicKey(addr);
6085
6211
  const result = await connection.getAddressLookupTable(pubkey);
6086
6212
  return result.value ?? null;
6087
6213
  } catch {
@@ -6171,7 +6297,7 @@ function calculateConfiguredProtocolFee(amount, config) {
6171
6297
  return total;
6172
6298
  }
6173
6299
  async function readLiveProtocolFee(connection, programId, mint, amount, requireSwapOpen = false) {
6174
- const [poolConfigPda] = import_web39.PublicKey.findProgramAddressSync(
6300
+ const [poolConfigPda] = import_web311.PublicKey.findProgramAddressSync(
6175
6301
  [Buffer.from("pool_config"), mint.toBuffer()],
6176
6302
  programId
6177
6303
  );
@@ -6293,6 +6419,26 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6293
6419
  if (_registeredViewingKeys.has(cacheKey)) {
6294
6420
  return;
6295
6421
  }
6422
+ const inFlight = _viewingKeyRegistrationsInFlight.get(cacheKey);
6423
+ if (inFlight) {
6424
+ return inFlight;
6425
+ }
6426
+ const registration = registerViewingKeyOnce(
6427
+ relayUrl,
6428
+ userPubkey,
6429
+ viewingKeyHex,
6430
+ cacheKey,
6431
+ options,
6432
+ onProgress
6433
+ );
6434
+ _viewingKeyRegistrationsInFlight.set(cacheKey, registration);
6435
+ try {
6436
+ await registration;
6437
+ } finally {
6438
+ _viewingKeyRegistrationsInFlight.delete(cacheKey);
6439
+ }
6440
+ }
6441
+ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cacheKey, options, onProgress) {
6296
6442
  const challengeResponse = await relayFetch(`${relayUrl}/viewing-key/challenge`, {
6297
6443
  method: "POST",
6298
6444
  headers: { "Content-Type": "application/json" },
@@ -6313,17 +6459,27 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6313
6459
  viewingKeyHex
6314
6460
  );
6315
6461
  let signatureBase64;
6462
+ let authMode = "message";
6463
+ const messageBytes = new TextEncoder().encode(challenge.message);
6316
6464
  if (options.signMessage) {
6317
- const messageBytes = new TextEncoder().encode(challenge.message);
6318
6465
  const sig = await options.signMessage(messageBytes);
6319
6466
  signatureBase64 = Buffer.from(sig).toString("base64");
6320
6467
  } else if (options.depositorKeypair) {
6321
- const messageBytes = new TextEncoder().encode(challenge.message);
6322
6468
  const sig = import_tweetnacl6.default.sign.detached(messageBytes, options.depositorKeypair.secretKey);
6323
6469
  signatureBase64 = Buffer.from(sig).toString("base64");
6470
+ } else if (options.signAuthTransaction) {
6471
+ onProgress?.(
6472
+ "Approve the viewing-key registration in your wallet. It shows as a 0 SOL transfer to yourself and is never sent to the network."
6473
+ );
6474
+ const signed = await signRelayAuthPayload(
6475
+ { walletPublicKey: userPubkey, signAuthTransaction: options.signAuthTransaction },
6476
+ messageBytes
6477
+ );
6478
+ signatureBase64 = Buffer.from(signed.signature).toString("base64");
6479
+ authMode = signed.mode;
6324
6480
  } else {
6325
6481
  throw new Error(
6326
- "Viewing key registration is mandatory: signMessage (wallet) or depositorKeypair is required."
6482
+ "Viewing key registration is mandatory: signMessage or signAuthTransaction (wallet) or depositorKeypair is required."
6327
6483
  );
6328
6484
  }
6329
6485
  onProgress?.("Registering viewing key...");
@@ -6334,7 +6490,8 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6334
6490
  user_pubkey: userPubkey.toBase58(),
6335
6491
  viewing_key: viewingKeyHex,
6336
6492
  nonce: challenge.nonce,
6337
- signature: signatureBase64
6493
+ signature: signatureBase64,
6494
+ ...authMode === "transaction" ? { auth_mode: authMode } : {}
6338
6495
  })
6339
6496
  });
6340
6497
  if (!response.ok) {
@@ -6428,7 +6585,7 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6428
6585
  var TRANSACT_DISCRIMINATOR = 0;
6429
6586
  var RANGE_QUOTE_TAG_DEPOSIT = 1;
6430
6587
  function deriveRiskNoncePDA(programId, nonce) {
6431
- return import_web39.PublicKey.findProgramAddressSync(
6588
+ return import_web311.PublicKey.findProgramAddressSync(
6432
6589
  [Buffer.from("risk_nonce"), Buffer.from(nonce)],
6433
6590
  programId
6434
6591
  );
@@ -6447,7 +6604,7 @@ function extractDepositNonceFromEd25519Ix(ix) {
6447
6604
  }
6448
6605
  }
6449
6606
  function deriveNullifierPDA(programId, poolPDA, nullifier) {
6450
- return import_web39.PublicKey.findProgramAddressSync(
6607
+ return import_web311.PublicKey.findProgramAddressSync(
6451
6608
  [Buffer.from("nullifier"), poolPDA.toBuffer(), Buffer.from(nullifier)],
6452
6609
  programId
6453
6610
  );
@@ -6480,7 +6637,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6480
6637
  }
6481
6638
  if (!isDepositData) {
6482
6639
  data[offset++] = 3;
6483
- data.set((relayer ?? import_web39.PublicKey.default).toBytes(), offset);
6640
+ data.set((relayer ?? import_web311.PublicKey.default).toBytes(), offset);
6484
6641
  offset += 32;
6485
6642
  writeBigUInt64LE(data, relayerFee ?? BigInt(0), offset);
6486
6643
  offset += 8;
@@ -6510,7 +6667,7 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6510
6667
  // 4. nullifier PDA 0 (writable)
6511
6668
  { pubkey: nullifierPDA1, isSigner: false, isWritable: true },
6512
6669
  // 5. nullifier PDA 1 (writable)
6513
- { pubkey: import_web39.SystemProgram.programId, isSigner: false, isWritable: false }
6670
+ { pubkey: import_web311.SystemProgram.programId, isSigner: false, isWritable: false }
6514
6671
  // 6. system_program
6515
6672
  ];
6516
6673
  if (splAccounts) {
@@ -6519,34 +6676,34 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6519
6676
  accounts.push({ pubkey: splAccounts.tokenProgram, isSigner: false, isWritable: false });
6520
6677
  if (splAccounts.payerAta) {
6521
6678
  if (enableRiskCheck) {
6522
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6679
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6523
6680
  }
6524
6681
  accounts.push({ pubkey: splAccounts.payerAta, isSigner: false, isWritable: true });
6525
6682
  if (riskNonce) {
6526
6683
  accounts.push({ pubkey: riskNonce, isSigner: false, isWritable: true });
6527
6684
  }
6528
6685
  } else if (enableRiskCheck && !recipient) {
6529
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6686
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6530
6687
  }
6531
6688
  } else {
6532
6689
  if (recipient) {
6533
6690
  accounts.push({ pubkey: recipient, isSigner: false, isWritable: true });
6534
6691
  if (enableRiskCheck) {
6535
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6692
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6536
6693
  }
6537
6694
  } else if (enableRiskCheck) {
6538
6695
  if (publicAmountForAccounts === BigInt(0)) {
6539
6696
  accounts.push({ pubkey: payer, isSigner: true, isWritable: false });
6540
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6697
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6541
6698
  } else {
6542
- accounts.push({ pubkey: import_web39.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6699
+ accounts.push({ pubkey: import_web311.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false });
6543
6700
  if (riskNonce) {
6544
6701
  accounts.push({ pubkey: riskNonce, isSigner: false, isWritable: true });
6545
6702
  }
6546
6703
  }
6547
6704
  }
6548
6705
  }
6549
- return new import_web39.TransactionInstruction({
6706
+ return new import_web311.TransactionInstruction({
6550
6707
  programId,
6551
6708
  keys: accounts,
6552
6709
  data
@@ -6555,10 +6712,10 @@ function buildTransactInstruction(programId, payer, poolPDA, treasuryPDA, merkle
6555
6712
  var PACKET_LIMIT_BYTES = 1232;
6556
6713
  function getCommonALTAddresses() {
6557
6714
  return [
6558
- import_web39.SystemProgram.programId,
6559
- import_web39.SYSVAR_SLOT_HASHES_PUBKEY,
6560
- import_web39.SYSVAR_INSTRUCTIONS_PUBKEY,
6561
- import_web39.ComputeBudgetProgram.programId
6715
+ import_web311.SystemProgram.programId,
6716
+ import_web311.SYSVAR_SLOT_HASHES_PUBKEY,
6717
+ import_web311.SYSVAR_INSTRUCTIONS_PUBKEY,
6718
+ import_web311.ComputeBudgetProgram.programId
6562
6719
  ];
6563
6720
  }
6564
6721
  function dedupePubkeys(addresses) {
@@ -6609,12 +6766,12 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
6609
6766
  try {
6610
6767
  const slot = await connection.getSlot("finalized");
6611
6768
  const altPayerPubkey = externalFeePayer ? await externalFeePayer.getPayerPubkey() : depositor.publicKey;
6612
- const [createIx, altAddress] = import_web39.AddressLookupTableProgram.createLookupTable({
6769
+ const [createIx, altAddress] = import_web311.AddressLookupTableProgram.createLookupTable({
6613
6770
  authority: depositor.publicKey,
6614
6771
  payer: altPayerPubkey,
6615
6772
  recentSlot: slot
6616
6773
  });
6617
- const extendIx = import_web39.AddressLookupTableProgram.extendLookupTable({
6774
+ const extendIx = import_web311.AddressLookupTableProgram.extendLookupTable({
6618
6775
  payer: altPayerPubkey,
6619
6776
  authority: depositor.publicKey,
6620
6777
  lookupTable: altAddress,
@@ -6633,12 +6790,12 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
6633
6790
  allowSupplementalAlt
6634
6791
  );
6635
6792
  } else {
6636
- const tx = new import_web39.Transaction().add(createIx).add(extendIx);
6793
+ const tx = new import_web311.Transaction().add(createIx).add(extendIx);
6637
6794
  const { blockhash } = await connection.getLatestBlockhash();
6638
6795
  tx.recentBlockhash = blockhash;
6639
6796
  tx.feePayer = depositor.publicKey;
6640
6797
  if (depositor.keypair) {
6641
- await (0, import_web39.sendAndConfirmTransaction)(connection, tx, [depositor.keypair], { commitment: "confirmed" });
6798
+ await (0, import_web311.sendAndConfirmTransaction)(connection, tx, [depositor.keypair], { commitment: "confirmed" });
6642
6799
  } else if (depositor.signTransaction) {
6643
6800
  const signedTx = await depositor.signTransaction(tx);
6644
6801
  const sig = await connection.sendRawTransaction(signedTx.serialize());
@@ -6677,7 +6834,7 @@ async function createEphemeralALT(connection, depositor, onProgress, additionalA
6677
6834
  var SOLANA_PACKET_DATA_SIZE = 1232;
6678
6835
  function estimateV0TransactionSize(payerKey, recentBlockhash, instructions, addressLookupTableAccounts) {
6679
6836
  try {
6680
- const messageV0 = new import_web39.TransactionMessage({
6837
+ const messageV0 = new import_web311.TransactionMessage({
6681
6838
  payerKey,
6682
6839
  recentBlockhash,
6683
6840
  instructions
@@ -6746,7 +6903,7 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6746
6903
  const { blockhash: quoteBlockhash } = await connection.getLatestBlockhash();
6747
6904
  const measure = (instrs, alts) => {
6748
6905
  try {
6749
- const message = new import_web39.TransactionMessage({
6906
+ const message = new import_web311.TransactionMessage({
6750
6907
  payerKey: externalFeePayerPubkey,
6751
6908
  recentBlockhash: quoteBlockhash,
6752
6909
  instructions: instrs
@@ -6804,12 +6961,12 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6804
6961
  pre = measure(instructions, addressLookupTableAccounts);
6805
6962
  }
6806
6963
  failIfOverLimit(pre.size, pre.error);
6807
- const quoteMessage = new import_web39.TransactionMessage({
6964
+ const quoteMessage = new import_web311.TransactionMessage({
6808
6965
  payerKey: externalFeePayerPubkey,
6809
6966
  recentBlockhash: quoteBlockhash,
6810
6967
  instructions
6811
6968
  }).compileToV0Message(addressLookupTableAccounts ?? []);
6812
- const quoteTxBase64 = Buffer.from(new import_web39.VersionedTransaction(quoteMessage).serialize()).toString("base64");
6969
+ const quoteTxBase64 = Buffer.from(new import_web311.VersionedTransaction(quoteMessage).serialize()).toString("base64");
6813
6970
  const paymentInstruction = await externalFeePayer.getPaymentInstruction(quoteTxBase64);
6814
6971
  const finalInstructions = [...instructions, paymentInstruction];
6815
6972
  let post = measure(finalInstructions, addressLookupTableAccounts);
@@ -6820,12 +6977,12 @@ async function submitViaExternalFeePayer(connection, depositor, externalFeePayer
6820
6977
  failIfOverLimit(post.size, post.error);
6821
6978
  onProgress?.("Building final transaction...");
6822
6979
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
6823
- const finalMessage = new import_web39.TransactionMessage({
6980
+ const finalMessage = new import_web311.TransactionMessage({
6824
6981
  payerKey: externalFeePayerPubkey,
6825
6982
  recentBlockhash: blockhash,
6826
6983
  instructions: finalInstructions
6827
6984
  }).compileToV0Message(addressLookupTableAccounts ?? []);
6828
- const finalTx = new import_web39.VersionedTransaction(finalMessage);
6985
+ const finalTx = new import_web311.VersionedTransaction(finalMessage);
6829
6986
  onProgress?.("Waiting for wallet signature...");
6830
6987
  const partiallySignedTx = await depositor.signTransaction(finalTx);
6831
6988
  const partiallySignedBase64 = Buffer.from(partiallySignedTx.serialize()).toString("base64");
@@ -7046,8 +7203,8 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7046
7203
  baseInstructions.splice(riskQuoteIx ? 1 : 0, 0, ...topUpInstructions);
7047
7204
  }
7048
7205
  }
7049
- const cuLimitIx = import_web39.ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 });
7050
- const cuPriceIx = import_web39.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1e5 });
7206
+ const cuLimitIx = import_web311.ComputeBudgetProgram.setComputeUnitLimit({ units: 12e5 });
7207
+ const cuPriceIx = import_web311.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1e5 });
7051
7208
  const fullInstructions = [...baseInstructions, cuLimitIx, cuPriceIx, transactIx];
7052
7209
  const compactInstructions = [...baseInstructions, cuLimitIx, transactIx];
7053
7210
  const minimalInstructions = [...baseInstructions, cuLimitIx, transactIx];
@@ -7159,12 +7316,12 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7159
7316
  }
7160
7317
  let transportAttempt = 0;
7161
7318
  while (true) {
7162
- const messageV0 = new import_web39.TransactionMessage({
7319
+ const messageV0 = new import_web311.TransactionMessage({
7163
7320
  payerKey: depositor.publicKey,
7164
7321
  recentBlockhash: blockhash,
7165
7322
  instructions: ixs
7166
7323
  }).compileToV0Message(addressLookupTableAccounts);
7167
- const versionedTx = new import_web39.VersionedTransaction(messageV0);
7324
+ const versionedTx = new import_web311.VersionedTransaction(messageV0);
7168
7325
  if (onTransactProofBuilt) {
7169
7326
  await onTransactProofBuilt();
7170
7327
  }
@@ -7294,7 +7451,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7294
7451
  let legacyTransportAttempt = 0;
7295
7452
  while (true) {
7296
7453
  try {
7297
- const tx = new import_web39.Transaction();
7454
+ const tx = new import_web311.Transaction();
7298
7455
  for (const ix of instructions) {
7299
7456
  tx.add(ix);
7300
7457
  }
@@ -7302,7 +7459,7 @@ async function submitTransactionDirect(connection, programId, depositor, proofBy
7302
7459
  tx.feePayer = depositor.publicKey;
7303
7460
  if (depositor.keypair) {
7304
7461
  onProgress?.("Signing and sending transaction...");
7305
- signature = await (0, import_web39.sendAndConfirmTransaction)(
7462
+ signature = await (0, import_web311.sendAndConfirmTransaction)(
7306
7463
  connection,
7307
7464
  tx,
7308
7465
  [depositor.keypair],
@@ -7518,7 +7675,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
7518
7675
  const messageArr = hexToBytes2(messageHex);
7519
7676
  let signerPubkey;
7520
7677
  try {
7521
- signerPubkey = new import_web39.PublicKey(signerB58);
7678
+ signerPubkey = new import_web311.PublicKey(signerB58);
7522
7679
  } catch {
7523
7680
  throw new Error("Invalid risk quote response: signer_pubkey is not a public key");
7524
7681
  }
@@ -7542,7 +7699,7 @@ async function fetchRiskQuote(riskQuoteUrl, wallet, options) {
7542
7699
  const signature = new Uint8Array(signatureBuf);
7543
7700
  const message = new Uint8Array(messageArr);
7544
7701
  const publicKey = new Uint8Array(publicKeyBytes);
7545
- const instruction = import_web39.Ed25519Program.createInstructionWithPublicKey({
7702
+ const instruction = import_web311.Ed25519Program.createInstructionWithPublicKey({
7546
7703
  publicKey,
7547
7704
  message,
7548
7705
  signature
@@ -7619,18 +7776,22 @@ function planRelayAuth(options) {
7619
7776
  const walletPublicKey = resolveUserWallet(options);
7620
7777
  if (options.depositorKeypair) return { kind: "keypair" };
7621
7778
  const signMessage = options.signMessage;
7779
+ const signAuthTransaction = options.signAuthTransaction;
7622
7780
  if (walletPublicKey && signMessage) return { kind: "wallet", signer: { walletPublicKey, signMessage } };
7623
- if (!walletPublicKey && !signMessage) return { kind: "none" };
7781
+ if (walletPublicKey && signAuthTransaction) {
7782
+ return { kind: "wallet", signer: { walletPublicKey, signAuthTransaction } };
7783
+ }
7784
+ if (!walletPublicKey && !signMessage && !signAuthTransaction) return { kind: "none" };
7624
7785
  return {
7625
7786
  kind: "incomplete",
7626
- detail: signMessage ? "`signMessage` was provided but no wallet public key, so the request has no sender to authenticate as. Add `walletPublicKey` (or `depositorPublicKey`)." : "a wallet public key was provided but no `signMessage`, so nothing can sign. Add `signMessage` from the same wallet adapter."
7787
+ detail: signMessage || signAuthTransaction ? "a signer was provided but no wallet public key, so the request has no sender to authenticate as. Add `walletPublicKey` (or `depositorPublicKey`)." : "a wallet public key was provided but no `signMessage` and no `signAuthTransaction`, so nothing can sign. Add `signMessage` from the wallet adapter, or `signAuthTransaction` (its `signTransaction`) for a wallet that cannot sign messages."
7627
7788
  };
7628
7789
  }
7629
7790
  function assertRelayAuthAvailable(plan, flow) {
7630
7791
  if (plan.kind === "keypair" || plan.kind === "wallet") return;
7631
7792
  const cause = plan.kind === "none" ? "no signer was provided." : `the signer provided cannot produce one: ${plan.detail}`;
7632
7793
  throw new Error(
7633
- `Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local Keypair) or \`signMessage\` together with \`walletPublicKey\` (a browser wallet adapter). The sender must be the end user's own wallet. Checked before proof generation, so nothing has been computed or submitted yet.`
7794
+ `Cloak ${flow} requires an authenticated sender, and ${cause} Pass either \`depositorKeypair\` (a local Keypair), or \`signMessage\` (a browser wallet adapter) or \`signAuthTransaction\` (a hardware wallet that cannot sign messages) together with \`walletPublicKey\`. The sender must be the end user's own wallet. Checked up front, so nothing has been computed or submitted yet.`
7634
7795
  );
7635
7796
  }
7636
7797
  async function submitTransactToRelay(args) {
@@ -7648,12 +7809,12 @@ async function submitTransactToRelay(args) {
7648
7809
  const doFetch = args.fetchImpl ?? fetch;
7649
7810
  const maxNetworkRetries = args.maxNetworkRetries ?? relayNetworkRetries();
7650
7811
  const requestTimeoutMs = args.requestTimeoutMs ?? relayRequestTimeoutMs();
7651
- if (!depositorKeypair && args.relayAuthSigner) {
7812
+ if (!depositorKeypair && args.relayAuthSigner && !args.relayAuthBatch) {
7652
7813
  onProgress?.(
7653
7814
  "Approve the request in your wallet. This signs the request for the relay, not a transaction, and it must be approved within a few minutes to stay valid."
7654
7815
  );
7655
7816
  }
7656
- const authFields = await buildRelayAuthFields("/transact", programId, requestBody, {
7817
+ const authFields = args.relayAuthBatch ? await args.relayAuthBatch.authorize("/transact", programId, requestBody, TRANSACT_AUTH_FIELDS) : await buildRelayAuthFields("/transact", programId, requestBody, {
7657
7818
  depositorKeypair,
7658
7819
  relayAuthSigner: args.relayAuthSigner
7659
7820
  });
@@ -7849,7 +8010,7 @@ async function transact(params, options) {
7849
8010
  // names is refused.
7850
8011
  maxRootRetries = 40,
7851
8012
  // Increased to handle prolonged relay sync recovery under high concurrency
7852
- retryDelayMs = 500,
8013
+ retryDelayMs: retryDelayMs2 = 500,
7853
8014
  // Start with short delay, will exponentially back off
7854
8015
  riskOracleQueue,
7855
8016
  riskQuoteUrl: riskQuoteUrlOption,
@@ -8106,6 +8267,29 @@ async function transact(params, options) {
8106
8267
  "Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
8107
8268
  );
8108
8269
  }
8270
+ if (needsTreeForProof && treeState) {
8271
+ const tip = treeState.nextIndex;
8272
+ const unprovable = paddedInputs.filter((utxo) => {
8273
+ if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
8274
+ if (merkleTree && utxo.index < merkleTree.length) return false;
8275
+ if (utxo.index >= tip) return false;
8276
+ const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
8277
+ return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
8278
+ });
8279
+ if (unprovable.length > 0) {
8280
+ onProgress?.(
8281
+ `On-chain frontier can no longer prove leaf ${unprovable.map((u) => u.index).join(", ")} (a later leaf overwrote a frontier level on its path); rebuilding the full tree from chain...`
8282
+ );
8283
+ forceChainIndexing = true;
8284
+ try {
8285
+ merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, mint);
8286
+ } catch (e) {
8287
+ onProgress?.(
8288
+ `Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
8289
+ );
8290
+ }
8291
+ }
8292
+ }
8109
8293
  const merkleProofs = [];
8110
8294
  let resolvedRootHex = treeState?.root ?? "0";
8111
8295
  let proofRootHex = null;
@@ -8271,7 +8455,7 @@ async function transact(params, options) {
8271
8455
  while (submissionAttempts <= maxRootRetries) {
8272
8456
  const isRetry = submissionAttempts > 0;
8273
8457
  if (isRetry) {
8274
- const exponentialDelay = Math.min(retryDelayMs * Math.pow(1.5, submissionAttempts - 1), 5e3);
8458
+ const exponentialDelay = Math.min(retryDelayMs2 * Math.pow(1.5, submissionAttempts - 1), 5e3);
8275
8459
  const jitter = Math.random() * 500;
8276
8460
  const totalDelay = Math.floor(exponentialDelay + jitter);
8277
8461
  await sleep2(totalDelay);
@@ -8410,11 +8594,14 @@ async function transact(params, options) {
8410
8594
  }
8411
8595
  let proof;
8412
8596
  let publicSignals;
8597
+ const releaseProofSlot = options.relayAuthBatch ? await options.relayAuthBatch.proofSlot() : void 0;
8413
8598
  try {
8414
8599
  const result = await generateTransactionProof(circuitInputs, onProofProgress);
8415
8600
  proof = result.proof;
8416
8601
  publicSignals = result.publicSignals;
8602
+ releaseProofSlot?.();
8417
8603
  } catch (proofError) {
8604
+ releaseProofSlot?.();
8418
8605
  const errorMsg = proofError?.message || String(proofError);
8419
8606
  if ((errorMsg.includes("ForceEqual") || errorMsg.includes("Assert Failed")) && submissionAttempts < maxRootRetries) {
8420
8607
  onProgress?.(`Merkle proof error (stale sibling data), will regenerate with fresh tree...`);
@@ -8434,7 +8621,7 @@ async function transact(params, options) {
8434
8621
  }
8435
8622
  treeState = null;
8436
8623
  useSiblingInfo = false;
8437
- const waitMs = Math.min(retryDelayMs * Math.pow(2, Math.min(submissionAttempts, 4)), 5e3);
8624
+ const waitMs = Math.min(retryDelayMs2 * Math.pow(2, Math.min(submissionAttempts, 4)), 5e3);
8438
8625
  if (waitMs > 0) {
8439
8626
  onProgress?.(`Waiting ${waitMs}ms for relay sync before retry...`);
8440
8627
  await new Promise((r) => setTimeout(r, waitMs));
@@ -8727,6 +8914,7 @@ async function transact(params, options) {
8727
8914
  // point where they reach the relay submission instead of stopping at viewing-key
8728
8915
  // registration. The keypair still wins when both are present.
8729
8916
  relayAuthSigner: relayAuthPlan.kind === "wallet" ? relayAuthPlan.signer : void 0,
8917
+ relayAuthBatch: options.relayAuthBatch,
8730
8918
  settlement: {
8731
8919
  connection,
8732
8920
  programId,
@@ -8772,7 +8960,7 @@ async function transact(params, options) {
8772
8960
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
8773
8961
  );
8774
8962
  try {
8775
- const [merkleTreePda] = import_web39.PublicKey.findProgramAddressSync(
8963
+ const [merkleTreePda] = import_web311.PublicKey.findProgramAddressSync(
8776
8964
  [Buffer.from("merkle_tree"), mint.toBuffer()],
8777
8965
  programId
8778
8966
  );
@@ -9128,7 +9316,7 @@ async function swapUtxo(params, options) {
9128
9316
  riskQuoteUrl: riskQuoteUrlOption,
9129
9317
  maxRootRetries = 40,
9130
9318
  // Increased to handle prolonged relay sync recovery under high concurrency
9131
- retryDelayMs = 500,
9319
+ retryDelayMs: retryDelayMs2 = 500,
9132
9320
  // Start with short delay, will exponentially back off
9133
9321
  useUniqueNullifiers,
9134
9322
  useChainRootForProof = true
@@ -9386,6 +9574,29 @@ async function swapUtxo(params, options) {
9386
9574
  "Merkle tree unavailable from relay/indexer; using on-chain proof fallback (may require retries under high churn)"
9387
9575
  );
9388
9576
  }
9577
+ if (needsTreeForProof && merkleState) {
9578
+ const tip = merkleState.nextIndex;
9579
+ const unprovable = paddedInputs.filter((utxo) => {
9580
+ if (utxo.amount === BigInt(0) || utxo.index === void 0 || utxo.index < 0) return false;
9581
+ if (merkleTree && utxo.index < merkleTree.length) return false;
9582
+ if (utxo.index >= tip) return false;
9583
+ const canFillLevel0 = useSiblingInfo && (!!utxo.siblingCommitment || !!utxo.leftSiblingCommitment);
9584
+ return nearTipProofUndecidableLevels(utxo.index, tip).some((level) => level !== 0 || !canFillLevel0);
9585
+ });
9586
+ if (unprovable.length > 0) {
9587
+ onProgress?.(
9588
+ `On-chain frontier can no longer prove leaf ${unprovable.map((u) => u.index).join(", ")} (a later leaf overwrote a frontier level on its path); rebuilding the full tree from chain...`
9589
+ );
9590
+ forceChainIndexing = true;
9591
+ try {
9592
+ merkleTree = await buildMerkleTreeFromChain(connection, programId, pdas.merkleTree, onProgress, NATIVE_SOL_MINT);
9593
+ } catch (e) {
9594
+ onProgress?.(
9595
+ `Failed to rebuild the tree from chain (${e instanceof Error ? e.message : String(e)}); continuing with the on-chain proof fallback.`
9596
+ );
9597
+ }
9598
+ }
9599
+ }
9389
9600
  const merkleProofs = [];
9390
9601
  let resolvedRootHex = merkleState?.root ?? "0";
9391
9602
  let proofRootHex = null;
@@ -9539,7 +9750,7 @@ async function swapUtxo(params, options) {
9539
9750
  let walletApprovals = 0;
9540
9751
  for (let attempt = 0; attempt <= maxRootRetries; attempt++) {
9541
9752
  if (attempt > 0) {
9542
- const exponentialDelay = Math.min(retryDelayMs * Math.pow(1.5, attempt - 1), 5e3);
9753
+ const exponentialDelay = Math.min(retryDelayMs2 * Math.pow(1.5, attempt - 1), 5e3);
9543
9754
  const jitter = Math.random() * 500;
9544
9755
  const totalDelay = Math.floor(exponentialDelay + jitter);
9545
9756
  await sleep2(totalDelay);
@@ -9677,7 +9888,7 @@ async function swapUtxo(params, options) {
9677
9888
  }
9678
9889
  merkleState = null;
9679
9890
  useSiblingInfo = false;
9680
- const waitMs = Math.min(retryDelayMs * Math.pow(2, Math.min(attempt, 4)), 5e3);
9891
+ const waitMs = Math.min(retryDelayMs2 * Math.pow(2, Math.min(attempt, 4)), 5e3);
9681
9892
  if (waitMs > 0) {
9682
9893
  onProgress?.(`Waiting ${waitMs}ms for relay sync before retry...`);
9683
9894
  await new Promise((r) => setTimeout(r, waitMs));
@@ -9760,7 +9971,7 @@ async function swapUtxo(params, options) {
9760
9971
  }
9761
9972
  if (options.onSwapStatePredicted && inputNullifiers.length > 0) {
9762
9973
  const nBytes = bigintToBytes323(inputNullifiers[0]);
9763
- const [ssp] = import_web39.PublicKey.findProgramAddressSync(
9974
+ const [ssp] = import_web311.PublicKey.findProgramAddressSync(
9764
9975
  [Buffer.from("swap_state"), pdas.pool.toBuffer(), Buffer.from(nBytes)],
9765
9976
  programId
9766
9977
  );
@@ -10182,13 +10393,279 @@ function cleanupStalePendingOperations(maxAgeMs = 24 * 60 * 60 * 1e3) {
10182
10393
  // src/index.ts
10183
10394
  init_utxo();
10184
10395
 
10185
- // src/scanning/scan.ts
10186
- var import_bs583 = __toESM(require("bs58"), 1);
10187
- var import_web310 = require("@solana/web3.js");
10188
- var import_spl_token2 = require("@solana/spl-token");
10189
- init_inputs();
10190
- init_utxo();
10191
- var bs583 = import_bs583.default.default || import_bs583.default;
10396
+ // src/relay/batch-auth.ts
10397
+ var import_web312 = require("@solana/web3.js");
10398
+ var RelayBatchAuthCoordinator = class {
10399
+ constructor(options) {
10400
+ this.proofSlotsInUse = 0;
10401
+ this.proofQueue = [];
10402
+ this.items = [];
10403
+ this.signing = false;
10404
+ this.slotsInUse = 0;
10405
+ this.ready = [];
10406
+ this.waves = 0;
10407
+ if (!Number.isInteger(options.items) || options.items < 1) {
10408
+ throw new Error(`A batch needs at least one item (got ${options.items}).`);
10409
+ }
10410
+ if (options.items > RELAY_BATCH_AUTH_MAX_ITEMS) {
10411
+ throw new Error(
10412
+ `A batch may cover at most ${RELAY_BATCH_AUTH_MAX_ITEMS} requests (got ${options.items}); the relay refuses longer digest lists. Chunk the payout. The practical bound is lower still: each spend appends two roots to the on-chain ring of 100, so a batch proved against one root evicts it by itself before 50 items.`
10413
+ );
10414
+ }
10415
+ const concurrency = options.submitConcurrency ?? 3;
10416
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
10417
+ throw new Error(`submitConcurrency must be a positive integer (got ${concurrency}).`);
10418
+ }
10419
+ this.signer = options.signer;
10420
+ this.sender = options.signer instanceof import_web312.Keypair ? options.signer.publicKey : options.signer.walletPublicKey;
10421
+ this.expectedItems = options.items;
10422
+ this.submitConcurrency = concurrency;
10423
+ const proofConcurrency = options.proofConcurrency ?? 2;
10424
+ if (!Number.isInteger(proofConcurrency) || proofConcurrency < 1) {
10425
+ throw new Error(`proofConcurrency must be a positive integer (got ${proofConcurrency}).`);
10426
+ }
10427
+ this.proofConcurrency = proofConcurrency;
10428
+ this.onProgress = options.onProgress;
10429
+ }
10430
+ /** The wallet that signs and is every item's authenticated `sender`. */
10431
+ get walletPublicKey() {
10432
+ return this.sender;
10433
+ }
10434
+ /** How many times the signer has been asked so far: one per wave. */
10435
+ get approvals() {
10436
+ return this.waves;
10437
+ }
10438
+ /** Where every item is right now. For progress UIs and for diagnosing a batch that never signs. */
10439
+ snapshot() {
10440
+ const count = (state) => this.items.filter((i) => i.state === state).length;
10441
+ return {
10442
+ building: count("building"),
10443
+ waiting: count("waiting"),
10444
+ submitting: count("submitting"),
10445
+ done: count("done"),
10446
+ proving: this.proofSlotsInUse,
10447
+ proofQueue: this.proofQueue.length,
10448
+ registered: this.items.length,
10449
+ expected: this.expectedItems
10450
+ };
10451
+ }
10452
+ /** Register one item. Throws past `items`: the wave condition would never be reachable. */
10453
+ item() {
10454
+ if (this.items.length >= this.expectedItems) {
10455
+ throw new Error(
10456
+ `This batch was created for ${this.expectedItems} item(s) and all of them are registered.`
10457
+ );
10458
+ }
10459
+ const item = { state: "building", waiting: null, holdsSlot: false };
10460
+ this.items.push(item);
10461
+ return {
10462
+ proofSlot: () => this.acquireProofSlot(),
10463
+ authorize: (endpoint, programId, body, fields) => this.authorize(item, endpoint, programId, body, fields),
10464
+ finish: () => this.finish(item)
10465
+ };
10466
+ }
10467
+ acquireProofSlot() {
10468
+ return new Promise((resolve) => {
10469
+ const grant = () => {
10470
+ this.proofSlotsInUse += 1;
10471
+ let released = false;
10472
+ resolve(() => {
10473
+ if (released) return;
10474
+ released = true;
10475
+ this.proofSlotsInUse -= 1;
10476
+ const next = this.proofQueue.shift();
10477
+ if (next) next();
10478
+ });
10479
+ };
10480
+ if (this.proofSlotsInUse < this.proofConcurrency) grant();
10481
+ else this.proofQueue.push(grant);
10482
+ });
10483
+ }
10484
+ authorize(item, endpoint, programId, body, fields) {
10485
+ if (item.state === "done") {
10486
+ return Promise.reject(new Error("This batch item already finished; it cannot authorize."));
10487
+ }
10488
+ if (item.state === "waiting") {
10489
+ return Promise.reject(new Error("This batch item is already waiting for a signature."));
10490
+ }
10491
+ this.releaseSlot(item);
10492
+ return new Promise((resolve, reject) => {
10493
+ item.state = "waiting";
10494
+ item.waiting = { endpoint, programId, body, fields, resolve, reject };
10495
+ this.maybeSign();
10496
+ });
10497
+ }
10498
+ finish(item) {
10499
+ if (item.state === "done") return;
10500
+ if (item.state === "waiting" && item.waiting) {
10501
+ item.waiting.reject(new Error("Batch item finished before it was signed."));
10502
+ item.waiting = null;
10503
+ }
10504
+ this.releaseSlot(item);
10505
+ item.state = "done";
10506
+ this.maybeSign();
10507
+ this.pump();
10508
+ }
10509
+ releaseSlot(item) {
10510
+ if (!item.holdsSlot) return;
10511
+ item.holdsSlot = false;
10512
+ this.slotsInUse -= 1;
10513
+ }
10514
+ /** Sign when every registered item is either waiting here or finished, and nothing is building. */
10515
+ maybeSign() {
10516
+ if (this.signing) return;
10517
+ if (this.items.length < this.expectedItems) return;
10518
+ if (this.items.some((item) => item.state === "building" || item.state === "submitting")) return;
10519
+ const wave = this.items.filter((item) => item.state === "waiting");
10520
+ if (wave.length === 0) return;
10521
+ this.signing = true;
10522
+ void this.signWave(wave).finally(() => {
10523
+ this.signing = false;
10524
+ this.maybeSign();
10525
+ });
10526
+ }
10527
+ async signWave(wave) {
10528
+ const waiting = wave.map((item) => item.waiting);
10529
+ try {
10530
+ const programId = waiting[0].programId;
10531
+ for (const w of waiting) {
10532
+ if (!w.programId.equals(programId)) {
10533
+ throw new Error("Every item of a batch must target the same program id.");
10534
+ }
10535
+ }
10536
+ const nowSeconds = Math.floor(Date.now() / 1e3);
10537
+ const preimages = waiting.map(
10538
+ (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10539
+ );
10540
+ const digests = preimages.map(relayRequestDigestHex);
10541
+ const issuedAt = preimages[0].auth_issued_at;
10542
+ const message = buildRelayBatchAuthMessage(programId, issuedAt, digests);
10543
+ this.waves += 1;
10544
+ if (!(this.signer instanceof import_web312.Keypair)) {
10545
+ const asTransaction = !this.signer.signMessage;
10546
+ this.onProgress?.(
10547
+ `Approve ${waiting.length} request(s) in your wallet` + (this.waves > 1 ? ` (approval ${this.waves}, for the rows that had to re-prove)` : "") + (asTransaction ? `. Your wallet shows this as a 0 SOL transfer to yourself: it is how a wallet that cannot sign messages authorizes the requests for the relay, and it is never sent to the network. Approve it on the device within a few minutes.` : `. This signs the requests for the relay, not a transaction, and must be approved within a few minutes to stay valid.`)
10548
+ );
10549
+ }
10550
+ const approvalStartedMs = Date.now();
10551
+ const { signature, mode } = await signRelayAuthPayload(this.signer, message);
10552
+ if (!(this.signer instanceof import_web312.Keypair)) {
10553
+ assertApprovalWithinFreshnessWindow(
10554
+ Date.now() - approvalStartedMs,
10555
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS
10556
+ );
10557
+ }
10558
+ const signatureB64 = Buffer.from(signature).toString("base64");
10559
+ wave.forEach((item, i) => {
10560
+ const preimage = preimages[i];
10561
+ this.ready.push({
10562
+ item,
10563
+ fields: {
10564
+ sender: preimage.sender,
10565
+ auth_issued_at: preimage.auth_issued_at,
10566
+ auth_nonce: preimage.auth_nonce,
10567
+ auth_signature: signatureB64,
10568
+ ...mode === "transaction" ? { auth_mode: mode } : {},
10569
+ // A fresh array per item: `Object.assign` puts this on the wire body, and the body is
10570
+ // serialized again on every network retry.
10571
+ auth_batch: { digests: [...digests] }
10572
+ }
10573
+ });
10574
+ });
10575
+ this.pump();
10576
+ } catch (error) {
10577
+ for (const item of wave) {
10578
+ const w = item.waiting;
10579
+ item.waiting = null;
10580
+ item.state = "done";
10581
+ w?.reject(error);
10582
+ }
10583
+ }
10584
+ }
10585
+ /** Release signed items to submit, `submitConcurrency` at a time, in signing order. */
10586
+ pump() {
10587
+ while (this.ready.length > 0 && this.slotsInUse < this.submitConcurrency) {
10588
+ const next = this.ready.shift();
10589
+ const w = next.item.waiting;
10590
+ next.item.waiting = null;
10591
+ if (next.item.state !== "waiting" || !w) continue;
10592
+ next.item.state = "submitting";
10593
+ next.item.holdsSlot = true;
10594
+ this.slotsInUse += 1;
10595
+ w.resolve(next.fields);
10596
+ }
10597
+ }
10598
+ };
10599
+ function createRelayBatchAuthCoordinator(options) {
10600
+ return new RelayBatchAuthCoordinator(options);
10601
+ }
10602
+
10603
+ // src/flows/transact-batch.ts
10604
+ async function transactBatch(items, options) {
10605
+ if (items.length === 0) {
10606
+ return { results: [], approvals: 0 };
10607
+ }
10608
+ if (items.length > RELAY_BATCH_AUTH_MAX_ITEMS) {
10609
+ throw new Error(
10610
+ `transactBatch accepts at most ${RELAY_BATCH_AUTH_MAX_ITEMS} items per call (got ${items.length}). Chunk the payout; see RELAY_BATCH_AUTH_MAX_ITEMS for why the practical bound is lower.`
10611
+ );
10612
+ }
10613
+ if (!options.relayUrl) {
10614
+ throw new Error("transactBatch requires relayUrl: batch approval is a relay authentication scheme.");
10615
+ }
10616
+ const { proofConcurrency, submitConcurrency, ...shared } = options;
10617
+ const signer = shared.depositorKeypair ? shared.depositorKeypair : (() => {
10618
+ const wallet = shared.walletPublicKey ?? shared.depositorPublicKey;
10619
+ if (!wallet) return null;
10620
+ if (shared.signMessage) return { walletPublicKey: wallet, signMessage: shared.signMessage };
10621
+ if (shared.signAuthTransaction) {
10622
+ return { walletPublicKey: wallet, signAuthTransaction: shared.signAuthTransaction };
10623
+ }
10624
+ return null;
10625
+ })();
10626
+ if (!signer) {
10627
+ throw new Error(
10628
+ "transactBatch requires an authenticated sender: pass `depositorKeypair` (a local Keypair), or `walletPublicKey` with `signMessage` (a browser wallet adapter) or `signAuthTransaction` (a hardware wallet). Checked up front, so nothing has been computed or submitted yet."
10629
+ );
10630
+ }
10631
+ const coordinator = createRelayBatchAuthCoordinator({
10632
+ signer,
10633
+ items: items.length,
10634
+ proofConcurrency,
10635
+ submitConcurrency,
10636
+ onProgress: shared.onProgress
10637
+ });
10638
+ const handles = items.map(() => coordinator.item());
10639
+ const results = new Array(items.length);
10640
+ const runOne = async (index) => {
10641
+ const item = items[index];
10642
+ const handle = handles[index];
10643
+ const label = `[batch ${index + 1}/${items.length}]`;
10644
+ try {
10645
+ const value = await transact(item.params, {
10646
+ ...shared,
10647
+ ...item.options,
10648
+ relayAuthBatch: handle,
10649
+ onProgress: shared.onProgress ? (status) => shared.onProgress?.(`${label} ${status}`) : void 0
10650
+ });
10651
+ results[index] = { status: "fulfilled", value };
10652
+ } catch (reason) {
10653
+ results[index] = { status: "rejected", reason };
10654
+ } finally {
10655
+ handle.finish();
10656
+ }
10657
+ };
10658
+ await Promise.all(items.map((_, index) => runOne(index)));
10659
+ return { results, approvals: coordinator.approvals };
10660
+ }
10661
+
10662
+ // src/scanning/scan.ts
10663
+ var import_bs583 = __toESM(require("bs58"), 1);
10664
+ var import_web313 = require("@solana/web3.js");
10665
+ var import_spl_token2 = require("@solana/spl-token");
10666
+ init_inputs();
10667
+ init_utxo();
10668
+ var bs583 = import_bs583.default.default || import_bs583.default;
10192
10669
  var TRANSACT_TAG2 = 0;
10193
10670
  var TRANSACT_SWAP_TAG3 = 1;
10194
10671
  var PROOF_LEN3 = 256;
@@ -10273,7 +10750,7 @@ function parseSwapOutputMint(data) {
10273
10750
  const mintBytes = data.slice(SWAP_OUTPUT_MINT_OFFSET, end);
10274
10751
  if (mintBytes.every((byte) => byte === 0)) return void 0;
10275
10752
  try {
10276
- return new import_web310.PublicKey(mintBytes).toBase58();
10753
+ return new import_web313.PublicKey(mintBytes).toBase58();
10277
10754
  } catch {
10278
10755
  return void 0;
10279
10756
  }
@@ -10363,7 +10840,7 @@ function parseSwapRecipientAta(data) {
10363
10840
  const recipientAtaBytes = data.slice(recipientAtaStart, recipientAtaEnd);
10364
10841
  if (recipientAtaBytes.every((byte) => byte === 0)) return void 0;
10365
10842
  try {
10366
- return new import_web310.PublicKey(recipientAtaBytes).toBase58();
10843
+ return new import_web313.PublicKey(recipientAtaBytes).toBase58();
10367
10844
  } catch {
10368
10845
  return void 0;
10369
10846
  }
@@ -10525,7 +11002,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
10525
11002
  let rpcCalls = 0;
10526
11003
  const candidates = Array.from(swapCtxByCommitment.keys());
10527
11004
  if (candidates.length === 0) return { records, rpcCalls };
10528
- const [registry] = import_web310.PublicKey.findProgramAddressSync(
11005
+ const [registry] = import_web313.PublicKey.findProgramAddressSync(
10529
11006
  [Buffer.from("cloak_chain_note_registry")],
10530
11007
  programId
10531
11008
  );
@@ -10556,7 +11033,7 @@ async function scanSwapNoteCarriers(connection, programId, viewingKeyNk, swapCtx
10556
11033
  tx = await withRpcRetry(
10557
11034
  () => connection.getTransaction(si.signature, {
10558
11035
  commitment: "confirmed",
10559
- maxSupportedTransactionVersion: 0
11036
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10560
11037
  })
10561
11038
  );
10562
11039
  } catch {
@@ -10657,7 +11134,7 @@ async function scanRecipientDeliveryNotes(opts) {
10657
11134
  tx = await withRpcRetry(
10658
11135
  () => connection.getTransaction(si.signature, {
10659
11136
  commitment: "confirmed",
10660
- maxSupportedTransactionVersion: 0
11137
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10661
11138
  })
10662
11139
  );
10663
11140
  } catch {
@@ -10828,7 +11305,7 @@ async function scanTransactions(opts) {
10828
11305
  return await withRpcRetry(
10829
11306
  () => connection.getTransaction(sigInfo.signature, {
10830
11307
  commitment: "confirmed",
10831
- maxSupportedTransactionVersion: 0
11308
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
10832
11309
  })
10833
11310
  );
10834
11311
  } catch {
@@ -10928,8 +11405,8 @@ async function scanTransactions(opts) {
10928
11405
  if (onChainAta) {
10929
11406
  try {
10930
11407
  const expectedAta = (0, import_spl_token2.getAssociatedTokenAddressSync)(
10931
- new import_web310.PublicKey(asset.mint),
10932
- new import_web310.PublicKey(walletPublicKey)
11408
+ new import_web313.PublicKey(asset.mint),
11409
+ new import_web313.PublicKey(walletPublicKey)
10933
11410
  ).toBase58();
10934
11411
  if (onChainAta === expectedAta) {
10935
11412
  isOurs = true;
@@ -11143,7 +11620,7 @@ async function scanTransactions(opts) {
11143
11620
  // deposit — that is the public deposit amount. A deposit that also merged inputs
11144
11621
  // carries a larger output 0 and is not recoverable from public data alone.
11145
11622
  amount: grossAmount,
11146
- mintAddress: new import_web310.PublicKey(asset.mint),
11623
+ mintAddress: new import_web313.PublicKey(asset.mint),
11147
11624
  outputCommitments: ixCtx.outputCommitments ?? []
11148
11625
  });
11149
11626
  if (recoveredDeposit) {
@@ -11169,7 +11646,7 @@ async function scanTransactions(opts) {
11169
11646
  noteSalt: compactNote.noteSalt,
11170
11647
  amount: compactNote.outAmount0,
11171
11648
  keypair: { privateKey: 0n, publicKey: compactNote.outPubkey0 },
11172
- mintAddress: new import_web310.PublicKey(asset.mint),
11649
+ mintAddress: new import_web313.PublicKey(asset.mint),
11173
11650
  outputIndex: 0,
11174
11651
  // v4 describes output 0, which is where change lands
11175
11652
  outputCommitments: ixCtx.outputCommitments ?? []
@@ -11362,7 +11839,7 @@ function formatComplianceCsv(report) {
11362
11839
  }
11363
11840
 
11364
11841
  // src/wallet/utxo-wallet.ts
11365
- var import_web311 = require("@solana/web3.js");
11842
+ var import_web314 = require("@solana/web3.js");
11366
11843
  init_utxo();
11367
11844
  var UtxoWallet = class _UtxoWallet {
11368
11845
  constructor(viewingKey) {
@@ -11575,7 +12052,7 @@ var UtxoWallet = class _UtxoWallet {
11575
12052
  data.viewingKey ? new Uint8Array(data.viewingKey) : void 0
11576
12053
  );
11577
12054
  for (const w of data.wallets) {
11578
- const mint = new import_web311.PublicKey(w.mint);
12055
+ const mint = new import_web314.PublicKey(w.mint);
11579
12056
  for (const u of w.utxos) {
11580
12057
  wallet.addUtxo({
11581
12058
  amount: BigInt(u.amount),
@@ -11657,13 +12134,783 @@ var SimpleWallet = class {
11657
12134
  }
11658
12135
  };
11659
12136
 
12137
+ // src/bridge/rail-verify.ts
12138
+ var import_tweetnacl7 = __toESM(require("tweetnacl"), 1);
12139
+ var import_sha256 = require("@noble/hashes/sha256");
12140
+ var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
12141
+ var b58 = /* @__PURE__ */ (() => {
12142
+ const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
12143
+ return {
12144
+ decode(s) {
12145
+ let n = 0n;
12146
+ for (const c of s) {
12147
+ const i = A.indexOf(c);
12148
+ if (i < 0) throw new Error("bad base58");
12149
+ n = n * 58n + BigInt(i);
12150
+ }
12151
+ const bytes = [];
12152
+ while (n > 0n) {
12153
+ bytes.unshift(Number(n & 255n));
12154
+ n >>= 8n;
12155
+ }
12156
+ for (const c of s) {
12157
+ if (c === "1") bytes.unshift(0);
12158
+ else break;
12159
+ }
12160
+ return Uint8Array.from(bytes);
12161
+ },
12162
+ encode(b) {
12163
+ let n = 0n;
12164
+ for (const x of b) n = n * 256n + BigInt(x);
12165
+ let s = "";
12166
+ while (n > 0n) {
12167
+ s = A[Number(n % 58n)] + s;
12168
+ n /= 58n;
12169
+ }
12170
+ for (const x of b) {
12171
+ if (x === 0) s = "1" + s;
12172
+ else break;
12173
+ }
12174
+ return s;
12175
+ }
12176
+ };
12177
+ })();
12178
+ function stable(v) {
12179
+ if (v === null || typeof v !== "object") return JSON.stringify(v) ?? "null";
12180
+ if (Array.isArray(v)) return `[${v.map(stable).join(",")}]`;
12181
+ const o = v;
12182
+ const parts = Object.keys(o).sort().filter((k) => o[k] !== void 0).map((k) => `${JSON.stringify(k)}:${stable(o[k])}`);
12183
+ return `{${parts.join(",")}}`;
12184
+ }
12185
+ function signedRequest(r) {
12186
+ const q = r.quoteRequest ?? {};
12187
+ return {
12188
+ dry: q.dry,
12189
+ swapType: q.swapType,
12190
+ slippageTolerance: q.slippageTolerance,
12191
+ originAsset: q.originAsset,
12192
+ depositType: q.depositType,
12193
+ destinationAsset: q.destinationAsset,
12194
+ amount: q.amount,
12195
+ refundTo: q.refundTo,
12196
+ refundType: q.refundType,
12197
+ recipient: q.recipient,
12198
+ recipientType: q.recipientType,
12199
+ deadline: q.deadline,
12200
+ quoteWaitingTimeMs: q.quoteWaitingTimeMs || void 0,
12201
+ referral: q.referral || void 0,
12202
+ virtualChainRecipient: q.virtualChainRecipient || void 0,
12203
+ virtualChainRefundRecipient: q.virtualChainRefundRecipient || void 0,
12204
+ customRecipientMsg: q.customRecipientMsg || void 0
12205
+ // Deliberately unsigned by the rail: sessionId, connectedWallets, correlationId, appFees,
12206
+ // partnerId, userAccountId, depositMode. APP FEES ARE NOT AUTHENTICATED — never display a fee
12207
+ // caption as if the signature vouched for it.
12208
+ };
12209
+ }
12210
+ function signedQuote(r) {
12211
+ const q = r.quote ?? {};
12212
+ const base = {
12213
+ amountIn: q.amountIn,
12214
+ amountInFormatted: q.amountInFormatted,
12215
+ amountInUsd: q.amountInUsd,
12216
+ minAmountIn: q.minAmountIn,
12217
+ amountOut: q.amountOut,
12218
+ amountOutFormatted: q.amountOutFormatted,
12219
+ amountOutUsd: q.amountOutUsd,
12220
+ minAmountOut: q.minAmountOut
12221
+ };
12222
+ if (r.quoteRequest?.dry) return base;
12223
+ return {
12224
+ ...base,
12225
+ depositAddress: q.depositAddress || void 0,
12226
+ // <- the field that makes substitution detectable
12227
+ depositMemo: q.depositMemo || void 0,
12228
+ deadline: q.deadline || void 0,
12229
+ // <- a real, SIGNED expiry
12230
+ timeWhenInactive: q.timeWhenInactive || void 0,
12231
+ timeEstimate: q.timeEstimate || void 0,
12232
+ virtualChainRecipient: q.virtualChainRecipient || void 0,
12233
+ virtualChainRefundRecipient: q.virtualChainRefundRecipient || void 0,
12234
+ customRecipientMsg: q.customRecipientMsg || void 0,
12235
+ refundFee: q.refundFee || void 0,
12236
+ withdrawFee: q.withdrawFee || void 0
12237
+ };
12238
+ }
12239
+ function canonicalPayloadString(resp) {
12240
+ return stable({ ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp });
12241
+ }
12242
+ function verifyQuoteSignature(resp) {
12243
+ if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
12244
+ const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
12245
+ const digest = (0, import_sha256.sha256)(new TextEncoder().encode(stable(payload)));
12246
+ const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
12247
+ const sig = resp.signature.replace(/^ed25519:/, "");
12248
+ try {
12249
+ return { valid: import_tweetnacl7.default.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
12250
+ } catch (e) {
12251
+ return { valid: false, reason: e instanceof Error ? e.message : String(e) };
12252
+ }
12253
+ }
12254
+
12255
+ // src/bridge/rails.ts
12256
+ async function parseBridgeResponse(res, what) {
12257
+ let body;
12258
+ try {
12259
+ body = await res.json();
12260
+ } catch {
12261
+ throw new Error(`${what} failed: ${res.status} ${res.statusText} (response body was not JSON)`);
12262
+ }
12263
+ if (!res.ok) {
12264
+ const b = body ?? {};
12265
+ throw new Error(
12266
+ `${what} failed: ${b.message ?? res.statusText} (${b.code ?? res.status}${b.retryable ? ", retryable" : ""})`
12267
+ );
12268
+ }
12269
+ return body;
12270
+ }
12271
+ function toAttestation(raw) {
12272
+ if (raw.kind === "ed25519") {
12273
+ return { kind: "ed25519", verified: raw.verified ?? false, signer: raw.signer ?? "" };
12274
+ }
12275
+ return { kind: "none", checks: raw.checks ?? [], note: raw.note ?? "" };
12276
+ }
12277
+ async function fetchBridgeQuote(relayUrl, req) {
12278
+ const body = {
12279
+ recipient: req.recipient,
12280
+ origin_chain: req.originChain,
12281
+ amount_base_units: req.amountBaseUnits.toString(),
12282
+ allocate: req.allocate ?? false
12283
+ };
12284
+ if (req.refundTo !== void 0) body.refund_to = req.refundTo;
12285
+ if (req.rails !== void 0) body.rails = req.rails;
12286
+ const res = await relayFetch(`${relayUrl}/bridge/quote`, {
12287
+ method: "POST",
12288
+ headers: { "Content-Type": "application/json" },
12289
+ body: JSON.stringify(body)
12290
+ });
12291
+ const raw = await parseBridgeResponse(res, "bridge quote");
12292
+ const options = [];
12293
+ const unavailable = (raw.unavailable ?? []).map((p) => ({
12294
+ rail: p.rail,
12295
+ reason: p.reason
12296
+ }));
12297
+ for (const opt of raw.options) {
12298
+ const attestation = toAttestation(opt.attestation);
12299
+ if (attestation.kind === "ed25519") {
12300
+ const verdict = opt.rail_response ? verifyQuoteSignature(opt.rail_response) : { valid: false, reason: "no rail_response to verify against" };
12301
+ if (!verdict.valid) {
12302
+ unavailable.push({
12303
+ rail: opt.rail,
12304
+ reason: `deposit address failed independent signature verification, refusing to display it (${verdict.reason ?? "signature did not verify"})`
12305
+ });
12306
+ continue;
12307
+ }
12308
+ }
12309
+ options.push({
12310
+ rail: opt.rail,
12311
+ refunds: opt.refunds,
12312
+ addressLifetime: opt.address_lifetime,
12313
+ amountOut: BigInt(opt.amount_out),
12314
+ minAmountOut: BigInt(opt.min_amount_out),
12315
+ timeEstimateSeconds: opt.time_estimate_s,
12316
+ expiresAt: opt.expires_at,
12317
+ depositAddress: opt.deposit_address,
12318
+ attestation
12319
+ });
12320
+ }
12321
+ return { options, unavailable };
12322
+ }
12323
+ var STATUS_STATES = [
12324
+ "pending",
12325
+ "delivered",
12326
+ "refunded",
12327
+ "expired",
12328
+ "unknown"
12329
+ ];
12330
+ async function fetchBridgeStatus(relayUrl, depositAddress, rail) {
12331
+ const qs = new URLSearchParams({ deposit_address: depositAddress, rail });
12332
+ const res = await relayFetch(`${relayUrl}/bridge/status?${qs.toString()}`);
12333
+ const raw = await parseBridgeResponse(res, "bridge status");
12334
+ const state = STATUS_STATES.includes(raw.state ?? "") ? raw.state : "unknown";
12335
+ return { rail: raw.rail ?? rail, state, detail: raw.detail ?? "" };
12336
+ }
12337
+ function cloakBridgeRail(relayUrl) {
12338
+ assertAllowedRelayOrigin(relayUrl);
12339
+ return {
12340
+ id: "cloak-bridge",
12341
+ quote: (req) => fetchBridgeQuote(relayUrl, req),
12342
+ status: (depositAddress, rail) => fetchBridgeStatus(relayUrl, depositAddress, rail)
12343
+ };
12344
+ }
12345
+
12346
+ // src/bridge/paymaster-client.ts
12347
+ var import_web315 = require("@solana/web3.js");
12348
+ var import_spl_token3 = require("@solana/spl-token");
12349
+ function validatePaymasterTopUpTransaction(tx, expect) {
12350
+ const ixs = tx.instructions;
12351
+ if (ixs.length !== 1 && ixs.length !== 2) {
12352
+ throw new Error(
12353
+ `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`
12354
+ );
12355
+ }
12356
+ const ix0 = ixs[0];
12357
+ if (!ix0.programId.equals(import_web315.SystemProgram.programId)) {
12358
+ throw new Error(
12359
+ `paymaster top-up instruction 0 is owned by ${ix0.programId.toBase58()}, not the System Program \u2014 refusing to sign an unrecognised first instruction`
12360
+ );
12361
+ }
12362
+ const transfer2 = import_web315.SystemInstruction.decodeTransfer(ix0);
12363
+ if (!transfer2.toPubkey.equals(expect.recipient)) {
12364
+ throw new Error(
12365
+ `paymaster top-up sends SOL to ${transfer2.toPubkey.toBase58()}, which is not our recipient ${expect.recipient.toBase58()} \u2014 refusing to sign a transaction that funds a key we do not control`
12366
+ );
12367
+ }
12368
+ if (BigInt(transfer2.lamports) > expect.maxGrantLamports) {
12369
+ throw new Error(
12370
+ `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`
12371
+ );
12372
+ }
12373
+ if (ixs.length === 1) return;
12374
+ const ix1 = ixs[1];
12375
+ if (!ix1.programId.equals(import_spl_token3.TOKEN_PROGRAM_ID)) {
12376
+ throw new Error(
12377
+ `paymaster top-up instruction 1 is owned by ${ix1.programId.toBase58()}, not the SPL Token program \u2014 refusing to sign an unrecognised second instruction`
12378
+ );
12379
+ }
12380
+ const spl = (0, import_spl_token3.decodeTransferInstruction)(ix1, import_spl_token3.TOKEN_PROGRAM_ID);
12381
+ const authority = spl.keys.owner.pubkey;
12382
+ if (!authority.equals(expect.recipient)) {
12383
+ throw new Error(
12384
+ `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`
12385
+ );
12386
+ }
12387
+ const expectedDestination = (0, import_spl_token3.getAssociatedTokenAddressSync)(
12388
+ expect.feeMint,
12389
+ expect.paymentAddress,
12390
+ false
12391
+ );
12392
+ const destination = spl.keys.destination.pubkey;
12393
+ if (!destination.equals(expectedDestination)) {
12394
+ throw new Error(
12395
+ `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`
12396
+ );
12397
+ }
12398
+ const paidAmount = BigInt(spl.data.amount);
12399
+ if (paidAmount !== expect.feeTokenAmount) {
12400
+ throw new Error(
12401
+ `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`
12402
+ );
12403
+ }
12404
+ }
12405
+ async function parseBridgeResponse2(res, what) {
12406
+ let body;
12407
+ try {
12408
+ body = await res.json();
12409
+ } catch {
12410
+ throw new Error(`${what} failed: ${res.status} ${res.statusText} (response body was not JSON)`);
12411
+ }
12412
+ if (!res.ok) {
12413
+ const b = body ?? {};
12414
+ throw new Error(
12415
+ `${what} failed: ${b.message ?? res.statusText} (${b.code ?? res.status}${b.retryable ? ", retryable" : ""})`
12416
+ );
12417
+ }
12418
+ return body;
12419
+ }
12420
+ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12421
+ assertAllowedRelayOrigin(relayUrl);
12422
+ if (grantLamports <= 0n || grantLamports > BigInt(Number.MAX_SAFE_INTEGER)) {
12423
+ throw new Error(
12424
+ `grantLamports must be a positive value representable as a JS number, got ${grantLamports}`
12425
+ );
12426
+ }
12427
+ const prepareRes = await relayFetch(`${relayUrl}/bridge/paymaster/prepare`, {
12428
+ method: "POST",
12429
+ headers: { "Content-Type": "application/json" },
12430
+ body: JSON.stringify({
12431
+ recipient: receiver.publicKey.toBase58(),
12432
+ grant_lamports: Number(grantLamports)
12433
+ })
12434
+ });
12435
+ const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12436
+ if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
12437
+ throw new Error(
12438
+ "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12439
+ );
12440
+ }
12441
+ const feeMint = new import_web315.PublicKey(prepared.fee_mint);
12442
+ const paymentAddress = new import_web315.PublicKey(prepared.payment_address);
12443
+ const feeTokenAmount = BigInt(prepared.fee_token_amount);
12444
+ const tx = import_web315.Transaction.from(Buffer.from(prepared.transaction, "base64"));
12445
+ validatePaymasterTopUpTransaction(tx, {
12446
+ recipient: receiver.publicKey,
12447
+ maxGrantLamports: grantLamports,
12448
+ feeMint,
12449
+ feeTokenAmount,
12450
+ paymentAddress
12451
+ });
12452
+ tx.partialSign(receiver);
12453
+ const cosignRes = await relayFetch(`${relayUrl}/bridge/paymaster/cosign`, {
12454
+ method: "POST",
12455
+ headers: { "Content-Type": "application/json" },
12456
+ body: JSON.stringify({
12457
+ transaction: tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString("base64"),
12458
+ voucher: prepared.voucher
12459
+ })
12460
+ });
12461
+ const cosigned = await parseBridgeResponse2(cosignRes, "paymaster cosign");
12462
+ return {
12463
+ transaction: import_web315.Transaction.from(Buffer.from(cosigned.transaction, "base64")),
12464
+ feeTokenAmount,
12465
+ feeMint: prepared.fee_mint,
12466
+ paymentAddress: prepared.payment_address
12467
+ };
12468
+ }
12469
+
12470
+ // src/bridge/derive.ts
12471
+ var import_web316 = require("@solana/web3.js");
12472
+ var import_hmac = require("@noble/hashes/hmac");
12473
+ var import_sha512 = require("@noble/hashes/sha512");
12474
+ var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
12475
+ var MAX_RECEIVER_INDEX = 1e4;
12476
+ function deriveBridgeReceiver(nk, index) {
12477
+ if (!Number.isInteger(index) || index < 0) {
12478
+ throw new Error(`index must be a non-negative integer, got ${index}`);
12479
+ }
12480
+ if (index > MAX_RECEIVER_INDEX) {
12481
+ throw new Error(
12482
+ `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.`
12483
+ );
12484
+ }
12485
+ const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12486
+ return import_web316.Keypair.fromSeed(h.slice(0, 32));
12487
+ }
12488
+
12489
+ // src/bridge/discover.ts
12490
+ var import_web317 = require("@solana/web3.js");
12491
+ var import_spl_token4 = require("@solana/spl-token");
12492
+ function describeError(err) {
12493
+ return err instanceof Error ? err.message : String(err);
12494
+ }
12495
+ async function listBridgeDeposits(conn, nk, opts) {
12496
+ const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12497
+ const stopAfterUnused = opts.stopAfterUnused ?? 5;
12498
+ const out = [];
12499
+ let consecutiveUnused = 0;
12500
+ for (let index = 0; index < scanDepth; index++) {
12501
+ const kp = deriveBridgeReceiver(nk, index);
12502
+ const receiver = kp.publicKey;
12503
+ const tokenAccount = (0, import_spl_token4.getAssociatedTokenAddressSync)(opts.mint, receiver, false);
12504
+ try {
12505
+ const [recvInfo, ataInfo] = await conn.getMultipleAccountsInfo([receiver, tokenAccount]);
12506
+ const lamports = recvInfo?.lamports ?? 0;
12507
+ let tokenBalance = 0n;
12508
+ if (ataInfo) {
12509
+ try {
12510
+ tokenBalance = BigInt((await conn.getTokenAccountBalance(tokenAccount)).value.amount);
12511
+ } catch (err) {
12512
+ if (!(err instanceof import_web317.SolanaJSONRPCError && /could not find account/i.test(err.message))) {
12513
+ throw err;
12514
+ }
12515
+ }
12516
+ }
12517
+ if (lamports === 0 && !ataInfo) {
12518
+ consecutiveUnused++;
12519
+ if (consecutiveUnused >= stopAfterUnused) break;
12520
+ continue;
12521
+ }
12522
+ consecutiveUnused = 0;
12523
+ const shieldSignatures = [];
12524
+ const sigs = await conn.getSignaturesForAddress(receiver, { limit: 20 });
12525
+ for (const s of sigs) {
12526
+ if (s.err) continue;
12527
+ const tx = await conn.getTransaction(s.signature, {
12528
+ maxSupportedTransactionVersion: MAX_SUPPORTED_TRANSACTION_VERSION
12529
+ });
12530
+ const keys = tx?.transaction.message.getAccountKeys({
12531
+ accountKeysFromLookups: tx.meta?.loadedAddresses
12532
+ });
12533
+ if (keys && [...Array(keys.length).keys()].some((i) => keys.get(i)?.equals(opts.programId))) {
12534
+ shieldSignatures.push(s.signature);
12535
+ }
12536
+ }
12537
+ const shieldSignature = shieldSignatures[0];
12538
+ const indexReused = shieldSignatures.length > 1;
12539
+ let state;
12540
+ if (tokenBalance > 0n) state = shieldSignature ? "needs-cleanup" : "arrived";
12541
+ else if (shieldSignature) state = ataInfo ? "needs-cleanup" : "complete";
12542
+ else state = "awaiting";
12543
+ out.push({
12544
+ index,
12545
+ receiver,
12546
+ tokenAccount,
12547
+ state,
12548
+ tokenBalance,
12549
+ lamports,
12550
+ shieldSignature,
12551
+ ...indexReused ? { indexReused, shieldSignatures } : {}
12552
+ });
12553
+ } catch (err) {
12554
+ out.push({
12555
+ index,
12556
+ receiver,
12557
+ tokenAccount,
12558
+ state: "unknown",
12559
+ tokenBalance: 0n,
12560
+ lamports: 0,
12561
+ error: describeError(err)
12562
+ });
12563
+ }
12564
+ }
12565
+ return out;
12566
+ }
12567
+
12568
+ // src/bridge/deposit-core.ts
12569
+ var import_web319 = require("@solana/web3.js");
12570
+ var import_tweetnacl8 = __toESM(require("tweetnacl"), 1);
12571
+ init_utxo();
12572
+
12573
+ // src/bridge/funder.ts
12574
+ var import_web318 = require("@solana/web3.js");
12575
+ var import_spl_token5 = require("@solana/spl-token");
12576
+ var MAINNET_RENT_0 = 890880;
12577
+ var MAINNET_RENT_1 = 897840;
12578
+ var FEE_BUDGET = 13e4;
12579
+ var CLEANUP_FEE_BUDGET = 5e3;
12580
+ var pda = (seeds, programId) => import_web318.PublicKey.findProgramAddressSync(seeds.map((s) => Buffer.from(s)), programId)[0];
12581
+ function deriveFundingTargets(d) {
12582
+ const pool = pda([Buffer.from("pool"), d.mint.toBuffer()], d.programId);
12583
+ return {
12584
+ pool,
12585
+ // program: NullifierAccount::derive_pda_with_pool -> [b"nullifier", pool, nullifier]
12586
+ nullifier0: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[0]], d.programId),
12587
+ nullifier1: pda([Buffer.from("nullifier"), pool.toBuffer(), d.nullifiers[1]], d.programId),
12588
+ // relay: derive_risk_nonce_pda -> [b"risk_nonce", bind0]
12589
+ riskNonce: pda([Buffer.from("risk_nonce"), d.bind0], d.programId),
12590
+ depositorAta: (0, import_spl_token5.getAssociatedTokenAddressSync)(d.mint, d.depositor, false)
12591
+ };
12592
+ }
12593
+ async function readRent(conn) {
12594
+ const [zero, one] = await Promise.all([
12595
+ conn.getMinimumBalanceForRentExemption(0),
12596
+ conn.getMinimumBalanceForRentExemption(1)
12597
+ ]);
12598
+ return { zero, one };
12599
+ }
12600
+
12601
+ // src/bridge/deposit-core.ts
12602
+ var DepositError = class extends Error {
12603
+ constructor(message, fundedAccounts, measuredTxSize) {
12604
+ super(message);
12605
+ this.fundedAccounts = fundedAccounts;
12606
+ this.measuredTxSize = measuredTxSize;
12607
+ this.name = "DepositError";
12608
+ }
12609
+ };
12610
+ async function depositFromDerivedKey(conn, R, funder, amount, log = console.log, grantOverride, opts) {
12611
+ if (!opts.noteSpendKey || opts.noteSpendKey.length !== 32) {
12612
+ throw new Error(
12613
+ "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."
12614
+ );
12615
+ }
12616
+ if (!opts.relayUrl) {
12617
+ throw new Error(
12618
+ "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."
12619
+ );
12620
+ }
12621
+ if (!opts.programId) {
12622
+ throw new Error(
12623
+ "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."
12624
+ );
12625
+ }
12626
+ if (!opts.mint) {
12627
+ throw new Error(
12628
+ "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."
12629
+ );
12630
+ }
12631
+ assertAllowedRpcConnection(conn);
12632
+ const relayUrl = opts.relayUrl;
12633
+ const programId = opts.programId;
12634
+ const mint = opts.mint;
12635
+ setCircuitsPath(resolveCircuitsBase());
12636
+ const grantR = grantOverride ?? MAINNET_RENT_0 + FEE_BUDGET + CLEANUP_FEE_BUDGET;
12637
+ const heldByR = await conn.getBalance(R.publicKey);
12638
+ if (heldByR >= grantR) {
12639
+ log(` R already holds ${heldByR} (>= ${grantR}) \u2014 no top-up needed`);
12640
+ } else {
12641
+ await (0, import_web319.sendAndConfirmTransaction)(conn, new import_web319.Transaction().add(
12642
+ import_web319.SystemProgram.transfer({ fromPubkey: funder.publicKey, toPubkey: R.publicKey, lamports: grantR - heldByR })
12643
+ ), [funder]);
12644
+ log(` funder topped R up by ${grantR - heldByR} to ${grantR}${grantOverride !== void 0 ? " (OVERRIDDEN for a deliberate test)" : " \u2014 floor + deposit fee + cleanup fee, no rent"}`);
12645
+ }
12646
+ let measuredSize = -1;
12647
+ let fundedAccounts = [];
12648
+ const signTransaction2 = async (tx) => {
12649
+ if (tx instanceof import_web319.VersionedTransaction) {
12650
+ measuredSize = tx.serialize().length;
12651
+ const alts = await Promise.all(
12652
+ tx.message.addressTableLookups.map(async (l) => (await conn.getAddressLookupTable(l.accountKey)).value)
12653
+ );
12654
+ const keys = tx.message.getAccountKeys({ addressLookupTableAccounts: alts });
12655
+ const ix = tx.message.compiledInstructions.find((i) => keys.get(i.programIdIndex).equals(programId));
12656
+ const at = (n) => keys.get(ix.accountKeyIndexes[n]);
12657
+ const targets = [
12658
+ { a: at(12), need: MAINNET_RENT_0, name: "risk_nonce" },
12659
+ { a: at(4), need: MAINNET_RENT_1, name: "nullifier_0" },
12660
+ { a: at(5), need: MAINNET_RENT_1, name: "nullifier_1" }
12661
+ ];
12662
+ const infos = await conn.getMultipleAccountsInfo(targets.map((t) => t.a));
12663
+ fundedAccounts = targets.map((t, i) => ({
12664
+ name: t.name,
12665
+ address: t.a.toBase58(),
12666
+ lamportsSent: Math.max(0, t.need - (infos[i]?.lamports ?? 0))
12667
+ }));
12668
+ const ixs = targets.flatMap((t, i) => (infos[i]?.lamports ?? 0) >= t.need ? [] : [import_web319.SystemProgram.transfer({
12669
+ fromPubkey: funder.publicKey,
12670
+ toPubkey: t.a,
12671
+ lamports: t.need - (infos[i]?.lamports ?? 0)
12672
+ })]);
12673
+ if (ixs.length) {
12674
+ const sig = await (0, import_web319.sendAndConfirmTransaction)(conn, new import_web319.Transaction().add(...ixs), [funder]);
12675
+ log(` seam: funded ${ixs.length} program accounts read off the built tx \u2014 ${sig.slice(0, 16)}\u2026`);
12676
+ }
12677
+ tx.sign([R]);
12678
+ return tx;
12679
+ }
12680
+ tx.partialSign(R);
12681
+ return tx;
12682
+ };
12683
+ const signMessage = async (m) => import_tweetnacl8.default.sign.detached(m, R.secretKey);
12684
+ const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
12685
+ const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
12686
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
12687
+ const zeroInput = await createZeroUtxo(mint);
12688
+ const rBefore = await conn.getBalance(R.publicKey);
12689
+ let result;
12690
+ try {
12691
+ result = await transact(
12692
+ { inputUtxos: [zeroInput], outputUtxos: [utxo], externalAmount: amount, depositor: R.publicKey },
12693
+ {
12694
+ connection: conn,
12695
+ programId,
12696
+ relayUrl,
12697
+ // NO depositorKeypair: the SDK branches `if (keypair) … else if (signTransaction)`
12698
+ // (transact.ts:2786, :2936), so passing one silently skips the funding seam.
12699
+ depositorPublicKey: R.publicKey,
12700
+ walletPublicKey: R.publicKey,
12701
+ signTransaction: signTransaction2,
12702
+ signMessage,
12703
+ chainNoteViewingKeyNk: nk,
12704
+ chainNoteSalt: noteSalt,
12705
+ relaySupplementalAlt: true,
12706
+ onProgress: (s) => log(` \xB7 ${s}`)
12707
+ }
12708
+ );
12709
+ } catch (e) {
12710
+ const msg = e instanceof Error ? e.message : String(e);
12711
+ throw new DepositError(msg, fundedAccounts, measuredSize);
12712
+ }
12713
+ const rAfter = await conn.getBalance(R.publicKey);
12714
+ const noteIndex = result.outputUtxos[0].index;
12715
+ if (noteIndex === void 0) throw new Error("deposit landed but the note has no index \u2014 it cannot be discovered later");
12716
+ return {
12717
+ signature: result.signature,
12718
+ noteIndex,
12719
+ amount: result.outputUtxos[0].amount,
12720
+ txSize: measuredSize,
12721
+ rBefore,
12722
+ rAfter,
12723
+ rentExempt: rAfter >= MAINNET_RENT_0,
12724
+ inputNullifiers: result.inputNullifiers,
12725
+ fundedAccounts
12726
+ };
12727
+ }
12728
+
12729
+ // src/bridge/cleanup.ts
12730
+ var import_web320 = require("@solana/web3.js");
12731
+ var import_spl_token6 = require("@solana/spl-token");
12732
+ var DEFAULT_MINT = new import_web320.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
12733
+ async function cleanupReceivingAddress(conn, R, dustDestination, mint = DEFAULT_MINT) {
12734
+ assertAllowedRpcConnection(conn);
12735
+ const rAta = (0, import_spl_token6.getAssociatedTokenAddressSync)(mint, R.publicKey);
12736
+ const info = await conn.getAccountInfo(rAta);
12737
+ if (!info) {
12738
+ return {
12739
+ closed: false,
12740
+ dustSwept: 0n,
12741
+ rentReturned: 0,
12742
+ destination: null,
12743
+ signature: null,
12744
+ note: "no token account \u2014 nothing to recover"
12745
+ };
12746
+ }
12747
+ const bal = BigInt((await conn.getTokenAccountBalance(rAta)).value.amount);
12748
+ const rentHeld = info.lamports;
12749
+ const before = await conn.getBalance(R.publicKey);
12750
+ const ixs = [];
12751
+ let destination = null;
12752
+ if (bal > 0n && !dustDestination) {
12753
+ return {
12754
+ closed: false,
12755
+ dustSwept: 0n,
12756
+ rentReturned: 0,
12757
+ destination: null,
12758
+ signature: null,
12759
+ 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`
12760
+ };
12761
+ }
12762
+ if (bal > 0n && dustDestination) {
12763
+ const destAta = (0, import_spl_token6.getAssociatedTokenAddressSync)(mint, dustDestination);
12764
+ const destInfo = await conn.getAccountInfo(destAta);
12765
+ if (!destInfo) {
12766
+ const ataRent = await (0, import_spl_token6.getMinimumBalanceForRentExemptAccount)(conn);
12767
+ if (before < ataRent + CLEANUP_FEE_BUDGET) {
12768
+ throw new Error(
12769
+ `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.`
12770
+ );
12771
+ }
12772
+ ixs.push((0, import_spl_token6.createAssociatedTokenAccountIdempotentInstruction)(R.publicKey, destAta, dustDestination, mint));
12773
+ }
12774
+ ixs.push((0, import_spl_token6.createTransferInstruction)(rAta, destAta, R.publicKey, bal));
12775
+ destination = destAta.toBase58();
12776
+ }
12777
+ ixs.push((0, import_spl_token6.createCloseAccountInstruction)(rAta, R.publicKey, R.publicKey));
12778
+ const signature = await (0, import_web320.sendAndConfirmTransaction)(conn, new import_web320.Transaction().add(...ixs), [R], {
12779
+ commitment: "confirmed"
12780
+ });
12781
+ const after = await conn.getBalance(R.publicKey);
12782
+ const gone = await conn.getAccountInfo(rAta) === null;
12783
+ return {
12784
+ closed: gone,
12785
+ dustSwept: bal,
12786
+ rentReturned: after - before,
12787
+ destination,
12788
+ signature,
12789
+ 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`
12790
+ };
12791
+ }
12792
+
12793
+ // src/bridge/quote.ts
12794
+ var MIN_DEPOSIT_SPL_BASE_UNITS = 1000000n;
12795
+ var WITHDRAW_FIXED_FEE = 450000n;
12796
+ var WITHDRAW_FEE_BPS = 30n;
12797
+ function withdrawFeeAt(amount, fixedFee, feeBps) {
12798
+ return fixedFee + amount * feeBps / 10000n;
12799
+ }
12800
+ var MAX_FEE_FRACTION = 0.063;
12801
+ var FIXED_ROUND_TRIP = 903000n;
12802
+ var ECONOMIC_MINIMUM = FIXED_ROUND_TRIP * 1000000n / BigInt(Math.round((MAX_FEE_FRACTION - 3e-3) * 1e6));
12803
+ function withdrawFeeFor(amount) {
12804
+ return withdrawFeeAt(amount, WITHDRAW_FIXED_FEE, WITHDRAW_FEE_BPS);
12805
+ }
12806
+ function assessBridgeQuote(q) {
12807
+ if (q.sent < 0n) {
12808
+ throw new Error(`assessBridgeQuote: sent must not be negative (got ${q.sent}).`);
12809
+ }
12810
+ if (q.arrivesMin > q.sent) {
12811
+ throw new Error(
12812
+ `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.`
12813
+ );
12814
+ }
12815
+ const shieldedMinRaw = q.arrivesMin - q.paymasterFee;
12816
+ const shieldedTargetRaw = q.arrivesTarget - q.paymasterFee;
12817
+ const shieldedMin = shieldedMinRaw > 0n ? shieldedMinRaw : 0n;
12818
+ const shieldedTarget = shieldedTargetRaw > 0n ? shieldedTargetRaw : 0n;
12819
+ const viable = shieldedMinRaw >= MIN_DEPOSIT_SPL_BASE_UNITS;
12820
+ const economic = q.sent >= ECONOMIC_MINIMUM;
12821
+ const withdrawFee = shieldedMin > 0n ? withdrawFeeAt(shieldedMin, q.liveWithdrawFixedFee ?? WITHDRAW_FIXED_FEE, q.liveWithdrawFeeBps ?? WITHDRAW_FEE_BPS) : 0n;
12822
+ const roundTripCost = q.sent - (shieldedMin > withdrawFee ? shieldedMin - withdrawFee : 0n);
12823
+ const roundTripFraction = q.sent > 0n ? Number(roundTripCost) / Number(q.sent) : 0;
12824
+ const reasons = [];
12825
+ if (!viable) {
12826
+ const short = MIN_DEPOSIT_SPL_BASE_UNITS - shieldedMinRaw;
12827
+ reasons.push(
12828
+ (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.`
12829
+ );
12830
+ }
12831
+ if (viable && !economic) {
12832
+ reasons.push(
12833
+ `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.`
12834
+ );
12835
+ }
12836
+ return {
12837
+ ...q,
12838
+ shieldedMin,
12839
+ shieldedTarget,
12840
+ viable,
12841
+ economic,
12842
+ withdrawFee,
12843
+ roundTripCost,
12844
+ roundTripFraction,
12845
+ reasons
12846
+ };
12847
+ }
12848
+ var fmt = (v) => `${(Number(v) / 1e6).toFixed(6)} USDC`;
12849
+ function renderAssessment(a) {
12850
+ const L = [];
12851
+ L.push(` you send ${fmt(a.sent)}`);
12852
+ L.push(` arrives at least ${fmt(a.arrivesMin)} (target ${fmt(a.arrivesTarget)}, not a promise)`);
12853
+ L.push(` paymaster fee ${fmt(a.paymasterFee)} buys the receiver its SOL, so your wallet stays off chain`);
12854
+ L.push(` SHIELDED ${fmt(a.shieldedMin)} at least \u2014 this is what you end up with`);
12855
+ L.push(` to withdraw later ${fmt(a.withdrawFee)} the program's fee, whenever you take it out`);
12856
+ for (const r of a.reasons) L.push(`
12857
+ ${a.viable ? "NOTE" : "REFUSED"}: ${r}`);
12858
+ return L.join("\n");
12859
+ }
12860
+
12861
+ // src/bridge/retry.ts
12862
+ var TERMINAL_FAILURE = /DepositTooSmall|minimum is 1\.000000|insufficient|holds only|below the program|kora wants|over the .* ceiling/i;
12863
+ function isTerminalFailure(message) {
12864
+ return TERMINAL_FAILURE.test(message);
12865
+ }
12866
+ function classifyPostFailure(attempted, after) {
12867
+ if (after === null) return "unknown";
12868
+ if (after === 0n) return "landed";
12869
+ if (after >= attempted) return "did-not-land";
12870
+ return "unknown";
12871
+ }
12872
+ function mayRetry(verdict, message) {
12873
+ return verdict === "did-not-land" && !isTerminalFailure(message);
12874
+ }
12875
+ function retryDelayMs(attempt) {
12876
+ return 15e3 * Math.max(0, attempt - 1);
12877
+ }
12878
+ var DoNotRetry = class extends Error {
12879
+ constructor(message) {
12880
+ super(message);
12881
+ this.name = "DoNotRetry";
12882
+ }
12883
+ };
12884
+ async function withShieldRetries(attempt, hooks = {}) {
12885
+ const attempts = hooks.attempts ?? 3;
12886
+ const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
12887
+ let last = "";
12888
+ for (let n = 1; n <= attempts; n++) {
12889
+ if (n > 1) {
12890
+ const delay = retryDelayMs(n);
12891
+ hooks.onRetry?.(n, delay, last);
12892
+ await sleep4(delay);
12893
+ }
12894
+ try {
12895
+ return await attempt(n);
12896
+ } catch (e) {
12897
+ if (e instanceof DoNotRetry) throw e;
12898
+ last = e instanceof Error ? e.message : String(e);
12899
+ if (isTerminalFailure(last) || n === attempts) throw e;
12900
+ }
12901
+ }
12902
+ throw new Error("unreachable");
12903
+ }
12904
+
11660
12905
  // src/index.ts
11661
- var VERSION = "0.2.3";
12906
+ var VERSION = "0.2.4";
11662
12907
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11663
12908
  // Annotate the CommonJS export names for ESM import in node:
11664
12909
  0 && (module.exports = {
12910
+ BRIDGE_ESCROW_LABEL,
11665
12911
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
11666
12912
  CHAIN_NOTE_SALT_BITS,
12913
+ CLEANUP_FEE_BUDGET,
11667
12914
  CLOAK_PRODUCTION_RELAY_URL,
11668
12915
  CLOAK_PROGRAM_ID,
11669
12916
  CloakError,
@@ -11671,25 +12918,38 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11671
12918
  DEFAULT_TRANSACTION_CIRCUITS_URL,
11672
12919
  DELIVERY_MEMO_TAG,
11673
12920
  DELIVERY_REGISTRY_SEED,
12921
+ DepositError,
12922
+ DoNotRetry,
12923
+ ECONOMIC_MINIMUM,
11674
12924
  EXPECTED_CIRCUIT_HASHES,
12925
+ FEE_BUDGET,
11675
12926
  FIXED_FEE_LAMPORTS,
11676
12927
  InsecureRandomnessError,
11677
12928
  LAMPORTS_PER_SOL,
11678
12929
  LocalStorageAdapter,
12930
+ MAINNET_RENT_0,
12931
+ MAINNET_RENT_1,
12932
+ MAX_RECEIVER_INDEX,
11679
12933
  MERKLE_TREE_HEIGHT,
11680
12934
  MIN_DEPOSIT_LAMPORTS,
12935
+ MIN_DEPOSIT_SPL_BASE_UNITS,
11681
12936
  MemoryStorageAdapter,
11682
12937
  MerkleTree,
11683
12938
  NATIVE_SOL_MINT,
12939
+ ONECLICK_PUBKEY_B58,
11684
12940
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
11685
12941
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
11686
12942
  RECIPIENT_DELIVERY_NONCE_LEN,
11687
12943
  RECIPIENT_DELIVERY_NOTE_BYTES,
11688
12944
  RECIPIENT_DELIVERY_PLAINTEXT_LEN,
11689
12945
  RECIPIENT_DELIVERY_TAG_LEN,
12946
+ RELAY_BATCH_AUTH_MAX_ITEMS,
11690
12947
  RELAY_ORIGIN_ALLOWLIST,
12948
+ REQUEST_AUTH_BATCH_DOMAIN,
12949
+ REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
11691
12950
  REQUEST_AUTH_MAX_AGE_SECONDS,
11692
12951
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
12952
+ RelayBatchAuthCoordinator,
11693
12953
  RelayInternalError,
11694
12954
  RelayService,
11695
12955
  RootNotFoundError,
@@ -11699,6 +12959,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11699
12959
  SettlementVerificationError,
11700
12960
  ShieldPoolErrors,
11701
12961
  SimpleWallet,
12962
+ TERMINAL_FAILURE,
11702
12963
  TRANSACTION_CIRCUITS_VERSION,
11703
12964
  TRANSACT_AUTH_FIELDS,
11704
12965
  TRANSACT_SWAP_AUTH_FIELDS,
@@ -11708,16 +12969,21 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11708
12969
  VARIABLE_FEE_NUMERATOR,
11709
12970
  VARIABLE_FEE_RATE,
11710
12971
  VERSION,
12972
+ WITHDRAW_FEE_BPS,
12973
+ WITHDRAW_FIXED_FEE,
11711
12974
  assertDirectSubmissionLanded,
11712
12975
  assertInputMints,
11713
12976
  assertTransactionCircuitIntegrity,
12977
+ assessBridgeQuote,
11714
12978
  bigintToBytes32,
11715
12979
  bigintToHex,
12980
+ buildAuthTransactionMessage,
11716
12981
  buildMerkleTree,
11717
12982
  buildMerkleTreeFromChain,
11718
12983
  buildMerkleTreeFromRelay,
11719
12984
  buildRecipientDeliveryNotes,
11720
12985
  buildRelayAuthPreimage,
12986
+ buildRelayBatchAuthMessage,
11721
12987
  buildTransactRequestBody,
11722
12988
  bytesToHex,
11723
12989
  calculateFee,
@@ -11725,12 +12991,16 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11725
12991
  calculateRelayFee,
11726
12992
  canRebuildMerkleTreeFromChain,
11727
12993
  canonicalJson,
12994
+ canonicalPayloadString,
11728
12995
  chainNoteFromBase64,
11729
12996
  chainNoteToBase64,
12997
+ classifyPostFailure,
11730
12998
  classifyRelayError,
12999
+ cleanupReceivingAddress,
11731
13000
  cleanupStalePendingOperations,
11732
13001
  clearPendingDeposits,
11733
13002
  clearPendingWithdrawals,
13003
+ cloakBridgeRail,
11734
13004
  computeChainNoteHash,
11735
13005
  computeExtDataHash,
11736
13006
  computeMerkleRoot,
@@ -11747,15 +13017,19 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11747
13017
  createLogger,
11748
13018
  createRecoverableChangeUtxo,
11749
13019
  createRecoverableDepositUtxo,
13020
+ createRelayBatchAuthCoordinator,
11750
13021
  createUtxo,
11751
13022
  createZeroUtxo,
11752
13023
  decryptCompactChainNote,
11753
13024
  decryptComplianceMetadataWithMasterKey,
11754
13025
  decryptTransactionMetadata,
13026
+ depositFromDerivedKey,
13027
+ deriveBridgeReceiver,
11755
13028
  deriveChangeNoteBlinding,
11756
13029
  deriveDepositNoteSecrets,
11757
13030
  deriveDiversifiedViewingKey,
11758
13031
  deriveDiversifier,
13032
+ deriveFundingTargets,
11759
13033
  deriveInputNullifierPdas,
11760
13034
  derivePublicKey,
11761
13035
  deriveSpendKey,
@@ -11794,6 +13068,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11794
13068
  formatErrorForLogging,
11795
13069
  formatSol,
11796
13070
  fullWithdraw,
13071
+ fundReceiverViaPaymaster,
11797
13072
  generateCloakKeys,
11798
13073
  generateCommitmentAsync,
11799
13074
  generateMasterSeed,
@@ -11829,18 +13104,21 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11829
13104
  isReactNative,
11830
13105
  isRootNotFoundError,
11831
13106
  isSubmissionOutcomeUnknownResponse,
13107
+ isTerminalFailure,
11832
13108
  isValidHex,
11833
13109
  isValidRpcUrl,
11834
13110
  isValidSolanaAddress,
11835
13111
  isWithdrawAmountSufficient,
11836
13112
  isWithdrawable,
11837
13113
  keypairToAdapter,
13114
+ listBridgeDeposits,
11838
13115
  loadPendingDeposits,
11839
13116
  loadPendingWithdrawals,
11840
13117
  loadVerifiedCircuitArtifacts,
11841
13118
  matchChangeNote,
11842
13119
  matchDepositNote,
11843
13120
  matchSwapRefundLeaf,
13121
+ mayRetry,
11844
13122
  openRecipientDeliveryNote,
11845
13123
  parseAmount,
11846
13124
  parseDeliveryCarrierMemo,
@@ -11863,11 +13141,15 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11863
13141
  randomDepositNoteSalt,
11864
13142
  randomFieldElement,
11865
13143
  readMerkleTreeState,
13144
+ readRent,
11866
13145
  recipientDeliveryNoteToBase64,
11867
13146
  registerViewingKey,
13147
+ relayRequestDigestHex,
11868
13148
  removePendingDeposit,
11869
13149
  removePendingWithdrawal,
13150
+ renderAssessment,
11870
13151
  resolveCircuitsBase,
13152
+ retryDelayMs,
11871
13153
  savePendingDeposit,
11872
13154
  savePendingWithdrawal,
11873
13155
  scanNotesForWallet,
@@ -11876,10 +13158,12 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11876
13158
  sdkLogger,
11877
13159
  selectUtxos,
11878
13160
  sendTransaction,
13161
+ serializeAuthTransactionMessage,
11879
13162
  serializeNote,
11880
13163
  serializeUtxo,
11881
13164
  setCircuitsPath,
11882
13165
  setDebugMode,
13166
+ signRelayAuthPayload,
11883
13167
  signTransaction,
11884
13168
  splitTo2Limbs,
11885
13169
  submitTransactToRelay,
@@ -11888,6 +13172,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11888
13172
  swapWithChange,
11889
13173
  toComplianceReport,
11890
13174
  transact,
13175
+ transactBatch,
11891
13176
  transfer,
11892
13177
  truncate,
11893
13178
  tryDecryptNote,
@@ -11900,13 +13185,17 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
11900
13185
  validateDepositParams,
11901
13186
  validateNote,
11902
13187
  validateOutputsSum,
13188
+ validatePaymasterTopUpTransaction,
11903
13189
  validateRoot,
11904
13190
  validateTransfers,
11905
13191
  validateWalletConnected,
11906
13192
  validateWithdrawableNote,
11907
13193
  verifyAllCircuits,
11908
13194
  verifyCircuitIntegrity,
13195
+ verifyQuoteSignature,
11909
13196
  verifyUtxos,
11910
13197
  waitForRoot,
11911
- withTiming
13198
+ withShieldRetries,
13199
+ withTiming,
13200
+ withdrawFeeFor
11912
13201
  });