@cloak.dev/sdk 0.2.5 → 0.2.6-staging.4f665f8

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
@@ -577,6 +577,7 @@ var index_exports = {};
577
577
  __export(index_exports, {
578
578
  AccountRole: () => import_kit7.AccountRole,
579
579
  BRIDGE_ESCROW_LABEL: () => BRIDGE_ESCROW_LABEL,
580
+ BRIDGE_ESCROW_LABEL_V2: () => BRIDGE_ESCROW_LABEL_V2,
580
581
  BUILD_ALLOWS_LOCAL_ENDPOINTS: () => BUILD_ALLOWS_LOCAL_ENDPOINTS,
581
582
  CHAIN_NOTE_SALT_BITS: () => CHAIN_NOTE_SALT_BITS,
582
583
  CLEANUP_FEE_BUDGET: () => CLEANUP_FEE_BUDGET,
@@ -605,6 +606,10 @@ __export(index_exports, {
605
606
  MemoryStorageAdapter: () => MemoryStorageAdapter,
606
607
  MerkleTree: () => MerkleTree,
607
608
  NATIVE_SOL_MINT: () => NATIVE_SOL_MINT,
609
+ NOTE_INDEX_NO_LEAF: () => NOTE_INDEX_NO_LEAF,
610
+ NOTE_INDEX_PAGE_SIZE: () => NOTE_INDEX_PAGE_SIZE,
611
+ NoteIndexFormatError: () => NoteIndexFormatError,
612
+ NoteIndexHeadBehindError: () => NoteIndexHeadBehindError,
608
613
  ONECLICK_PUBKEY_B58: () => ONECLICK_PUBKEY_B58,
609
614
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN: () => RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
610
615
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN: () => RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -681,6 +686,7 @@ __export(index_exports, {
681
686
  computeChainNoteHash: () => computeChainNoteHash,
682
687
  computeExtDataHash: () => computeExtDataHash,
683
688
  computeMerkleRoot: () => computeMerkleRoot,
689
+ computeNoteIndexChain: () => computeNoteIndexChain,
684
690
  computeProofForLatestDeposit: () => computeProofForLatestDeposit,
685
691
  computeProofFromChain: () => computeProofFromChain,
686
692
  computeSignature: () => computeSignature,
@@ -705,14 +711,18 @@ __export(index_exports, {
705
711
  depositFromDerivedKey: () => depositFromDerivedKey,
706
712
  deriveBridgeReceiver: () => deriveBridgeReceiver,
707
713
  deriveChangeNoteBlinding: () => deriveChangeNoteBlinding,
708
- deriveDepositNoteSecrets: () => deriveDepositNoteSecrets,
714
+ deriveDepositNoteBlinding: () => deriveDepositNoteBlinding,
709
715
  deriveDiversifiedViewingKey: () => deriveDiversifiedViewingKey,
710
716
  deriveDiversifier: () => deriveDiversifier,
711
717
  deriveFundingTargets: () => deriveFundingTargets,
712
718
  deriveInputNullifierPdas: () => deriveInputNullifierPdas,
719
+ deriveLegacyBridgeReceiver: () => deriveLegacyBridgeReceiver,
720
+ deriveLegacyDepositNoteSecrets: () => deriveLegacyDepositNoteSecrets,
721
+ deriveLegacySwapRefundAuthorization: () => deriveLegacySwapRefundAuthorization,
713
722
  derivePublicKey: () => derivePublicKey,
714
723
  deriveSpendKey: () => deriveSpendKey,
715
724
  deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
725
+ deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
716
726
  deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
717
727
  deriveUserComplianceScalar: () => deriveUserComplianceScalar,
718
728
  deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
@@ -725,6 +735,8 @@ __export(index_exports, {
725
735
  discoverSwapRefunds: () => discoverSwapRefunds,
726
736
  downloadNote: () => downloadNote,
727
737
  encodeDeliveryCarrierMemo: () => encodeDeliveryCarrierMemo,
738
+ encodeNoteIndexItem: () => encodeNoteIndexItem,
739
+ encodeNoteIndexPage: () => encodeNoteIndexPage,
728
740
  encodeNoteSimple: () => encodeNoteSimple,
729
741
  encodeRecipientDeliveryNote: () => encodeRecipientDeliveryNote,
730
742
  encryptCompactChainNote: () => encryptCompactChainNote,
@@ -740,6 +752,8 @@ __export(index_exports, {
740
752
  fetchCommitments: () => fetchCommitments,
741
753
  fetchLatestBlockhash: () => fetchLatestBlockhash,
742
754
  fetchLookupTables: () => fetchLookupTables,
755
+ fetchNoteIndexHead: () => fetchNoteIndexHead,
756
+ fetchNoteIndexPage: () => fetchNoteIndexPage,
743
757
  fetchRiskQuoteInstruction: () => fetchRiskQuoteInstruction,
744
758
  fetchRiskQuoteIx: () => fetchRiskQuoteIx,
745
759
  fetchSignaturesForAddress: () => fetchSignaturesForAddress,
@@ -812,6 +826,8 @@ __export(index_exports, {
812
826
  parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
813
827
  parseError: () => parseError,
814
828
  parseNote: () => parseNote2,
829
+ parseNoteIndexItem: () => parseNoteIndexItem,
830
+ parseNoteIndexPage: () => parseNoteIndexPage,
815
831
  parseRelayErrorResponse: () => parseRelayErrorResponse,
816
832
  parseRelayErrorSignature: () => parseRelayErrorSignature,
817
833
  parseTransactionError: () => parseTransactionError,
@@ -833,6 +849,7 @@ __export(index_exports, {
833
849
  readMerkleTreeState: () => readMerkleTreeState,
834
850
  readRent: () => readRent,
835
851
  recipientDeliveryNoteToBase64: () => recipientDeliveryNoteToBase64,
852
+ recoverNotesFromIndex: () => recoverNotesFromIndex,
836
853
  registerViewingKey: () => registerViewingKey,
837
854
  relayRequestDigestHex: () => relayRequestDigestHex,
838
855
  removePendingDeposit: () => removePendingDeposit,
@@ -1545,7 +1562,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
1545
1562
 
1546
1563
  // src/config/relay.ts
1547
1564
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
1548
- var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
1565
+ var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
1549
1566
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
1550
1567
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1551
1568
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -1622,6 +1639,44 @@ function isLoopbackHost(value) {
1622
1639
  }
1623
1640
  var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
1624
1641
 
1642
+ // src/relay/clock.ts
1643
+ var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
1644
+ var MAX_CLOCK_DIVERGENCE_MS = 2e3;
1645
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
1646
+ var sample = null;
1647
+ function monotonicNowMs() {
1648
+ const perf = globalThis.performance;
1649
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
1650
+ }
1651
+ function observeRelayClock(response) {
1652
+ const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
1653
+ if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
1654
+ const serverMs = Number(raw.trim());
1655
+ const wallMs = Date.now();
1656
+ const offsetMs = serverMs - wallMs;
1657
+ if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
1658
+ sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
1659
+ }
1660
+ function relayNowMs() {
1661
+ const wallMs = Date.now();
1662
+ if (!sample) return wallMs;
1663
+ const wallElapsed = wallMs - sample.wallAtSampleMs;
1664
+ const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
1665
+ if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
1666
+ sample = null;
1667
+ return wallMs;
1668
+ }
1669
+ return wallMs + sample.offsetMs;
1670
+ }
1671
+ function hasRelayClockSample() {
1672
+ if (!sample) return false;
1673
+ relayNowMs();
1674
+ return sample !== null;
1675
+ }
1676
+ function relayNowSeconds() {
1677
+ return Math.floor(relayNowMs() / 1e3);
1678
+ }
1679
+
1625
1680
  // src/relay/endpoint.ts
1626
1681
  var ALLOWED_ORIGINS = new Set(
1627
1682
  RELAY_ORIGIN_ALLOWLIST.map((entry) => {
@@ -1670,9 +1725,48 @@ function assertAllowedRelayOrigin(value) {
1670
1725
  }
1671
1726
  return trimmed.replace(/\/$/, "");
1672
1727
  }
1673
- async function relayFetch(url, init) {
1728
+ async function relayFetch(url, init, options) {
1674
1729
  assertAllowedRelayOrigin(url);
1675
- return fetch(url, init);
1730
+ const extra = sanitizeExtraHeaders(options?.extraHeaders);
1731
+ const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
1732
+ if (options?.observeClock !== false) observeRelayClock(response);
1733
+ return response;
1734
+ }
1735
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1736
+ var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
1737
+ function sanitizeExtraHeaders(extra) {
1738
+ if (!extra || typeof extra !== "object") return void 0;
1739
+ const out = {};
1740
+ let any = false;
1741
+ for (const [name, value] of Object.entries(extra)) {
1742
+ if (typeof name !== "string" || !HEADER_NAME.test(name)) continue;
1743
+ if (typeof value !== "string" || FORBIDDEN_HEADER_VALUE_CHARS.test(value)) continue;
1744
+ out[name] = value;
1745
+ any = true;
1746
+ }
1747
+ return any ? out : void 0;
1748
+ }
1749
+ function mergeRelayHeaders(base, extraHeaders) {
1750
+ const extra = sanitizeExtraHeaders(extraHeaders);
1751
+ if (!extra) return base;
1752
+ const merged = {};
1753
+ const taken = /* @__PURE__ */ new Set();
1754
+ const put = (name, value) => {
1755
+ merged[name] = value;
1756
+ taken.add(name.toLowerCase());
1757
+ };
1758
+ if (typeof Headers !== "undefined" && base instanceof Headers) {
1759
+ base.forEach((value, name) => put(name, value));
1760
+ } else if (Array.isArray(base)) {
1761
+ for (const [name, value] of base) put(name, value);
1762
+ } else if (base) {
1763
+ for (const [name, value] of Object.entries(base)) put(name, value);
1764
+ }
1765
+ for (const [name, value] of Object.entries(extra)) {
1766
+ if (taken.has(name.toLowerCase())) continue;
1767
+ put(name, value);
1768
+ }
1769
+ return merged;
1676
1770
  }
1677
1771
  function assertAllowedRpcEndpoint(endpoint) {
1678
1772
  if (BUILD_ALLOWS_LOCAL_ENDPOINTS) return;
@@ -2022,6 +2116,7 @@ var TRANSACT_SWAP_AUTH_FIELDS = [
2022
2116
  "slippage_bps",
2023
2117
  "swap_max_retries"
2024
2118
  ];
2119
+ var RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT = ["affiliate_code"];
2025
2120
  var UTF8 = new TextEncoder();
2026
2121
  function compareKeysBytewise(a, b) {
2027
2122
  if (a === b) return 0;
@@ -2085,6 +2180,11 @@ function buildAuthRequest(body, sender, fields) {
2085
2180
  }
2086
2181
  out[k] = value;
2087
2182
  }
2183
+ for (const k of RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT) {
2184
+ const value = body[k];
2185
+ if (value === void 0 || value === null) continue;
2186
+ out[k] = value;
2187
+ }
2088
2188
  return out;
2089
2189
  }
2090
2190
  function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
@@ -2100,7 +2200,7 @@ ${digest}`
2100
2200
  }
2101
2201
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
2102
2202
  const senderB58 = sender;
2103
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
2203
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
2104
2204
  const nonce = randomNonceUuid();
2105
2205
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
2106
2206
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -2179,7 +2279,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
2179
2279
  `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.`
2180
2280
  );
2181
2281
  }
2182
- function explainRelayAuthRejection(responseText) {
2282
+ function explainRelayAuthRejection(responseText, context) {
2183
2283
  const text = String(responseText);
2184
2284
  const has = (needle) => text.includes(needle);
2185
2285
  if (has("issued too far in the future")) {
@@ -2189,7 +2289,9 @@ function explainRelayAuthRejection(responseText) {
2189
2289
  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.`;
2190
2290
  }
2191
2291
  if (has("does not match the exact request")) {
2192
- 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\`.`;
2292
+ const base = `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\`.`;
2293
+ if (!context?.carriedAffiliateCode) return base;
2294
+ return `${base} This request carried \`affiliate_code\`, which is signed with the rest of the body. A relay that predates the affiliate release (REL-010/REL-011) ignores that field and leaves it out of its digest, which produces exactly this mismatch. Upgrade the relay, or send the request without \`affiliateCode\`.`;
2193
2295
  }
2194
2296
  if (has("has no registered viewing key")) {
2195
2297
  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.`;
@@ -4753,6 +4855,27 @@ function isRootAccepted(data, rootHex) {
4753
4855
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
4754
4856
  return readRootHistory(data).some((r) => r === want);
4755
4857
  }
4858
+ function treeAccountAcceptsRoot(data, rootHex) {
4859
+ const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
4860
+ if (data.length >= ROOT_OFFSET + 32) {
4861
+ const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
4862
+ if (current === want) return true;
4863
+ }
4864
+ return isRootAccepted(data, want);
4865
+ }
4866
+ function readTreeAccountFrontier(data) {
4867
+ if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
4868
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
4869
+ const next = readBigUInt64LE(buf, 32);
4870
+ if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
4871
+ const subtrees = [];
4872
+ for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
4873
+ const offset = SUBTREES_OFFSET + level * 32;
4874
+ subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
4875
+ }
4876
+ const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
4877
+ return { nextIndex: Number(next), subtrees, root };
4878
+ }
4756
4879
 
4757
4880
  // src/proving/merkle.ts
4758
4881
  var import_circomlibjs3 = require("circomlibjs");
@@ -4912,6 +5035,89 @@ var MerkleTree = class _MerkleTree {
4912
5035
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4913
5036
  return MerkleTree.create(height, commitments);
4914
5037
  }
5038
+ var MerkleFrontier = class _MerkleFrontier {
5039
+ constructor(levels, zeros, poseidon3, count, left) {
5040
+ this.levels = levels;
5041
+ this.zeros = zeros;
5042
+ this.poseidon = poseidon3;
5043
+ this.count = count;
5044
+ this.left = left;
5045
+ }
5046
+ static async create(state, levels = MERKLE_TREE_HEIGHT2) {
5047
+ const zeros = await getZeroValues();
5048
+ const poseidon3 = await getPoseidon3();
5049
+ const left = new Array(levels).fill(null);
5050
+ let count = 0;
5051
+ if (state) {
5052
+ if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
5053
+ throw new Error("MerkleFrontierState.nextIndex out of range");
5054
+ }
5055
+ if (!Array.isArray(state.left) || state.left.length !== levels) {
5056
+ throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
5057
+ }
5058
+ count = state.nextIndex;
5059
+ for (let l = 0; l < levels; l++) {
5060
+ const odd = Math.floor(count / 2 ** l) % 2 === 1;
5061
+ const entry = state.left[l];
5062
+ if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
5063
+ if (odd) {
5064
+ if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
5065
+ left[l] = BigInt("0x" + entry);
5066
+ }
5067
+ }
5068
+ }
5069
+ return new _MerkleFrontier(levels, zeros, poseidon3, count, left);
5070
+ }
5071
+ get nextIndex() {
5072
+ return this.count;
5073
+ }
5074
+ /**
5075
+ * The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
5076
+ * present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
5077
+ * With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
5078
+ */
5079
+ leftAt(level) {
5080
+ if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
5081
+ return this.left[level];
5082
+ }
5083
+ hash(a, b) {
5084
+ return this.poseidon.F.toObject(this.poseidon([a, b]));
5085
+ }
5086
+ /** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
5087
+ append(leaves) {
5088
+ if (leaves.length === 0) return;
5089
+ if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
5090
+ let nodes = leaves;
5091
+ for (let l = 0; l < this.levels && nodes.length > 0; l++) {
5092
+ const before = Math.floor(this.count / 2 ** l);
5093
+ const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
5094
+ const parents = [];
5095
+ for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
5096
+ this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
5097
+ nodes = parents;
5098
+ }
5099
+ this.count += leaves.length;
5100
+ }
5101
+ /** The root of the first `nextIndex` leaves, zero-padded to the right. */
5102
+ root() {
5103
+ let partial = this.zeros[0];
5104
+ for (let l = 0; l < this.levels; l++) {
5105
+ const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
5106
+ if (odd) partial = this.hash(this.left[l], partial);
5107
+ else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
5108
+ }
5109
+ return partial;
5110
+ }
5111
+ toState() {
5112
+ return {
5113
+ nextIndex: this.count,
5114
+ left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
5115
+ };
5116
+ }
5117
+ clone() {
5118
+ return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
5119
+ }
5120
+ };
4915
5121
 
4916
5122
  // src/relay/client.ts
4917
5123
  init_address();
@@ -5063,6 +5269,7 @@ async function fetchWithRetry(url, options = {}) {
5063
5269
  try {
5064
5270
  const response = await fetch(url, { signal: controller.signal });
5065
5271
  clearTimeout(timeoutId);
5272
+ observeRelayClock(response);
5066
5273
  return response;
5067
5274
  } finally {
5068
5275
  clearTimeout(timeoutId);
@@ -5415,38 +5622,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
5415
5622
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
5416
5623
  return new Uint8Array(plaintext);
5417
5624
  }
5418
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
5625
+ async function importNkHkdfKey(nk) {
5419
5626
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5420
5627
  throw new Error("nk must be 32 bytes");
5421
5628
  }
5629
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
5630
+ }
5631
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
5422
5632
  const subtle = getSubtleCrypto2();
5423
- const ikm = await subtle.importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
5424
- const salt = hexToBytes32(commitmentHex);
5425
- const keyBits = await subtle.deriveBits(
5426
- {
5427
- name: "HKDF",
5428
- hash: "SHA-256",
5429
- salt: toArrayBuffer2(salt),
5430
- info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
5431
- },
5432
- ikm,
5433
- 256
5434
- );
5435
- const nonceBits = await subtle.deriveBits(
5436
- {
5437
- name: "HKDF",
5438
- hash: "SHA-256",
5439
- salt: toArrayBuffer2(salt),
5440
- info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
5441
- },
5442
- ikm,
5443
- 96
5444
- );
5633
+ const [keyBits, nonceBits] = await Promise.all([
5634
+ subtle.deriveBits(
5635
+ {
5636
+ name: "HKDF",
5637
+ hash: "SHA-256",
5638
+ salt: toArrayBuffer2(salt),
5639
+ info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
5640
+ },
5641
+ ikm,
5642
+ 256
5643
+ ),
5644
+ subtle.deriveBits(
5645
+ {
5646
+ name: "HKDF",
5647
+ hash: "SHA-256",
5648
+ salt: toArrayBuffer2(salt),
5649
+ info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
5650
+ },
5651
+ ikm,
5652
+ 96
5653
+ )
5654
+ ]);
5445
5655
  return {
5446
5656
  key: new Uint8Array(keyBits),
5447
5657
  nonce: new Uint8Array(nonceBits)
5448
5658
  };
5449
5659
  }
5660
+ async function deriveAesKeyAndNonce(nk, commitmentHex) {
5661
+ const ikm = await importNkHkdfKey(nk);
5662
+ return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
5663
+ }
5664
+ function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
5665
+ if (version === NOTE_VERSION_V4) {
5666
+ if (plaintext.length !== PLAINTEXT_LEN_V4) {
5667
+ throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
5668
+ }
5669
+ return {
5670
+ timestamp: readU64LE(plaintext, 0),
5671
+ commitment: commitmentHex.toLowerCase(),
5672
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
5673
+ outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
5674
+ outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
5675
+ isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
5676
+ };
5677
+ }
5678
+ if (version === NOTE_VERSION_V3) {
5679
+ if (plaintext.length !== PLAINTEXT_LEN_V3) {
5680
+ throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
5681
+ }
5682
+ return {
5683
+ timestamp: readU64LE(plaintext, 0),
5684
+ commitment: commitmentHex.toLowerCase(),
5685
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
5686
+ };
5687
+ }
5688
+ if (plaintext.length !== PLAINTEXT_LEN_V2) {
5689
+ throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
5690
+ }
5691
+ return {
5692
+ timestamp: readU64LE(plaintext, 0),
5693
+ commitment: commitmentHex.toLowerCase()
5694
+ };
5695
+ }
5450
5696
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
5451
5697
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5452
5698
  throw new Error("nk must be 32 bytes");
@@ -5510,36 +5756,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5510
5756
  try {
5511
5757
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
5512
5758
  const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
5513
- if (version === NOTE_VERSION_V4) {
5514
- if (plaintext.length !== PLAINTEXT_LEN_V4) {
5515
- throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
5516
- }
5517
- return {
5518
- timestamp: readU64LE(plaintext, 0),
5519
- commitment: commitment.toLowerCase(),
5520
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
5521
- outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
5522
- outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
5523
- isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
5524
- };
5525
- }
5526
- if (version === NOTE_VERSION_V3) {
5527
- if (plaintext.length !== PLAINTEXT_LEN_V3) {
5528
- throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
5529
- }
5530
- return {
5531
- timestamp: readU64LE(plaintext, 0),
5532
- commitment: commitment.toLowerCase(),
5533
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
5534
- };
5535
- }
5536
- if (plaintext.length !== PLAINTEXT_LEN_V2) {
5537
- throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
5538
- }
5539
- return {
5540
- timestamp: readU64LE(plaintext, 0),
5541
- commitment: commitment.toLowerCase()
5542
- };
5759
+ return decodeChainNotePlaintext(version, plaintext, commitment);
5543
5760
  } catch (error) {
5544
5761
  lastError = error;
5545
5762
  }
@@ -5548,6 +5765,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5548
5765
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
5549
5766
  );
5550
5767
  }
5768
+ async function createCompactChainNoteDecryptor(nk) {
5769
+ const ikm = await importNkHkdfKey(nk);
5770
+ return async (noteBytes, commitment) => {
5771
+ if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
5772
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
5773
+ const version = noteBytes[0];
5774
+ if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
5775
+ return null;
5776
+ }
5777
+ try {
5778
+ const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
5779
+ const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
5780
+ let hex = "";
5781
+ for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
5782
+ return decodeChainNotePlaintext(version, plaintext, hex);
5783
+ } catch {
5784
+ return null;
5785
+ }
5786
+ };
5787
+ }
5551
5788
  function chainNoteToBase64(noteBytes) {
5552
5789
  return Buffer.from(noteBytes).toString("base64");
5553
5790
  }
@@ -5644,6 +5881,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
5644
5881
  return null;
5645
5882
  }
5646
5883
  }
5884
+ var X25519_PKCS8_PREFIX = Uint8Array.from([
5885
+ 48,
5886
+ 46,
5887
+ 2,
5888
+ 1,
5889
+ 0,
5890
+ 48,
5891
+ 5,
5892
+ 6,
5893
+ 3,
5894
+ 43,
5895
+ 101,
5896
+ 110,
5897
+ 4,
5898
+ 34,
5899
+ 4,
5900
+ 32
5901
+ ]);
5902
+ var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
5903
+ function decodeOpened(plaintext) {
5904
+ if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5905
+ return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5906
+ }
5907
+ async function createRecipientDeliveryOpener(viewingSecretKey) {
5908
+ if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
5909
+ throw new Error("viewingSecretKey must be 32 bytes");
5910
+ }
5911
+ const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5912
+ const subtle = globalThis.crypto?.subtle;
5913
+ const hsalsa = import_tweetnacl4.default.lowlevel?.crypto_core_hsalsa20;
5914
+ if (!subtle || typeof hsalsa !== "function") return slow;
5915
+ let privateKey;
5916
+ const sharedKey = async (ephemeralPk) => {
5917
+ const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
5918
+ const shared = new Uint8Array(
5919
+ await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
5920
+ );
5921
+ const key = new Uint8Array(32);
5922
+ hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
5923
+ return key;
5924
+ };
5925
+ try {
5926
+ const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
5927
+ pkcs8.set(X25519_PKCS8_PREFIX);
5928
+ pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5929
+ privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5930
+ const probe = import_tweetnacl4.default.box.keyPair().publicKey;
5931
+ const fast = await sharedKey(probe);
5932
+ const reference = import_tweetnacl4.default.box.before(probe, viewingSecretKey);
5933
+ if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5934
+ } catch {
5935
+ return slow;
5936
+ }
5937
+ return async (envelope) => {
5938
+ if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
5939
+ const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
5940
+ const nonce = envelope.subarray(
5941
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
5942
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5943
+ );
5944
+ const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
5945
+ let key;
5946
+ try {
5947
+ key = await sharedKey(ephemeralPk);
5948
+ } catch {
5949
+ return openRecipientDeliveryNote(envelope, viewingSecretKey);
5950
+ }
5951
+ try {
5952
+ return decodeOpened(import_tweetnacl4.default.secretbox.open(ciphertext, nonce, key));
5953
+ } catch {
5954
+ return null;
5955
+ }
5956
+ };
5957
+ }
5647
5958
  function recipientDeliveryNoteToBase64(envelope) {
5648
5959
  return Buffer.from(envelope).toString("base64");
5649
5960
  }
@@ -5698,10 +6009,43 @@ var import_blake34 = require("@noble/hashes/blake3");
5698
6009
  init_address();
5699
6010
  var import_bs582 = __toESM(require("bs58"), 1);
5700
6011
  init_utxo();
6012
+
6013
+ // src/notes/owner-key.ts
6014
+ init_utxo();
6015
+ var FIELD_MODULUS2 = BigInt(
6016
+ "21888242871839275222246405745257275088548364400416034343698204186575808495617"
6017
+ );
6018
+ async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
6019
+ if (!keypair || typeof keypair !== "object") {
6020
+ throw new Error(
6021
+ `${label} is required: pass the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). Self-owned notes are never owned by a key derived from the viewing key nk.`
6022
+ );
6023
+ }
6024
+ const { privateKey, publicKey } = keypair;
6025
+ if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS2) {
6026
+ throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
6027
+ }
6028
+ if (typeof publicKey !== "bigint" || publicKey === 0n) {
6029
+ throw new Error(`${label}.publicKey must be a non-zero bigint`);
6030
+ }
6031
+ if (await derivePublicKey(privateKey) !== publicKey) {
6032
+ throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
6033
+ }
6034
+ return { privateKey, publicKey };
6035
+ }
6036
+ function normalizeOwnerPublicKey(publicKey, label) {
6037
+ if (publicKey === void 0 || publicKey === null) return void 0;
6038
+ if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS2) {
6039
+ throw new Error(`${label} must be a non-zero field element (bigint)`);
6040
+ }
6041
+ return publicKey;
6042
+ }
6043
+
6044
+ // src/notes/swap-refund.ts
5701
6045
  init_inputs();
5702
6046
  var bs582 = import_bs582.default.default || import_bs582.default;
5703
6047
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
5704
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6048
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5705
6049
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
5706
6050
  function normalizeNullifier(inputNullifier) {
5707
6051
  if (inputNullifier instanceof Uint8Array) {
@@ -5735,13 +6079,29 @@ function derive(nk, nullifier, info) {
5735
6079
  preimage.set(info, off);
5736
6080
  return (0, import_blake34.blake3)(preimage);
5737
6081
  }
5738
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
6082
+ function assertNk(viewingKeyNk) {
5739
6083
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5740
6084
  throw new Error("viewingKeyNk must be 32 bytes");
5741
6085
  }
6086
+ return viewingKeyNk;
6087
+ }
6088
+ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
6089
+ const nk = assertNk(viewingKeyNk);
6090
+ return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
6091
+ }
6092
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
6093
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
6094
+ const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
6095
+ if (owner.publicKey === 0n || blinding === 0n) {
6096
+ throw new Error("refund authorization is degenerate");
6097
+ }
6098
+ return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
6099
+ }
6100
+ async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
6101
+ const nk = assertNk(viewingKeyNk);
5742
6102
  const nullifier = normalizeNullifier(inputNullifier);
5743
- const privateKey = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_PRIVATE_KEY_INFO));
5744
- const blinding = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_BLINDING_INFO));
6103
+ const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
6104
+ const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
5745
6105
  const publicKey = await derivePublicKey(privateKey);
5746
6106
  if (publicKey === 0n || blinding === 0n) {
5747
6107
  throw new Error("derived refund authorization is degenerate");
@@ -5759,19 +6119,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
5759
6119
  async function matchSwapRefundLeaf(params) {
5760
6120
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
5761
6121
  const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
5762
- let auth;
6122
+ let blinding;
6123
+ try {
6124
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
6125
+ } catch {
6126
+ return null;
6127
+ }
6128
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
6129
+ if (ownerPub !== void 0) {
6130
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
6131
+ if (candidate === expected) {
6132
+ return {
6133
+ keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
6134
+ blinding,
6135
+ amount: amountAfterFee,
6136
+ commitment: candidate,
6137
+ legacyExposed: false
6138
+ };
6139
+ }
6140
+ }
6141
+ let legacy;
5763
6142
  try {
5764
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
6143
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
5765
6144
  } catch {
5766
6145
  return null;
5767
6146
  }
5768
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
5769
- if (candidate !== expected) return null;
6147
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
6148
+ if (legacyCandidate !== expected) return null;
5770
6149
  return {
5771
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
5772
- blinding: auth.blinding,
6150
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
6151
+ blinding: legacy.blinding,
5773
6152
  amount: amountAfterFee,
5774
- commitment: candidate
6153
+ commitment: legacyCandidate,
6154
+ legacyExposed: true
5775
6155
  };
5776
6156
  }
5777
6157
  var TRANSACT_SWAP_TAG2 = 1;
@@ -5835,10 +6215,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
5835
6215
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
5836
6216
  return out;
5837
6217
  }
5838
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
6218
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
5839
6219
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5840
6220
  throw new Error("viewingKeyNk must be 32 bytes");
5841
6221
  }
6222
+ if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
6223
+ throw new Error(
6224
+ "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are owned by it, and nk alone can only find legacy refunds."
6225
+ );
6226
+ }
6227
+ const ownerUtxoKeypair = options.ownerUtxoKeypair;
5842
6228
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5843
6229
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5844
6230
  const programIdBase58 = programId;
@@ -5913,7 +6299,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5913
6299
  viewingKeyNk,
5914
6300
  inputNullifier: candidate.nullifier,
5915
6301
  amountAfterFee: event.amountAfterFee,
5916
- commitment: event.commitmentField
6302
+ commitment: event.commitmentField,
6303
+ ownerUtxoKeypair
5917
6304
  });
5918
6305
  if (!recovered) continue;
5919
6306
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5939,7 +6326,7 @@ var import_blake35 = require("@noble/hashes/blake3");
5939
6326
  init_utxo();
5940
6327
  init_inputs();
5941
6328
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5942
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6329
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5943
6330
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5944
6331
  var CHAIN_NOTE_SALT_BITS = 96;
5945
6332
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -5975,30 +6362,47 @@ function derive2(nk, salt, info) {
5975
6362
  preimage.set(info, off);
5976
6363
  return (0, import_blake35.blake3)(preimage);
5977
6364
  }
6365
+ function assertNk2(viewingKeyNk) {
6366
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
6367
+ throw new Error("viewingKeyNk must be 32 bytes");
6368
+ }
6369
+ return viewingKeyNk;
6370
+ }
5978
6371
  function randomDepositNoteSalt() {
5979
6372
  const bytes = randomBytes(12);
5980
6373
  let v = 0n;
5981
6374
  for (const b of bytes) v = v << 8n | BigInt(b);
5982
6375
  return v === 0n ? 1n : v;
5983
6376
  }
5984
- async function deriveDepositNoteSecrets(viewingKeyNk, noteSalt) {
5985
- if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5986
- throw new Error("viewingKeyNk must be 32 bytes");
5987
- }
6377
+ function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
6378
+ const nk = assertNk2(viewingKeyNk);
6379
+ return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
6380
+ }
6381
+ async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
6382
+ const nk = assertNk2(viewingKeyNk);
5988
6383
  const salt = saltToBytes(noteSalt);
5989
- const privateKey = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_PRIVATE_KEY_INFO));
5990
- const blinding = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_BLINDING_INFO));
6384
+ const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
6385
+ const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
5991
6386
  const publicKey = await derivePublicKey(privateKey);
5992
6387
  if (publicKey === 0n || blinding === 0n) {
5993
6388
  throw new Error("derived deposit note secrets are degenerate");
5994
6389
  }
5995
6390
  return { keypair: { privateKey, publicKey }, blinding };
5996
6391
  }
5997
- async function createRecoverableDepositUtxo(amount, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomDepositNoteSalt()) {
6392
+ async function createRecoverableDepositUtxo(params) {
6393
+ if (!params || typeof params !== "object" || params instanceof Uint8Array) {
6394
+ throw new Error(
6395
+ "createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
6396
+ );
6397
+ }
6398
+ const { amount, viewingKeyNk } = params;
5998
6399
  if (typeof amount !== "bigint" || amount <= 0n) {
5999
6400
  throw new Error("amount must be a positive bigint");
6000
6401
  }
6001
- const { keypair, blinding } = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
6402
+ const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
6403
+ const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
6404
+ const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
6405
+ const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
6002
6406
  const utxo = { amount, keypair, blinding, mintAddress };
6003
6407
  utxo.commitment = await computeCommitment2(utxo);
6004
6408
  return { utxo, noteSalt };
@@ -6013,21 +6417,46 @@ function normalizeCommitment(value) {
6013
6417
  async function matchDepositNote(params) {
6014
6418
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
6015
6419
  if (typeof amount !== "bigint" || amount <= 0n) return null;
6016
- let secrets;
6420
+ let blinding;
6421
+ try {
6422
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
6423
+ } catch {
6424
+ return null;
6425
+ }
6426
+ const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
6427
+ if (published.length === 0) return null;
6428
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
6429
+ if (ownerPub !== void 0) {
6430
+ const keypair = {
6431
+ privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
6432
+ publicKey: ownerPub
6433
+ };
6434
+ const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
6435
+ if (published.some((value) => value === candidate)) {
6436
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
6437
+ }
6438
+ }
6439
+ let legacy;
6017
6440
  try {
6018
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
6441
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
6019
6442
  } catch {
6020
6443
  return null;
6021
6444
  }
6022
- const candidate = await computeCommitment2({
6445
+ const legacyCandidate = await computeCommitment2({
6023
6446
  amount,
6024
- keypair: secrets.keypair,
6025
- blinding: secrets.blinding,
6447
+ keypair: legacy.keypair,
6448
+ blinding: legacy.blinding,
6026
6449
  mintAddress
6027
6450
  });
6028
- const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
6029
- if (!published.some((value) => value === candidate)) return null;
6030
- return { ...secrets, amount, mintAddress, commitment: candidate, noteSalt };
6451
+ if (!published.some((value) => value === legacyCandidate)) return null;
6452
+ return {
6453
+ ...legacy,
6454
+ amount,
6455
+ mintAddress,
6456
+ commitment: legacyCandidate,
6457
+ noteSalt,
6458
+ legacyExposed: true
6459
+ };
6031
6460
  }
6032
6461
 
6033
6462
  // src/notes/change-note.ts
@@ -6085,10 +6514,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
6085
6514
  preimage.set(CHANGE_BLINDING_INFO, off);
6086
6515
  return toFieldSecret3((0, import_blake36.blake3)(preimage));
6087
6516
  }
6088
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
6517
+ async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
6089
6518
  if (typeof amount !== "bigint" || amount <= 0n) {
6090
6519
  throw new Error("amount must be a positive bigint");
6091
6520
  }
6521
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
6092
6522
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
6093
6523
  const utxo = { amount, keypair, blinding, mintAddress };
6094
6524
  utxo.commitment = await computeCommitment2(utxo);
@@ -6114,12 +6544,28 @@ async function matchChangeNote(params) {
6114
6544
  const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
6115
6545
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
6116
6546
  if (!published.some((value) => value === candidate)) return null;
6117
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
6547
+ const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
6548
+ const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
6549
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
6118
6550
  }
6119
6551
 
6120
6552
  // src/flows/transact.ts
6121
6553
  var import_circomlibjs4 = require("circomlibjs");
6122
6554
  var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
6555
+
6556
+ // src/relay/chain-note-time.ts
6557
+ async function relayChainNoteTimestampMs(relayUrl) {
6558
+ if (relayUrl && !hasRelayClockSample()) {
6559
+ try {
6560
+ const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
6561
+ await response.body?.cancel?.().catch(() => void 0);
6562
+ } catch {
6563
+ }
6564
+ }
6565
+ return BigInt(relayNowMs());
6566
+ }
6567
+
6568
+ // src/flows/transact.ts
6123
6569
  init_inputs();
6124
6570
 
6125
6571
  // src/proving/artifacts.ts
@@ -6742,6 +7188,9 @@ function assertInputMints(inputUtxos, expectedMint) {
6742
7188
  );
6743
7189
  }
6744
7190
  }
7191
+ function affiliateCodeOrUndefined(code) {
7192
+ return typeof code === "string" && code.length > 0 ? code : void 0;
7193
+ }
6745
7194
  function parseNkInput(input) {
6746
7195
  if (typeof input !== "string") {
6747
7196
  if (input.length !== 32) {
@@ -6755,6 +7204,33 @@ function parseNkInput(input) {
6755
7204
  }
6756
7205
  return Uint8Array.from(Buffer.from(clean, "hex"));
6757
7206
  }
7207
+ async function resolveWalletNk(options) {
7208
+ const explicit = await resolveChainNoteNk(options);
7209
+ if (explicit) return explicit;
7210
+ if (options.ownerUtxoKeypair) {
7211
+ const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
7212
+ return getNkFromUtxoPrivateKey(owner.privateKey);
7213
+ }
7214
+ return null;
7215
+ }
7216
+ function missingWalletNkError(flow) {
7217
+ return new Error(
7218
+ `${flow} requires the wallet's viewing key: pass chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair to use its canonical nk. The SDK no longer infers nk from a note's own key.`
7219
+ );
7220
+ }
7221
+ async function requireWalletNk(options, flow) {
7222
+ const nk = await resolveWalletNk(options);
7223
+ if (nk) return nk;
7224
+ throw missingWalletNkError(flow);
7225
+ }
7226
+ async function requireOwnerUtxoKeypair(options, flow) {
7227
+ if (!options.ownerUtxoKeypair) {
7228
+ throw new Error(
7229
+ `${flow} requires options.ownerUtxoKeypair, the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). It owns the change and refund notes this flow creates; the SDK no longer inherits that owner from inputUtxos[0].`
7230
+ );
7231
+ }
7232
+ return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
7233
+ }
6758
7234
  async function resolveChainNoteNk(options) {
6759
7235
  if (options.chainNoteViewingKeyNk) {
6760
7236
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -6772,7 +7248,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
6772
7248
  function toHex(bytes) {
6773
7249
  return Buffer.from(bytes).toString("hex");
6774
7250
  }
6775
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
7251
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
6776
7252
  if (options.enforceViewingKeyRegistration === false) {
6777
7253
  return;
6778
7254
  }
@@ -6786,7 +7262,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6786
7262
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
6787
7263
  );
6788
7264
  }
6789
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
7265
+ const nk = walletNk;
6790
7266
  if (!nk || nk.length !== 32) {
6791
7267
  throw new Error(
6792
7268
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6928,10 +7404,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6928
7404
  result.set(bigintToBytes323(BigInt(publicSignals[0])), offset);
6929
7405
  offset += 32;
6930
7406
  let amount = BigInt(publicSignals[1]);
6931
- const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6932
- const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
7407
+ const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
7408
+ const HALF_FIELD = FIELD_MODULUS3 / BigInt(2);
6933
7409
  if (amount > HALF_FIELD) {
6934
- amount = amount - FIELD_MODULUS2;
7410
+ amount = amount - FIELD_MODULUS3;
6935
7411
  }
6936
7412
  const amountBytes = new Uint8Array(8);
6937
7413
  let amountValue = amount;
@@ -7878,8 +8354,9 @@ function chargeWalletApproval(used, budget, lastError) {
7878
8354
  }
7879
8355
  return used + 1;
7880
8356
  }
7881
- function relayFailureMessage(prefix, responseText) {
7882
- const explanation = explainRelayAuthRejection(responseText);
8357
+ function relayFailureMessage(prefix, responseText, requestBody) {
8358
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
8359
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7883
8360
  return explanation ? `${prefix}: ${responseText}
7884
8361
 
7885
8362
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -8085,6 +8562,39 @@ function buildTransactRequestBody(params) {
8085
8562
  if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
8086
8563
  body.recipient_delivery_notes = params.recipientDeliveryNotes;
8087
8564
  }
8565
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
8566
+ if (affiliateCode && params.externalAmount < BigInt(0) && params.recipient) {
8567
+ body.affiliate_code = affiliateCode;
8568
+ }
8569
+ return body;
8570
+ }
8571
+ function buildTransactSwapRequestBody(params) {
8572
+ const body = {
8573
+ proof_bytes: params.proofB64,
8574
+ public_inputs: params.publicInputsB64,
8575
+ output_mint: params.outputMint,
8576
+ recipient_ata: params.recipientAta,
8577
+ recipient: params.recipientWallet,
8578
+ // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
8579
+ // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
8580
+ min_output_amount: params.minOutputAmount.toString(),
8581
+ // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
8582
+ max_fee: params.maxFee.toString(),
8583
+ slippage_bps: params.slippageBps,
8584
+ dexes: params.dexes && params.dexes.length > 0 ? params.dexes : void 0,
8585
+ exclude_dexes: params.excludeDexes && params.excludeDexes.length > 0 ? params.excludeDexes : void 0,
8586
+ route_retry_attempts: params.routeRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(params.routeRetryAttempts))) : void 0,
8587
+ swap_max_retries: params.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(params.swapMaxRetries))) : void 0,
8588
+ encrypted_notes: params.encryptedNotes,
8589
+ risk_quote: params.riskQuote,
8590
+ // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
8591
+ // bound into the proof's ext_data_hash. The relay forwards both verbatim into the swap
8592
+ // params; the program builds the amount-bound R_fb from them at close.
8593
+ refund_pubkey: params.refundPubkeyB64,
8594
+ refund_blinding: params.refundBlindingB64
8595
+ };
8596
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
8597
+ if (affiliateCode) body.affiliate_code = affiliateCode;
8088
8598
  return body;
8089
8599
  }
8090
8600
  function resolveUserWallet(options) {
@@ -8220,10 +8730,11 @@ async function submitTransactToRelay(args) {
8220
8730
  try {
8221
8731
  response = await doFetch(`${relayUrl}/transact`, {
8222
8732
  method: "POST",
8223
- headers: { "Content-Type": "application/json" },
8733
+ headers: mergeRelayHeaders({ "Content-Type": "application/json" }, args.extraHeaders),
8224
8734
  body: requestPayload,
8225
8735
  signal: controller.signal
8226
8736
  });
8737
+ observeRelayClock(response);
8227
8738
  } finally {
8228
8739
  clearTimeout(timeoutId);
8229
8740
  }
@@ -8254,7 +8765,9 @@ async function submitTransactToRelay(args) {
8254
8765
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
8255
8766
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
8256
8767
  }
8257
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
8768
+ return await resolveFailure(
8769
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8770
+ );
8258
8771
  }
8259
8772
  const apiResponse = JSON.parse(responseText);
8260
8773
  if (!apiResponse.success || !apiResponse.data) {
@@ -8271,7 +8784,7 @@ async function submitTransactToRelay(args) {
8271
8784
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
8272
8785
  }
8273
8786
  return await resolveFailure(
8274
- new Error(relayFailureMessage("Relay returned error", errorStr))
8787
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
8275
8788
  );
8276
8789
  }
8277
8790
  const result = apiResponse.data;
@@ -8379,34 +8892,37 @@ async function transact(params, options) {
8379
8892
  );
8380
8893
  }
8381
8894
  onProgress?.("Validating transaction parameters...");
8382
- const firstInputWithAmount = inputUtxos.find((u) => u.amount > BigInt(0));
8383
- const firstOutputWithAmount = outputUtxos.find((u) => u.amount > BigInt(0));
8384
- const fallbackNk = firstOutputWithAmount ? getNkFromUtxoPrivateKey(firstOutputWithAmount.keypair.privateKey) : firstInputWithAmount ? getNkFromUtxoPrivateKey(firstInputWithAmount.keypair.privateKey) : void 0;
8385
- const explicitChainNoteNk = await resolveChainNoteNk(options);
8386
- if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
8895
+ const walletNk = await resolveWalletNk(options);
8896
+ const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
8897
+ if (options.chainNoteSalt !== void 0 && !walletNk) {
8387
8898
  throw new Error(
8388
- "options.chainNoteSalt requires an explicit chainNoteViewingKeyNk (or getChainNoteViewingKeyNk). The salt anchors a deposit note derived from that nk; inferring nk from the output note's own key would encrypt the chain note under a different key than the note was derived from, and the deposit would be undiscoverable."
8899
+ "options.chainNoteSalt requires the wallet's viewing key: chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair. The salt anchors a note derived from that nk, and the chain note has to be encrypted under the same key or the note is undiscoverable."
8389
8900
  );
8390
8901
  }
8391
8902
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
8392
8903
  const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
8393
- if (explicitChainNoteNk && chainNoteWillCarrySalt) {
8394
- const inputOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8904
+ if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
8905
+ throw missingWalletNkError("transact");
8906
+ }
8907
+ if (walletNk && chainNoteWillCarrySalt) {
8908
+ const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8909
+ if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
8910
+ const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
8395
8911
  for (let i = 0; i < outputUtxos.length; i++) {
8396
8912
  const out = outputUtxos[i];
8397
8913
  if (!out || out.amount <= BigInt(0)) continue;
8398
- if (!inputOwners.has(out.keypair.publicKey)) continue;
8399
- if (out.blinding !== deriveChangeNoteBlinding(explicitChainNoteNk, chainNoteSalt, i)) {
8914
+ if (!selfOwners.has(out.keypair.publicKey)) continue;
8915
+ if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
8400
8916
  throw new Error(
8401
- `Output ${i} is change (amount ${out.amount}, owned by an input's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
8917
+ `Output ${i} is change (amount ${out.amount}, owned by an input's or the wallet's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
8402
8918
  );
8403
8919
  }
8404
8920
  }
8405
8921
  }
8406
8922
  assertAllowedRpcConnection(connection);
8407
8923
  assertInputMints(inputUtxos, options.expectedMint);
8408
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
8409
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
8924
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
8925
+ const resolvedChainNoteNk = walletNk;
8410
8926
  if (inputUtxos.length > 2) {
8411
8927
  throw new Error("Maximum 2 input UTXOs allowed");
8412
8928
  }
@@ -8780,7 +9296,7 @@ async function transact(params, options) {
8780
9296
  }
8781
9297
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
8782
9298
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
8783
- const chainNoteTimestamp = BigInt(Date.now());
9299
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
8784
9300
  const mintField = pubkeyToFieldElement(mint);
8785
9301
  let signature = "pending-" + Date.now().toString();
8786
9302
  let commitmentIndices = [-1, -1];
@@ -8876,9 +9392,9 @@ async function transact(params, options) {
8876
9392
  ]));
8877
9393
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8878
9394
  const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
8879
- const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8880
- if (chainNoteHash >= FIELD_MODULUS2) {
8881
- throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
9395
+ const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
9396
+ if (chainNoteHash >= FIELD_MODULUS3) {
9397
+ throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS3.toString()}`);
8882
9398
  }
8883
9399
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8884
9400
  const totalInputs = 1 + // root
@@ -9243,7 +9759,10 @@ async function transact(params, options) {
9243
9759
  // For Send (shield-to-shield): always include sender so relay can enforce sanctions checks.
9244
9760
  sender: externalAmount === BigInt(0) && !recipient ? depositorPubkey : void 0,
9245
9761
  externalAmount,
9246
- recipientDeliveryNotes
9762
+ recipientDeliveryNotes,
9763
+ // SDK-002: attached only to a withdrawal / send to a public address; the builder ignores it
9764
+ // for deposits and shield-to-shield sends.
9765
+ affiliateCode: options.affiliateCode
9247
9766
  });
9248
9767
  void metadataBundle;
9249
9768
  const relaySubmission = await submitTransactToRelay({
@@ -9264,7 +9783,8 @@ async function transact(params, options) {
9264
9783
  inputNullifiers
9265
9784
  },
9266
9785
  canRetryStaleRoot: submissionAttempts < maxRootRetries,
9267
- onProgress
9786
+ onProgress,
9787
+ extraHeaders: options.relayHeaders
9268
9788
  });
9269
9789
  if (relaySubmission.kind === "stale-root") {
9270
9790
  lastError = relaySubmission.error;
@@ -9296,7 +9816,8 @@ async function transact(params, options) {
9296
9816
  throw lastError;
9297
9817
  }
9298
9818
  const classified = classifyRelayError(lastError.message);
9299
- const isMerkleClass = !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9819
+ const isDepositSubmission = externalAmount > BigInt(0);
9820
+ const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9300
9821
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
9301
9822
  onProgress?.(
9302
9823
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -9445,54 +9966,83 @@ async function transact(params, options) {
9445
9966
  };
9446
9967
  }
9447
9968
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
9969
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
9970
+ const transferNk = await requireWalletNk(options, "transfer");
9448
9971
  const inputSum = sumUtxoAmounts(inputUtxos);
9449
9972
  if (inputSum < amount) {
9450
9973
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
9451
9974
  }
9452
9975
  const change = inputSum - amount;
9453
- const myKeypair = inputUtxos[0].keypair;
9454
9976
  const mint = inputUtxos[0].mintAddress;
9455
- const transferNk = await resolveChainNoteNk(options);
9456
- const changeNoteSalt = transferNk ? randomChangeNoteSalt() : void 0;
9457
- const isSendToSelf = inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
9977
+ let spendInputs = [
9978
+ ...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
9979
+ ...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
9980
+ ];
9981
+ let spendOptions = options;
9982
+ if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
9983
+ if (spendInputs.length > 2) {
9984
+ throw new Error(
9985
+ `transfer: none of the ${spendInputs.length} inputs is owned by ownerUtxoKeypair (they are notes from before SDK 0.2.6), so they must first be moved under the wallet key, and one transaction moves at most 2 notes. Consolidate the older notes first (send them to yourself, ownerUtxoKeypair.publicKey, at most 2 per transfer) or withdraw them, then retry this transfer with at most 2 inputs.`
9986
+ );
9987
+ }
9988
+ if (options.relayAuthBatch) {
9989
+ throw new Error(
9990
+ "transfer: no input is owned by ownerUtxoKeypair, so the inputs must first be moved under the wallet key in a separate transaction, which a single batch item cannot carry. Spend them to yourself first, or run this transfer outside the batch."
9991
+ );
9992
+ }
9993
+ options.onProgress?.("Moving notes under the wallet key before the transfer...");
9994
+ const migrationSalt = randomChangeNoteSalt();
9995
+ const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
9996
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
9997
+ void _recipientViewingPublicKey;
9998
+ const migration = await transact(
9999
+ { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
10000
+ { ...migrationOptions, chainNoteSalt: migrationSalt }
10001
+ );
10002
+ const migratedNote = migration.outputUtxos?.[0] ?? migrated;
10003
+ if (migration.commitmentIndices?.[0] >= 0) {
10004
+ migratedNote.index = migration.commitmentIndices[0];
10005
+ }
10006
+ spendInputs = [migratedNote];
10007
+ spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
10008
+ }
10009
+ const changeNoteSalt = randomChangeNoteSalt();
10010
+ const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
9458
10011
  const recipientKeypair = {
9459
10012
  privateKey: BigInt(0),
9460
10013
  // Recipient's private key unknown
9461
10014
  publicKey: recipientPubkey
9462
10015
  };
9463
- const recipientUtxo = transferNk && isSendToSelf ? (await createRecoverableChangeUtxo(amount, myKeypair, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
10016
+ const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
9464
10017
  const outputUtxos = [recipientUtxo];
9465
10018
  if (change > BigInt(0)) {
9466
- if (transferNk) {
9467
- const { utxo } = await createRecoverableChangeUtxo(
9468
- change,
9469
- myKeypair,
9470
- transferNk,
9471
- mint,
9472
- changeNoteSalt,
9473
- 1
9474
- );
9475
- outputUtxos.push(utxo);
9476
- } else {
9477
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
9478
- }
10019
+ const { utxo } = await createRecoverableChangeUtxo(
10020
+ change,
10021
+ owner,
10022
+ transferNk,
10023
+ mint,
10024
+ changeNoteSalt,
10025
+ 1
10026
+ );
10027
+ outputUtxos.push(utxo);
9479
10028
  }
9480
10029
  return transact(
9481
10030
  {
9482
- inputUtxos,
10031
+ inputUtxos: spendInputs,
9483
10032
  outputUtxos,
9484
10033
  externalAmount: BigInt(0)
9485
10034
  // Pure shield-to-shield
9486
10035
  },
9487
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
10036
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
9488
10037
  );
9489
10038
  }
9490
10039
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
10040
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
10041
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
9491
10042
  const inputSum = sumUtxoAmounts(inputUtxos);
9492
10043
  if (inputSum < withdrawAmount) {
9493
10044
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
9494
10045
  }
9495
- const myKeypair = inputUtxos[0].keypair;
9496
10046
  const mint = inputUtxos[0].mintAddress;
9497
10047
  let utxos = [...inputUtxos];
9498
10048
  let cachedTree = options.cachedMerkleTree;
@@ -9501,9 +10051,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9501
10051
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
9502
10052
  const [small1, small2, ...rest] = utxos;
9503
10053
  const mergedAmount = small1.amount + small2.amount;
9504
- const mergeNk = await resolveChainNoteNk(options);
9505
- const mergeSalt = mergeNk ? randomChangeNoteSalt() : void 0;
9506
- const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
10054
+ const mergeSalt = randomChangeNoteSalt();
10055
+ const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
9507
10056
  const mergeResult = await transact(
9508
10057
  {
9509
10058
  inputUtxos: [small1, small2],
@@ -9514,7 +10063,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9514
10063
  {
9515
10064
  ...options,
9516
10065
  cachedMerkleTree: cachedTree,
9517
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
10066
+ chainNoteSalt: mergeSalt
9518
10067
  }
9519
10068
  );
9520
10069
  cachedTree = mergeResult.merkleTree;
@@ -9529,23 +10078,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9529
10078
  const outputUtxos = [];
9530
10079
  let changeNoteSalt;
9531
10080
  if (change > BigInt(0)) {
9532
- const changeNk = await resolveChainNoteNk(options);
9533
- if (changeNk) {
9534
- const salt = randomChangeNoteSalt();
9535
- const { utxo } = await createRecoverableChangeUtxo(
9536
- change,
9537
- myKeypair,
9538
- changeNk,
9539
- mint,
9540
- salt,
9541
- 0
9542
- // partialWithdraw puts change at output 0
9543
- );
9544
- outputUtxos.push(utxo);
9545
- changeNoteSalt = salt;
9546
- } else {
9547
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
9548
- }
10081
+ const salt = randomChangeNoteSalt();
10082
+ const { utxo } = await createRecoverableChangeUtxo(
10083
+ change,
10084
+ owner,
10085
+ walletNk,
10086
+ mint,
10087
+ salt,
10088
+ 0
10089
+ // partialWithdraw puts change at output 0
10090
+ );
10091
+ outputUtxos.push(utxo);
10092
+ changeNoteSalt = salt;
9549
10093
  }
9550
10094
  return transact(
9551
10095
  {
@@ -9668,6 +10212,8 @@ async function swapUtxo(params, options) {
9668
10212
  if (relayUrl) {
9669
10213
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
9670
10214
  }
10215
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
10216
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
9671
10217
  if (inputUtxos.length === 0) {
9672
10218
  throw new Error("At least one input UTXO required");
9673
10219
  }
@@ -9693,15 +10239,12 @@ async function swapUtxo(params, options) {
9693
10239
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
9694
10240
  }
9695
10241
  onProgress?.("Validating transaction parameters...");
9696
- const swapFallbackNk = getNkFromUtxoPrivateKey(inputUtxos[0].keypair.privateKey);
9697
- await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
9698
- const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
9699
- const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
10242
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
9700
10243
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
9701
- if (explicitSwapChainNoteNk && changeUtxo && changeUtxo.amount > BigInt(0) && inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey)) {
9702
- if (changeUtxo.blinding !== deriveChangeNoteBlinding(explicitSwapChainNoteNk, chainNoteSalt, 0)) {
10244
+ if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
10245
+ if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
9703
10246
  throw new Error(
9704
- `Swap change (amount ${changeUtxo.amount}, owned by an input's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
10247
+ `Swap change (amount ${changeUtxo.amount}, owned by an input's or the wallet's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
9705
10248
  );
9706
10249
  }
9707
10250
  }
@@ -9725,24 +10268,18 @@ async function swapUtxo(params, options) {
9725
10268
  );
9726
10269
  }
9727
10270
  const externalAmount = -swapAmount;
9728
- let refundKeypair;
9729
- let refundBlinding;
9730
- let refundDerivedFromNk = false;
9731
- if (resolvedSwapChainNoteNk) {
9732
- try {
9733
- const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
9734
- const derived = await deriveSwapRefundAuthorization(resolvedSwapChainNoteNk, refundNullifier);
9735
- refundKeypair = { privateKey: derived.privateKey, publicKey: derived.publicKey };
9736
- refundBlinding = derived.blinding;
9737
- refundDerivedFromNk = true;
9738
- } catch {
9739
- refundKeypair = await generateUtxoKeypair();
9740
- refundBlinding = randomFieldElement();
9741
- }
9742
- } else {
9743
- refundKeypair = await generateUtxoKeypair();
9744
- refundBlinding = randomFieldElement();
9745
- }
10271
+ const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
10272
+ const refundAuthorization = await deriveSwapRefundAuthorization(
10273
+ resolvedSwapChainNoteNk,
10274
+ refundNullifier,
10275
+ swapOwner
10276
+ );
10277
+ const refundKeypair = {
10278
+ privateKey: refundAuthorization.privateKey,
10279
+ publicKey: refundAuthorization.publicKey
10280
+ };
10281
+ const refundBlinding = refundAuthorization.blinding;
10282
+ const refundDerivedFromNk = true;
9746
10283
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
9747
10284
  throw new Error(
9748
10285
  "Refund authorization derivation produced a zero pubkey/blinding \u2014 aborting swap to avoid an unclaimable timeout refund. Retry; a persistent failure indicates a keygen/RNG fault."
@@ -10068,7 +10605,7 @@ async function swapUtxo(params, options) {
10068
10605
  for (const utxo of paddedOutputs) {
10069
10606
  outputCommitments.push(await computeCommitment2(utxo));
10070
10607
  }
10071
- const chainNoteTimestamp = BigInt(Date.now());
10608
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
10072
10609
  onProgress?.("Computing external data hash...");
10073
10610
  const mint = swapPoolMint;
10074
10611
  const mintField = pubkeyToFieldElement(mint);
@@ -10311,30 +10848,27 @@ async function swapUtxo(params, options) {
10311
10848
  const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
10312
10849
  await options.onSwapStatePredicted(ssp);
10313
10850
  }
10314
- const requestBody = {
10315
- proof_bytes: proofB64,
10316
- public_inputs: publicInputsB64,
10317
- output_mint: outputMint,
10318
- recipient_ata: recipientAta,
10319
- recipient: recipientWallet,
10320
- // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
10321
- // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
10322
- min_output_amount: minOutputAmount.toString(),
10323
- // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
10324
- max_fee: swapMaxFee.toString(),
10325
- slippage_bps: swapSlippageBps,
10326
- dexes: swapDexes && swapDexes.length > 0 ? swapDexes : void 0,
10327
- exclude_dexes: swapExcludeDexes && swapExcludeDexes.length > 0 ? swapExcludeDexes : void 0,
10328
- route_retry_attempts: options.swapRouteRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(options.swapRouteRetryAttempts))) : void 0,
10329
- swap_max_retries: options.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(options.swapMaxRetries))) : void 0,
10330
- encrypted_notes: encryptedNotes,
10331
- risk_quote: riskQuoteData,
10332
- // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
10333
- // bound into the proof's ext_data_hash above. The relay forwards both verbatim into the swap
10334
- // params; the program builds the amount-bound R_fb from them at close.
10335
- refund_pubkey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("base64"),
10336
- refund_blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("base64")
10337
- };
10851
+ const requestBody = buildTransactSwapRequestBody({
10852
+ proofB64,
10853
+ publicInputsB64,
10854
+ outputMint,
10855
+ recipientAta,
10856
+ recipientWallet,
10857
+ minOutputAmount,
10858
+ maxFee: swapMaxFee,
10859
+ slippageBps: swapSlippageBps,
10860
+ dexes: swapDexes,
10861
+ excludeDexes: swapExcludeDexes,
10862
+ routeRetryAttempts: options.swapRouteRetryAttempts,
10863
+ swapMaxRetries: options.swapMaxRetries,
10864
+ encryptedNotes,
10865
+ riskQuote: riskQuoteData,
10866
+ refundPubkeyB64: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("base64"),
10867
+ refundBlindingB64: Buffer.from(bigintToBytes323(refundBlinding)).toString("base64"),
10868
+ // SDK-001/002: a swap intake is fee-bearing. Every attempt of this loop is a new intake with
10869
+ // a fresh proof, so each one carries the code; none of them is a `retry_request_id` retry.
10870
+ affiliateCode: options.affiliateCode
10871
+ });
10338
10872
  try {
10339
10873
  if (relayAuthPlan.kind === "wallet") {
10340
10874
  walletApprovals = chargeWalletApproval(walletApprovals, walletApprovalBudget, lastError);
@@ -10353,11 +10887,16 @@ async function swapUtxo(params, options) {
10353
10887
  TRANSACT_SWAP_AUTH_FIELDS
10354
10888
  );
10355
10889
  if (swapAuthFields) Object.assign(requestBody, swapAuthFields);
10356
- const response = await relayFetch(`${relayUrl}/transact_swap`, {
10357
- method: "POST",
10358
- headers: { "Content-Type": "application/json" },
10359
- body: JSON.stringify(requestBody)
10360
- });
10890
+ const response = await relayFetch(
10891
+ `${relayUrl}/transact_swap`,
10892
+ {
10893
+ method: "POST",
10894
+ headers: { "Content-Type": "application/json" },
10895
+ body: JSON.stringify(requestBody)
10896
+ },
10897
+ // SDK-004: e.g. the mobile app's `X-Cloak-Client`. Omitted, this is the old call exactly.
10898
+ { extraHeaders: options.relayHeaders }
10899
+ );
10361
10900
  const responseText = await response.text();
10362
10901
  if (!response.ok) {
10363
10902
  if (isRetryableRelayStatus(response.status) && attempt < maxRootRetries) {
@@ -10380,7 +10919,7 @@ async function swapUtxo(params, options) {
10380
10919
  forceChainIndexing = !relayUrl;
10381
10920
  continue;
10382
10921
  }
10383
- throw new Error(relayFailureMessage("Relay error", responseText));
10922
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
10384
10923
  }
10385
10924
  const apiResponse = JSON.parse(responseText);
10386
10925
  if (!apiResponse.success || !apiResponse.data) {
@@ -10516,7 +11055,6 @@ async function swapUtxo(params, options) {
10516
11055
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
10517
11056
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
10518
11057
  refund: {
10519
- privateKey: Buffer.from(bigintToBytes323(refundKeypair.privateKey)).toString("hex"),
10520
11058
  publicKey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("hex"),
10521
11059
  blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("hex"),
10522
11060
  derivedFromNk: refundDerivedFromNk
@@ -10524,6 +11062,7 @@ async function swapUtxo(params, options) {
10524
11062
  };
10525
11063
  }
10526
11064
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
11065
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
10527
11066
  const totalInput = sumUtxoAmounts(inputUtxos);
10528
11067
  const change = totalInput - swapAmount;
10529
11068
  if (change < BigInt(0)) {
@@ -10532,16 +11071,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
10532
11071
  let changeUtxo;
10533
11072
  let changeNoteSalt;
10534
11073
  if (change > BigInt(0)) {
10535
- const myKeypair = inputUtxos[0].keypair;
10536
11074
  const mint = inputUtxos[0].mintAddress;
10537
- const changeNk = await resolveChainNoteNk(options);
10538
- if (changeNk) {
10539
- const salt = randomChangeNoteSalt();
10540
- changeUtxo = (await createRecoverableChangeUtxo(change, myKeypair, changeNk, mint, salt, 0)).utxo;
10541
- changeNoteSalt = salt;
10542
- } else {
10543
- changeUtxo = await createUtxo(change, myKeypair, mint);
10544
- }
11075
+ const changeNk = await requireWalletNk(options, "swapWithChange");
11076
+ const salt = randomChangeNoteSalt();
11077
+ changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
11078
+ changeNoteSalt = salt;
10545
11079
  }
10546
11080
  return swapUtxo(
10547
11081
  {
@@ -10867,7 +11401,7 @@ var RelayBatchAuthCoordinator = class {
10867
11401
  throw new Error("Every item of a batch must target the same program id.");
10868
11402
  }
10869
11403
  }
10870
- const nowSeconds = Math.floor(Date.now() / 1e3);
11404
+ const nowSeconds = relayNowSeconds();
10871
11405
  const preimages = waiting.map(
10872
11406
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10873
11407
  );
@@ -11308,7 +11842,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
11308
11842
  const cached = depositSecretsCache.get(key);
11309
11843
  if (cached) return cached;
11310
11844
  try {
11311
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
11845
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
11312
11846
  if (depositSecretsCache.size >= 4096) {
11313
11847
  const oldest = depositSecretsCache.keys().next();
11314
11848
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11891,6 +12425,7 @@ async function scanTransactions(opts) {
11891
12425
  } else {
11892
12426
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11893
12427
  const candidateKeys = [
12428
+ opts.ownerUtxoPublicKey,
11894
12429
  derived?.keypair.publicKey,
11895
12430
  opts.ownUtxoPublicKey,
11896
12431
  BigInt(0)
@@ -11944,6 +12479,7 @@ async function scanTransactions(opts) {
11944
12479
  try {
11945
12480
  const recoveredDeposit = await matchDepositNote({
11946
12481
  viewingKeyNk,
12482
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
11947
12483
  noteSalt: compactNote.noteSalt,
11948
12484
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
11949
12485
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -11978,7 +12514,8 @@ async function scanTransactions(opts) {
11978
12514
  mintAddress: (0, import_kit.address)(asset.mint),
11979
12515
  outputIndex: 0,
11980
12516
  // v4 describes output 0, which is where change lands
11981
- outputCommitments: ixCtx.outputCommitments ?? []
12517
+ outputCommitments: ixCtx.outputCommitments ?? [],
12518
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
11982
12519
  });
11983
12520
  if (recoveredChange) {
11984
12521
  recoveredChangeNotes.push({
@@ -12088,6 +12625,17 @@ async function scanTransactions(opts) {
12088
12625
  runningByAsset.set(key, running);
12089
12626
  tx.runningBalance = running;
12090
12627
  }
12628
+ const legacyKeys = /* @__PURE__ */ new Map();
12629
+ for (const note of recoveredDepositNotes) {
12630
+ if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
12631
+ }
12632
+ for (const change of recoveredChangeNotes) {
12633
+ const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
12634
+ if (legacyPrivateKey !== void 0) {
12635
+ change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
12636
+ change.legacyExposed = true;
12637
+ }
12638
+ }
12091
12639
  return {
12092
12640
  transactions: txs,
12093
12641
  summary: {
@@ -12167,17 +12715,1593 @@ function formatComplianceCsv(report) {
12167
12715
  return header + rows;
12168
12716
  }
12169
12717
 
12170
- // src/wallet/utxo-wallet.ts
12718
+ // src/relay/note-index-format.ts
12719
+ var import_sha25 = require("@noble/hashes/sha2");
12171
12720
  init_address();
12172
12721
  init_utxo();
12173
- var UtxoWallet = class _UtxoWallet {
12174
- constructor(viewingKey) {
12175
- this.wallets = /* @__PURE__ */ new Map();
12176
- this.viewingKey = viewingKey;
12722
+ var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
12723
+ var NOTE_INDEX_FORMAT_VERSION = 1;
12724
+ var NOTE_INDEX_PAGE_SIZE = 1024;
12725
+ var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
12726
+ var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
12727
+ var NOTE_INDEX_HEADER_LEN = 68;
12728
+ var NOTE_INDEX_KIND_TX = 1;
12729
+ var NOTE_INDEX_KIND_DELIVERY = 2;
12730
+ var NOTE_INDEX_KIND_SWAP_REFUND = 3;
12731
+ var NOTE_SOURCE_NONE = 0;
12732
+ var NOTE_SOURCE_CARRIER = 2;
12733
+ var ITEM_HEADER_LEN = 3;
12734
+ var TX_FIXED_LEN = 263;
12735
+ var DELIVERY_BODY_LEN = 256;
12736
+ var SWAP_REFUND_BODY_LEN = 184;
12737
+ var MAX_UNKNOWN_BODY_LEN = 1024;
12738
+ var DELIVERY_ENVELOPE_LEN = 112;
12739
+ var SIGNATURE_LEN = 64;
12740
+ var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
12741
+ [25, 2],
12742
+ [57, 3],
12743
+ [98, 4]
12744
+ ]);
12745
+ var COMPLETE_FLAG = 1;
12746
+ var U64_MAX2 = (1n << 64n) - 1n;
12747
+ var U32_MAX = 4294967295;
12748
+ var MAX_LEAF_INDEX = (1n << 32n) - 1n;
12749
+ var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
12750
+ var NoteIndexFormatError = class extends Error {
12751
+ constructor(message) {
12752
+ super(`Note index format error: ${message}`);
12753
+ this.name = "NoteIndexFormatError";
12177
12754
  }
12178
- /**
12179
- * Add a UTXO to the wallet (discovered from chain or created)
12180
- */
12755
+ };
12756
+ function isAllZero2(bytes) {
12757
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12758
+ return true;
12759
+ }
12760
+ function bytesEqual(a, b) {
12761
+ if (a.length !== b.length) return false;
12762
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
12763
+ return true;
12764
+ }
12765
+ function checkLeafPair(commitment, leaf, label) {
12766
+ if (isAllZero2(commitment)) {
12767
+ if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
12768
+ return;
12769
+ }
12770
+ if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
12771
+ }
12772
+ var Reader = class {
12773
+ constructor(bytes, start, end) {
12774
+ this.bytes = bytes;
12775
+ this.end = end;
12776
+ this.offset = start;
12777
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12778
+ }
12779
+ take(len) {
12780
+ if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
12781
+ const at = this.offset;
12782
+ this.offset += len;
12783
+ return at;
12784
+ }
12785
+ u8() {
12786
+ return this.bytes[this.take(1)];
12787
+ }
12788
+ u32() {
12789
+ return this.view.getUint32(this.take(4), true);
12790
+ }
12791
+ u64() {
12792
+ return this.view.getBigUint64(this.take(8), true);
12793
+ }
12794
+ i64() {
12795
+ return this.view.getBigInt64(this.take(8), true);
12796
+ }
12797
+ raw(len) {
12798
+ const at = this.take(len);
12799
+ return this.bytes.slice(at, at + len);
12800
+ }
12801
+ get position() {
12802
+ return this.offset;
12803
+ }
12804
+ };
12805
+ function parseTx(r, bodyLen) {
12806
+ const mint = r.raw(32);
12807
+ const slot = r.u64();
12808
+ const blockPos = r.u32();
12809
+ const ixTag = r.u8();
12810
+ if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
12811
+ const publicAmount = r.i64();
12812
+ const nullifier0 = r.raw(32);
12813
+ const nullifier1 = r.raw(32);
12814
+ const comm0 = r.raw(32);
12815
+ const leaf0 = r.u64();
12816
+ const comm1 = r.raw(32);
12817
+ const leaf1 = r.u64();
12818
+ const noteSource = r.u8();
12819
+ if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
12820
+ const noteLen = r.u8();
12821
+ if (noteSource === NOTE_SOURCE_NONE) {
12822
+ if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
12823
+ } else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
12824
+ throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
12825
+ }
12826
+ if (bodyLen !== TX_FIXED_LEN + noteLen) {
12827
+ throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
12828
+ }
12829
+ const note = r.raw(noteLen);
12830
+ if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
12831
+ throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
12832
+ }
12833
+ const signature = r.raw(SIGNATURE_LEN);
12834
+ checkLeafPair(comm0, leaf0, "TX comm0");
12835
+ checkLeafPair(comm1, leaf1, "TX comm1");
12836
+ return {
12837
+ kind: 1,
12838
+ mint,
12839
+ slot,
12840
+ blockPos,
12841
+ ixTag,
12842
+ publicAmount,
12843
+ nullifier0,
12844
+ nullifier1,
12845
+ comm0,
12846
+ leaf0,
12847
+ comm1,
12848
+ leaf1,
12849
+ noteSource,
12850
+ note,
12851
+ signature
12852
+ };
12853
+ }
12854
+ function parseDelivery(r) {
12855
+ const mint = r.raw(32);
12856
+ const slot = r.u64();
12857
+ const commitment = r.raw(32);
12858
+ const leaf = r.u64();
12859
+ const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
12860
+ const signature = r.raw(SIGNATURE_LEN);
12861
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
12862
+ checkLeafPair(commitment, leaf, "DELIVERY");
12863
+ return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
12864
+ }
12865
+ function parseSwapRefund(r) {
12866
+ const mint = r.raw(32);
12867
+ if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
12868
+ const slot = r.u64();
12869
+ const commitment = r.raw(32);
12870
+ const leaf = r.u64();
12871
+ const amountAfterFee = r.u64();
12872
+ const nullifier0 = r.raw(32);
12873
+ const signature = r.raw(SIGNATURE_LEN);
12874
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
12875
+ checkLeafPair(commitment, leaf, "SWAP_REFUND");
12876
+ return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
12877
+ }
12878
+ function parseNoteIndexPage(bytes, expect) {
12879
+ if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
12880
+ if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
12881
+ throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
12882
+ }
12883
+ if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12884
+ for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
12885
+ if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
12886
+ }
12887
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12888
+ const version = bytes[4];
12889
+ if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
12890
+ const flags = bytes[5];
12891
+ if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
12892
+ if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
12893
+ const epoch = view.getBigUint64(8, true);
12894
+ const page = view.getBigUint64(16, true);
12895
+ const firstSeq = view.getBigUint64(24, true);
12896
+ const count = view.getUint32(32, true);
12897
+ const prevChain = bytes.slice(36, 68);
12898
+ const complete = (flags & COMPLETE_FLAG) !== 0;
12899
+ if (expect) {
12900
+ if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
12901
+ if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
12902
+ }
12903
+ if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12904
+ if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
12905
+ if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
12906
+ throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
12907
+ }
12908
+ const items = [];
12909
+ const rawItems = [];
12910
+ let skippedUnknown = 0;
12911
+ let offset = NOTE_INDEX_HEADER_LEN;
12912
+ for (let i = 0; i < count; i++) {
12913
+ if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
12914
+ const kind = bytes[offset];
12915
+ const bodyLen = view.getUint16(offset + 1, true);
12916
+ const bodyStart = offset + ITEM_HEADER_LEN;
12917
+ const bodyEnd = bodyStart + bodyLen;
12918
+ if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12919
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12920
+ let item;
12921
+ switch (kind) {
12922
+ case NOTE_INDEX_KIND_TX:
12923
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12924
+ item = parseTx(r, bodyLen);
12925
+ break;
12926
+ case NOTE_INDEX_KIND_DELIVERY:
12927
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12928
+ item = parseDelivery(r);
12929
+ break;
12930
+ case NOTE_INDEX_KIND_SWAP_REFUND:
12931
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12932
+ item = parseSwapRefund(r);
12933
+ break;
12934
+ default:
12935
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12936
+ skippedUnknown++;
12937
+ offset = bodyEnd;
12938
+ continue;
12939
+ }
12940
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12941
+ items.push(item);
12942
+ rawItems.push(bytes.slice(offset, bodyEnd));
12943
+ offset = bodyEnd;
12944
+ }
12945
+ if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12946
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown };
12947
+ }
12948
+ function parseNoteIndexItem(raw) {
12949
+ if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
12950
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
12951
+ const kind = raw[0];
12952
+ const bodyLen = view.getUint16(1, true);
12953
+ if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
12954
+ const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
12955
+ let item;
12956
+ if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
12957
+ else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
12958
+ else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
12959
+ else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
12960
+ if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
12961
+ return item;
12962
+ }
12963
+ function computeNoteIndexChain(prevChain, pageBytes) {
12964
+ if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
12965
+ if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12966
+ const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
12967
+ const input = new Uint8Array(32 + items.length);
12968
+ input.set(prevChain);
12969
+ input.set(items, 32);
12970
+ return (0, import_sha25.sha256)(input);
12971
+ }
12972
+ var Writer = class {
12973
+ constructor() {
12974
+ this.chunks = [];
12975
+ this.length = 0;
12976
+ }
12977
+ push(bytes) {
12978
+ this.chunks.push(bytes);
12979
+ this.length += bytes.length;
12980
+ }
12981
+ u8(v) {
12982
+ if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
12983
+ this.push(Uint8Array.of(v));
12984
+ }
12985
+ u16(v) {
12986
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
12987
+ const b = new Uint8Array(2);
12988
+ new DataView(b.buffer).setUint16(0, v, true);
12989
+ this.push(b);
12990
+ }
12991
+ u32(v) {
12992
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
12993
+ const b = new Uint8Array(4);
12994
+ new DataView(b.buffer).setUint32(0, v, true);
12995
+ this.push(b);
12996
+ }
12997
+ u64(v) {
12998
+ if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
12999
+ const b = new Uint8Array(8);
13000
+ new DataView(b.buffer).setBigUint64(0, v, true);
13001
+ this.push(b);
13002
+ }
13003
+ i64(v) {
13004
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
13005
+ const b = new Uint8Array(8);
13006
+ new DataView(b.buffer).setBigInt64(0, v, true);
13007
+ this.push(b);
13008
+ }
13009
+ fixed(bytes, len, label) {
13010
+ if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
13011
+ this.push(bytes);
13012
+ }
13013
+ finish() {
13014
+ const out = new Uint8Array(this.length);
13015
+ let off = 0;
13016
+ for (const c of this.chunks) {
13017
+ out.set(c, off);
13018
+ off += c.length;
13019
+ }
13020
+ return out;
13021
+ }
13022
+ };
13023
+ function encodeItemBody(item) {
13024
+ const w = new Writer();
13025
+ switch (item.kind) {
13026
+ case NOTE_INDEX_KIND_TX: {
13027
+ w.fixed(item.mint, 32, "mint");
13028
+ w.u64(item.slot);
13029
+ w.u32(item.blockPos);
13030
+ w.u8(item.ixTag);
13031
+ w.i64(item.publicAmount);
13032
+ w.fixed(item.nullifier0, 32, "nullifier0");
13033
+ w.fixed(item.nullifier1, 32, "nullifier1");
13034
+ w.fixed(item.comm0, 32, "comm0");
13035
+ w.u64(item.leaf0);
13036
+ w.fixed(item.comm1, 32, "comm1");
13037
+ w.u64(item.leaf1);
13038
+ w.u8(item.noteSource);
13039
+ const noteLen = item.note.length;
13040
+ if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
13041
+ throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
13042
+ }
13043
+ w.u8(noteLen);
13044
+ w.push(item.note);
13045
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13046
+ break;
13047
+ }
13048
+ case NOTE_INDEX_KIND_DELIVERY:
13049
+ w.fixed(item.mint, 32, "mint");
13050
+ w.u64(item.slot);
13051
+ w.fixed(item.commitment, 32, "commitment");
13052
+ w.u64(item.leaf);
13053
+ w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
13054
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13055
+ break;
13056
+ case NOTE_INDEX_KIND_SWAP_REFUND:
13057
+ w.fixed(item.mint, 32, "mint");
13058
+ w.u64(item.slot);
13059
+ w.fixed(item.commitment, 32, "commitment");
13060
+ w.u64(item.leaf);
13061
+ w.u64(item.amountAfterFee);
13062
+ w.fixed(item.nullifier0, 32, "nullifier0");
13063
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13064
+ break;
13065
+ default:
13066
+ throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
13067
+ }
13068
+ return w.finish();
13069
+ }
13070
+ function encodeNoteIndexItem(item) {
13071
+ const body = encodeItemBody(item);
13072
+ const w = new Writer();
13073
+ w.u8(item.kind);
13074
+ w.u16(body.length);
13075
+ w.push(body);
13076
+ return w.finish();
13077
+ }
13078
+ function encodeNoteIndexPage(params) {
13079
+ const items = params.items ?? [];
13080
+ if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
13081
+ const w = new Writer();
13082
+ w.push(NOTE_INDEX_MAGIC);
13083
+ w.u8(NOTE_INDEX_FORMAT_VERSION);
13084
+ w.u8(params.complete ? COMPLETE_FLAG : 0);
13085
+ w.u16(0);
13086
+ w.u64(BigInt(params.epoch));
13087
+ w.u64(BigInt(params.page));
13088
+ w.u64(BigInt(params.firstSeq));
13089
+ w.u32(items.length);
13090
+ w.fixed(params.prevChain, 32, "prevChain");
13091
+ for (const item of items) w.push(encodeNoteIndexItem(item));
13092
+ return w.finish();
13093
+ }
13094
+
13095
+ // src/relay/note-index-client.ts
13096
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
13097
+ var DEFAULT_MAX_RETRIES2 = 3;
13098
+ var RETRY_BASE_DELAY_MS = 500;
13099
+ var U64_MAX3 = (1n << 64n) - 1n;
13100
+ function joinPath(relayUrl, path) {
13101
+ const url = new URL(relayUrl);
13102
+ url.pathname = url.pathname.replace(/\/$/, "") + path;
13103
+ return url;
13104
+ }
13105
+ function abortError() {
13106
+ const error = new Error("Note index request aborted");
13107
+ error.name = "AbortError";
13108
+ return error;
13109
+ }
13110
+ function sleep4(ms, signal) {
13111
+ return new Promise((resolve, reject) => {
13112
+ if (signal?.aborted) return reject(abortError());
13113
+ const timer = setTimeout(() => {
13114
+ signal?.removeEventListener("abort", onAbort);
13115
+ resolve();
13116
+ }, ms);
13117
+ const onAbort = () => {
13118
+ clearTimeout(timer);
13119
+ reject(abortError());
13120
+ };
13121
+ signal?.addEventListener("abort", onAbort, { once: true });
13122
+ });
13123
+ }
13124
+ var RetryableStatusError = class extends Error {
13125
+ };
13126
+ var HttpStatusError = class extends Error {
13127
+ constructor(status, message) {
13128
+ super(message);
13129
+ this.status = status;
13130
+ this.name = "HttpStatusError";
13131
+ }
13132
+ };
13133
+ async function requestWithRetry(url, options, read) {
13134
+ assertAllowedRelayOrigin(url);
13135
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
13136
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
13137
+ let lastError;
13138
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
13139
+ if (options.signal?.aborted) throw abortError();
13140
+ const controller = new AbortController();
13141
+ const onAbort = () => controller.abort();
13142
+ options.signal?.addEventListener("abort", onAbort, { once: true });
13143
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
13144
+ try {
13145
+ const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
13146
+ if (response.status === 429 || response.status >= 500) {
13147
+ throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
13148
+ }
13149
+ return await read(response, controller.signal);
13150
+ } catch (error) {
13151
+ if (options.signal?.aborted) throw abortError();
13152
+ const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
13153
+ if (!retryable || attempt >= maxRetries) throw error;
13154
+ lastError = error;
13155
+ await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
13156
+ } finally {
13157
+ clearTimeout(timer);
13158
+ options.signal?.removeEventListener("abort", onAbort);
13159
+ }
13160
+ }
13161
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
13162
+ }
13163
+ async function readBoundedBody(response, maxBytes) {
13164
+ const declaredHeader = response.headers?.get?.("content-length") ?? null;
13165
+ const declared = declaredHeader === null ? NaN : Number(declaredHeader);
13166
+ if (Number.isFinite(declared) && declared > maxBytes) {
13167
+ throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
13168
+ }
13169
+ const reader = response.body?.getReader?.();
13170
+ if (!reader) {
13171
+ const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
13172
+ if (!Number.isSafeInteger(declared) || declared < 0) {
13173
+ throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
13174
+ }
13175
+ if (encoding !== "" && encoding !== "identity") {
13176
+ throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
13177
+ }
13178
+ const buffer = new Uint8Array(await response.arrayBuffer());
13179
+ if (buffer.length > maxBytes || buffer.length !== declared) {
13180
+ throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
13181
+ }
13182
+ return buffer;
13183
+ }
13184
+ const chunks = [];
13185
+ let total = 0;
13186
+ for (; ; ) {
13187
+ const { done, value } = await reader.read();
13188
+ if (done) break;
13189
+ total += value.length;
13190
+ if (total > maxBytes) {
13191
+ await reader.cancel().catch(() => void 0);
13192
+ throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
13193
+ }
13194
+ chunks.push(value);
13195
+ }
13196
+ const out = new Uint8Array(total);
13197
+ let off = 0;
13198
+ for (const c of chunks) {
13199
+ out.set(c, off);
13200
+ off += c.length;
13201
+ }
13202
+ return out;
13203
+ }
13204
+ function isNonNegativeSafeInteger(value) {
13205
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
13206
+ }
13207
+ async function fetchNoteIndexHead(relayUrl, options = {}) {
13208
+ const url = joinPath(relayUrl, "/note-index/v1/head").toString();
13209
+ const raw = await requestWithRetry(url, options, async (response) => {
13210
+ if (!response.ok) {
13211
+ throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
13212
+ }
13213
+ const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
13214
+ try {
13215
+ return JSON.parse(text);
13216
+ } catch {
13217
+ throw new NoteIndexFormatError("head is not JSON");
13218
+ }
13219
+ });
13220
+ if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
13221
+ if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
13222
+ throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
13223
+ }
13224
+ if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
13225
+ throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
13226
+ }
13227
+ if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
13228
+ throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
13229
+ }
13230
+ if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
13231
+ throw new NoteIndexFormatError(
13232
+ `complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
13233
+ );
13234
+ }
13235
+ if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
13236
+ throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
13237
+ }
13238
+ if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
13239
+ throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
13240
+ }
13241
+ return {
13242
+ format: 1,
13243
+ epoch: BigInt(raw.epoch),
13244
+ pageSize: NOTE_INDEX_PAGE_SIZE,
13245
+ watermark: raw.watermark,
13246
+ completePages: raw.complete_pages,
13247
+ chainTip: raw.chain_tip.toLowerCase()
13248
+ };
13249
+ }
13250
+ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
13251
+ if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
13252
+ if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
13253
+ const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
13254
+ return requestWithRetry(url, options, async (response) => {
13255
+ if (!response.ok) {
13256
+ throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
13257
+ }
13258
+ return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
13259
+ });
13260
+ }
13261
+
13262
+ // src/scanning/note-index.ts
13263
+ var import_bs584 = __toESM(require("bs58"), 1);
13264
+ var import_sha26 = require("@noble/hashes/sha2");
13265
+ init_address();
13266
+ init_utxo();
13267
+ var bs584 = import_bs584.default.default || import_bs584.default;
13268
+ var CURSOR_VERSION = 2;
13269
+ var DEFAULT_CONCURRENCY = 6;
13270
+ var MAX_CONCURRENCY = 32;
13271
+ var ITEM_BATCH = 64;
13272
+ var CURSOR_PAGE_ALIGN = 8;
13273
+ var MAX_PERSISTED_PENDING_LEAVES = 4096;
13274
+ var MAX_CARRIED_PENDING = 256;
13275
+ var MAX_REJECTED_IDS = 1024;
13276
+ var LEAF_WINDOW = 512;
13277
+ var MAX_OVERRIDES = 256;
13278
+ var MAX_CURSOR_OWN_ITEMS = 65536;
13279
+ var MAX_LEGACY_VIEWING_KEYS = 8;
13280
+ var MAX_CURSOR_KEYS = 131072;
13281
+ var MAX_CURSOR_POOLS = 256;
13282
+ var MAX_CURSOR_PAGE = 2 ** 32;
13283
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
13284
+ var ZERO_CHAIN = "00".repeat(32);
13285
+ var U64_MAX4 = (1n << 64n) - 1n;
13286
+ var NoteIndexHeadBehindError = class extends Error {
13287
+ constructor(cursorWatermark, headWatermark) {
13288
+ super(
13289
+ `note index head is behind this cursor (watermark ${headWatermark} < ${cursorWatermark} seen before in this epoch): a stale cache or a rollback; retry later with the same cursor`
13290
+ );
13291
+ this.cursorWatermark = cursorWatermark;
13292
+ this.headWatermark = headWatermark;
13293
+ this.retryable = true;
13294
+ this.name = "NoteIndexHeadBehindError";
13295
+ }
13296
+ };
13297
+ var FullPassSignal = class {
13298
+ constructor(reason) {
13299
+ this.reason = reason;
13300
+ }
13301
+ };
13302
+ function abortError2() {
13303
+ const error = new Error("recoverNotesFromIndex aborted");
13304
+ error.name = "AbortError";
13305
+ return error;
13306
+ }
13307
+ function bytesToBigint3(bytes) {
13308
+ let v = 0n;
13309
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
13310
+ return v;
13311
+ }
13312
+ function toHex2(bytes) {
13313
+ let s = "";
13314
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
13315
+ return s;
13316
+ }
13317
+ function fromHex(hex) {
13318
+ return Uint8Array.from(Buffer.from(hex, "hex"));
13319
+ }
13320
+ function hex32(v) {
13321
+ return v.toString(16).padStart(64, "0");
13322
+ }
13323
+ function isAllZero3(bytes) {
13324
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
13325
+ return true;
13326
+ }
13327
+ function floorAlign(page) {
13328
+ return page - page % CURSOR_PAGE_ALIGN;
13329
+ }
13330
+ function verifiedKey(mint, leaf, commitment) {
13331
+ return `${mint}:${leaf}:${hex32(commitment)}`;
13332
+ }
13333
+ function itemIdentity(raw) {
13334
+ return toHex2((0, import_sha26.sha256)(raw).subarray(0, 16));
13335
+ }
13336
+ var LeafBuffer = class {
13337
+ constructor() {
13338
+ this.bytes = new Uint8Array(32 * 1024);
13339
+ this.view = new DataView(this.bytes.buffer);
13340
+ this.count = 0;
13341
+ }
13342
+ get length() {
13343
+ return this.count;
13344
+ }
13345
+ push(values) {
13346
+ const need = (this.count + values.length) * 32;
13347
+ if (need > this.bytes.length) {
13348
+ let size = this.bytes.length;
13349
+ while (size < need) size *= 2;
13350
+ const next = new Uint8Array(size);
13351
+ next.set(this.bytes.subarray(0, this.count * 32));
13352
+ this.bytes = next;
13353
+ this.view = new DataView(next.buffer);
13354
+ }
13355
+ for (const v of values) {
13356
+ const o = this.count * 32;
13357
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
13358
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
13359
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
13360
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
13361
+ this.count++;
13362
+ }
13363
+ }
13364
+ get(i) {
13365
+ if (i < 0 || i >= this.count) return void 0;
13366
+ const o = i * 32;
13367
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
13368
+ }
13369
+ };
13370
+ async function trialItem(item, trials) {
13371
+ for (const trial of trials) {
13372
+ if (trial.legacy && item.kind === 2) continue;
13373
+ const opened = await trialItemWith(item, trial);
13374
+ if (opened) return { ...opened, trial };
13375
+ }
13376
+ return null;
13377
+ }
13378
+ async function trialItemWith(item, trial) {
13379
+ if (item.kind === 1) {
13380
+ if (item.note.length === 0) return null;
13381
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
13382
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
13383
+ return note ? { note } : null;
13384
+ }
13385
+ if (item.kind === 2) {
13386
+ const delivery = await trial.open(item.envelope);
13387
+ return delivery ? { delivery } : null;
13388
+ }
13389
+ if (item.amountAfterFee === 0n) return null;
13390
+ const refund = await matchSwapRefundLeaf({
13391
+ viewingKeyNk: trial.nk,
13392
+ inputNullifier: item.nullifier0,
13393
+ amountAfterFee: item.amountAfterFee,
13394
+ commitment: item.commitment,
13395
+ ownerUtxoKeypair: trial.owner
13396
+ });
13397
+ return refund ? { refund } : null;
13398
+ }
13399
+ function txOutputs(item) {
13400
+ const out = [toHex2(item.comm0)];
13401
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
13402
+ return out;
13403
+ }
13404
+ function leafOfTxOutput(item, commitment) {
13405
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint3(item.comm0)) return Number(item.leaf0);
13406
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
13407
+ return null;
13408
+ }
13409
+ async function matchOwnItems(own, owner, onReject) {
13410
+ const candidates = [];
13411
+ const claimed = /* @__PURE__ */ new Set();
13412
+ const byNullifier = /* @__PURE__ */ new Map();
13413
+ const legacyKeys = /* @__PURE__ */ new Map();
13414
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
13415
+ const spendsOf = /* @__PURE__ */ new Map();
13416
+ const byOutKey = /* @__PURE__ */ new Map();
13417
+ const index = (map, key, o) => {
13418
+ const list = map.get(key);
13419
+ if (list) list.push(o);
13420
+ else map.set(key, [o]);
13421
+ };
13422
+ for (const o of ownTxs) {
13423
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
13424
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
13425
+ }
13426
+ const queue = [];
13427
+ const queued = /* @__PURE__ */ new Set();
13428
+ const enqueue = (o) => {
13429
+ if (queued.has(o)) return;
13430
+ queued.add(o);
13431
+ queue.push(o);
13432
+ };
13433
+ const add = async (o, c) => {
13434
+ const nullifier = hex32(
13435
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
13436
+ );
13437
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
13438
+ candidates.push(full);
13439
+ if (!byNullifier.has(nullifier)) {
13440
+ byNullifier.set(nullifier, full);
13441
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
13442
+ }
13443
+ if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
13444
+ legacyKeys.set(c.keypair.publicKey, c.keypair);
13445
+ for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
13446
+ }
13447
+ };
13448
+ const tryDeposit = async (o, item, amount) => {
13449
+ const note = o.note;
13450
+ const mint = addressFromBytes(item.mint);
13451
+ const deposit = await matchDepositNote({
13452
+ viewingKeyNk: o.trial.nk,
13453
+ noteSalt: note.noteSalt,
13454
+ amount,
13455
+ mintAddress: mint,
13456
+ outputCommitments: txOutputs(item),
13457
+ ownerUtxoKeypair: owner
13458
+ });
13459
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
13460
+ if (!deposit || leaf === null) return false;
13461
+ await add(o, {
13462
+ kind: "deposit",
13463
+ atRisk: deposit.legacyExposed,
13464
+ amount: deposit.amount,
13465
+ blinding: deposit.blinding,
13466
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
13467
+ mint,
13468
+ commitment: deposit.commitment,
13469
+ leaf
13470
+ });
13471
+ return true;
13472
+ };
13473
+ const tryChange0 = async (o, item, keypair, atRisk) => {
13474
+ const note = o.note;
13475
+ const mint = addressFromBytes(item.mint);
13476
+ const change = await matchChangeNote({
13477
+ viewingKeyNk: o.trial.nk,
13478
+ noteSalt: note.noteSalt,
13479
+ amount: note.outAmount0,
13480
+ keypair,
13481
+ mintAddress: mint,
13482
+ outputIndex: 0,
13483
+ outputCommitments: [toHex2(item.comm0)],
13484
+ ownerUtxoPublicKey: owner.publicKey
13485
+ });
13486
+ if (!change) return false;
13487
+ await add(o, {
13488
+ kind: "change",
13489
+ atRisk,
13490
+ amount: change.amount,
13491
+ blinding: change.blinding,
13492
+ keypair,
13493
+ mint,
13494
+ commitment: change.commitment,
13495
+ leaf: Number(item.leaf0)
13496
+ });
13497
+ return true;
13498
+ };
13499
+ for (const o of own) {
13500
+ const item = o.item;
13501
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
13502
+ const note = o.note;
13503
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13504
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
13505
+ }
13506
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
13507
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
13508
+ }
13509
+ } else if (item.kind === 2 && o.delivery) {
13510
+ const mint = addressFromBytes(item.mint);
13511
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
13512
+ onReject(o);
13513
+ continue;
13514
+ }
13515
+ const commitment = await computeCommitment2({
13516
+ amount: o.delivery.amount,
13517
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
13518
+ blinding: o.delivery.blinding,
13519
+ mintAddress: mint
13520
+ });
13521
+ if (commitment !== bytesToBigint3(item.commitment)) {
13522
+ onReject(o);
13523
+ continue;
13524
+ }
13525
+ await add(o, {
13526
+ kind: "received",
13527
+ atRisk: false,
13528
+ amount: o.delivery.amount,
13529
+ blinding: o.delivery.blinding,
13530
+ keypair: owner,
13531
+ mint,
13532
+ commitment,
13533
+ leaf: Number(item.leaf)
13534
+ });
13535
+ } else if (item.kind === 3 && o.refund) {
13536
+ await add(o, {
13537
+ kind: "swap_refund",
13538
+ atRisk: o.refund.legacyExposed,
13539
+ amount: o.refund.amount,
13540
+ blinding: o.refund.blinding,
13541
+ keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
13542
+ mint: NATIVE_SOL_MINT,
13543
+ commitment: o.refund.commitment,
13544
+ leaf: Number(item.leaf)
13545
+ });
13546
+ }
13547
+ }
13548
+ const processTx = async (o) => {
13549
+ const item = o.item;
13550
+ const note = o.note;
13551
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
13552
+ const legacy = legacyKeys.get(note.outPubkey0);
13553
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
13554
+ }
13555
+ const mint = addressFromBytes(item.mint);
13556
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
13557
+ if (inputs.length === 0) return;
13558
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
13559
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
13560
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
13561
+ if (out1 > 0n) {
13562
+ const blinding = deriveChangeNoteBlinding(o.trial.nk, note.noteSalt, 1);
13563
+ const owners = [{ keypair: owner, atRisk: false }];
13564
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
13565
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
13566
+ for (const { keypair, atRisk } of owners) {
13567
+ const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
13568
+ if (commitment !== bytesToBigint3(item.comm1)) continue;
13569
+ claimed.add(`${o.seq}:1`);
13570
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
13571
+ break;
13572
+ }
13573
+ }
13574
+ }
13575
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13576
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
13577
+ }
13578
+ };
13579
+ for (const o of ownTxs) enqueue(o);
13580
+ for (let i = 0; i < queue.length; i++) {
13581
+ const o = queue[i];
13582
+ queued.delete(o);
13583
+ await processTx(o);
13584
+ }
13585
+ return candidates;
13586
+ }
13587
+ async function replayStream(start, pages, overrides, chain, targetPage) {
13588
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
13589
+ const startN = frontier.nextIndex;
13590
+ const pending = new Map(start.pending);
13591
+ const flushed = new LeafBuffer();
13592
+ const corrections = /* @__PURE__ */ new Map();
13593
+ let conflicts = 0;
13594
+ let verifiedPrefix = 0;
13595
+ let mismatch = false;
13596
+ const checks = [];
13597
+ const setBits = [];
13598
+ if (chain && chain.nextIndex > 0) {
13599
+ const last = chain.nextIndex - 1;
13600
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
13601
+ for (const l of setBits) {
13602
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
13603
+ if (at >= startN) checks.push({ at, level: l });
13604
+ }
13605
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
13606
+ checks.sort((a, b) => a.at - b.at);
13607
+ }
13608
+ let nextCheck = 0;
13609
+ const runChecks = () => {
13610
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
13611
+ const { at, level } = checks[nextCheck++];
13612
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
13613
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
13614
+ else mismatch = true;
13615
+ }
13616
+ };
13617
+ const append = (values) => {
13618
+ let i = 0;
13619
+ while (i < values.length) {
13620
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
13621
+ const take = Math.min(values.length - i, room);
13622
+ if (take > 0) {
13623
+ const part = values.slice(i, i + take);
13624
+ frontier.append(part);
13625
+ flushed.push(part);
13626
+ i += take;
13627
+ }
13628
+ runChecks();
13629
+ }
13630
+ };
13631
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
13632
+ const flush = () => {
13633
+ const batch = [];
13634
+ let next = frontier.nextIndex;
13635
+ while (pending.has(next)) {
13636
+ batch.push(pending.get(next));
13637
+ pending.delete(next);
13638
+ next++;
13639
+ }
13640
+ if (batch.length > 0) append(batch);
13641
+ };
13642
+ let snapshot = null;
13643
+ let taken = false;
13644
+ const takeSnapshot = () => {
13645
+ taken = true;
13646
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
13647
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
13648
+ };
13649
+ runChecks();
13650
+ flush();
13651
+ for (const { page, entries } of pages) {
13652
+ if (!taken && page >= targetPage) takeSnapshot();
13653
+ for (const e of entries) {
13654
+ if (e.leaf < startN) continue;
13655
+ const prior = valueAt(e.leaf);
13656
+ if (prior !== void 0) {
13657
+ if (prior !== e.commitment) {
13658
+ conflicts++;
13659
+ corrections.set(e.leaf, e.commitment);
13660
+ }
13661
+ continue;
13662
+ }
13663
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
13664
+ }
13665
+ flush();
13666
+ }
13667
+ if (!taken) takeSnapshot();
13668
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
13669
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
13670
+ }
13671
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
13672
+ }
13673
+ var HEX64 = /^[0-9a-f]{64}$/;
13674
+ var HEX32 = /^[0-9a-f]{32}$/;
13675
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
13676
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
13677
+ function isRecord(v) {
13678
+ return typeof v === "object" && v !== null && !Array.isArray(v);
13679
+ }
13680
+ function isIntIn(v, min, max) {
13681
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
13682
+ }
13683
+ function isBoundedArray(v, max) {
13684
+ return Array.isArray(v) && v.length <= max;
13685
+ }
13686
+ function emptyStartTree() {
13687
+ return {
13688
+ frontier: null,
13689
+ nextIndex: 0,
13690
+ pending: /* @__PURE__ */ new Map(),
13691
+ window: [],
13692
+ windowStart: 0,
13693
+ verified: 0,
13694
+ overrides: /* @__PURE__ */ new Map(),
13695
+ mismatch: false,
13696
+ hiBefore: -1
13697
+ };
13698
+ }
13699
+ async function parseCursor(cursor, poolMints) {
13700
+ try {
13701
+ if (!isRecord(cursor)) return "not an object";
13702
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
13703
+ const c = cursor;
13704
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
13705
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
13706
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
13707
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
13708
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
13709
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
13710
+ const trees = /* @__PURE__ */ new Map();
13711
+ for (const mint of poolMints) {
13712
+ const t = c.trees[mint];
13713
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
13714
+ const tree = t;
13715
+ if (!isRecord(tree.frontier)) return "bad frontier";
13716
+ let frontier;
13717
+ try {
13718
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
13719
+ } catch {
13720
+ return "bad frontier";
13721
+ }
13722
+ const nextIndex = frontier.nextIndex;
13723
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
13724
+ const pending = /* @__PURE__ */ new Map();
13725
+ let hiBefore = nextIndex - 1;
13726
+ for (const entry of tree.pending) {
13727
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
13728
+ const [leaf, value] = entry;
13729
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
13730
+ return "bad pending leaves";
13731
+ }
13732
+ pending.set(leaf, BigInt("0x" + value));
13733
+ hiBefore = Math.max(hiBefore, leaf);
13734
+ }
13735
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
13736
+ const windowLen = tree.window.length / 64;
13737
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
13738
+ const window2 = [];
13739
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
13740
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
13741
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
13742
+ const overrides = /* @__PURE__ */ new Map();
13743
+ for (const entry of tree.overrides) {
13744
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
13745
+ const [leaf, value] = entry;
13746
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
13747
+ overrides.set(leaf, BigInt("0x" + value));
13748
+ }
13749
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
13750
+ trees.set(mint, {
13751
+ frontier: frontier.toState(),
13752
+ nextIndex,
13753
+ pending,
13754
+ window: window2,
13755
+ windowStart: nextIndex - windowLen,
13756
+ verified: tree.verified,
13757
+ overrides,
13758
+ mismatch: tree.mismatch,
13759
+ hiBefore
13760
+ });
13761
+ }
13762
+ const own = c.own;
13763
+ if (!isRecord(own)) return "bad own state";
13764
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
13765
+ const items = [];
13766
+ const seqs = /* @__PURE__ */ new Set();
13767
+ for (const entry of own.items) {
13768
+ if (!isRecord(entry)) return "bad own items";
13769
+ const { seq, item } = entry;
13770
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
13771
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
13772
+ seqs.add(seq);
13773
+ const raw = fromHex(item);
13774
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
13775
+ }
13776
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
13777
+ return "bad verified notes";
13778
+ }
13779
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
13780
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
13781
+ const pendingLeaves = /* @__PURE__ */ new Map();
13782
+ for (const entry of own.pendingLeaves) {
13783
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
13784
+ const [mint, leaf, value] = entry;
13785
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
13786
+ return "bad pending notes";
13787
+ }
13788
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
13789
+ }
13790
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
13791
+ return "bad rejected set";
13792
+ }
13793
+ return {
13794
+ raw: c,
13795
+ trees,
13796
+ items,
13797
+ verified: new Set(own.verified),
13798
+ spent: new Set(own.spent),
13799
+ pendingLeaves,
13800
+ rejected: own.rejected
13801
+ };
13802
+ } catch {
13803
+ return "unreadable state";
13804
+ }
13805
+ }
13806
+ async function recoverNotesFromIndex(params) {
13807
+ const startedAt = Date.now();
13808
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
13809
+ assertAllowedRelayOrigin(relayUrl);
13810
+ assertAllowedRpcConnection(connection);
13811
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
13812
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
13813
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
13814
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
13815
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
13816
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
13817
+ }
13818
+ if (params.signal?.aborted) throw abortError2();
13819
+ const stats = {
13820
+ pages: 0,
13821
+ items: 0,
13822
+ bytes: 0,
13823
+ rpcCalls: 0,
13824
+ ms: 0,
13825
+ dropped: 0,
13826
+ decrypted: 0,
13827
+ candidates: 0,
13828
+ spent: 0,
13829
+ conflicts: 0,
13830
+ pendingDropped: 0
13831
+ };
13832
+ const rpc = new Proxy(connection, {
13833
+ get(target, prop, receiver) {
13834
+ const value = Reflect.get(target, prop, receiver);
13835
+ if (typeof value !== "function") return value;
13836
+ return (...args) => {
13837
+ const pending = value.apply(target, args);
13838
+ if (pending && typeof pending.send === "function") {
13839
+ const send = pending.send.bind(pending);
13840
+ return {
13841
+ ...pending,
13842
+ send: (...sendArgs) => {
13843
+ stats.rpcCalls++;
13844
+ return send(...sendArgs);
13845
+ }
13846
+ };
13847
+ }
13848
+ return pending;
13849
+ };
13850
+ }
13851
+ });
13852
+ const makeTrial = async (nk, legacy) => ({
13853
+ nk,
13854
+ legacy,
13855
+ owner,
13856
+ decrypt: await createCompactChainNoteDecryptor(nk),
13857
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
13858
+ });
13859
+ const trials = [await makeTrial(viewingKeyNk, false)];
13860
+ const legacyNks = params.legacyViewingKeyNks ?? [];
13861
+ if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
13862
+ if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
13863
+ const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
13864
+ for (const nk of legacyNks) {
13865
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
13866
+ const key = toHex2(nk);
13867
+ if (seenNks.has(key)) continue;
13868
+ seenNks.add(key);
13869
+ trials.push(await makeTrial(Uint8Array.from(nk), true));
13870
+ }
13871
+ const poolMints = Array.from(new Set(params.poolMints));
13872
+ const warnings = [];
13873
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
13874
+ let cursor;
13875
+ if (params.cursor !== void 0) {
13876
+ const checked = await parseCursor(params.cursor, poolMints);
13877
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
13878
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
13879
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
13880
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
13881
+ } else cursor = checked;
13882
+ }
13883
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
13884
+ let treeRead;
13885
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
13886
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
13887
+ return poolMints.map((_, i) => {
13888
+ const account = accounts[i];
13889
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
13890
+ return account && parsed ? { ...parsed, data: account.data } : null;
13891
+ });
13892
+ })());
13893
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
13894
+ let outcome = await runOnce(ctx, cursor);
13895
+ if (outcome instanceof FullPassSignal) {
13896
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
13897
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
13898
+ outcome = await runOnce(ctx, void 0);
13899
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13900
+ }
13901
+ stats.ms = Date.now() - startedAt;
13902
+ return { ...outcome, stats, warnings };
13903
+ }
13904
+ async function runOnce(ctx, cursor) {
13905
+ const { params, head, trials, owner, stats, poolMints } = ctx;
13906
+ const { relayUrl, onProgress } = params;
13907
+ const poolSet = new Set(poolMints);
13908
+ const startPage = cursor?.raw.page ?? 0;
13909
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
13910
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
13911
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
13912
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
13913
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
13914
+ const rejectedIds = new Set(cursor?.rejected ?? []);
13915
+ const controller = new AbortController();
13916
+ const onCallerAbort = () => controller.abort();
13917
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
13918
+ const signal = controller.signal;
13919
+ try {
13920
+ const pageData = /* @__PURE__ */ new Map();
13921
+ const ownItems = [];
13922
+ const nullifiers = /* @__PURE__ */ new Set();
13923
+ let fullPassReason = null;
13924
+ const lateReference = (mint, leaf, value, seq) => {
13925
+ if (!cursor || seq < fullPassSeq) return null;
13926
+ const t = startTrees.get(mint);
13927
+ if (leaf < t.nextIndex) {
13928
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
13929
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
13930
+ return null;
13931
+ }
13932
+ const held = t.pending.get(leaf);
13933
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
13934
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
13935
+ return null;
13936
+ };
13937
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
13938
+ const waiting = /* @__PURE__ */ new Map();
13939
+ let chainNext = startPage;
13940
+ let chainError = null;
13941
+ let wakers = [];
13942
+ const wakeAll = () => {
13943
+ const w = wakers;
13944
+ wakers = [];
13945
+ for (const f of w) f();
13946
+ };
13947
+ signal.addEventListener("abort", wakeAll);
13948
+ const advanceChain = () => {
13949
+ while (!chainError && waiting.has(chainNext)) {
13950
+ const w = waiting.get(chainNext);
13951
+ waiting.delete(chainNext);
13952
+ const expected = chainAt.get(chainNext);
13953
+ if (w.prevChain !== expected) {
13954
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
13955
+ controller.abort();
13956
+ return;
13957
+ }
13958
+ if (!w.complete) break;
13959
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
13960
+ chainNext++;
13961
+ }
13962
+ wakeAll();
13963
+ };
13964
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
13965
+ const lookahead = 2 * workerCount + 2;
13966
+ let nextToFetch = startPage;
13967
+ let pagesDone = 0;
13968
+ const worker = async () => {
13969
+ for (; ; ) {
13970
+ if (signal.aborted) throw abortError2();
13971
+ const pageNo = nextToFetch++;
13972
+ if (pageNo >= pagesTotal) return;
13973
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
13974
+ if (signal.aborted) throw abortError2();
13975
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13976
+ stats.bytes += bytes.length;
13977
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
13978
+ if (pageNo < head.completePages && !page2.complete) {
13979
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13980
+ }
13981
+ stats.pages++;
13982
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13983
+ advanceChain();
13984
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
13985
+ const late = (reason) => {
13986
+ if (reason && !fullPassReason) {
13987
+ fullPassReason = reason;
13988
+ controller.abort();
13989
+ }
13990
+ };
13991
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
13992
+ if (isAllZero3(commitment)) return;
13993
+ const mint = addressFromBytes(mintBytes);
13994
+ if (!poolSet.has(mint)) return;
13995
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint3(commitment) };
13996
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
13997
+ const list = data.leaves.get(mint);
13998
+ if (list) list.push(entry);
13999
+ else data.leaves.set(mint, [entry]);
14000
+ };
14001
+ page2.items.forEach((item, i) => {
14002
+ const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
14003
+ if (item.kind === 1) {
14004
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
14005
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
14006
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
14007
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
14008
+ } else if (item.kind === 3) {
14009
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
14010
+ } else {
14011
+ const mint = addressFromBytes(item.mint);
14012
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
14013
+ }
14014
+ });
14015
+ if (signal.aborted) throw abortError2();
14016
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
14017
+ if (signal.aborted) throw abortError2();
14018
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
14019
+ const opened = await Promise.all(batch.map((item) => trialItem(item, trials)));
14020
+ opened.forEach((o, k) => {
14021
+ if (!o) return;
14022
+ stats.decrypted++;
14023
+ const raw = page2.rawItems[i + k];
14024
+ const id = itemIdentity(raw);
14025
+ if (rejectedIds.has(id)) {
14026
+ stats.dropped++;
14027
+ return;
14028
+ }
14029
+ ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
14030
+ });
14031
+ stats.items += batch.length;
14032
+ }
14033
+ pageData.set(pageNo, data);
14034
+ pagesDone++;
14035
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
14036
+ }
14037
+ };
14038
+ const workers = Array.from(
14039
+ { length: workerCount },
14040
+ () => worker().catch((error) => {
14041
+ controller.abort();
14042
+ throw error;
14043
+ })
14044
+ );
14045
+ const settled = await Promise.allSettled(workers);
14046
+ signal.removeEventListener("abort", wakeAll);
14047
+ if (params.signal?.aborted) throw abortError2();
14048
+ const lateReason = fullPassReason;
14049
+ if (lateReason) return new FullPassSignal(lateReason);
14050
+ const chainFailure = chainError;
14051
+ if (chainFailure) {
14052
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
14053
+ throw chainFailure;
14054
+ }
14055
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
14056
+ if (failure) throw failure.reason;
14057
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
14058
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
14059
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
14060
+ }
14061
+ for (const entry of cursor?.items ?? []) {
14062
+ const o = await trialItem(entry.item, trials);
14063
+ if (!o) continue;
14064
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
14065
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
14066
+ if (entry.item.kind === 1) {
14067
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
14068
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
14069
+ }
14070
+ }
14071
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
14072
+ ownItems.sort((a, b) => a.seq - b.seq);
14073
+ const rejectedNow = /* @__PURE__ */ new Set();
14074
+ const allCandidates = await matchOwnItems(ownItems, owner, (o) => {
14075
+ stats.dropped++;
14076
+ rejectedNow.add(o.id);
14077
+ });
14078
+ stats.candidates = allCandidates.length;
14079
+ const cutoff = params.legacyCutoffLeaf ?? {};
14080
+ const candidates = allCandidates.filter((c) => {
14081
+ const limit = cutoff[c.mint];
14082
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
14083
+ stats.dropped++;
14084
+ return false;
14085
+ }
14086
+ return true;
14087
+ });
14088
+ const chainTrees = await ctx.readTrees();
14089
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
14090
+ const replays = /* @__PURE__ */ new Map();
14091
+ for (let i = 0; i < poolMints.length; i++) {
14092
+ const mint = poolMints[i];
14093
+ const start = startTrees.get(mint);
14094
+ const chainTree = chainTrees[i] ?? null;
14095
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
14096
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
14097
+ let overrides = start.overrides;
14098
+ stats.conflicts += r.conflicts;
14099
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
14100
+ const merged = new Map([...start.overrides, ...r.corrections]);
14101
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
14102
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
14103
+ r = alternative;
14104
+ overrides = merged;
14105
+ }
14106
+ }
14107
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
14108
+ replays.set(mint, { r, overrides });
14109
+ }
14110
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
14111
+ const streamValue = (mint, leaf) => {
14112
+ const v = replays.get(mint)?.r.valueAt(leaf);
14113
+ if (v !== void 0) return v;
14114
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
14115
+ if (carried !== void 0) return carried;
14116
+ const t = startTrees.get(mint);
14117
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
14118
+ return void 0;
14119
+ };
14120
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
14121
+ const verified = [];
14122
+ const pendingByKey = /* @__PURE__ */ new Map();
14123
+ const rejectedCandidates = /* @__PURE__ */ new Set();
14124
+ const outcomeOf = /* @__PURE__ */ new Map();
14125
+ const tally = (c, what) => {
14126
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
14127
+ t.total++;
14128
+ if (what === "kept") t.kept = true;
14129
+ if (what === "rejected") t.rejected++;
14130
+ outcomeOf.set(c.seq, t);
14131
+ };
14132
+ const pend = (c, rank) => {
14133
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
14134
+ const prior = pendingByKey.get(key);
14135
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
14136
+ };
14137
+ for (const c of candidates) {
14138
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
14139
+ verified.push(c);
14140
+ continue;
14141
+ }
14142
+ if (!poolSet.has(c.mint)) {
14143
+ pend(c, 3);
14144
+ continue;
14145
+ }
14146
+ const value = streamValue(c.mint, c.leaf);
14147
+ if (value === void 0) {
14148
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
14149
+ stats.dropped++;
14150
+ tally(c, "other");
14151
+ } else pend(c, 1);
14152
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
14153
+ pend(c, value === c.commitment ? 0 : 2);
14154
+ } else if (value === c.commitment) {
14155
+ verified.push(c);
14156
+ } else {
14157
+ stats.dropped++;
14158
+ rejectedCandidates.add(c);
14159
+ tally(c, "rejected");
14160
+ }
14161
+ }
14162
+ verified.sort((a, b) => a.seq - b.seq);
14163
+ const byLeaf = /* @__PURE__ */ new Map();
14164
+ for (const c of verified) {
14165
+ const key = `${c.mint}:${c.leaf}`;
14166
+ if (byLeaf.has(key)) {
14167
+ stats.dropped++;
14168
+ tally(c, "other");
14169
+ continue;
14170
+ }
14171
+ byLeaf.set(key, c);
14172
+ }
14173
+ const notes = [];
14174
+ const atRisk = [];
14175
+ const spentOut = new Set(knownSpent);
14176
+ const verifiedOut = new Set(knownVerified);
14177
+ const keyChecked = /* @__PURE__ */ new Map();
14178
+ for (const c of byLeaf.values()) {
14179
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
14180
+ keyChecked.set(c.keypair.privateKey, pubOk);
14181
+ if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
14182
+ stats.dropped++;
14183
+ tally(c, "rejected");
14184
+ continue;
14185
+ }
14186
+ tally(c, "kept");
14187
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
14188
+ const utxo = {
14189
+ amount: c.amount,
14190
+ keypair: c.atRisk ? { ...c.keypair } : owner,
14191
+ blinding: c.blinding,
14192
+ mintAddress: c.mint,
14193
+ index: c.leaf,
14194
+ commitment: c.commitment
14195
+ };
14196
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
14197
+ stats.spent++;
14198
+ spentOut.add(c.nullifier);
14199
+ continue;
14200
+ }
14201
+ const note = {
14202
+ kind: c.kind,
14203
+ utxo,
14204
+ signature: bs584.encode(c.signature),
14205
+ legacyExposed: c.atRisk
14206
+ };
14207
+ (c.atRisk ? atRisk : notes).push(note);
14208
+ }
14209
+ const sortNotes = (list) => list.sort((a, b) => a.utxo.mintAddress === b.utxo.mintAddress ? a.utxo.index - b.utxo.index : a.utxo.mintAddress < b.utxo.mintAddress ? -1 : 1);
14210
+ sortNotes(notes);
14211
+ sortNotes(atRisk);
14212
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
14213
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
14214
+ const overflow = pendingList.length - carriedPending.length;
14215
+ if (overflow > 0) {
14216
+ stats.pendingDropped += overflow;
14217
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
14218
+ }
14219
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
14220
+ for (const c of carriedPending) tally(c, "kept");
14221
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
14222
+ let page = targetPage;
14223
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
14224
+ const trees = {};
14225
+ const treeEnd = /* @__PURE__ */ new Map();
14226
+ for (const mint of poolMints) {
14227
+ const start = startTrees.get(mint);
14228
+ const { r, overrides } = replays.get(mint);
14229
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
14230
+ const n = snap.nextIndex;
14231
+ const window2 = [];
14232
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
14233
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
14234
+ if (v === void 0) break;
14235
+ window2.push(hex32(v));
14236
+ }
14237
+ window2.reverse();
14238
+ trees[mint] = {
14239
+ frontier: snap.frontier,
14240
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
14241
+ window: window2.join(""),
14242
+ verified: Math.min(verifiedUpTo(mint), n),
14243
+ overrides: Array.from(overrides.entries()).filter(([leaf]) => leaf >= n && !snap.pending.has(leaf)).sort((a, b) => a[0] - b[0]).slice(0, MAX_OVERRIDES).map(([leaf, v]) => [leaf, hex32(v)]),
14244
+ mismatch: r.mismatch
14245
+ };
14246
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
14247
+ }
14248
+ const pendingLeaves = [];
14249
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
14250
+ for (const c of carriedPending) {
14251
+ const end = treeEnd.get(c.mint);
14252
+ if (!end || c.leaf >= end.nextIndex) continue;
14253
+ const value = streamValue(c.mint, c.leaf);
14254
+ const key = `${c.mint}:${c.leaf}`;
14255
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
14256
+ pendingLeafSeen.add(key);
14257
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
14258
+ }
14259
+ const keptItems = [];
14260
+ const keptIds = /* @__PURE__ */ new Set();
14261
+ for (const o of ownItems) {
14262
+ const t = outcomeOf.get(o.seq);
14263
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
14264
+ rejectedNow.add(o.id);
14265
+ continue;
14266
+ }
14267
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
14268
+ keptIds.add(o.id);
14269
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
14270
+ }
14271
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
14272
+ const nextCursor = {
14273
+ v: CURSOR_VERSION,
14274
+ epoch: head.epoch.toString(10),
14275
+ page,
14276
+ chain: chainAt.get(page) ?? startChain,
14277
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
14278
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
14279
+ trees,
14280
+ own: {
14281
+ items: keptItems,
14282
+ verified: Array.from(verifiedOut),
14283
+ spent: Array.from(spentOut),
14284
+ pendingLeaves,
14285
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
14286
+ }
14287
+ };
14288
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
14289
+ } finally {
14290
+ params.signal?.removeEventListener("abort", onCallerAbort);
14291
+ }
14292
+ }
14293
+
14294
+ // src/wallet/utxo-wallet.ts
14295
+ init_address();
14296
+ init_utxo();
14297
+ var UtxoWallet = class _UtxoWallet {
14298
+ constructor(viewingKey) {
14299
+ this.wallets = /* @__PURE__ */ new Map();
14300
+ this.viewingKey = viewingKey;
14301
+ }
14302
+ /**
14303
+ * Add a UTXO to the wallet (discovered from chain or created)
14304
+ */
12181
14305
  addUtxo(utxo, mint = NATIVE_SOL_MINT) {
12182
14306
  const mintKey = mint;
12183
14307
  if (!this.wallets.has(mintKey)) {
@@ -12826,7 +14950,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12826
14950
  })
12827
14951
  });
12828
14952
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12829
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
14953
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
12830
14954
  throw new Error(
12831
14955
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12832
14956
  );
@@ -12863,9 +14987,13 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12863
14987
  // src/bridge/derive.ts
12864
14988
  var import_hmac = require("@noble/hashes/hmac");
12865
14989
  var import_sha512 = require("@noble/hashes/sha512");
14990
+ var import_blake37 = require("@noble/hashes/blake3");
14991
+ init_utxo();
12866
14992
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
14993
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
14994
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
12867
14995
  var MAX_RECEIVER_INDEX = 1e4;
12868
- async function deriveBridgeReceiver(nk, index) {
14996
+ function assertReceiverIndex(index) {
12869
14997
  if (!Number.isInteger(index) || index < 0) {
12870
14998
  throw new Error(`index must be a non-negative integer, got ${index}`);
12871
14999
  }
@@ -12874,6 +15002,26 @@ async function deriveBridgeReceiver(nk, index) {
12874
15002
  `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.`
12875
15003
  );
12876
15004
  }
15005
+ }
15006
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
15007
+ if (ownerUtxoKeypair instanceof Uint8Array) {
15008
+ throw new Error(
15009
+ "deriveBridgeReceiver takes the wallet's UTXO keypair, not a byte key. Receivers are no longer derived from nk; use deriveLegacyBridgeReceiver(nk, index) only to find old deposits."
15010
+ );
15011
+ }
15012
+ assertReceiverIndex(index);
15013
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
15014
+ const priv = bigintToBytes323(owner.privateKey);
15015
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
15016
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
15017
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
15018
+ const key = (0, import_blake37.blake3)(preimage);
15019
+ const h = (0, import_hmac.hmac)(import_sha512.sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
15020
+ return signerFromSecretKey(h.slice(0, 32));
15021
+ }
15022
+ async function deriveLegacyBridgeReceiver(nk, index) {
15023
+ assertReceiverIndex(index);
15024
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
12877
15025
  const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12878
15026
  return signerFromSecretKey(h.slice(0, 32));
12879
15027
  }
@@ -12884,13 +15032,44 @@ var import_token4 = require("@solana-program/token");
12884
15032
  function describeError(err) {
12885
15033
  return err instanceof Error ? err.message : String(err);
12886
15034
  }
12887
- async function listBridgeDeposits(rpc, nk, opts) {
15035
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
15036
+ if (ownerUtxoKeypair instanceof Uint8Array) {
15037
+ throw new Error(
15038
+ "listBridgeDeposits takes the wallet's UTXO keypair, not nk. Receivers are no longer derived from nk; legacy nk receivers are scanned automatically (see DiscoverOptions.includeLegacy)."
15039
+ );
15040
+ }
15041
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
15042
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
15043
+ legacyExposed: false
15044
+ });
15045
+ if (opts.includeLegacy === false) return out;
15046
+ const nks = [];
15047
+ const seen = /* @__PURE__ */ new Set();
15048
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
15049
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
15050
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
15051
+ }
15052
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
15053
+ if (seen.has(key)) continue;
15054
+ seen.add(key);
15055
+ nks.push(nk);
15056
+ }
15057
+ for (const nk of nks) {
15058
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
15059
+ legacyExposed: true,
15060
+ legacyViewingKeyNk: nk
15061
+ });
15062
+ out.push(...legacy);
15063
+ }
15064
+ return out;
15065
+ }
15066
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12888
15067
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12889
15068
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12890
15069
  const out = [];
12891
15070
  let consecutiveUnused = 0;
12892
15071
  for (let index = 0; index < scanDepth; index++) {
12893
- const kp = await deriveBridgeReceiver(nk, index);
15072
+ const kp = await receiverAt(index);
12894
15073
  const receiver = kp.address;
12895
15074
  const [tokenAccount] = await (0, import_token4.findAssociatedTokenPda)({
12896
15075
  mint: opts.mint,
@@ -12942,7 +15121,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12942
15121
  tokenBalance,
12943
15122
  lamports,
12944
15123
  shieldSignature,
12945
- ...indexReused ? { indexReused, shieldSignatures } : {}
15124
+ ...indexReused ? { indexReused, shieldSignatures } : {},
15125
+ ...provenance
12946
15126
  });
12947
15127
  } catch (err) {
12948
15128
  out.push({
@@ -12952,7 +15132,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12952
15132
  state: "unknown",
12953
15133
  tokenBalance: 0n,
12954
15134
  lamports: 0n,
12955
- error: describeError(err)
15135
+ error: describeError(err),
15136
+ ...provenance
12956
15137
  });
12957
15138
  }
12958
15139
  }
@@ -13106,7 +15287,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13106
15287
  const signMessage = (m) => signMessageBytes(R, m);
13107
15288
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
13108
15289
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
13109
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
15290
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
15291
+ amount,
15292
+ viewingKeyNk: nk,
15293
+ ownerUtxoKeypair: utxoKeypair,
15294
+ mintAddress: mint
15295
+ });
13110
15296
  const zeroInput = await createZeroUtxo(mint);
13111
15297
  const rBefore = (await rpc.getBalance(R.address).send()).value;
13112
15298
  let result;
@@ -13125,6 +15311,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13125
15311
  signMessage,
13126
15312
  chainNoteViewingKeyNk: nk,
13127
15313
  chainNoteSalt: noteSalt,
15314
+ ownerUtxoKeypair: utxoKeypair,
13128
15315
  relaySupplementalAlt: true,
13129
15316
  onProgress: (s) => log(` \xB7 ${s}`)
13130
15317
  }
@@ -13312,13 +15499,13 @@ var DoNotRetry = class extends Error {
13312
15499
  };
13313
15500
  async function withShieldRetries(attempt, hooks = {}) {
13314
15501
  const attempts = hooks.attempts ?? 3;
13315
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
15502
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13316
15503
  let last = "";
13317
15504
  for (let n = 1; n <= attempts; n++) {
13318
15505
  if (n > 1) {
13319
15506
  const delay = retryDelayMs(n);
13320
15507
  hooks.onRetry?.(n, delay, last);
13321
- await sleep4(delay);
15508
+ await sleep5(delay);
13322
15509
  }
13323
15510
  try {
13324
15511
  return await attempt(n);
@@ -13332,12 +15519,13 @@ async function withShieldRetries(attempt, hooks = {}) {
13332
15519
  }
13333
15520
 
13334
15521
  // src/index.ts
13335
- var VERSION = "0.2.5";
15522
+ var VERSION = "0.2.6";
13336
15523
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13337
15524
  // Annotate the CommonJS export names for ESM import in node:
13338
15525
  0 && (module.exports = {
13339
15526
  AccountRole,
13340
15527
  BRIDGE_ESCROW_LABEL,
15528
+ BRIDGE_ESCROW_LABEL_V2,
13341
15529
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
13342
15530
  CHAIN_NOTE_SALT_BITS,
13343
15531
  CLEANUP_FEE_BUDGET,
@@ -13366,6 +15554,10 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13366
15554
  MemoryStorageAdapter,
13367
15555
  MerkleTree,
13368
15556
  NATIVE_SOL_MINT,
15557
+ NOTE_INDEX_NO_LEAF,
15558
+ NOTE_INDEX_PAGE_SIZE,
15559
+ NoteIndexFormatError,
15560
+ NoteIndexHeadBehindError,
13369
15561
  ONECLICK_PUBKEY_B58,
13370
15562
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
13371
15563
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -13442,6 +15634,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13442
15634
  computeChainNoteHash,
13443
15635
  computeExtDataHash,
13444
15636
  computeMerkleRoot,
15637
+ computeNoteIndexChain,
13445
15638
  computeProofForLatestDeposit,
13446
15639
  computeProofFromChain,
13447
15640
  computeSignature,
@@ -13466,14 +15659,18 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13466
15659
  depositFromDerivedKey,
13467
15660
  deriveBridgeReceiver,
13468
15661
  deriveChangeNoteBlinding,
13469
- deriveDepositNoteSecrets,
15662
+ deriveDepositNoteBlinding,
13470
15663
  deriveDiversifiedViewingKey,
13471
15664
  deriveDiversifier,
13472
15665
  deriveFundingTargets,
13473
15666
  deriveInputNullifierPdas,
15667
+ deriveLegacyBridgeReceiver,
15668
+ deriveLegacyDepositNoteSecrets,
15669
+ deriveLegacySwapRefundAuthorization,
13474
15670
  derivePublicKey,
13475
15671
  deriveSpendKey,
13476
15672
  deriveSwapRefundAuthorization,
15673
+ deriveSwapRefundBlinding,
13477
15674
  deriveUserCompliancePublicKey,
13478
15675
  deriveUserComplianceScalar,
13479
15676
  deriveUtxoKeypairFromSpendKey,
@@ -13486,6 +15683,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13486
15683
  discoverSwapRefunds,
13487
15684
  downloadNote,
13488
15685
  encodeDeliveryCarrierMemo,
15686
+ encodeNoteIndexItem,
15687
+ encodeNoteIndexPage,
13489
15688
  encodeNoteSimple,
13490
15689
  encodeRecipientDeliveryNote,
13491
15690
  encryptCompactChainNote,
@@ -13501,6 +15700,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13501
15700
  fetchCommitments,
13502
15701
  fetchLatestBlockhash,
13503
15702
  fetchLookupTables,
15703
+ fetchNoteIndexHead,
15704
+ fetchNoteIndexPage,
13504
15705
  fetchRiskQuoteInstruction,
13505
15706
  fetchRiskQuoteIx,
13506
15707
  fetchSignaturesForAddress,
@@ -13573,6 +15774,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13573
15774
  parseDeliveryCarrierMemo,
13574
15775
  parseError,
13575
15776
  parseNote,
15777
+ parseNoteIndexItem,
15778
+ parseNoteIndexPage,
13576
15779
  parseRelayErrorResponse,
13577
15780
  parseRelayErrorSignature,
13578
15781
  parseTransactionError,
@@ -13594,6 +15797,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13594
15797
  readMerkleTreeState,
13595
15798
  readRent,
13596
15799
  recipientDeliveryNoteToBase64,
15800
+ recoverNotesFromIndex,
13597
15801
  registerViewingKey,
13598
15802
  relayRequestDigestHex,
13599
15803
  removePendingDeposit,