@cloak.dev/sdk 0.2.6-staging.6c85601 → 0.2.6-staging.f92dd96

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,
@@ -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 = 365 * 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) => {
@@ -1673,8 +1728,9 @@ function assertAllowedRelayOrigin(value) {
1673
1728
  async function relayFetch(url, init, options) {
1674
1729
  assertAllowedRelayOrigin(url);
1675
1730
  const extra = sanitizeExtraHeaders(options?.extraHeaders);
1676
- if (!extra) return fetch(url, init);
1677
- return fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) });
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;
1678
1734
  }
1679
1735
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1680
1736
  var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
@@ -2144,7 +2200,7 @@ ${digest}`
2144
2200
  }
2145
2201
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
2146
2202
  const senderB58 = sender;
2147
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
2203
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
2148
2204
  const nonce = randomNonceUuid();
2149
2205
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
2150
2206
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -2223,7 +2279,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
2223
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.`
2224
2280
  );
2225
2281
  }
2226
- function explainRelayAuthRejection(responseText) {
2282
+ function explainRelayAuthRejection(responseText, context) {
2227
2283
  const text = String(responseText);
2228
2284
  const has = (needle) => text.includes(needle);
2229
2285
  if (has("issued too far in the future")) {
@@ -2233,7 +2289,9 @@ function explainRelayAuthRejection(responseText) {
2233
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.`;
2234
2290
  }
2235
2291
  if (has("does not match the exact request")) {
2236
- 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\`.`;
2237
2295
  }
2238
2296
  if (has("has no registered viewing key")) {
2239
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.`;
@@ -4797,6 +4855,27 @@ function isRootAccepted(data, rootHex) {
4797
4855
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
4798
4856
  return readRootHistory(data).some((r) => r === want);
4799
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
+ }
4800
4879
 
4801
4880
  // src/proving/merkle.ts
4802
4881
  var import_circomlibjs3 = require("circomlibjs");
@@ -4956,6 +5035,89 @@ var MerkleTree = class _MerkleTree {
4956
5035
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4957
5036
  return MerkleTree.create(height, commitments);
4958
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
+ };
4959
5121
 
4960
5122
  // src/relay/client.ts
4961
5123
  init_address();
@@ -5107,6 +5269,7 @@ async function fetchWithRetry(url, options = {}) {
5107
5269
  try {
5108
5270
  const response = await fetch(url, { signal: controller.signal });
5109
5271
  clearTimeout(timeoutId);
5272
+ observeRelayClock(response);
5110
5273
  return response;
5111
5274
  } finally {
5112
5275
  clearTimeout(timeoutId);
@@ -5459,38 +5622,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
5459
5622
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
5460
5623
  return new Uint8Array(plaintext);
5461
5624
  }
5462
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
5625
+ async function importNkHkdfKey(nk) {
5463
5626
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5464
5627
  throw new Error("nk must be 32 bytes");
5465
5628
  }
5629
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
5630
+ }
5631
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
5466
5632
  const subtle = getSubtleCrypto2();
5467
- const ikm = await subtle.importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
5468
- const salt = hexToBytes32(commitmentHex);
5469
- const keyBits = await subtle.deriveBits(
5470
- {
5471
- name: "HKDF",
5472
- hash: "SHA-256",
5473
- salt: toArrayBuffer2(salt),
5474
- info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
5475
- },
5476
- ikm,
5477
- 256
5478
- );
5479
- const nonceBits = await subtle.deriveBits(
5480
- {
5481
- name: "HKDF",
5482
- hash: "SHA-256",
5483
- salt: toArrayBuffer2(salt),
5484
- info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
5485
- },
5486
- ikm,
5487
- 96
5488
- );
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
+ ]);
5489
5655
  return {
5490
5656
  key: new Uint8Array(keyBits),
5491
5657
  nonce: new Uint8Array(nonceBits)
5492
5658
  };
5493
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
+ }
5494
5696
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
5495
5697
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5496
5698
  throw new Error("nk must be 32 bytes");
@@ -5554,36 +5756,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5554
5756
  try {
5555
5757
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
5556
5758
  const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
5557
- if (version === NOTE_VERSION_V4) {
5558
- if (plaintext.length !== PLAINTEXT_LEN_V4) {
5559
- throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
5560
- }
5561
- return {
5562
- timestamp: readU64LE(plaintext, 0),
5563
- commitment: commitment.toLowerCase(),
5564
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
5565
- outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
5566
- outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
5567
- isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
5568
- };
5569
- }
5570
- if (version === NOTE_VERSION_V3) {
5571
- if (plaintext.length !== PLAINTEXT_LEN_V3) {
5572
- throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
5573
- }
5574
- return {
5575
- timestamp: readU64LE(plaintext, 0),
5576
- commitment: commitment.toLowerCase(),
5577
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
5578
- };
5579
- }
5580
- if (plaintext.length !== PLAINTEXT_LEN_V2) {
5581
- throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
5582
- }
5583
- return {
5584
- timestamp: readU64LE(plaintext, 0),
5585
- commitment: commitment.toLowerCase()
5586
- };
5759
+ return decodeChainNotePlaintext(version, plaintext, commitment);
5587
5760
  } catch (error) {
5588
5761
  lastError = error;
5589
5762
  }
@@ -5592,6 +5765,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5592
5765
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
5593
5766
  );
5594
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
+ }
5595
5788
  function chainNoteToBase64(noteBytes) {
5596
5789
  return Buffer.from(noteBytes).toString("base64");
5597
5790
  }
@@ -5688,6 +5881,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
5688
5881
  return null;
5689
5882
  }
5690
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
+ }
5691
5958
  function recipientDeliveryNoteToBase64(envelope) {
5692
5959
  return Buffer.from(envelope).toString("base64");
5693
5960
  }
@@ -5742,10 +6009,43 @@ var import_blake34 = require("@noble/hashes/blake3");
5742
6009
  init_address();
5743
6010
  var import_bs582 = __toESM(require("bs58"), 1);
5744
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
5745
6045
  init_inputs();
5746
6046
  var bs582 = import_bs582.default.default || import_bs582.default;
5747
6047
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
5748
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6048
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5749
6049
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
5750
6050
  function normalizeNullifier(inputNullifier) {
5751
6051
  if (inputNullifier instanceof Uint8Array) {
@@ -5779,13 +6079,29 @@ function derive(nk, nullifier, info) {
5779
6079
  preimage.set(info, off);
5780
6080
  return (0, import_blake34.blake3)(preimage);
5781
6081
  }
5782
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
6082
+ function assertNk(viewingKeyNk) {
5783
6083
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5784
6084
  throw new Error("viewingKeyNk must be 32 bytes");
5785
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);
5786
6102
  const nullifier = normalizeNullifier(inputNullifier);
5787
- const privateKey = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_PRIVATE_KEY_INFO));
5788
- 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));
5789
6105
  const publicKey = await derivePublicKey(privateKey);
5790
6106
  if (publicKey === 0n || blinding === 0n) {
5791
6107
  throw new Error("derived refund authorization is degenerate");
@@ -5803,19 +6119,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
5803
6119
  async function matchSwapRefundLeaf(params) {
5804
6120
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
5805
6121
  const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
5806
- let auth;
6122
+ let blinding;
5807
6123
  try {
5808
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
6124
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5809
6125
  } catch {
5810
6126
  return null;
5811
6127
  }
5812
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
5813
- if (candidate !== expected) return null;
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;
6142
+ try {
6143
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
6144
+ } catch {
6145
+ return null;
6146
+ }
6147
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
6148
+ if (legacyCandidate !== expected) return null;
5814
6149
  return {
5815
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
5816
- blinding: auth.blinding,
6150
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
6151
+ blinding: legacy.blinding,
5817
6152
  amount: amountAfterFee,
5818
- commitment: candidate
6153
+ commitment: legacyCandidate,
6154
+ legacyExposed: true
5819
6155
  };
5820
6156
  }
5821
6157
  var TRANSACT_SWAP_TAG2 = 1;
@@ -5879,10 +6215,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
5879
6215
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
5880
6216
  return out;
5881
6217
  }
5882
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
6218
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
5883
6219
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5884
6220
  throw new Error("viewingKeyNk must be 32 bytes");
5885
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;
5886
6228
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5887
6229
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5888
6230
  const programIdBase58 = programId;
@@ -5957,7 +6299,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5957
6299
  viewingKeyNk,
5958
6300
  inputNullifier: candidate.nullifier,
5959
6301
  amountAfterFee: event.amountAfterFee,
5960
- commitment: event.commitmentField
6302
+ commitment: event.commitmentField,
6303
+ ownerUtxoKeypair
5961
6304
  });
5962
6305
  if (!recovered) continue;
5963
6306
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5983,7 +6326,7 @@ var import_blake35 = require("@noble/hashes/blake3");
5983
6326
  init_utxo();
5984
6327
  init_inputs();
5985
6328
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5986
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6329
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5987
6330
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5988
6331
  var CHAIN_NOTE_SALT_BITS = 96;
5989
6332
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -6019,30 +6362,47 @@ function derive2(nk, salt, info) {
6019
6362
  preimage.set(info, off);
6020
6363
  return (0, import_blake35.blake3)(preimage);
6021
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
+ }
6022
6371
  function randomDepositNoteSalt() {
6023
6372
  const bytes = randomBytes(12);
6024
6373
  let v = 0n;
6025
6374
  for (const b of bytes) v = v << 8n | BigInt(b);
6026
6375
  return v === 0n ? 1n : v;
6027
6376
  }
6028
- async function deriveDepositNoteSecrets(viewingKeyNk, noteSalt) {
6029
- if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
6030
- throw new Error("viewingKeyNk must be 32 bytes");
6031
- }
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);
6032
6383
  const salt = saltToBytes(noteSalt);
6033
- const privateKey = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_PRIVATE_KEY_INFO));
6034
- 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));
6035
6386
  const publicKey = await derivePublicKey(privateKey);
6036
6387
  if (publicKey === 0n || blinding === 0n) {
6037
6388
  throw new Error("derived deposit note secrets are degenerate");
6038
6389
  }
6039
6390
  return { keypair: { privateKey, publicKey }, blinding };
6040
6391
  }
6041
- 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;
6042
6399
  if (typeof amount !== "bigint" || amount <= 0n) {
6043
6400
  throw new Error("amount must be a positive bigint");
6044
6401
  }
6045
- 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);
6046
6406
  const utxo = { amount, keypair, blinding, mintAddress };
6047
6407
  utxo.commitment = await computeCommitment2(utxo);
6048
6408
  return { utxo, noteSalt };
@@ -6057,21 +6417,46 @@ function normalizeCommitment(value) {
6057
6417
  async function matchDepositNote(params) {
6058
6418
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
6059
6419
  if (typeof amount !== "bigint" || amount <= 0n) return null;
6060
- let secrets;
6420
+ let blinding;
6061
6421
  try {
6062
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
6422
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
6063
6423
  } catch {
6064
6424
  return null;
6065
6425
  }
6066
- const candidate = await computeCommitment2({
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;
6440
+ try {
6441
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
6442
+ } catch {
6443
+ return null;
6444
+ }
6445
+ const legacyCandidate = await computeCommitment2({
6067
6446
  amount,
6068
- keypair: secrets.keypair,
6069
- blinding: secrets.blinding,
6447
+ keypair: legacy.keypair,
6448
+ blinding: legacy.blinding,
6070
6449
  mintAddress
6071
6450
  });
6072
- const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
6073
- if (!published.some((value) => value === candidate)) return null;
6074
- 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
+ };
6075
6460
  }
6076
6461
 
6077
6462
  // src/notes/change-note.ts
@@ -6129,10 +6514,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
6129
6514
  preimage.set(CHANGE_BLINDING_INFO, off);
6130
6515
  return toFieldSecret3((0, import_blake36.blake3)(preimage));
6131
6516
  }
6132
- 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) {
6133
6518
  if (typeof amount !== "bigint" || amount <= 0n) {
6134
6519
  throw new Error("amount must be a positive bigint");
6135
6520
  }
6521
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
6136
6522
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
6137
6523
  const utxo = { amount, keypair, blinding, mintAddress };
6138
6524
  utxo.commitment = await computeCommitment2(utxo);
@@ -6158,12 +6544,28 @@ async function matchChangeNote(params) {
6158
6544
  const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
6159
6545
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
6160
6546
  if (!published.some((value) => value === candidate)) return null;
6161
- 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 };
6162
6550
  }
6163
6551
 
6164
6552
  // src/flows/transact.ts
6165
6553
  var import_circomlibjs4 = require("circomlibjs");
6166
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
6167
6569
  init_inputs();
6168
6570
 
6169
6571
  // src/proving/artifacts.ts
@@ -6802,6 +7204,33 @@ function parseNkInput(input) {
6802
7204
  }
6803
7205
  return Uint8Array.from(Buffer.from(clean, "hex"));
6804
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
+ }
6805
7234
  async function resolveChainNoteNk(options) {
6806
7235
  if (options.chainNoteViewingKeyNk) {
6807
7236
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -6819,7 +7248,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
6819
7248
  function toHex(bytes) {
6820
7249
  return Buffer.from(bytes).toString("hex");
6821
7250
  }
6822
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
7251
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
6823
7252
  if (options.enforceViewingKeyRegistration === false) {
6824
7253
  return;
6825
7254
  }
@@ -6833,7 +7262,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6833
7262
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
6834
7263
  );
6835
7264
  }
6836
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
7265
+ const nk = walletNk;
6837
7266
  if (!nk || nk.length !== 32) {
6838
7267
  throw new Error(
6839
7268
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6975,10 +7404,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6975
7404
  result.set(bigintToBytes323(BigInt(publicSignals[0])), offset);
6976
7405
  offset += 32;
6977
7406
  let amount = BigInt(publicSignals[1]);
6978
- const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6979
- const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
7407
+ const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
7408
+ const HALF_FIELD = FIELD_MODULUS3 / BigInt(2);
6980
7409
  if (amount > HALF_FIELD) {
6981
- amount = amount - FIELD_MODULUS2;
7410
+ amount = amount - FIELD_MODULUS3;
6982
7411
  }
6983
7412
  const amountBytes = new Uint8Array(8);
6984
7413
  let amountValue = amount;
@@ -7925,8 +8354,9 @@ function chargeWalletApproval(used, budget, lastError) {
7925
8354
  }
7926
8355
  return used + 1;
7927
8356
  }
7928
- function relayFailureMessage(prefix, responseText) {
7929
- const explanation = explainRelayAuthRejection(responseText);
8357
+ function relayFailureMessage(prefix, responseText, requestBody) {
8358
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
8359
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7930
8360
  return explanation ? `${prefix}: ${responseText}
7931
8361
 
7932
8362
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -8304,6 +8734,7 @@ async function submitTransactToRelay(args) {
8304
8734
  body: requestPayload,
8305
8735
  signal: controller.signal
8306
8736
  });
8737
+ observeRelayClock(response);
8307
8738
  } finally {
8308
8739
  clearTimeout(timeoutId);
8309
8740
  }
@@ -8334,7 +8765,9 @@ async function submitTransactToRelay(args) {
8334
8765
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
8335
8766
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
8336
8767
  }
8337
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
8768
+ return await resolveFailure(
8769
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8770
+ );
8338
8771
  }
8339
8772
  const apiResponse = JSON.parse(responseText);
8340
8773
  if (!apiResponse.success || !apiResponse.data) {
@@ -8351,7 +8784,7 @@ async function submitTransactToRelay(args) {
8351
8784
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
8352
8785
  }
8353
8786
  return await resolveFailure(
8354
- new Error(relayFailureMessage("Relay returned error", errorStr))
8787
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
8355
8788
  );
8356
8789
  }
8357
8790
  const result = apiResponse.data;
@@ -8459,34 +8892,37 @@ async function transact(params, options) {
8459
8892
  );
8460
8893
  }
8461
8894
  onProgress?.("Validating transaction parameters...");
8462
- const firstInputWithAmount = inputUtxos.find((u) => u.amount > BigInt(0));
8463
- const firstOutputWithAmount = outputUtxos.find((u) => u.amount > BigInt(0));
8464
- const fallbackNk = firstOutputWithAmount ? getNkFromUtxoPrivateKey(firstOutputWithAmount.keypair.privateKey) : firstInputWithAmount ? getNkFromUtxoPrivateKey(firstInputWithAmount.keypair.privateKey) : void 0;
8465
- const explicitChainNoteNk = await resolveChainNoteNk(options);
8466
- 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) {
8467
8898
  throw new Error(
8468
- "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."
8469
8900
  );
8470
8901
  }
8471
8902
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
8472
8903
  const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
8473
- if (explicitChainNoteNk && chainNoteWillCarrySalt) {
8474
- 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);
8475
8911
  for (let i = 0; i < outputUtxos.length; i++) {
8476
8912
  const out = outputUtxos[i];
8477
8913
  if (!out || out.amount <= BigInt(0)) continue;
8478
- if (!inputOwners.has(out.keypair.publicKey)) continue;
8479
- 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) {
8480
8916
  throw new Error(
8481
- `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.`
8482
8918
  );
8483
8919
  }
8484
8920
  }
8485
8921
  }
8486
8922
  assertAllowedRpcConnection(connection);
8487
8923
  assertInputMints(inputUtxos, options.expectedMint);
8488
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
8489
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
8924
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
8925
+ const resolvedChainNoteNk = walletNk;
8490
8926
  if (inputUtxos.length > 2) {
8491
8927
  throw new Error("Maximum 2 input UTXOs allowed");
8492
8928
  }
@@ -8860,7 +9296,7 @@ async function transact(params, options) {
8860
9296
  }
8861
9297
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
8862
9298
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
8863
- const chainNoteTimestamp = BigInt(Date.now());
9299
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
8864
9300
  const mintField = pubkeyToFieldElement(mint);
8865
9301
  let signature = "pending-" + Date.now().toString();
8866
9302
  let commitmentIndices = [-1, -1];
@@ -8956,9 +9392,9 @@ async function transact(params, options) {
8956
9392
  ]));
8957
9393
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8958
9394
  const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
8959
- const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8960
- if (chainNoteHash >= FIELD_MODULUS2) {
8961
- 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()}`);
8962
9398
  }
8963
9399
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8964
9400
  const totalInputs = 1 + // root
@@ -9380,7 +9816,8 @@ async function transact(params, options) {
9380
9816
  throw lastError;
9381
9817
  }
9382
9818
  const classified = classifyRelayError(lastError.message);
9383
- 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);
9384
9821
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
9385
9822
  onProgress?.(
9386
9823
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -9529,54 +9966,83 @@ async function transact(params, options) {
9529
9966
  };
9530
9967
  }
9531
9968
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
9969
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
9970
+ const transferNk = await requireWalletNk(options, "transfer");
9532
9971
  const inputSum = sumUtxoAmounts(inputUtxos);
9533
9972
  if (inputSum < amount) {
9534
9973
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
9535
9974
  }
9536
9975
  const change = inputSum - amount;
9537
- const myKeypair = inputUtxos[0].keypair;
9538
9976
  const mint = inputUtxos[0].mintAddress;
9539
- const transferNk = await resolveChainNoteNk(options);
9540
- const changeNoteSalt = transferNk ? randomChangeNoteSalt() : void 0;
9541
- 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);
9542
10011
  const recipientKeypair = {
9543
10012
  privateKey: BigInt(0),
9544
10013
  // Recipient's private key unknown
9545
10014
  publicKey: recipientPubkey
9546
10015
  };
9547
- 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);
9548
10017
  const outputUtxos = [recipientUtxo];
9549
10018
  if (change > BigInt(0)) {
9550
- if (transferNk) {
9551
- const { utxo } = await createRecoverableChangeUtxo(
9552
- change,
9553
- myKeypair,
9554
- transferNk,
9555
- mint,
9556
- changeNoteSalt,
9557
- 1
9558
- );
9559
- outputUtxos.push(utxo);
9560
- } else {
9561
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
9562
- }
10019
+ const { utxo } = await createRecoverableChangeUtxo(
10020
+ change,
10021
+ owner,
10022
+ transferNk,
10023
+ mint,
10024
+ changeNoteSalt,
10025
+ 1
10026
+ );
10027
+ outputUtxos.push(utxo);
9563
10028
  }
9564
10029
  return transact(
9565
10030
  {
9566
- inputUtxos,
10031
+ inputUtxos: spendInputs,
9567
10032
  outputUtxos,
9568
10033
  externalAmount: BigInt(0)
9569
10034
  // Pure shield-to-shield
9570
10035
  },
9571
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
10036
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
9572
10037
  );
9573
10038
  }
9574
10039
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
10040
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
10041
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
9575
10042
  const inputSum = sumUtxoAmounts(inputUtxos);
9576
10043
  if (inputSum < withdrawAmount) {
9577
10044
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
9578
10045
  }
9579
- const myKeypair = inputUtxos[0].keypair;
9580
10046
  const mint = inputUtxos[0].mintAddress;
9581
10047
  let utxos = [...inputUtxos];
9582
10048
  let cachedTree = options.cachedMerkleTree;
@@ -9585,9 +10051,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9585
10051
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
9586
10052
  const [small1, small2, ...rest] = utxos;
9587
10053
  const mergedAmount = small1.amount + small2.amount;
9588
- const mergeNk = await resolveChainNoteNk(options);
9589
- const mergeSalt = mergeNk ? randomChangeNoteSalt() : void 0;
9590
- 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;
9591
10056
  const mergeResult = await transact(
9592
10057
  {
9593
10058
  inputUtxos: [small1, small2],
@@ -9598,7 +10063,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9598
10063
  {
9599
10064
  ...options,
9600
10065
  cachedMerkleTree: cachedTree,
9601
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
10066
+ chainNoteSalt: mergeSalt
9602
10067
  }
9603
10068
  );
9604
10069
  cachedTree = mergeResult.merkleTree;
@@ -9613,23 +10078,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9613
10078
  const outputUtxos = [];
9614
10079
  let changeNoteSalt;
9615
10080
  if (change > BigInt(0)) {
9616
- const changeNk = await resolveChainNoteNk(options);
9617
- if (changeNk) {
9618
- const salt = randomChangeNoteSalt();
9619
- const { utxo } = await createRecoverableChangeUtxo(
9620
- change,
9621
- myKeypair,
9622
- changeNk,
9623
- mint,
9624
- salt,
9625
- 0
9626
- // partialWithdraw puts change at output 0
9627
- );
9628
- outputUtxos.push(utxo);
9629
- changeNoteSalt = salt;
9630
- } else {
9631
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
9632
- }
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;
9633
10093
  }
9634
10094
  return transact(
9635
10095
  {
@@ -9752,6 +10212,8 @@ async function swapUtxo(params, options) {
9752
10212
  if (relayUrl) {
9753
10213
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
9754
10214
  }
10215
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
10216
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
9755
10217
  if (inputUtxos.length === 0) {
9756
10218
  throw new Error("At least one input UTXO required");
9757
10219
  }
@@ -9777,15 +10239,12 @@ async function swapUtxo(params, options) {
9777
10239
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
9778
10240
  }
9779
10241
  onProgress?.("Validating transaction parameters...");
9780
- const swapFallbackNk = getNkFromUtxoPrivateKey(inputUtxos[0].keypair.privateKey);
9781
- await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
9782
- const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
9783
- const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
10242
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
9784
10243
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
9785
- if (explicitSwapChainNoteNk && changeUtxo && changeUtxo.amount > BigInt(0) && inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey)) {
9786
- 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)) {
9787
10246
  throw new Error(
9788
- `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.`
9789
10248
  );
9790
10249
  }
9791
10250
  }
@@ -9809,24 +10268,18 @@ async function swapUtxo(params, options) {
9809
10268
  );
9810
10269
  }
9811
10270
  const externalAmount = -swapAmount;
9812
- let refundKeypair;
9813
- let refundBlinding;
9814
- let refundDerivedFromNk = false;
9815
- if (resolvedSwapChainNoteNk) {
9816
- try {
9817
- const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
9818
- const derived = await deriveSwapRefundAuthorization(resolvedSwapChainNoteNk, refundNullifier);
9819
- refundKeypair = { privateKey: derived.privateKey, publicKey: derived.publicKey };
9820
- refundBlinding = derived.blinding;
9821
- refundDerivedFromNk = true;
9822
- } catch {
9823
- refundKeypair = await generateUtxoKeypair();
9824
- refundBlinding = randomFieldElement();
9825
- }
9826
- } else {
9827
- refundKeypair = await generateUtxoKeypair();
9828
- refundBlinding = randomFieldElement();
9829
- }
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;
9830
10283
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
9831
10284
  throw new Error(
9832
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."
@@ -10152,7 +10605,7 @@ async function swapUtxo(params, options) {
10152
10605
  for (const utxo of paddedOutputs) {
10153
10606
  outputCommitments.push(await computeCommitment2(utxo));
10154
10607
  }
10155
- const chainNoteTimestamp = BigInt(Date.now());
10608
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
10156
10609
  onProgress?.("Computing external data hash...");
10157
10610
  const mint = swapPoolMint;
10158
10611
  const mintField = pubkeyToFieldElement(mint);
@@ -10466,7 +10919,7 @@ async function swapUtxo(params, options) {
10466
10919
  forceChainIndexing = !relayUrl;
10467
10920
  continue;
10468
10921
  }
10469
- throw new Error(relayFailureMessage("Relay error", responseText));
10922
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
10470
10923
  }
10471
10924
  const apiResponse = JSON.parse(responseText);
10472
10925
  if (!apiResponse.success || !apiResponse.data) {
@@ -10602,7 +11055,6 @@ async function swapUtxo(params, options) {
10602
11055
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
10603
11056
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
10604
11057
  refund: {
10605
- privateKey: Buffer.from(bigintToBytes323(refundKeypair.privateKey)).toString("hex"),
10606
11058
  publicKey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("hex"),
10607
11059
  blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("hex"),
10608
11060
  derivedFromNk: refundDerivedFromNk
@@ -10610,6 +11062,7 @@ async function swapUtxo(params, options) {
10610
11062
  };
10611
11063
  }
10612
11064
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
11065
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
10613
11066
  const totalInput = sumUtxoAmounts(inputUtxos);
10614
11067
  const change = totalInput - swapAmount;
10615
11068
  if (change < BigInt(0)) {
@@ -10618,16 +11071,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
10618
11071
  let changeUtxo;
10619
11072
  let changeNoteSalt;
10620
11073
  if (change > BigInt(0)) {
10621
- const myKeypair = inputUtxos[0].keypair;
10622
11074
  const mint = inputUtxos[0].mintAddress;
10623
- const changeNk = await resolveChainNoteNk(options);
10624
- if (changeNk) {
10625
- const salt = randomChangeNoteSalt();
10626
- changeUtxo = (await createRecoverableChangeUtxo(change, myKeypair, changeNk, mint, salt, 0)).utxo;
10627
- changeNoteSalt = salt;
10628
- } else {
10629
- changeUtxo = await createUtxo(change, myKeypair, mint);
10630
- }
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;
10631
11079
  }
10632
11080
  return swapUtxo(
10633
11081
  {
@@ -10953,7 +11401,7 @@ var RelayBatchAuthCoordinator = class {
10953
11401
  throw new Error("Every item of a batch must target the same program id.");
10954
11402
  }
10955
11403
  }
10956
- const nowSeconds = Math.floor(Date.now() / 1e3);
11404
+ const nowSeconds = relayNowSeconds();
10957
11405
  const preimages = waiting.map(
10958
11406
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10959
11407
  );
@@ -11394,7 +11842,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
11394
11842
  const cached = depositSecretsCache.get(key);
11395
11843
  if (cached) return cached;
11396
11844
  try {
11397
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
11845
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
11398
11846
  if (depositSecretsCache.size >= 4096) {
11399
11847
  const oldest = depositSecretsCache.keys().next();
11400
11848
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11977,6 +12425,7 @@ async function scanTransactions(opts) {
11977
12425
  } else {
11978
12426
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11979
12427
  const candidateKeys = [
12428
+ opts.ownerUtxoPublicKey,
11980
12429
  derived?.keypair.publicKey,
11981
12430
  opts.ownUtxoPublicKey,
11982
12431
  BigInt(0)
@@ -12030,6 +12479,7 @@ async function scanTransactions(opts) {
12030
12479
  try {
12031
12480
  const recoveredDeposit = await matchDepositNote({
12032
12481
  viewingKeyNk,
12482
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
12033
12483
  noteSalt: compactNote.noteSalt,
12034
12484
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
12035
12485
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -12064,7 +12514,8 @@ async function scanTransactions(opts) {
12064
12514
  mintAddress: (0, import_kit.address)(asset.mint),
12065
12515
  outputIndex: 0,
12066
12516
  // v4 describes output 0, which is where change lands
12067
- outputCommitments: ixCtx.outputCommitments ?? []
12517
+ outputCommitments: ixCtx.outputCommitments ?? [],
12518
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
12068
12519
  });
12069
12520
  if (recoveredChange) {
12070
12521
  recoveredChangeNotes.push({
@@ -12174,6 +12625,17 @@ async function scanTransactions(opts) {
12174
12625
  runningByAsset.set(key, running);
12175
12626
  tx.runningBalance = running;
12176
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
+ }
12177
12639
  return {
12178
12640
  transactions: txs,
12179
12641
  summary: {
@@ -12253,6 +12715,1567 @@ function formatComplianceCsv(report) {
12253
12715
  return header + rows;
12254
12716
  }
12255
12717
 
12718
+ // src/relay/note-index-format.ts
12719
+ var import_sha25 = require("@noble/hashes/sha2");
12720
+ init_address();
12721
+ init_utxo();
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";
12754
+ }
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_CURSOR_KEYS = 131072;
13280
+ var MAX_CURSOR_POOLS = 256;
13281
+ var MAX_CURSOR_PAGE = 2 ** 32;
13282
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
13283
+ var ZERO_CHAIN = "00".repeat(32);
13284
+ var U64_MAX4 = (1n << 64n) - 1n;
13285
+ var NoteIndexHeadBehindError = class extends Error {
13286
+ constructor(cursorWatermark, headWatermark) {
13287
+ super(
13288
+ `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`
13289
+ );
13290
+ this.cursorWatermark = cursorWatermark;
13291
+ this.headWatermark = headWatermark;
13292
+ this.retryable = true;
13293
+ this.name = "NoteIndexHeadBehindError";
13294
+ }
13295
+ };
13296
+ var FullPassSignal = class {
13297
+ constructor(reason) {
13298
+ this.reason = reason;
13299
+ }
13300
+ };
13301
+ function abortError2() {
13302
+ const error = new Error("recoverNotesFromIndex aborted");
13303
+ error.name = "AbortError";
13304
+ return error;
13305
+ }
13306
+ function bytesToBigint3(bytes) {
13307
+ let v = 0n;
13308
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
13309
+ return v;
13310
+ }
13311
+ function toHex2(bytes) {
13312
+ let s = "";
13313
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
13314
+ return s;
13315
+ }
13316
+ function fromHex(hex) {
13317
+ return Uint8Array.from(Buffer.from(hex, "hex"));
13318
+ }
13319
+ function hex32(v) {
13320
+ return v.toString(16).padStart(64, "0");
13321
+ }
13322
+ function isAllZero3(bytes) {
13323
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
13324
+ return true;
13325
+ }
13326
+ function floorAlign(page) {
13327
+ return page - page % CURSOR_PAGE_ALIGN;
13328
+ }
13329
+ function verifiedKey(mint, leaf, commitment) {
13330
+ return `${mint}:${leaf}:${hex32(commitment)}`;
13331
+ }
13332
+ function itemIdentity(raw) {
13333
+ return toHex2((0, import_sha26.sha256)(raw).subarray(0, 16));
13334
+ }
13335
+ var LeafBuffer = class {
13336
+ constructor() {
13337
+ this.bytes = new Uint8Array(32 * 1024);
13338
+ this.view = new DataView(this.bytes.buffer);
13339
+ this.count = 0;
13340
+ }
13341
+ get length() {
13342
+ return this.count;
13343
+ }
13344
+ push(values) {
13345
+ const need = (this.count + values.length) * 32;
13346
+ if (need > this.bytes.length) {
13347
+ let size = this.bytes.length;
13348
+ while (size < need) size *= 2;
13349
+ const next = new Uint8Array(size);
13350
+ next.set(this.bytes.subarray(0, this.count * 32));
13351
+ this.bytes = next;
13352
+ this.view = new DataView(next.buffer);
13353
+ }
13354
+ for (const v of values) {
13355
+ const o = this.count * 32;
13356
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
13357
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
13358
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
13359
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
13360
+ this.count++;
13361
+ }
13362
+ }
13363
+ get(i) {
13364
+ if (i < 0 || i >= this.count) return void 0;
13365
+ const o = i * 32;
13366
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
13367
+ }
13368
+ };
13369
+ async function trialItem(item, trial) {
13370
+ if (item.kind === 1) {
13371
+ if (item.note.length === 0) return null;
13372
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
13373
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
13374
+ return note ? { note } : null;
13375
+ }
13376
+ if (item.kind === 2) {
13377
+ const delivery = await trial.open(item.envelope);
13378
+ return delivery ? { delivery } : null;
13379
+ }
13380
+ if (item.amountAfterFee === 0n) return null;
13381
+ const refund = await matchSwapRefundLeaf({
13382
+ viewingKeyNk: trial.nk,
13383
+ inputNullifier: item.nullifier0,
13384
+ amountAfterFee: item.amountAfterFee,
13385
+ commitment: item.commitment,
13386
+ ownerUtxoKeypair: trial.owner
13387
+ });
13388
+ return refund ? { refund } : null;
13389
+ }
13390
+ function txOutputs(item) {
13391
+ const out = [toHex2(item.comm0)];
13392
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
13393
+ return out;
13394
+ }
13395
+ function leafOfTxOutput(item, commitment) {
13396
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint3(item.comm0)) return Number(item.leaf0);
13397
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
13398
+ return null;
13399
+ }
13400
+ async function matchOwnItems(own, trial, onReject) {
13401
+ const { nk, owner } = trial;
13402
+ const candidates = [];
13403
+ const claimed = /* @__PURE__ */ new Set();
13404
+ const byNullifier = /* @__PURE__ */ new Map();
13405
+ const legacyKeys = /* @__PURE__ */ new Map();
13406
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
13407
+ const spendsOf = /* @__PURE__ */ new Map();
13408
+ const byOutKey = /* @__PURE__ */ new Map();
13409
+ const index = (map, key, o) => {
13410
+ const list = map.get(key);
13411
+ if (list) list.push(o);
13412
+ else map.set(key, [o]);
13413
+ };
13414
+ for (const o of ownTxs) {
13415
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
13416
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
13417
+ }
13418
+ const queue = [];
13419
+ const queued = /* @__PURE__ */ new Set();
13420
+ const enqueue = (o) => {
13421
+ if (queued.has(o)) return;
13422
+ queued.add(o);
13423
+ queue.push(o);
13424
+ };
13425
+ const add = async (c) => {
13426
+ const nullifier = hex32(
13427
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
13428
+ );
13429
+ const full = { ...c, nullifier };
13430
+ candidates.push(full);
13431
+ if (!byNullifier.has(nullifier)) {
13432
+ byNullifier.set(nullifier, full);
13433
+ for (const o of spendsOf.get(nullifier) ?? []) enqueue(o);
13434
+ }
13435
+ if (full.atRisk && !legacyKeys.has(full.keypair.publicKey)) {
13436
+ legacyKeys.set(full.keypair.publicKey, full.keypair);
13437
+ for (const o of byOutKey.get(full.keypair.publicKey) ?? []) enqueue(o);
13438
+ }
13439
+ };
13440
+ const base = (o) => ({ signature: o.item.signature, page: o.page, seq: o.seq });
13441
+ const tryDeposit = async (o, item, amount) => {
13442
+ const note = o.note;
13443
+ const mint = addressFromBytes(item.mint);
13444
+ const deposit = await matchDepositNote({
13445
+ viewingKeyNk: nk,
13446
+ noteSalt: note.noteSalt,
13447
+ amount,
13448
+ mintAddress: mint,
13449
+ outputCommitments: txOutputs(item),
13450
+ ownerUtxoKeypair: owner
13451
+ });
13452
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
13453
+ if (!deposit || leaf === null) return false;
13454
+ await add({
13455
+ kind: "deposit",
13456
+ atRisk: deposit.legacyExposed,
13457
+ amount: deposit.amount,
13458
+ blinding: deposit.blinding,
13459
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
13460
+ mint,
13461
+ commitment: deposit.commitment,
13462
+ leaf,
13463
+ ...base(o)
13464
+ });
13465
+ return true;
13466
+ };
13467
+ const tryChange0 = async (o, item, keypair, atRisk) => {
13468
+ const note = o.note;
13469
+ const mint = addressFromBytes(item.mint);
13470
+ const change = await matchChangeNote({
13471
+ viewingKeyNk: nk,
13472
+ noteSalt: note.noteSalt,
13473
+ amount: note.outAmount0,
13474
+ keypair,
13475
+ mintAddress: mint,
13476
+ outputIndex: 0,
13477
+ outputCommitments: [toHex2(item.comm0)],
13478
+ ownerUtxoPublicKey: owner.publicKey
13479
+ });
13480
+ if (!change) return false;
13481
+ await add({
13482
+ kind: "change",
13483
+ atRisk,
13484
+ amount: change.amount,
13485
+ blinding: change.blinding,
13486
+ keypair,
13487
+ mint,
13488
+ commitment: change.commitment,
13489
+ leaf: Number(item.leaf0),
13490
+ ...base(o)
13491
+ });
13492
+ return true;
13493
+ };
13494
+ for (const o of own) {
13495
+ const item = o.item;
13496
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
13497
+ const note = o.note;
13498
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13499
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
13500
+ }
13501
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
13502
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
13503
+ }
13504
+ } else if (item.kind === 2 && o.delivery) {
13505
+ const mint = addressFromBytes(item.mint);
13506
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
13507
+ onReject(o);
13508
+ continue;
13509
+ }
13510
+ const commitment = await computeCommitment2({
13511
+ amount: o.delivery.amount,
13512
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
13513
+ blinding: o.delivery.blinding,
13514
+ mintAddress: mint
13515
+ });
13516
+ if (commitment !== bytesToBigint3(item.commitment)) {
13517
+ onReject(o);
13518
+ continue;
13519
+ }
13520
+ await add({
13521
+ kind: "received",
13522
+ atRisk: false,
13523
+ amount: o.delivery.amount,
13524
+ blinding: o.delivery.blinding,
13525
+ keypair: owner,
13526
+ mint,
13527
+ commitment,
13528
+ leaf: Number(item.leaf),
13529
+ ...base(o)
13530
+ });
13531
+ } else if (item.kind === 3 && o.refund) {
13532
+ await add({
13533
+ kind: "swap_refund",
13534
+ atRisk: o.refund.legacyExposed,
13535
+ amount: o.refund.amount,
13536
+ blinding: o.refund.blinding,
13537
+ keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
13538
+ mint: NATIVE_SOL_MINT,
13539
+ commitment: o.refund.commitment,
13540
+ leaf: Number(item.leaf),
13541
+ ...base(o)
13542
+ });
13543
+ }
13544
+ }
13545
+ const processTx = async (o) => {
13546
+ const item = o.item;
13547
+ const note = o.note;
13548
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
13549
+ const legacy = legacyKeys.get(note.outPubkey0);
13550
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
13551
+ }
13552
+ const mint = addressFromBytes(item.mint);
13553
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
13554
+ if (inputs.length === 0) return;
13555
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
13556
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
13557
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
13558
+ if (out1 > 0n) {
13559
+ const blinding = deriveChangeNoteBlinding(nk, note.noteSalt, 1);
13560
+ const owners = [{ keypair: owner, atRisk: false }];
13561
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
13562
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
13563
+ for (const { keypair, atRisk } of owners) {
13564
+ const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
13565
+ if (commitment !== bytesToBigint3(item.comm1)) continue;
13566
+ claimed.add(`${o.seq}:1`);
13567
+ await add({ kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1), ...base(o) });
13568
+ break;
13569
+ }
13570
+ }
13571
+ }
13572
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13573
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
13574
+ }
13575
+ };
13576
+ for (const o of ownTxs) enqueue(o);
13577
+ for (let i = 0; i < queue.length; i++) {
13578
+ const o = queue[i];
13579
+ queued.delete(o);
13580
+ await processTx(o);
13581
+ }
13582
+ return candidates;
13583
+ }
13584
+ async function replayStream(start, pages, overrides, chain, targetPage) {
13585
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
13586
+ const startN = frontier.nextIndex;
13587
+ const pending = new Map(start.pending);
13588
+ const flushed = new LeafBuffer();
13589
+ const corrections = /* @__PURE__ */ new Map();
13590
+ let conflicts = 0;
13591
+ let verifiedPrefix = 0;
13592
+ let mismatch = false;
13593
+ const checks = [];
13594
+ const setBits = [];
13595
+ if (chain && chain.nextIndex > 0) {
13596
+ const last = chain.nextIndex - 1;
13597
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
13598
+ for (const l of setBits) {
13599
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
13600
+ if (at >= startN) checks.push({ at, level: l });
13601
+ }
13602
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
13603
+ checks.sort((a, b) => a.at - b.at);
13604
+ }
13605
+ let nextCheck = 0;
13606
+ const runChecks = () => {
13607
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
13608
+ const { at, level } = checks[nextCheck++];
13609
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
13610
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
13611
+ else mismatch = true;
13612
+ }
13613
+ };
13614
+ const append = (values) => {
13615
+ let i = 0;
13616
+ while (i < values.length) {
13617
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
13618
+ const take = Math.min(values.length - i, room);
13619
+ if (take > 0) {
13620
+ const part = values.slice(i, i + take);
13621
+ frontier.append(part);
13622
+ flushed.push(part);
13623
+ i += take;
13624
+ }
13625
+ runChecks();
13626
+ }
13627
+ };
13628
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
13629
+ const flush = () => {
13630
+ const batch = [];
13631
+ let next = frontier.nextIndex;
13632
+ while (pending.has(next)) {
13633
+ batch.push(pending.get(next));
13634
+ pending.delete(next);
13635
+ next++;
13636
+ }
13637
+ if (batch.length > 0) append(batch);
13638
+ };
13639
+ let snapshot = null;
13640
+ let taken = false;
13641
+ const takeSnapshot = () => {
13642
+ taken = true;
13643
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
13644
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
13645
+ };
13646
+ runChecks();
13647
+ flush();
13648
+ for (const { page, entries } of pages) {
13649
+ if (!taken && page >= targetPage) takeSnapshot();
13650
+ for (const e of entries) {
13651
+ if (e.leaf < startN) continue;
13652
+ const prior = valueAt(e.leaf);
13653
+ if (prior !== void 0) {
13654
+ if (prior !== e.commitment) {
13655
+ conflicts++;
13656
+ corrections.set(e.leaf, e.commitment);
13657
+ }
13658
+ continue;
13659
+ }
13660
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
13661
+ }
13662
+ flush();
13663
+ }
13664
+ if (!taken) takeSnapshot();
13665
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
13666
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
13667
+ }
13668
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
13669
+ }
13670
+ var HEX64 = /^[0-9a-f]{64}$/;
13671
+ var HEX32 = /^[0-9a-f]{32}$/;
13672
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
13673
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
13674
+ function isRecord(v) {
13675
+ return typeof v === "object" && v !== null && !Array.isArray(v);
13676
+ }
13677
+ function isIntIn(v, min, max) {
13678
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
13679
+ }
13680
+ function isBoundedArray(v, max) {
13681
+ return Array.isArray(v) && v.length <= max;
13682
+ }
13683
+ function emptyStartTree() {
13684
+ return {
13685
+ frontier: null,
13686
+ nextIndex: 0,
13687
+ pending: /* @__PURE__ */ new Map(),
13688
+ window: [],
13689
+ windowStart: 0,
13690
+ verified: 0,
13691
+ overrides: /* @__PURE__ */ new Map(),
13692
+ mismatch: false,
13693
+ hiBefore: -1
13694
+ };
13695
+ }
13696
+ async function parseCursor(cursor, poolMints) {
13697
+ try {
13698
+ if (!isRecord(cursor)) return "not an object";
13699
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
13700
+ const c = cursor;
13701
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
13702
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
13703
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
13704
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
13705
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
13706
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
13707
+ const trees = /* @__PURE__ */ new Map();
13708
+ for (const mint of poolMints) {
13709
+ const t = c.trees[mint];
13710
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
13711
+ const tree = t;
13712
+ if (!isRecord(tree.frontier)) return "bad frontier";
13713
+ let frontier;
13714
+ try {
13715
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
13716
+ } catch {
13717
+ return "bad frontier";
13718
+ }
13719
+ const nextIndex = frontier.nextIndex;
13720
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
13721
+ const pending = /* @__PURE__ */ new Map();
13722
+ let hiBefore = nextIndex - 1;
13723
+ for (const entry of tree.pending) {
13724
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
13725
+ const [leaf, value] = entry;
13726
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
13727
+ return "bad pending leaves";
13728
+ }
13729
+ pending.set(leaf, BigInt("0x" + value));
13730
+ hiBefore = Math.max(hiBefore, leaf);
13731
+ }
13732
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
13733
+ const windowLen = tree.window.length / 64;
13734
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
13735
+ const window2 = [];
13736
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
13737
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
13738
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
13739
+ const overrides = /* @__PURE__ */ new Map();
13740
+ for (const entry of tree.overrides) {
13741
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
13742
+ const [leaf, value] = entry;
13743
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
13744
+ overrides.set(leaf, BigInt("0x" + value));
13745
+ }
13746
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
13747
+ trees.set(mint, {
13748
+ frontier: frontier.toState(),
13749
+ nextIndex,
13750
+ pending,
13751
+ window: window2,
13752
+ windowStart: nextIndex - windowLen,
13753
+ verified: tree.verified,
13754
+ overrides,
13755
+ mismatch: tree.mismatch,
13756
+ hiBefore
13757
+ });
13758
+ }
13759
+ const own = c.own;
13760
+ if (!isRecord(own)) return "bad own state";
13761
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
13762
+ const items = [];
13763
+ const seqs = /* @__PURE__ */ new Set();
13764
+ for (const entry of own.items) {
13765
+ if (!isRecord(entry)) return "bad own items";
13766
+ const { seq, item } = entry;
13767
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
13768
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
13769
+ seqs.add(seq);
13770
+ const raw = fromHex(item);
13771
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
13772
+ }
13773
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
13774
+ return "bad verified notes";
13775
+ }
13776
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
13777
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
13778
+ const pendingLeaves = /* @__PURE__ */ new Map();
13779
+ for (const entry of own.pendingLeaves) {
13780
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
13781
+ const [mint, leaf, value] = entry;
13782
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
13783
+ return "bad pending notes";
13784
+ }
13785
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
13786
+ }
13787
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
13788
+ return "bad rejected set";
13789
+ }
13790
+ return {
13791
+ raw: c,
13792
+ trees,
13793
+ items,
13794
+ verified: new Set(own.verified),
13795
+ spent: new Set(own.spent),
13796
+ pendingLeaves,
13797
+ rejected: own.rejected
13798
+ };
13799
+ } catch {
13800
+ return "unreadable state";
13801
+ }
13802
+ }
13803
+ async function recoverNotesFromIndex(params) {
13804
+ const startedAt = Date.now();
13805
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
13806
+ assertAllowedRelayOrigin(relayUrl);
13807
+ assertAllowedRpcConnection(connection);
13808
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
13809
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
13810
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
13811
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
13812
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
13813
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
13814
+ }
13815
+ if (params.signal?.aborted) throw abortError2();
13816
+ const stats = {
13817
+ pages: 0,
13818
+ items: 0,
13819
+ bytes: 0,
13820
+ rpcCalls: 0,
13821
+ ms: 0,
13822
+ dropped: 0,
13823
+ decrypted: 0,
13824
+ candidates: 0,
13825
+ spent: 0,
13826
+ conflicts: 0,
13827
+ pendingDropped: 0
13828
+ };
13829
+ const rpc = new Proxy(connection, {
13830
+ get(target, prop, receiver) {
13831
+ const value = Reflect.get(target, prop, receiver);
13832
+ if (typeof value !== "function") return value;
13833
+ return (...args) => {
13834
+ const pending = value.apply(target, args);
13835
+ if (pending && typeof pending.send === "function") {
13836
+ const send = pending.send.bind(pending);
13837
+ return {
13838
+ ...pending,
13839
+ send: (...sendArgs) => {
13840
+ stats.rpcCalls++;
13841
+ return send(...sendArgs);
13842
+ }
13843
+ };
13844
+ }
13845
+ return pending;
13846
+ };
13847
+ }
13848
+ });
13849
+ const trial = {
13850
+ nk: viewingKeyNk,
13851
+ owner,
13852
+ decrypt: await createCompactChainNoteDecryptor(viewingKeyNk),
13853
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(viewingKeyNk).privateKey)
13854
+ };
13855
+ const poolMints = Array.from(new Set(params.poolMints));
13856
+ const warnings = [];
13857
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
13858
+ let cursor;
13859
+ if (params.cursor !== void 0) {
13860
+ const checked = await parseCursor(params.cursor, poolMints);
13861
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
13862
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
13863
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
13864
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
13865
+ } else cursor = checked;
13866
+ }
13867
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
13868
+ let treeRead;
13869
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
13870
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
13871
+ return poolMints.map((_, i) => {
13872
+ const account = accounts[i];
13873
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
13874
+ return account && parsed ? { ...parsed, data: account.data } : null;
13875
+ });
13876
+ })());
13877
+ const ctx = { params, head, trial, stats, poolMints, warnings, readTrees };
13878
+ let outcome = await runOnce(ctx, cursor);
13879
+ if (outcome instanceof FullPassSignal) {
13880
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
13881
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
13882
+ outcome = await runOnce(ctx, void 0);
13883
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13884
+ }
13885
+ stats.ms = Date.now() - startedAt;
13886
+ return { ...outcome, stats, warnings };
13887
+ }
13888
+ async function runOnce(ctx, cursor) {
13889
+ const { params, head, trial, stats, poolMints } = ctx;
13890
+ const { relayUrl, onProgress } = params;
13891
+ const owner = trial.owner;
13892
+ const poolSet = new Set(poolMints);
13893
+ const startPage = cursor?.raw.page ?? 0;
13894
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
13895
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
13896
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
13897
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
13898
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
13899
+ const rejectedIds = new Set(cursor?.rejected ?? []);
13900
+ const controller = new AbortController();
13901
+ const onCallerAbort = () => controller.abort();
13902
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
13903
+ const signal = controller.signal;
13904
+ try {
13905
+ const pageData = /* @__PURE__ */ new Map();
13906
+ const ownItems = [];
13907
+ const nullifiers = /* @__PURE__ */ new Set();
13908
+ let fullPassReason = null;
13909
+ const lateReference = (mint, leaf, value, seq) => {
13910
+ if (!cursor || seq < fullPassSeq) return null;
13911
+ const t = startTrees.get(mint);
13912
+ if (leaf < t.nextIndex) {
13913
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
13914
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
13915
+ return null;
13916
+ }
13917
+ const held = t.pending.get(leaf);
13918
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
13919
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
13920
+ return null;
13921
+ };
13922
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
13923
+ const waiting = /* @__PURE__ */ new Map();
13924
+ let chainNext = startPage;
13925
+ let chainError = null;
13926
+ let wakers = [];
13927
+ const wakeAll = () => {
13928
+ const w = wakers;
13929
+ wakers = [];
13930
+ for (const f of w) f();
13931
+ };
13932
+ signal.addEventListener("abort", wakeAll);
13933
+ const advanceChain = () => {
13934
+ while (!chainError && waiting.has(chainNext)) {
13935
+ const w = waiting.get(chainNext);
13936
+ waiting.delete(chainNext);
13937
+ const expected = chainAt.get(chainNext);
13938
+ if (w.prevChain !== expected) {
13939
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
13940
+ controller.abort();
13941
+ return;
13942
+ }
13943
+ if (!w.complete) break;
13944
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
13945
+ chainNext++;
13946
+ }
13947
+ wakeAll();
13948
+ };
13949
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
13950
+ const lookahead = 2 * workerCount + 2;
13951
+ let nextToFetch = startPage;
13952
+ let pagesDone = 0;
13953
+ const worker = async () => {
13954
+ for (; ; ) {
13955
+ if (signal.aborted) throw abortError2();
13956
+ const pageNo = nextToFetch++;
13957
+ if (pageNo >= pagesTotal) return;
13958
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
13959
+ if (signal.aborted) throw abortError2();
13960
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13961
+ stats.bytes += bytes.length;
13962
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
13963
+ if (pageNo < head.completePages && !page2.complete) {
13964
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13965
+ }
13966
+ stats.pages++;
13967
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13968
+ advanceChain();
13969
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
13970
+ const late = (reason) => {
13971
+ if (reason && !fullPassReason) {
13972
+ fullPassReason = reason;
13973
+ controller.abort();
13974
+ }
13975
+ };
13976
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
13977
+ if (isAllZero3(commitment)) return;
13978
+ const mint = addressFromBytes(mintBytes);
13979
+ if (!poolSet.has(mint)) return;
13980
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint3(commitment) };
13981
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
13982
+ const list = data.leaves.get(mint);
13983
+ if (list) list.push(entry);
13984
+ else data.leaves.set(mint, [entry]);
13985
+ };
13986
+ page2.items.forEach((item, i) => {
13987
+ const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
13988
+ if (item.kind === 1) {
13989
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
13990
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
13991
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
13992
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
13993
+ } else if (item.kind === 3) {
13994
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
13995
+ } else {
13996
+ const mint = addressFromBytes(item.mint);
13997
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
13998
+ }
13999
+ });
14000
+ if (signal.aborted) throw abortError2();
14001
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
14002
+ if (signal.aborted) throw abortError2();
14003
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
14004
+ const opened = await Promise.all(batch.map((item) => trialItem(item, trial)));
14005
+ opened.forEach((o, k) => {
14006
+ if (!o) return;
14007
+ stats.decrypted++;
14008
+ const raw = page2.rawItems[i + k];
14009
+ const id = itemIdentity(raw);
14010
+ if (rejectedIds.has(id)) {
14011
+ stats.dropped++;
14012
+ return;
14013
+ }
14014
+ ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o });
14015
+ });
14016
+ stats.items += batch.length;
14017
+ }
14018
+ pageData.set(pageNo, data);
14019
+ pagesDone++;
14020
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
14021
+ }
14022
+ };
14023
+ const workers = Array.from(
14024
+ { length: workerCount },
14025
+ () => worker().catch((error) => {
14026
+ controller.abort();
14027
+ throw error;
14028
+ })
14029
+ );
14030
+ const settled = await Promise.allSettled(workers);
14031
+ signal.removeEventListener("abort", wakeAll);
14032
+ if (params.signal?.aborted) throw abortError2();
14033
+ const lateReason = fullPassReason;
14034
+ if (lateReason) return new FullPassSignal(lateReason);
14035
+ const chainFailure = chainError;
14036
+ if (chainFailure) {
14037
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
14038
+ throw chainFailure;
14039
+ }
14040
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
14041
+ if (failure) throw failure.reason;
14042
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
14043
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
14044
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
14045
+ }
14046
+ for (const entry of cursor?.items ?? []) {
14047
+ const o = await trialItem(entry.item, trial);
14048
+ if (!o) continue;
14049
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
14050
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o });
14051
+ if (entry.item.kind === 1) {
14052
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
14053
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
14054
+ }
14055
+ }
14056
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
14057
+ ownItems.sort((a, b) => a.seq - b.seq);
14058
+ const rejectedNow = /* @__PURE__ */ new Set();
14059
+ const allCandidates = await matchOwnItems(ownItems, trial, (o) => {
14060
+ stats.dropped++;
14061
+ rejectedNow.add(o.id);
14062
+ });
14063
+ stats.candidates = allCandidates.length;
14064
+ const cutoff = params.legacyCutoffLeaf ?? {};
14065
+ const candidates = allCandidates.filter((c) => {
14066
+ const limit = cutoff[c.mint];
14067
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
14068
+ stats.dropped++;
14069
+ return false;
14070
+ }
14071
+ return true;
14072
+ });
14073
+ const chainTrees = await ctx.readTrees();
14074
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
14075
+ const replays = /* @__PURE__ */ new Map();
14076
+ for (let i = 0; i < poolMints.length; i++) {
14077
+ const mint = poolMints[i];
14078
+ const start = startTrees.get(mint);
14079
+ const chainTree = chainTrees[i] ?? null;
14080
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
14081
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
14082
+ let overrides = start.overrides;
14083
+ stats.conflicts += r.conflicts;
14084
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
14085
+ const merged = new Map([...start.overrides, ...r.corrections]);
14086
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
14087
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
14088
+ r = alternative;
14089
+ overrides = merged;
14090
+ }
14091
+ }
14092
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
14093
+ replays.set(mint, { r, overrides });
14094
+ }
14095
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
14096
+ const streamValue = (mint, leaf) => {
14097
+ const v = replays.get(mint)?.r.valueAt(leaf);
14098
+ if (v !== void 0) return v;
14099
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
14100
+ if (carried !== void 0) return carried;
14101
+ const t = startTrees.get(mint);
14102
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
14103
+ return void 0;
14104
+ };
14105
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
14106
+ const verified = [];
14107
+ const pendingByKey = /* @__PURE__ */ new Map();
14108
+ const rejectedCandidates = /* @__PURE__ */ new Set();
14109
+ const outcomeOf = /* @__PURE__ */ new Map();
14110
+ const tally = (c, what) => {
14111
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
14112
+ t.total++;
14113
+ if (what === "kept") t.kept = true;
14114
+ if (what === "rejected") t.rejected++;
14115
+ outcomeOf.set(c.seq, t);
14116
+ };
14117
+ const pend = (c, rank) => {
14118
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
14119
+ const prior = pendingByKey.get(key);
14120
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
14121
+ };
14122
+ for (const c of candidates) {
14123
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
14124
+ verified.push(c);
14125
+ continue;
14126
+ }
14127
+ if (!poolSet.has(c.mint)) {
14128
+ pend(c, 3);
14129
+ continue;
14130
+ }
14131
+ const value = streamValue(c.mint, c.leaf);
14132
+ if (value === void 0) {
14133
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
14134
+ stats.dropped++;
14135
+ tally(c, "other");
14136
+ } else pend(c, 1);
14137
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
14138
+ pend(c, value === c.commitment ? 0 : 2);
14139
+ } else if (value === c.commitment) {
14140
+ verified.push(c);
14141
+ } else {
14142
+ stats.dropped++;
14143
+ rejectedCandidates.add(c);
14144
+ tally(c, "rejected");
14145
+ }
14146
+ }
14147
+ verified.sort((a, b) => a.seq - b.seq);
14148
+ const byLeaf = /* @__PURE__ */ new Map();
14149
+ for (const c of verified) {
14150
+ const key = `${c.mint}:${c.leaf}`;
14151
+ if (byLeaf.has(key)) {
14152
+ stats.dropped++;
14153
+ tally(c, "other");
14154
+ continue;
14155
+ }
14156
+ byLeaf.set(key, c);
14157
+ }
14158
+ const notes = [];
14159
+ const atRisk = [];
14160
+ const spentOut = new Set(knownSpent);
14161
+ const verifiedOut = new Set(knownVerified);
14162
+ const keyChecked = /* @__PURE__ */ new Map();
14163
+ for (const c of byLeaf.values()) {
14164
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
14165
+ keyChecked.set(c.keypair.privateKey, pubOk);
14166
+ if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
14167
+ stats.dropped++;
14168
+ tally(c, "rejected");
14169
+ continue;
14170
+ }
14171
+ tally(c, "kept");
14172
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
14173
+ const utxo = {
14174
+ amount: c.amount,
14175
+ keypair: c.atRisk ? { ...c.keypair } : owner,
14176
+ blinding: c.blinding,
14177
+ mintAddress: c.mint,
14178
+ index: c.leaf,
14179
+ commitment: c.commitment
14180
+ };
14181
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
14182
+ stats.spent++;
14183
+ spentOut.add(c.nullifier);
14184
+ continue;
14185
+ }
14186
+ const note = {
14187
+ kind: c.kind,
14188
+ utxo,
14189
+ signature: bs584.encode(c.signature),
14190
+ legacyExposed: c.atRisk
14191
+ };
14192
+ (c.atRisk ? atRisk : notes).push(note);
14193
+ }
14194
+ 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);
14195
+ sortNotes(notes);
14196
+ sortNotes(atRisk);
14197
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
14198
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
14199
+ const overflow = pendingList.length - carriedPending.length;
14200
+ if (overflow > 0) {
14201
+ stats.pendingDropped += overflow;
14202
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
14203
+ }
14204
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
14205
+ for (const c of carriedPending) tally(c, "kept");
14206
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
14207
+ let page = targetPage;
14208
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
14209
+ const trees = {};
14210
+ const treeEnd = /* @__PURE__ */ new Map();
14211
+ for (const mint of poolMints) {
14212
+ const start = startTrees.get(mint);
14213
+ const { r, overrides } = replays.get(mint);
14214
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
14215
+ const n = snap.nextIndex;
14216
+ const window2 = [];
14217
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
14218
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
14219
+ if (v === void 0) break;
14220
+ window2.push(hex32(v));
14221
+ }
14222
+ window2.reverse();
14223
+ trees[mint] = {
14224
+ frontier: snap.frontier,
14225
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
14226
+ window: window2.join(""),
14227
+ verified: Math.min(verifiedUpTo(mint), n),
14228
+ 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)]),
14229
+ mismatch: r.mismatch
14230
+ };
14231
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
14232
+ }
14233
+ const pendingLeaves = [];
14234
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
14235
+ for (const c of carriedPending) {
14236
+ const end = treeEnd.get(c.mint);
14237
+ if (!end || c.leaf >= end.nextIndex) continue;
14238
+ const value = streamValue(c.mint, c.leaf);
14239
+ const key = `${c.mint}:${c.leaf}`;
14240
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
14241
+ pendingLeafSeen.add(key);
14242
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
14243
+ }
14244
+ const keptItems = [];
14245
+ const keptIds = /* @__PURE__ */ new Set();
14246
+ for (const o of ownItems) {
14247
+ const t = outcomeOf.get(o.seq);
14248
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
14249
+ rejectedNow.add(o.id);
14250
+ continue;
14251
+ }
14252
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
14253
+ keptIds.add(o.id);
14254
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
14255
+ }
14256
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
14257
+ const nextCursor = {
14258
+ v: CURSOR_VERSION,
14259
+ epoch: head.epoch.toString(10),
14260
+ page,
14261
+ chain: chainAt.get(page) ?? startChain,
14262
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
14263
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
14264
+ trees,
14265
+ own: {
14266
+ items: keptItems,
14267
+ verified: Array.from(verifiedOut),
14268
+ spent: Array.from(spentOut),
14269
+ pendingLeaves,
14270
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
14271
+ }
14272
+ };
14273
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
14274
+ } finally {
14275
+ params.signal?.removeEventListener("abort", onCallerAbort);
14276
+ }
14277
+ }
14278
+
12256
14279
  // src/wallet/utxo-wallet.ts
12257
14280
  init_address();
12258
14281
  init_utxo();
@@ -12912,7 +14935,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12912
14935
  })
12913
14936
  });
12914
14937
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12915
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
14938
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
12916
14939
  throw new Error(
12917
14940
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12918
14941
  );
@@ -12949,9 +14972,13 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12949
14972
  // src/bridge/derive.ts
12950
14973
  var import_hmac = require("@noble/hashes/hmac");
12951
14974
  var import_sha512 = require("@noble/hashes/sha512");
14975
+ var import_blake37 = require("@noble/hashes/blake3");
14976
+ init_utxo();
12952
14977
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
14978
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
14979
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
12953
14980
  var MAX_RECEIVER_INDEX = 1e4;
12954
- async function deriveBridgeReceiver(nk, index) {
14981
+ function assertReceiverIndex(index) {
12955
14982
  if (!Number.isInteger(index) || index < 0) {
12956
14983
  throw new Error(`index must be a non-negative integer, got ${index}`);
12957
14984
  }
@@ -12960,6 +14987,26 @@ async function deriveBridgeReceiver(nk, index) {
12960
14987
  `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.`
12961
14988
  );
12962
14989
  }
14990
+ }
14991
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
14992
+ if (ownerUtxoKeypair instanceof Uint8Array) {
14993
+ throw new Error(
14994
+ "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."
14995
+ );
14996
+ }
14997
+ assertReceiverIndex(index);
14998
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
14999
+ const priv = bigintToBytes323(owner.privateKey);
15000
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
15001
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
15002
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
15003
+ const key = (0, import_blake37.blake3)(preimage);
15004
+ const h = (0, import_hmac.hmac)(import_sha512.sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
15005
+ return signerFromSecretKey(h.slice(0, 32));
15006
+ }
15007
+ async function deriveLegacyBridgeReceiver(nk, index) {
15008
+ assertReceiverIndex(index);
15009
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
12963
15010
  const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12964
15011
  return signerFromSecretKey(h.slice(0, 32));
12965
15012
  }
@@ -12970,13 +15017,44 @@ var import_token4 = require("@solana-program/token");
12970
15017
  function describeError(err) {
12971
15018
  return err instanceof Error ? err.message : String(err);
12972
15019
  }
12973
- async function listBridgeDeposits(rpc, nk, opts) {
15020
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
15021
+ if (ownerUtxoKeypair instanceof Uint8Array) {
15022
+ throw new Error(
15023
+ "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)."
15024
+ );
15025
+ }
15026
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
15027
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
15028
+ legacyExposed: false
15029
+ });
15030
+ if (opts.includeLegacy === false) return out;
15031
+ const nks = [];
15032
+ const seen = /* @__PURE__ */ new Set();
15033
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
15034
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
15035
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
15036
+ }
15037
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
15038
+ if (seen.has(key)) continue;
15039
+ seen.add(key);
15040
+ nks.push(nk);
15041
+ }
15042
+ for (const nk of nks) {
15043
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
15044
+ legacyExposed: true,
15045
+ legacyViewingKeyNk: nk
15046
+ });
15047
+ out.push(...legacy);
15048
+ }
15049
+ return out;
15050
+ }
15051
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12974
15052
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12975
15053
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12976
15054
  const out = [];
12977
15055
  let consecutiveUnused = 0;
12978
15056
  for (let index = 0; index < scanDepth; index++) {
12979
- const kp = await deriveBridgeReceiver(nk, index);
15057
+ const kp = await receiverAt(index);
12980
15058
  const receiver = kp.address;
12981
15059
  const [tokenAccount] = await (0, import_token4.findAssociatedTokenPda)({
12982
15060
  mint: opts.mint,
@@ -13028,7 +15106,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
13028
15106
  tokenBalance,
13029
15107
  lamports,
13030
15108
  shieldSignature,
13031
- ...indexReused ? { indexReused, shieldSignatures } : {}
15109
+ ...indexReused ? { indexReused, shieldSignatures } : {},
15110
+ ...provenance
13032
15111
  });
13033
15112
  } catch (err) {
13034
15113
  out.push({
@@ -13038,7 +15117,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
13038
15117
  state: "unknown",
13039
15118
  tokenBalance: 0n,
13040
15119
  lamports: 0n,
13041
- error: describeError(err)
15120
+ error: describeError(err),
15121
+ ...provenance
13042
15122
  });
13043
15123
  }
13044
15124
  }
@@ -13192,7 +15272,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13192
15272
  const signMessage = (m) => signMessageBytes(R, m);
13193
15273
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
13194
15274
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
13195
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
15275
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
15276
+ amount,
15277
+ viewingKeyNk: nk,
15278
+ ownerUtxoKeypair: utxoKeypair,
15279
+ mintAddress: mint
15280
+ });
13196
15281
  const zeroInput = await createZeroUtxo(mint);
13197
15282
  const rBefore = (await rpc.getBalance(R.address).send()).value;
13198
15283
  let result;
@@ -13211,6 +15296,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13211
15296
  signMessage,
13212
15297
  chainNoteViewingKeyNk: nk,
13213
15298
  chainNoteSalt: noteSalt,
15299
+ ownerUtxoKeypair: utxoKeypair,
13214
15300
  relaySupplementalAlt: true,
13215
15301
  onProgress: (s) => log(` \xB7 ${s}`)
13216
15302
  }
@@ -13398,13 +15484,13 @@ var DoNotRetry = class extends Error {
13398
15484
  };
13399
15485
  async function withShieldRetries(attempt, hooks = {}) {
13400
15486
  const attempts = hooks.attempts ?? 3;
13401
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
15487
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13402
15488
  let last = "";
13403
15489
  for (let n = 1; n <= attempts; n++) {
13404
15490
  if (n > 1) {
13405
15491
  const delay = retryDelayMs(n);
13406
15492
  hooks.onRetry?.(n, delay, last);
13407
- await sleep4(delay);
15493
+ await sleep5(delay);
13408
15494
  }
13409
15495
  try {
13410
15496
  return await attempt(n);
@@ -13424,6 +15510,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13424
15510
  0 && (module.exports = {
13425
15511
  AccountRole,
13426
15512
  BRIDGE_ESCROW_LABEL,
15513
+ BRIDGE_ESCROW_LABEL_V2,
13427
15514
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
13428
15515
  CHAIN_NOTE_SALT_BITS,
13429
15516
  CLEANUP_FEE_BUDGET,
@@ -13452,6 +15539,10 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13452
15539
  MemoryStorageAdapter,
13453
15540
  MerkleTree,
13454
15541
  NATIVE_SOL_MINT,
15542
+ NOTE_INDEX_NO_LEAF,
15543
+ NOTE_INDEX_PAGE_SIZE,
15544
+ NoteIndexFormatError,
15545
+ NoteIndexHeadBehindError,
13455
15546
  ONECLICK_PUBKEY_B58,
13456
15547
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
13457
15548
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -13528,6 +15619,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13528
15619
  computeChainNoteHash,
13529
15620
  computeExtDataHash,
13530
15621
  computeMerkleRoot,
15622
+ computeNoteIndexChain,
13531
15623
  computeProofForLatestDeposit,
13532
15624
  computeProofFromChain,
13533
15625
  computeSignature,
@@ -13552,14 +15644,18 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13552
15644
  depositFromDerivedKey,
13553
15645
  deriveBridgeReceiver,
13554
15646
  deriveChangeNoteBlinding,
13555
- deriveDepositNoteSecrets,
15647
+ deriveDepositNoteBlinding,
13556
15648
  deriveDiversifiedViewingKey,
13557
15649
  deriveDiversifier,
13558
15650
  deriveFundingTargets,
13559
15651
  deriveInputNullifierPdas,
15652
+ deriveLegacyBridgeReceiver,
15653
+ deriveLegacyDepositNoteSecrets,
15654
+ deriveLegacySwapRefundAuthorization,
13560
15655
  derivePublicKey,
13561
15656
  deriveSpendKey,
13562
15657
  deriveSwapRefundAuthorization,
15658
+ deriveSwapRefundBlinding,
13563
15659
  deriveUserCompliancePublicKey,
13564
15660
  deriveUserComplianceScalar,
13565
15661
  deriveUtxoKeypairFromSpendKey,
@@ -13572,6 +15668,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13572
15668
  discoverSwapRefunds,
13573
15669
  downloadNote,
13574
15670
  encodeDeliveryCarrierMemo,
15671
+ encodeNoteIndexItem,
15672
+ encodeNoteIndexPage,
13575
15673
  encodeNoteSimple,
13576
15674
  encodeRecipientDeliveryNote,
13577
15675
  encryptCompactChainNote,
@@ -13587,6 +15685,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13587
15685
  fetchCommitments,
13588
15686
  fetchLatestBlockhash,
13589
15687
  fetchLookupTables,
15688
+ fetchNoteIndexHead,
15689
+ fetchNoteIndexPage,
13590
15690
  fetchRiskQuoteInstruction,
13591
15691
  fetchRiskQuoteIx,
13592
15692
  fetchSignaturesForAddress,
@@ -13659,6 +15759,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13659
15759
  parseDeliveryCarrierMemo,
13660
15760
  parseError,
13661
15761
  parseNote,
15762
+ parseNoteIndexItem,
15763
+ parseNoteIndexPage,
13662
15764
  parseRelayErrorResponse,
13663
15765
  parseRelayErrorSignature,
13664
15766
  parseTransactionError,
@@ -13680,6 +15782,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13680
15782
  readMerkleTreeState,
13681
15783
  readRent,
13682
15784
  recipientDeliveryNoteToBase64,
15785
+ recoverNotesFromIndex,
13683
15786
  registerViewingKey,
13684
15787
  relayRequestDigestHex,
13685
15788
  removePendingDeposit,