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

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,19 @@ __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,
726
+ deriveSwapRefundKeypair: () => deriveSwapRefundKeypair,
716
727
  deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
717
728
  deriveUserComplianceScalar: () => deriveUserComplianceScalar,
718
729
  deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
@@ -725,6 +736,8 @@ __export(index_exports, {
725
736
  discoverSwapRefunds: () => discoverSwapRefunds,
726
737
  downloadNote: () => downloadNote,
727
738
  encodeDeliveryCarrierMemo: () => encodeDeliveryCarrierMemo,
739
+ encodeNoteIndexItem: () => encodeNoteIndexItem,
740
+ encodeNoteIndexPage: () => encodeNoteIndexPage,
728
741
  encodeNoteSimple: () => encodeNoteSimple,
729
742
  encodeRecipientDeliveryNote: () => encodeRecipientDeliveryNote,
730
743
  encryptCompactChainNote: () => encryptCompactChainNote,
@@ -740,6 +753,8 @@ __export(index_exports, {
740
753
  fetchCommitments: () => fetchCommitments,
741
754
  fetchLatestBlockhash: () => fetchLatestBlockhash,
742
755
  fetchLookupTables: () => fetchLookupTables,
756
+ fetchNoteIndexHead: () => fetchNoteIndexHead,
757
+ fetchNoteIndexPage: () => fetchNoteIndexPage,
743
758
  fetchRiskQuoteInstruction: () => fetchRiskQuoteInstruction,
744
759
  fetchRiskQuoteIx: () => fetchRiskQuoteIx,
745
760
  fetchSignaturesForAddress: () => fetchSignaturesForAddress,
@@ -812,6 +827,8 @@ __export(index_exports, {
812
827
  parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
813
828
  parseError: () => parseError,
814
829
  parseNote: () => parseNote2,
830
+ parseNoteIndexItem: () => parseNoteIndexItem,
831
+ parseNoteIndexPage: () => parseNoteIndexPage,
815
832
  parseRelayErrorResponse: () => parseRelayErrorResponse,
816
833
  parseRelayErrorSignature: () => parseRelayErrorSignature,
817
834
  parseTransactionError: () => parseTransactionError,
@@ -833,6 +850,7 @@ __export(index_exports, {
833
850
  readMerkleTreeState: () => readMerkleTreeState,
834
851
  readRent: () => readRent,
835
852
  recipientDeliveryNoteToBase64: () => recipientDeliveryNoteToBase64,
853
+ recoverNotesFromIndex: () => recoverNotesFromIndex,
836
854
  registerViewingKey: () => registerViewingKey,
837
855
  relayRequestDigestHex: () => relayRequestDigestHex,
838
856
  removePendingDeposit: () => removePendingDeposit,
@@ -1507,13 +1525,16 @@ init_inputs();
1507
1525
 
1508
1526
  // src/relay/viewing-key.ts
1509
1527
  var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
1528
+ var VIEWING_KEY_CHALLENGE_READABLE_HEADER = "Cloak: Enable private transactions\n\nShares your viewing key with Cloak so you can transact privately. Signing this does not move any funds.\n\n";
1529
+ var VIEWING_KEY_CHALLENGE_REQUEST_FORMAT = "readable";
1510
1530
  var UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1511
1531
  var MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS = 300;
1512
1532
  function normalizeViewingKeyHex(viewingKeyHex) {
1513
1533
  return viewingKeyHex.replace(/^0x/i, "").toLowerCase();
1514
1534
  }
1515
- function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex) {
1516
- return [
1535
+ function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format = "legacy") {
1536
+ const header = format === "readable" ? VIEWING_KEY_CHALLENGE_READABLE_HEADER : "";
1537
+ return header + [
1517
1538
  VIEWING_KEY_CHALLENGE_PREFIX,
1518
1539
  userPubkey,
1519
1540
  nonce,
@@ -1528,17 +1549,16 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
1528
1549
  const challenge = data;
1529
1550
  const nonce = typeof challenge.nonce === "string" ? challenge.nonce : "";
1530
1551
  const expiresInSeconds = challenge.expires_in_seconds;
1531
- const expectedMessage = buildViewingKeyChallengeMessage(
1532
- userPubkey,
1533
- nonce,
1534
- viewingKeyHex
1552
+ const messageFormat = ["readable", "legacy"].find(
1553
+ (format) => challenge.message === buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format)
1535
1554
  );
1536
- if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || challenge.message !== expectedMessage) {
1555
+ if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || messageFormat === void 0) {
1537
1556
  throw new Error("Relay returned an unsafe viewing-key challenge");
1538
1557
  }
1539
1558
  return {
1540
1559
  nonce,
1541
- message: expectedMessage,
1560
+ message: buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, messageFormat),
1561
+ messageFormat,
1542
1562
  expiresInSeconds
1543
1563
  };
1544
1564
  }
@@ -1622,6 +1642,44 @@ function isLoopbackHost(value) {
1622
1642
  }
1623
1643
  var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
1624
1644
 
1645
+ // src/relay/clock.ts
1646
+ var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
1647
+ var MAX_CLOCK_DIVERGENCE_MS = 2e3;
1648
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
1649
+ var sample = null;
1650
+ function monotonicNowMs() {
1651
+ const perf = globalThis.performance;
1652
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
1653
+ }
1654
+ function observeRelayClock(response) {
1655
+ const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
1656
+ if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
1657
+ const serverMs = Number(raw.trim());
1658
+ const wallMs = Date.now();
1659
+ const offsetMs = serverMs - wallMs;
1660
+ if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
1661
+ sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
1662
+ }
1663
+ function relayNowMs() {
1664
+ const wallMs = Date.now();
1665
+ if (!sample) return wallMs;
1666
+ const wallElapsed = wallMs - sample.wallAtSampleMs;
1667
+ const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
1668
+ if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
1669
+ sample = null;
1670
+ return wallMs;
1671
+ }
1672
+ return wallMs + sample.offsetMs;
1673
+ }
1674
+ function hasRelayClockSample() {
1675
+ if (!sample) return false;
1676
+ relayNowMs();
1677
+ return sample !== null;
1678
+ }
1679
+ function relayNowSeconds() {
1680
+ return Math.floor(relayNowMs() / 1e3);
1681
+ }
1682
+
1625
1683
  // src/relay/endpoint.ts
1626
1684
  var ALLOWED_ORIGINS = new Set(
1627
1685
  RELAY_ORIGIN_ALLOWLIST.map((entry) => {
@@ -1673,8 +1731,9 @@ function assertAllowedRelayOrigin(value) {
1673
1731
  async function relayFetch(url, init, options) {
1674
1732
  assertAllowedRelayOrigin(url);
1675
1733
  const extra = sanitizeExtraHeaders(options?.extraHeaders);
1676
- if (!extra) return fetch(url, init);
1677
- return fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) });
1734
+ const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
1735
+ if (options?.observeClock !== false) observeRelayClock(response);
1736
+ return response;
1678
1737
  }
1679
1738
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1680
1739
  var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
@@ -2144,7 +2203,7 @@ ${digest}`
2144
2203
  }
2145
2204
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
2146
2205
  const senderB58 = sender;
2147
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
2206
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
2148
2207
  const nonce = randomNonceUuid();
2149
2208
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
2150
2209
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -2223,7 +2282,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
2223
2282
  `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
2283
  );
2225
2284
  }
2226
- function explainRelayAuthRejection(responseText) {
2285
+ function explainRelayAuthRejection(responseText, context) {
2227
2286
  const text = String(responseText);
2228
2287
  const has = (needle) => text.includes(needle);
2229
2288
  if (has("issued too far in the future")) {
@@ -2233,7 +2292,9 @@ function explainRelayAuthRejection(responseText) {
2233
2292
  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
2293
  }
2235
2294
  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\`.`;
2295
+ 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\`.`;
2296
+ if (!context?.carriedAffiliateCode) return base;
2297
+ 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
2298
  }
2238
2299
  if (has("has no registered viewing key")) {
2239
2300
  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.`;
@@ -2439,7 +2500,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
2439
2500
  headers: { "Content-Type": "application/json" },
2440
2501
  body: JSON.stringify({
2441
2502
  user_pubkey: userPubkey,
2442
- viewing_key: nkHex
2503
+ viewing_key: nkHex,
2504
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
2443
2505
  })
2444
2506
  });
2445
2507
  if (!challengeResponse.ok) {
@@ -2467,7 +2529,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
2467
2529
  nonce: challenge.nonce,
2468
2530
  identifier: keyId,
2469
2531
  signature,
2470
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
2532
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
2533
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
2471
2534
  })
2472
2535
  });
2473
2536
  if (!response.ok) {
@@ -2755,6 +2818,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
2755
2818
  return false;
2756
2819
  }
2757
2820
  }
2821
+ function isRelayRequestInFlightResponse(responseText) {
2822
+ try {
2823
+ const parsed = JSON.parse(responseText);
2824
+ return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
2825
+ } catch {
2826
+ return false;
2827
+ }
2828
+ }
2758
2829
  function classifyRelayError(responseText, httpStatus) {
2759
2830
  let inner = "";
2760
2831
  try {
@@ -4302,7 +4373,11 @@ var RelayService = class {
4302
4373
  const challengeRes = await relayFetch(`${this.baseUrl}/viewing-key/challenge`, {
4303
4374
  method: "POST",
4304
4375
  headers: { "Content-Type": "application/json" },
4305
- body: JSON.stringify({ user_pubkey: userPubkey, viewing_key: viewingKey })
4376
+ body: JSON.stringify({
4377
+ user_pubkey: userPubkey,
4378
+ viewing_key: viewingKey,
4379
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
4380
+ })
4306
4381
  });
4307
4382
  if (!challengeRes.ok) {
4308
4383
  const error = await challengeRes.text();
@@ -4327,7 +4402,8 @@ var RelayService = class {
4327
4402
  nonce: challenge.nonce,
4328
4403
  identifier,
4329
4404
  signature,
4330
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
4405
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
4406
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
4331
4407
  })
4332
4408
  });
4333
4409
  if (!response.ok) {
@@ -4797,6 +4873,27 @@ function isRootAccepted(data, rootHex) {
4797
4873
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
4798
4874
  return readRootHistory(data).some((r) => r === want);
4799
4875
  }
4876
+ function treeAccountAcceptsRoot(data, rootHex) {
4877
+ const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
4878
+ if (data.length >= ROOT_OFFSET + 32) {
4879
+ const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
4880
+ if (current === want) return true;
4881
+ }
4882
+ return isRootAccepted(data, want);
4883
+ }
4884
+ function readTreeAccountFrontier(data) {
4885
+ if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
4886
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
4887
+ const next = readBigUInt64LE(buf, 32);
4888
+ if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
4889
+ const subtrees = [];
4890
+ for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
4891
+ const offset = SUBTREES_OFFSET + level * 32;
4892
+ subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
4893
+ }
4894
+ const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
4895
+ return { nextIndex: Number(next), subtrees, root };
4896
+ }
4800
4897
 
4801
4898
  // src/proving/merkle.ts
4802
4899
  var import_circomlibjs3 = require("circomlibjs");
@@ -4956,6 +5053,89 @@ var MerkleTree = class _MerkleTree {
4956
5053
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4957
5054
  return MerkleTree.create(height, commitments);
4958
5055
  }
5056
+ var MerkleFrontier = class _MerkleFrontier {
5057
+ constructor(levels, zeros, poseidon3, count, left) {
5058
+ this.levels = levels;
5059
+ this.zeros = zeros;
5060
+ this.poseidon = poseidon3;
5061
+ this.count = count;
5062
+ this.left = left;
5063
+ }
5064
+ static async create(state, levels = MERKLE_TREE_HEIGHT2) {
5065
+ const zeros = await getZeroValues();
5066
+ const poseidon3 = await getPoseidon3();
5067
+ const left = new Array(levels).fill(null);
5068
+ let count = 0;
5069
+ if (state) {
5070
+ if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
5071
+ throw new Error("MerkleFrontierState.nextIndex out of range");
5072
+ }
5073
+ if (!Array.isArray(state.left) || state.left.length !== levels) {
5074
+ throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
5075
+ }
5076
+ count = state.nextIndex;
5077
+ for (let l = 0; l < levels; l++) {
5078
+ const odd = Math.floor(count / 2 ** l) % 2 === 1;
5079
+ const entry = state.left[l];
5080
+ if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
5081
+ if (odd) {
5082
+ if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
5083
+ left[l] = BigInt("0x" + entry);
5084
+ }
5085
+ }
5086
+ }
5087
+ return new _MerkleFrontier(levels, zeros, poseidon3, count, left);
5088
+ }
5089
+ get nextIndex() {
5090
+ return this.count;
5091
+ }
5092
+ /**
5093
+ * The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
5094
+ * present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
5095
+ * With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
5096
+ */
5097
+ leftAt(level) {
5098
+ if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
5099
+ return this.left[level];
5100
+ }
5101
+ hash(a, b) {
5102
+ return this.poseidon.F.toObject(this.poseidon([a, b]));
5103
+ }
5104
+ /** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
5105
+ append(leaves) {
5106
+ if (leaves.length === 0) return;
5107
+ if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
5108
+ let nodes = leaves;
5109
+ for (let l = 0; l < this.levels && nodes.length > 0; l++) {
5110
+ const before = Math.floor(this.count / 2 ** l);
5111
+ const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
5112
+ const parents = [];
5113
+ for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
5114
+ this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
5115
+ nodes = parents;
5116
+ }
5117
+ this.count += leaves.length;
5118
+ }
5119
+ /** The root of the first `nextIndex` leaves, zero-padded to the right. */
5120
+ root() {
5121
+ let partial = this.zeros[0];
5122
+ for (let l = 0; l < this.levels; l++) {
5123
+ const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
5124
+ if (odd) partial = this.hash(this.left[l], partial);
5125
+ else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
5126
+ }
5127
+ return partial;
5128
+ }
5129
+ toState() {
5130
+ return {
5131
+ nextIndex: this.count,
5132
+ left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
5133
+ };
5134
+ }
5135
+ clone() {
5136
+ return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
5137
+ }
5138
+ };
4959
5139
 
4960
5140
  // src/relay/client.ts
4961
5141
  init_address();
@@ -5107,6 +5287,7 @@ async function fetchWithRetry(url, options = {}) {
5107
5287
  try {
5108
5288
  const response = await fetch(url, { signal: controller.signal });
5109
5289
  clearTimeout(timeoutId);
5290
+ observeRelayClock(response);
5110
5291
  return response;
5111
5292
  } finally {
5112
5293
  clearTimeout(timeoutId);
@@ -5459,38 +5640,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
5459
5640
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
5460
5641
  return new Uint8Array(plaintext);
5461
5642
  }
5462
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
5643
+ async function importNkHkdfKey(nk) {
5463
5644
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5464
5645
  throw new Error("nk must be 32 bytes");
5465
5646
  }
5647
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
5648
+ }
5649
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
5466
5650
  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
- );
5651
+ const [keyBits, nonceBits] = await Promise.all([
5652
+ subtle.deriveBits(
5653
+ {
5654
+ name: "HKDF",
5655
+ hash: "SHA-256",
5656
+ salt: toArrayBuffer2(salt),
5657
+ info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
5658
+ },
5659
+ ikm,
5660
+ 256
5661
+ ),
5662
+ subtle.deriveBits(
5663
+ {
5664
+ name: "HKDF",
5665
+ hash: "SHA-256",
5666
+ salt: toArrayBuffer2(salt),
5667
+ info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
5668
+ },
5669
+ ikm,
5670
+ 96
5671
+ )
5672
+ ]);
5489
5673
  return {
5490
5674
  key: new Uint8Array(keyBits),
5491
5675
  nonce: new Uint8Array(nonceBits)
5492
5676
  };
5493
5677
  }
5678
+ async function deriveAesKeyAndNonce(nk, commitmentHex) {
5679
+ const ikm = await importNkHkdfKey(nk);
5680
+ return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
5681
+ }
5682
+ function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
5683
+ if (version === NOTE_VERSION_V4) {
5684
+ if (plaintext.length !== PLAINTEXT_LEN_V4) {
5685
+ throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
5686
+ }
5687
+ return {
5688
+ timestamp: readU64LE(plaintext, 0),
5689
+ commitment: commitmentHex.toLowerCase(),
5690
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
5691
+ outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
5692
+ outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
5693
+ isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
5694
+ };
5695
+ }
5696
+ if (version === NOTE_VERSION_V3) {
5697
+ if (plaintext.length !== PLAINTEXT_LEN_V3) {
5698
+ throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
5699
+ }
5700
+ return {
5701
+ timestamp: readU64LE(plaintext, 0),
5702
+ commitment: commitmentHex.toLowerCase(),
5703
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
5704
+ };
5705
+ }
5706
+ if (plaintext.length !== PLAINTEXT_LEN_V2) {
5707
+ throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
5708
+ }
5709
+ return {
5710
+ timestamp: readU64LE(plaintext, 0),
5711
+ commitment: commitmentHex.toLowerCase()
5712
+ };
5713
+ }
5494
5714
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
5495
5715
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5496
5716
  throw new Error("nk must be 32 bytes");
@@ -5554,36 +5774,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5554
5774
  try {
5555
5775
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
5556
5776
  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
- };
5777
+ return decodeChainNotePlaintext(version, plaintext, commitment);
5587
5778
  } catch (error) {
5588
5779
  lastError = error;
5589
5780
  }
@@ -5592,6 +5783,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5592
5783
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
5593
5784
  );
5594
5785
  }
5786
+ async function createCompactChainNoteDecryptor(nk) {
5787
+ const ikm = await importNkHkdfKey(nk);
5788
+ return async (noteBytes, commitment) => {
5789
+ if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
5790
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
5791
+ const version = noteBytes[0];
5792
+ if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
5793
+ return null;
5794
+ }
5795
+ try {
5796
+ const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
5797
+ const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
5798
+ let hex = "";
5799
+ for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
5800
+ return decodeChainNotePlaintext(version, plaintext, hex);
5801
+ } catch {
5802
+ return null;
5803
+ }
5804
+ };
5805
+ }
5595
5806
  function chainNoteToBase64(noteBytes) {
5596
5807
  return Buffer.from(noteBytes).toString("base64");
5597
5808
  }
@@ -5688,6 +5899,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
5688
5899
  return null;
5689
5900
  }
5690
5901
  }
5902
+ var X25519_PKCS8_PREFIX = Uint8Array.from([
5903
+ 48,
5904
+ 46,
5905
+ 2,
5906
+ 1,
5907
+ 0,
5908
+ 48,
5909
+ 5,
5910
+ 6,
5911
+ 3,
5912
+ 43,
5913
+ 101,
5914
+ 110,
5915
+ 4,
5916
+ 34,
5917
+ 4,
5918
+ 32
5919
+ ]);
5920
+ var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
5921
+ function decodeOpened(plaintext) {
5922
+ if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5923
+ return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5924
+ }
5925
+ async function createRecipientDeliveryOpener(viewingSecretKey) {
5926
+ if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
5927
+ throw new Error("viewingSecretKey must be 32 bytes");
5928
+ }
5929
+ const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5930
+ const subtle = globalThis.crypto?.subtle;
5931
+ const hsalsa = import_tweetnacl4.default.lowlevel?.crypto_core_hsalsa20;
5932
+ if (!subtle || typeof hsalsa !== "function") return slow;
5933
+ let privateKey;
5934
+ const sharedKey = async (ephemeralPk) => {
5935
+ const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
5936
+ const shared = new Uint8Array(
5937
+ await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
5938
+ );
5939
+ const key = new Uint8Array(32);
5940
+ hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
5941
+ return key;
5942
+ };
5943
+ try {
5944
+ const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
5945
+ pkcs8.set(X25519_PKCS8_PREFIX);
5946
+ pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5947
+ privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5948
+ const probe = import_tweetnacl4.default.box.keyPair().publicKey;
5949
+ const fast = await sharedKey(probe);
5950
+ const reference = import_tweetnacl4.default.box.before(probe, viewingSecretKey);
5951
+ if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5952
+ } catch {
5953
+ return slow;
5954
+ }
5955
+ return async (envelope) => {
5956
+ if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
5957
+ const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
5958
+ const nonce = envelope.subarray(
5959
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
5960
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5961
+ );
5962
+ const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
5963
+ let key;
5964
+ try {
5965
+ key = await sharedKey(ephemeralPk);
5966
+ } catch {
5967
+ return openRecipientDeliveryNote(envelope, viewingSecretKey);
5968
+ }
5969
+ try {
5970
+ return decodeOpened(import_tweetnacl4.default.secretbox.open(ciphertext, nonce, key));
5971
+ } catch {
5972
+ return null;
5973
+ }
5974
+ };
5975
+ }
5691
5976
  function recipientDeliveryNoteToBase64(envelope) {
5692
5977
  return Buffer.from(envelope).toString("base64");
5693
5978
  }
@@ -5742,10 +6027,45 @@ var import_blake34 = require("@noble/hashes/blake3");
5742
6027
  init_address();
5743
6028
  var import_bs582 = __toESM(require("bs58"), 1);
5744
6029
  init_utxo();
6030
+
6031
+ // src/notes/owner-key.ts
6032
+ init_utxo();
6033
+ var FIELD_MODULUS2 = BigInt(
6034
+ "21888242871839275222246405745257275088548364400416034343698204186575808495617"
6035
+ );
6036
+ async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
6037
+ if (!keypair || typeof keypair !== "object") {
6038
+ throw new Error(
6039
+ `${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.`
6040
+ );
6041
+ }
6042
+ const { privateKey, publicKey } = keypair;
6043
+ if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS2) {
6044
+ throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
6045
+ }
6046
+ if (typeof publicKey !== "bigint" || publicKey === 0n) {
6047
+ throw new Error(`${label}.publicKey must be a non-zero bigint`);
6048
+ }
6049
+ if (await derivePublicKey(privateKey) !== publicKey) {
6050
+ throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
6051
+ }
6052
+ return { privateKey, publicKey };
6053
+ }
6054
+ function normalizeOwnerPublicKey(publicKey, label) {
6055
+ if (publicKey === void 0 || publicKey === null) return void 0;
6056
+ if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS2) {
6057
+ throw new Error(`${label} must be a non-zero field element (bigint)`);
6058
+ }
6059
+ return publicKey;
6060
+ }
6061
+
6062
+ // src/notes/swap-refund.ts
5745
6063
  init_inputs();
5746
6064
  var bs582 = import_bs582.default.default || import_bs582.default;
5747
6065
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
5748
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6066
+ var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
6067
+ var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
6068
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5749
6069
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
5750
6070
  function normalizeNullifier(inputNullifier) {
5751
6071
  if (inputNullifier instanceof Uint8Array) {
@@ -5779,13 +6099,51 @@ function derive(nk, nullifier, info) {
5779
6099
  preimage.set(info, off);
5780
6100
  return (0, import_blake34.blake3)(preimage);
5781
6101
  }
5782
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
6102
+ function assertNk(viewingKeyNk) {
5783
6103
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5784
6104
  throw new Error("viewingKeyNk must be 32 bytes");
5785
6105
  }
6106
+ return viewingKeyNk;
6107
+ }
6108
+ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
6109
+ const nk = assertNk(viewingKeyNk);
6110
+ return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
6111
+ }
6112
+ function privateKeyBytes(privateKey) {
6113
+ return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
6114
+ }
6115
+ async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
6116
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
6117
+ const nullifier = normalizeNullifier(inputNullifier);
6118
+ const preimage = new Uint8Array(
6119
+ REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
6120
+ );
6121
+ let off = 0;
6122
+ preimage.set(REFUND_KEY_DOMAIN_V2, off);
6123
+ off += REFUND_KEY_DOMAIN_V2.length;
6124
+ preimage.set(privateKeyBytes(owner.privateKey), off);
6125
+ off += 32;
6126
+ preimage.set(nullifier, off);
6127
+ off += nullifier.length;
6128
+ preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
6129
+ const privateKey = toFieldSecret((0, import_blake34.blake3)(preimage));
6130
+ const publicKey = await derivePublicKey(privateKey);
6131
+ if (publicKey === 0n) throw new Error("refund authorization is degenerate");
6132
+ return { privateKey, publicKey };
6133
+ }
6134
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
6135
+ const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
6136
+ const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
6137
+ if (keypair.publicKey === 0n || blinding === 0n) {
6138
+ throw new Error("refund authorization is degenerate");
6139
+ }
6140
+ return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
6141
+ }
6142
+ async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
6143
+ const nk = assertNk(viewingKeyNk);
5786
6144
  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));
6145
+ const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
6146
+ const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
5789
6147
  const publicKey = await derivePublicKey(privateKey);
5790
6148
  if (publicKey === 0n || blinding === 0n) {
5791
6149
  throw new Error("derived refund authorization is degenerate");
@@ -5800,22 +6158,90 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
5800
6158
  mintAddress: NATIVE_SOL_MINT
5801
6159
  });
5802
6160
  }
6161
+ function toField(value) {
6162
+ return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
6163
+ }
5803
6164
  async function matchSwapRefundLeaf(params) {
5804
6165
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
5805
- const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
5806
- let auth;
6166
+ const expected = toField(params.commitment);
6167
+ let blinding;
6168
+ try {
6169
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
6170
+ } catch {
6171
+ return null;
6172
+ }
6173
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
6174
+ const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
6175
+ let perSwapPub;
6176
+ let perSwapPriv = 0n;
6177
+ if (ownerPriv > 0n && ownerPub !== void 0) {
6178
+ try {
6179
+ const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
6180
+ perSwapPub = kp.publicKey;
6181
+ perSwapPriv = kp.privateKey;
6182
+ } catch {
6183
+ return null;
6184
+ }
6185
+ }
6186
+ if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
6187
+ const published = toField(params.publishedRefundPubkey);
6188
+ const publishedBlinding = toField(params.publishedRefundBlinding);
6189
+ if (published !== 0n && publishedBlinding === blinding) {
6190
+ if (perSwapPub === void 0 || perSwapPub === published) {
6191
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
6192
+ if (candidate === expected && published !== ownerPub) {
6193
+ return {
6194
+ keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
6195
+ shape: "per-swap",
6196
+ blinding,
6197
+ amount: amountAfterFee,
6198
+ commitment: candidate,
6199
+ legacyExposed: false
6200
+ };
6201
+ }
6202
+ }
6203
+ }
6204
+ } else if (perSwapPub !== void 0) {
6205
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
6206
+ if (candidate === expected) {
6207
+ return {
6208
+ keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
6209
+ shape: "per-swap",
6210
+ blinding,
6211
+ amount: amountAfterFee,
6212
+ commitment: candidate,
6213
+ legacyExposed: false
6214
+ };
6215
+ }
6216
+ }
6217
+ if (ownerPub !== void 0) {
6218
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
6219
+ if (candidate === expected) {
6220
+ return {
6221
+ keypair: { privateKey: ownerPriv, publicKey: ownerPub },
6222
+ shape: "owner",
6223
+ blinding,
6224
+ amount: amountAfterFee,
6225
+ commitment: candidate,
6226
+ legacyExposed: false
6227
+ };
6228
+ }
6229
+ }
6230
+ let legacy;
5807
6231
  try {
5808
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
6232
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
5809
6233
  } catch {
5810
6234
  return null;
5811
6235
  }
5812
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
5813
- if (candidate !== expected) return null;
6236
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
6237
+ if (legacyCandidate !== expected) return null;
5814
6238
  return {
5815
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
5816
- blinding: auth.blinding,
6239
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
6240
+ shape: "legacy-nk",
6241
+ blinding: legacy.blinding,
5817
6242
  amount: amountAfterFee,
5818
- commitment: candidate
6243
+ commitment: legacyCandidate,
6244
+ legacyExposed: true
5819
6245
  };
5820
6246
  }
5821
6247
  var TRANSACT_SWAP_TAG2 = 1;
@@ -5823,6 +6249,9 @@ var PROOF_LEN2 = 256;
5823
6249
  var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
5824
6250
  var PUBLIC_INPUTS_LEN2 = 264;
5825
6251
  var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
6252
+ var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
6253
+ var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
6254
+ var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
5826
6255
  function toBase58(key) {
5827
6256
  if (!key) return void 0;
5828
6257
  if (typeof key === "string") return key;
@@ -5879,10 +6308,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
5879
6308
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
5880
6309
  return out;
5881
6310
  }
5882
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
6311
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
5883
6312
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5884
6313
  throw new Error("viewingKeyNk must be 32 bytes");
5885
6314
  }
6315
+ if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
6316
+ throw new Error(
6317
+ "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): per-swap and owner-key refund leaves are matched against it, and nk alone can only find legacy refunds."
6318
+ );
6319
+ }
6320
+ const ownerUtxoKeypair = options.ownerUtxoKeypair;
5886
6321
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5887
6322
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5888
6323
  const programIdBase58 = programId;
@@ -5939,7 +6374,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5939
6374
  programId
5940
6375
  );
5941
6376
  const key = swapState;
5942
- if (!nullifierBySwapState.has(key)) nullifierBySwapState.set(key, { nullifier, signature });
6377
+ const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
6378
+ if (!nullifierBySwapState.has(key)) {
6379
+ nullifierBySwapState.set(key, {
6380
+ nullifier,
6381
+ signature,
6382
+ refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
6383
+ refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
6384
+ });
6385
+ }
5943
6386
  }
5944
6387
  const logs = tx.meta?.logMessages;
5945
6388
  const scan = scanRefundLeafEvents(logs, programIdBase58);
@@ -5957,7 +6400,10 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5957
6400
  viewingKeyNk,
5958
6401
  inputNullifier: candidate.nullifier,
5959
6402
  amountAfterFee: event.amountAfterFee,
5960
- commitment: event.commitmentField
6403
+ commitment: event.commitmentField,
6404
+ ownerUtxoKeypair,
6405
+ publishedRefundPubkey: candidate.refundPubkey,
6406
+ publishedRefundBlinding: candidate.refundBlinding
5961
6407
  });
5962
6408
  if (!recovered) continue;
5963
6409
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5983,7 +6429,7 @@ var import_blake35 = require("@noble/hashes/blake3");
5983
6429
  init_utxo();
5984
6430
  init_inputs();
5985
6431
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5986
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6432
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5987
6433
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5988
6434
  var CHAIN_NOTE_SALT_BITS = 96;
5989
6435
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -6019,30 +6465,47 @@ function derive2(nk, salt, info) {
6019
6465
  preimage.set(info, off);
6020
6466
  return (0, import_blake35.blake3)(preimage);
6021
6467
  }
6468
+ function assertNk2(viewingKeyNk) {
6469
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
6470
+ throw new Error("viewingKeyNk must be 32 bytes");
6471
+ }
6472
+ return viewingKeyNk;
6473
+ }
6022
6474
  function randomDepositNoteSalt() {
6023
6475
  const bytes = randomBytes(12);
6024
6476
  let v = 0n;
6025
6477
  for (const b of bytes) v = v << 8n | BigInt(b);
6026
6478
  return v === 0n ? 1n : v;
6027
6479
  }
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
- }
6480
+ function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
6481
+ const nk = assertNk2(viewingKeyNk);
6482
+ return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
6483
+ }
6484
+ async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
6485
+ const nk = assertNk2(viewingKeyNk);
6032
6486
  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));
6487
+ const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
6488
+ const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
6035
6489
  const publicKey = await derivePublicKey(privateKey);
6036
6490
  if (publicKey === 0n || blinding === 0n) {
6037
6491
  throw new Error("derived deposit note secrets are degenerate");
6038
6492
  }
6039
6493
  return { keypair: { privateKey, publicKey }, blinding };
6040
6494
  }
6041
- async function createRecoverableDepositUtxo(amount, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomDepositNoteSalt()) {
6495
+ async function createRecoverableDepositUtxo(params) {
6496
+ if (!params || typeof params !== "object" || params instanceof Uint8Array) {
6497
+ throw new Error(
6498
+ "createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
6499
+ );
6500
+ }
6501
+ const { amount, viewingKeyNk } = params;
6042
6502
  if (typeof amount !== "bigint" || amount <= 0n) {
6043
6503
  throw new Error("amount must be a positive bigint");
6044
6504
  }
6045
- const { keypair, blinding } = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
6505
+ const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
6506
+ const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
6507
+ const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
6508
+ const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
6046
6509
  const utxo = { amount, keypair, blinding, mintAddress };
6047
6510
  utxo.commitment = await computeCommitment2(utxo);
6048
6511
  return { utxo, noteSalt };
@@ -6057,21 +6520,46 @@ function normalizeCommitment(value) {
6057
6520
  async function matchDepositNote(params) {
6058
6521
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
6059
6522
  if (typeof amount !== "bigint" || amount <= 0n) return null;
6060
- let secrets;
6523
+ let blinding;
6524
+ try {
6525
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
6526
+ } catch {
6527
+ return null;
6528
+ }
6529
+ const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
6530
+ if (published.length === 0) return null;
6531
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
6532
+ if (ownerPub !== void 0) {
6533
+ const keypair = {
6534
+ privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
6535
+ publicKey: ownerPub
6536
+ };
6537
+ const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
6538
+ if (published.some((value) => value === candidate)) {
6539
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
6540
+ }
6541
+ }
6542
+ let legacy;
6061
6543
  try {
6062
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
6544
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
6063
6545
  } catch {
6064
6546
  return null;
6065
6547
  }
6066
- const candidate = await computeCommitment2({
6548
+ const legacyCandidate = await computeCommitment2({
6067
6549
  amount,
6068
- keypair: secrets.keypair,
6069
- blinding: secrets.blinding,
6550
+ keypair: legacy.keypair,
6551
+ blinding: legacy.blinding,
6070
6552
  mintAddress
6071
6553
  });
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 };
6554
+ if (!published.some((value) => value === legacyCandidate)) return null;
6555
+ return {
6556
+ ...legacy,
6557
+ amount,
6558
+ mintAddress,
6559
+ commitment: legacyCandidate,
6560
+ noteSalt,
6561
+ legacyExposed: true
6562
+ };
6075
6563
  }
6076
6564
 
6077
6565
  // src/notes/change-note.ts
@@ -6129,10 +6617,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
6129
6617
  preimage.set(CHANGE_BLINDING_INFO, off);
6130
6618
  return toFieldSecret3((0, import_blake36.blake3)(preimage));
6131
6619
  }
6132
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
6620
+ async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
6133
6621
  if (typeof amount !== "bigint" || amount <= 0n) {
6134
6622
  throw new Error("amount must be a positive bigint");
6135
6623
  }
6624
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
6136
6625
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
6137
6626
  const utxo = { amount, keypair, blinding, mintAddress };
6138
6627
  utxo.commitment = await computeCommitment2(utxo);
@@ -6158,12 +6647,28 @@ async function matchChangeNote(params) {
6158
6647
  const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
6159
6648
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
6160
6649
  if (!published.some((value) => value === candidate)) return null;
6161
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
6650
+ const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
6651
+ const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
6652
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
6162
6653
  }
6163
6654
 
6164
6655
  // src/flows/transact.ts
6165
6656
  var import_circomlibjs4 = require("circomlibjs");
6166
6657
  var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
6658
+
6659
+ // src/relay/chain-note-time.ts
6660
+ async function relayChainNoteTimestampMs(relayUrl) {
6661
+ if (relayUrl && !hasRelayClockSample()) {
6662
+ try {
6663
+ const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
6664
+ await response.body?.cancel?.().catch(() => void 0);
6665
+ } catch {
6666
+ }
6667
+ }
6668
+ return BigInt(relayNowMs());
6669
+ }
6670
+
6671
+ // src/flows/transact.ts
6167
6672
  init_inputs();
6168
6673
 
6169
6674
  // src/proving/artifacts.ts
@@ -6452,6 +6957,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
6452
6957
  var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
6453
6958
  var DEFAULT_RELAY_NETWORK_RETRIES = 6;
6454
6959
  var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
6960
+ var RELAY_SOURCE_LEASE_MS = 18e4;
6961
+ var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
6962
+ var MAX_LEASE_EXPIRY_REPLAYS = 2;
6963
+ var RELAY_IN_FLIGHT_POLL_MS = 5e3;
6964
+ var RELAY_LANDED_POLL_MS = 1e3;
6965
+ var MAX_LANDED_POLLS = 5;
6455
6966
  function parseMissingRelayIndexError(message) {
6456
6967
  const match = message.match(
6457
6968
  /Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
@@ -6802,6 +7313,33 @@ function parseNkInput(input) {
6802
7313
  }
6803
7314
  return Uint8Array.from(Buffer.from(clean, "hex"));
6804
7315
  }
7316
+ async function resolveWalletNk(options) {
7317
+ const explicit = await resolveChainNoteNk(options);
7318
+ if (explicit) return explicit;
7319
+ if (options.ownerUtxoKeypair) {
7320
+ const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
7321
+ return getNkFromUtxoPrivateKey(owner.privateKey);
7322
+ }
7323
+ return null;
7324
+ }
7325
+ function missingWalletNkError(flow) {
7326
+ return new Error(
7327
+ `${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.`
7328
+ );
7329
+ }
7330
+ async function requireWalletNk(options, flow) {
7331
+ const nk = await resolveWalletNk(options);
7332
+ if (nk) return nk;
7333
+ throw missingWalletNkError(flow);
7334
+ }
7335
+ async function requireOwnerUtxoKeypair(options, flow) {
7336
+ if (!options.ownerUtxoKeypair) {
7337
+ throw new Error(
7338
+ `${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].`
7339
+ );
7340
+ }
7341
+ return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
7342
+ }
6805
7343
  async function resolveChainNoteNk(options) {
6806
7344
  if (options.chainNoteViewingKeyNk) {
6807
7345
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -6819,7 +7357,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
6819
7357
  function toHex(bytes) {
6820
7358
  return Buffer.from(bytes).toString("hex");
6821
7359
  }
6822
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
7360
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
6823
7361
  if (options.enforceViewingKeyRegistration === false) {
6824
7362
  return;
6825
7363
  }
@@ -6833,7 +7371,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6833
7371
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
6834
7372
  );
6835
7373
  }
6836
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
7374
+ const nk = walletNk;
6837
7375
  if (!nk || nk.length !== 32) {
6838
7376
  throw new Error(
6839
7377
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6869,7 +7407,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6869
7407
  headers: { "Content-Type": "application/json" },
6870
7408
  body: JSON.stringify({
6871
7409
  user_pubkey: userPubkey,
6872
- viewing_key: viewingKeyHex
7410
+ viewing_key: viewingKeyHex,
7411
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
6873
7412
  })
6874
7413
  });
6875
7414
  if (!challengeResponse.ok) {
@@ -6916,7 +7455,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6916
7455
  viewing_key: viewingKeyHex,
6917
7456
  nonce: challenge.nonce,
6918
7457
  signature: signatureBase64,
6919
- ...authMode === "transaction" ? { auth_mode: authMode } : {}
7458
+ ...authMode === "transaction" ? { auth_mode: authMode } : {},
7459
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
6920
7460
  })
6921
7461
  });
6922
7462
  if (!response.ok) {
@@ -6975,10 +7515,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6975
7515
  result.set(bigintToBytes323(BigInt(publicSignals[0])), offset);
6976
7516
  offset += 32;
6977
7517
  let amount = BigInt(publicSignals[1]);
6978
- const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6979
- const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
7518
+ const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
7519
+ const HALF_FIELD = FIELD_MODULUS3 / BigInt(2);
6980
7520
  if (amount > HALF_FIELD) {
6981
- amount = amount - FIELD_MODULUS2;
7521
+ amount = amount - FIELD_MODULUS3;
6982
7522
  }
6983
7523
  const amountBytes = new Uint8Array(8);
6984
7524
  let amountValue = amount;
@@ -7925,8 +8465,9 @@ function chargeWalletApproval(used, budget, lastError) {
7925
8465
  }
7926
8466
  return used + 1;
7927
8467
  }
7928
- function relayFailureMessage(prefix, responseText) {
7929
- const explanation = explainRelayAuthRejection(responseText);
8468
+ function relayFailureMessage(prefix, responseText, requestBody) {
8469
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
8470
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7930
8471
  return explanation ? `${prefix}: ${responseText}
7931
8472
 
7932
8473
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -8008,6 +8549,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
8008
8549
  function sleep2(ms) {
8009
8550
  return new Promise((resolve) => setTimeout(resolve, ms));
8010
8551
  }
8552
+ function sleepUnlessAborted(ms, signal) {
8553
+ if (signal?.aborted) return Promise.resolve(false);
8554
+ return new Promise((resolve) => {
8555
+ const onAbort = () => {
8556
+ clearTimeout(timer);
8557
+ resolve(false);
8558
+ };
8559
+ const timer = setTimeout(() => {
8560
+ signal?.removeEventListener("abort", onAbort);
8561
+ resolve(true);
8562
+ }, ms);
8563
+ signal?.addEventListener("abort", onAbort, { once: true });
8564
+ });
8565
+ }
8011
8566
  function hexToBytes2(hex) {
8012
8567
  const bytes = new Uint8Array(hex.length / 2);
8013
8568
  for (let i = 0; i < hex.length; i += 2) {
@@ -8242,6 +8797,9 @@ async function submitTransactToRelay(args) {
8242
8797
  let unknownOutcomeSignature = null;
8243
8798
  let possiblySubmitted = false;
8244
8799
  let networkRetry = 0;
8800
+ let leaseReplays = 0;
8801
+ let landedPolls = 0;
8802
+ let leaseBaseMs = null;
8245
8803
  const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
8246
8804
  connection: settlement.connection,
8247
8805
  programId: settlement.programId,
@@ -8297,6 +8855,7 @@ async function submitTransactToRelay(args) {
8297
8855
  const controller = new AbortController();
8298
8856
  const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
8299
8857
  let response;
8858
+ leaseBaseMs ?? (leaseBaseMs = Date.now());
8300
8859
  try {
8301
8860
  response = await doFetch(`${relayUrl}/transact`, {
8302
8861
  method: "POST",
@@ -8304,6 +8863,7 @@ async function submitTransactToRelay(args) {
8304
8863
  body: requestPayload,
8305
8864
  signal: controller.signal
8306
8865
  });
8866
+ observeRelayClock(response);
8307
8867
  } finally {
8308
8868
  clearTimeout(timeoutId);
8309
8869
  }
@@ -8314,6 +8874,49 @@ async function submitTransactToRelay(args) {
8314
8874
  if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
8315
8875
  possiblySubmitted = true;
8316
8876
  }
8877
+ if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
8878
+ networkRetry = 0;
8879
+ const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
8880
+ const polling = Date.now() < leaseEndsMs;
8881
+ const probe = await verifySettlement(
8882
+ unknownOutcomeSignature,
8883
+ polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
8884
+ );
8885
+ if (probe.status === "landed") {
8886
+ landedPolls++;
8887
+ if (!polling || landedPolls > MAX_LANDED_POLLS) {
8888
+ return await resolveFailure(
8889
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8890
+ );
8891
+ }
8892
+ if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
8893
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8894
+ }
8895
+ continue;
8896
+ }
8897
+ if (polling) {
8898
+ onProgress?.("Relay is still processing this request; checking again shortly...");
8899
+ const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
8900
+ if (!await sleepUnlessAborted(pollMs, args.signal)) {
8901
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8902
+ }
8903
+ continue;
8904
+ }
8905
+ leaseReplays++;
8906
+ const waitMs = Math.max(
8907
+ 0,
8908
+ (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
8909
+ );
8910
+ onProgress?.(
8911
+ `Relay has not confirmed the outcome. Waiting ${Math.ceil(waitMs / 1e3)}s for its request lease to expire, then replaying the identical signed request (${leaseReplays}/${MAX_LEASE_EXPIRY_REPLAYS})...`
8912
+ );
8913
+ if (!await sleepUnlessAborted(waitMs, args.signal)) {
8914
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8915
+ }
8916
+ networkRetry = 0;
8917
+ leaseBaseMs = null;
8918
+ continue;
8919
+ }
8317
8920
  if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
8318
8921
  networkRetry++;
8319
8922
  const delay = relayBackoffMs(networkRetry);
@@ -8334,7 +8937,9 @@ async function submitTransactToRelay(args) {
8334
8937
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
8335
8938
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
8336
8939
  }
8337
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
8940
+ return await resolveFailure(
8941
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8942
+ );
8338
8943
  }
8339
8944
  const apiResponse = JSON.parse(responseText);
8340
8945
  if (!apiResponse.success || !apiResponse.data) {
@@ -8351,7 +8956,7 @@ async function submitTransactToRelay(args) {
8351
8956
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
8352
8957
  }
8353
8958
  return await resolveFailure(
8354
- new Error(relayFailureMessage("Relay returned error", errorStr))
8959
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
8355
8960
  );
8356
8961
  }
8357
8962
  const result = apiResponse.data;
@@ -8459,34 +9064,37 @@ async function transact(params, options) {
8459
9064
  );
8460
9065
  }
8461
9066
  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) {
9067
+ const walletNk = await resolveWalletNk(options);
9068
+ const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
9069
+ if (options.chainNoteSalt !== void 0 && !walletNk) {
8467
9070
  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."
9071
+ "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
9072
  );
8470
9073
  }
8471
9074
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
8472
9075
  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));
9076
+ if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
9077
+ throw missingWalletNkError("transact");
9078
+ }
9079
+ if (walletNk && chainNoteWillCarrySalt) {
9080
+ const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
9081
+ if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
9082
+ const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
8475
9083
  for (let i = 0; i < outputUtxos.length; i++) {
8476
9084
  const out = outputUtxos[i];
8477
9085
  if (!out || out.amount <= BigInt(0)) continue;
8478
- if (!inputOwners.has(out.keypair.publicKey)) continue;
8479
- if (out.blinding !== deriveChangeNoteBlinding(explicitChainNoteNk, chainNoteSalt, i)) {
9086
+ if (!selfOwners.has(out.keypair.publicKey)) continue;
9087
+ if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
8480
9088
  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.`
9089
+ `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
9090
  );
8483
9091
  }
8484
9092
  }
8485
9093
  }
8486
9094
  assertAllowedRpcConnection(connection);
8487
9095
  assertInputMints(inputUtxos, options.expectedMint);
8488
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
8489
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
9096
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
9097
+ const resolvedChainNoteNk = walletNk;
8490
9098
  if (inputUtxos.length > 2) {
8491
9099
  throw new Error("Maximum 2 input UTXOs allowed");
8492
9100
  }
@@ -8860,7 +9468,7 @@ async function transact(params, options) {
8860
9468
  }
8861
9469
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
8862
9470
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
8863
- const chainNoteTimestamp = BigInt(Date.now());
9471
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
8864
9472
  const mintField = pubkeyToFieldElement(mint);
8865
9473
  let signature = "pending-" + Date.now().toString();
8866
9474
  let commitmentIndices = [-1, -1];
@@ -8956,9 +9564,9 @@ async function transact(params, options) {
8956
9564
  ]));
8957
9565
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8958
9566
  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()}`);
9567
+ const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
9568
+ if (chainNoteHash >= FIELD_MODULUS3) {
9569
+ throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS3.toString()}`);
8962
9570
  }
8963
9571
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8964
9572
  const totalInputs = 1 + // root
@@ -9380,7 +9988,8 @@ async function transact(params, options) {
9380
9988
  throw lastError;
9381
9989
  }
9382
9990
  const classified = classifyRelayError(lastError.message);
9383
- const isMerkleClass = !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9991
+ const isDepositSubmission = externalAmount > BigInt(0);
9992
+ const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9384
9993
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
9385
9994
  onProgress?.(
9386
9995
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -9529,54 +10138,83 @@ async function transact(params, options) {
9529
10138
  };
9530
10139
  }
9531
10140
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
10141
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
10142
+ const transferNk = await requireWalletNk(options, "transfer");
9532
10143
  const inputSum = sumUtxoAmounts(inputUtxos);
9533
10144
  if (inputSum < amount) {
9534
10145
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
9535
10146
  }
9536
10147
  const change = inputSum - amount;
9537
- const myKeypair = inputUtxos[0].keypair;
9538
10148
  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);
10149
+ let spendInputs = [
10150
+ ...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
10151
+ ...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
10152
+ ];
10153
+ let spendOptions = options;
10154
+ if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
10155
+ if (spendInputs.length > 2) {
10156
+ throw new Error(
10157
+ `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.`
10158
+ );
10159
+ }
10160
+ if (options.relayAuthBatch) {
10161
+ throw new Error(
10162
+ "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."
10163
+ );
10164
+ }
10165
+ options.onProgress?.("Moving notes under the wallet key before the transfer...");
10166
+ const migrationSalt = randomChangeNoteSalt();
10167
+ const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
10168
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
10169
+ void _recipientViewingPublicKey;
10170
+ const migration = await transact(
10171
+ { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
10172
+ { ...migrationOptions, chainNoteSalt: migrationSalt }
10173
+ );
10174
+ const migratedNote = migration.outputUtxos?.[0] ?? migrated;
10175
+ if (migration.commitmentIndices?.[0] >= 0) {
10176
+ migratedNote.index = migration.commitmentIndices[0];
10177
+ }
10178
+ spendInputs = [migratedNote];
10179
+ spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
10180
+ }
10181
+ const changeNoteSalt = randomChangeNoteSalt();
10182
+ const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
9542
10183
  const recipientKeypair = {
9543
10184
  privateKey: BigInt(0),
9544
10185
  // Recipient's private key unknown
9545
10186
  publicKey: recipientPubkey
9546
10187
  };
9547
- const recipientUtxo = transferNk && isSendToSelf ? (await createRecoverableChangeUtxo(amount, myKeypair, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
10188
+ const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
9548
10189
  const outputUtxos = [recipientUtxo];
9549
10190
  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
- }
10191
+ const { utxo } = await createRecoverableChangeUtxo(
10192
+ change,
10193
+ owner,
10194
+ transferNk,
10195
+ mint,
10196
+ changeNoteSalt,
10197
+ 1
10198
+ );
10199
+ outputUtxos.push(utxo);
9563
10200
  }
9564
10201
  return transact(
9565
10202
  {
9566
- inputUtxos,
10203
+ inputUtxos: spendInputs,
9567
10204
  outputUtxos,
9568
10205
  externalAmount: BigInt(0)
9569
10206
  // Pure shield-to-shield
9570
10207
  },
9571
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
10208
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
9572
10209
  );
9573
10210
  }
9574
10211
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
10212
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
10213
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
9575
10214
  const inputSum = sumUtxoAmounts(inputUtxos);
9576
10215
  if (inputSum < withdrawAmount) {
9577
10216
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
9578
10217
  }
9579
- const myKeypair = inputUtxos[0].keypair;
9580
10218
  const mint = inputUtxos[0].mintAddress;
9581
10219
  let utxos = [...inputUtxos];
9582
10220
  let cachedTree = options.cachedMerkleTree;
@@ -9585,9 +10223,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9585
10223
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
9586
10224
  const [small1, small2, ...rest] = utxos;
9587
10225
  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);
10226
+ const mergeSalt = randomChangeNoteSalt();
10227
+ const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
9591
10228
  const mergeResult = await transact(
9592
10229
  {
9593
10230
  inputUtxos: [small1, small2],
@@ -9598,7 +10235,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9598
10235
  {
9599
10236
  ...options,
9600
10237
  cachedMerkleTree: cachedTree,
9601
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
10238
+ chainNoteSalt: mergeSalt
9602
10239
  }
9603
10240
  );
9604
10241
  cachedTree = mergeResult.merkleTree;
@@ -9613,23 +10250,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9613
10250
  const outputUtxos = [];
9614
10251
  let changeNoteSalt;
9615
10252
  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
- }
10253
+ const salt = randomChangeNoteSalt();
10254
+ const { utxo } = await createRecoverableChangeUtxo(
10255
+ change,
10256
+ owner,
10257
+ walletNk,
10258
+ mint,
10259
+ salt,
10260
+ 0
10261
+ // partialWithdraw puts change at output 0
10262
+ );
10263
+ outputUtxos.push(utxo);
10264
+ changeNoteSalt = salt;
9633
10265
  }
9634
10266
  return transact(
9635
10267
  {
@@ -9752,6 +10384,8 @@ async function swapUtxo(params, options) {
9752
10384
  if (relayUrl) {
9753
10385
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
9754
10386
  }
10387
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
10388
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
9755
10389
  if (inputUtxos.length === 0) {
9756
10390
  throw new Error("At least one input UTXO required");
9757
10391
  }
@@ -9777,15 +10411,12 @@ async function swapUtxo(params, options) {
9777
10411
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
9778
10412
  }
9779
10413
  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;
10414
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
9784
10415
  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)) {
10416
+ if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
10417
+ if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
9787
10418
  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.`
10419
+ `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
10420
  );
9790
10421
  }
9791
10422
  }
@@ -9809,24 +10440,18 @@ async function swapUtxo(params, options) {
9809
10440
  );
9810
10441
  }
9811
10442
  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
- }
10443
+ const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
10444
+ const refundAuthorization = await deriveSwapRefundAuthorization(
10445
+ resolvedSwapChainNoteNk,
10446
+ refundNullifier,
10447
+ swapOwner
10448
+ );
10449
+ const refundKeypair = {
10450
+ privateKey: refundAuthorization.privateKey,
10451
+ publicKey: refundAuthorization.publicKey
10452
+ };
10453
+ const refundBlinding = refundAuthorization.blinding;
10454
+ const refundDerivedFromNk = true;
9830
10455
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
9831
10456
  throw new Error(
9832
10457
  "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 +10777,7 @@ async function swapUtxo(params, options) {
10152
10777
  for (const utxo of paddedOutputs) {
10153
10778
  outputCommitments.push(await computeCommitment2(utxo));
10154
10779
  }
10155
- const chainNoteTimestamp = BigInt(Date.now());
10780
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
10156
10781
  onProgress?.("Computing external data hash...");
10157
10782
  const mint = swapPoolMint;
10158
10783
  const mintField = pubkeyToFieldElement(mint);
@@ -10466,7 +11091,7 @@ async function swapUtxo(params, options) {
10466
11091
  forceChainIndexing = !relayUrl;
10467
11092
  continue;
10468
11093
  }
10469
- throw new Error(relayFailureMessage("Relay error", responseText));
11094
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
10470
11095
  }
10471
11096
  const apiResponse = JSON.parse(responseText);
10472
11097
  if (!apiResponse.success || !apiResponse.data) {
@@ -10602,7 +11227,6 @@ async function swapUtxo(params, options) {
10602
11227
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
10603
11228
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
10604
11229
  refund: {
10605
- privateKey: Buffer.from(bigintToBytes323(refundKeypair.privateKey)).toString("hex"),
10606
11230
  publicKey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("hex"),
10607
11231
  blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("hex"),
10608
11232
  derivedFromNk: refundDerivedFromNk
@@ -10610,6 +11234,7 @@ async function swapUtxo(params, options) {
10610
11234
  };
10611
11235
  }
10612
11236
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
11237
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
10613
11238
  const totalInput = sumUtxoAmounts(inputUtxos);
10614
11239
  const change = totalInput - swapAmount;
10615
11240
  if (change < BigInt(0)) {
@@ -10618,16 +11243,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
10618
11243
  let changeUtxo;
10619
11244
  let changeNoteSalt;
10620
11245
  if (change > BigInt(0)) {
10621
- const myKeypair = inputUtxos[0].keypair;
10622
11246
  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
- }
11247
+ const changeNk = await requireWalletNk(options, "swapWithChange");
11248
+ const salt = randomChangeNoteSalt();
11249
+ changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
11250
+ changeNoteSalt = salt;
10631
11251
  }
10632
11252
  return swapUtxo(
10633
11253
  {
@@ -10953,7 +11573,7 @@ var RelayBatchAuthCoordinator = class {
10953
11573
  throw new Error("Every item of a batch must target the same program id.");
10954
11574
  }
10955
11575
  }
10956
- const nowSeconds = Math.floor(Date.now() / 1e3);
11576
+ const nowSeconds = relayNowSeconds();
10957
11577
  const preimages = waiting.map(
10958
11578
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10959
11579
  );
@@ -11394,7 +12014,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
11394
12014
  const cached = depositSecretsCache.get(key);
11395
12015
  if (cached) return cached;
11396
12016
  try {
11397
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
12017
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
11398
12018
  if (depositSecretsCache.size >= 4096) {
11399
12019
  const oldest = depositSecretsCache.keys().next();
11400
12020
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11977,6 +12597,7 @@ async function scanTransactions(opts) {
11977
12597
  } else {
11978
12598
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11979
12599
  const candidateKeys = [
12600
+ opts.ownerUtxoPublicKey,
11980
12601
  derived?.keypair.publicKey,
11981
12602
  opts.ownUtxoPublicKey,
11982
12603
  BigInt(0)
@@ -12030,6 +12651,7 @@ async function scanTransactions(opts) {
12030
12651
  try {
12031
12652
  const recoveredDeposit = await matchDepositNote({
12032
12653
  viewingKeyNk,
12654
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
12033
12655
  noteSalt: compactNote.noteSalt,
12034
12656
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
12035
12657
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -12064,7 +12686,8 @@ async function scanTransactions(opts) {
12064
12686
  mintAddress: (0, import_kit.address)(asset.mint),
12065
12687
  outputIndex: 0,
12066
12688
  // v4 describes output 0, which is where change lands
12067
- outputCommitments: ixCtx.outputCommitments ?? []
12689
+ outputCommitments: ixCtx.outputCommitments ?? [],
12690
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
12068
12691
  });
12069
12692
  if (recoveredChange) {
12070
12693
  recoveredChangeNotes.push({
@@ -12174,6 +12797,17 @@ async function scanTransactions(opts) {
12174
12797
  runningByAsset.set(key, running);
12175
12798
  tx.runningBalance = running;
12176
12799
  }
12800
+ const legacyKeys = /* @__PURE__ */ new Map();
12801
+ for (const note of recoveredDepositNotes) {
12802
+ if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
12803
+ }
12804
+ for (const change of recoveredChangeNotes) {
12805
+ const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
12806
+ if (legacyPrivateKey !== void 0) {
12807
+ change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
12808
+ change.legacyExposed = true;
12809
+ }
12810
+ }
12177
12811
  return {
12178
12812
  transactions: txs,
12179
12813
  summary: {
@@ -12253,6 +12887,1638 @@ function formatComplianceCsv(report) {
12253
12887
  return header + rows;
12254
12888
  }
12255
12889
 
12890
+ // src/relay/note-index-format.ts
12891
+ var import_sha25 = require("@noble/hashes/sha2");
12892
+ init_address();
12893
+ init_utxo();
12894
+ var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
12895
+ var NOTE_INDEX_FORMAT_VERSION = 1;
12896
+ var NOTE_INDEX_PAGE_SIZE = 1024;
12897
+ var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
12898
+ var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
12899
+ var NOTE_INDEX_HEADER_LEN = 68;
12900
+ var NOTE_INDEX_KIND_TX = 1;
12901
+ var NOTE_INDEX_KIND_DELIVERY = 2;
12902
+ var NOTE_INDEX_KIND_SWAP_REFUND = 3;
12903
+ var NOTE_SOURCE_NONE = 0;
12904
+ var NOTE_SOURCE_CARRIER = 2;
12905
+ var ITEM_HEADER_LEN = 3;
12906
+ var TX_FIXED_LEN = 263;
12907
+ var DELIVERY_BODY_LEN = 256;
12908
+ var SWAP_REFUND_BODY_LEN = 184;
12909
+ var MAX_UNKNOWN_BODY_LEN = 1024;
12910
+ var DELIVERY_ENVELOPE_LEN = 112;
12911
+ var SIGNATURE_LEN = 64;
12912
+ var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
12913
+ [25, 2],
12914
+ [57, 3],
12915
+ [98, 4]
12916
+ ]);
12917
+ var COMPLETE_FLAG = 1;
12918
+ var U64_MAX2 = (1n << 64n) - 1n;
12919
+ var U32_MAX = 4294967295;
12920
+ var MAX_LEAF_INDEX = (1n << 32n) - 1n;
12921
+ var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
12922
+ var NoteIndexFormatError = class extends Error {
12923
+ constructor(message) {
12924
+ super(`Note index format error: ${message}`);
12925
+ this.name = "NoteIndexFormatError";
12926
+ }
12927
+ };
12928
+ function isAllZero2(bytes) {
12929
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12930
+ return true;
12931
+ }
12932
+ function bytesEqual(a, b) {
12933
+ if (a.length !== b.length) return false;
12934
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
12935
+ return true;
12936
+ }
12937
+ function checkLeafPair(commitment, leaf, label) {
12938
+ if (isAllZero2(commitment)) {
12939
+ if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
12940
+ return;
12941
+ }
12942
+ if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
12943
+ }
12944
+ var Reader = class {
12945
+ constructor(bytes, start, end) {
12946
+ this.bytes = bytes;
12947
+ this.end = end;
12948
+ this.offset = start;
12949
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12950
+ }
12951
+ take(len) {
12952
+ if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
12953
+ const at = this.offset;
12954
+ this.offset += len;
12955
+ return at;
12956
+ }
12957
+ u8() {
12958
+ return this.bytes[this.take(1)];
12959
+ }
12960
+ u32() {
12961
+ return this.view.getUint32(this.take(4), true);
12962
+ }
12963
+ u64() {
12964
+ return this.view.getBigUint64(this.take(8), true);
12965
+ }
12966
+ i64() {
12967
+ return this.view.getBigInt64(this.take(8), true);
12968
+ }
12969
+ raw(len) {
12970
+ const at = this.take(len);
12971
+ return this.bytes.slice(at, at + len);
12972
+ }
12973
+ get position() {
12974
+ return this.offset;
12975
+ }
12976
+ };
12977
+ function parseTx(r, bodyLen) {
12978
+ const mint = r.raw(32);
12979
+ const slot = r.u64();
12980
+ const blockPos = r.u32();
12981
+ const ixTag = r.u8();
12982
+ if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
12983
+ const publicAmount = r.i64();
12984
+ const nullifier0 = r.raw(32);
12985
+ const nullifier1 = r.raw(32);
12986
+ const comm0 = r.raw(32);
12987
+ const leaf0 = r.u64();
12988
+ const comm1 = r.raw(32);
12989
+ const leaf1 = r.u64();
12990
+ const noteSource = r.u8();
12991
+ if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
12992
+ const noteLen = r.u8();
12993
+ if (noteSource === NOTE_SOURCE_NONE) {
12994
+ if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
12995
+ } else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
12996
+ throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
12997
+ }
12998
+ if (bodyLen !== TX_FIXED_LEN + noteLen) {
12999
+ throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
13000
+ }
13001
+ const note = r.raw(noteLen);
13002
+ if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
13003
+ throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
13004
+ }
13005
+ const signature = r.raw(SIGNATURE_LEN);
13006
+ checkLeafPair(comm0, leaf0, "TX comm0");
13007
+ checkLeafPair(comm1, leaf1, "TX comm1");
13008
+ return {
13009
+ kind: 1,
13010
+ mint,
13011
+ slot,
13012
+ blockPos,
13013
+ ixTag,
13014
+ publicAmount,
13015
+ nullifier0,
13016
+ nullifier1,
13017
+ comm0,
13018
+ leaf0,
13019
+ comm1,
13020
+ leaf1,
13021
+ noteSource,
13022
+ note,
13023
+ signature
13024
+ };
13025
+ }
13026
+ function parseDelivery(r) {
13027
+ const mint = r.raw(32);
13028
+ const slot = r.u64();
13029
+ const commitment = r.raw(32);
13030
+ const leaf = r.u64();
13031
+ const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
13032
+ const signature = r.raw(SIGNATURE_LEN);
13033
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
13034
+ checkLeafPair(commitment, leaf, "DELIVERY");
13035
+ return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
13036
+ }
13037
+ function parseSwapRefund(r) {
13038
+ const mint = r.raw(32);
13039
+ if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
13040
+ const slot = r.u64();
13041
+ const commitment = r.raw(32);
13042
+ const leaf = r.u64();
13043
+ const amountAfterFee = r.u64();
13044
+ const nullifier0 = r.raw(32);
13045
+ const signature = r.raw(SIGNATURE_LEN);
13046
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
13047
+ checkLeafPair(commitment, leaf, "SWAP_REFUND");
13048
+ return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
13049
+ }
13050
+ function parseNoteIndexPage(bytes, expect, options = {}) {
13051
+ if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
13052
+ if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
13053
+ throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
13054
+ }
13055
+ if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
13056
+ for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
13057
+ if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
13058
+ }
13059
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
13060
+ const version = bytes[4];
13061
+ if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
13062
+ const flags = bytes[5];
13063
+ if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
13064
+ if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
13065
+ const epoch = view.getBigUint64(8, true);
13066
+ const page = view.getBigUint64(16, true);
13067
+ const firstSeq = view.getBigUint64(24, true);
13068
+ const count = view.getUint32(32, true);
13069
+ const prevChain = bytes.slice(36, 68);
13070
+ const complete = (flags & COMPLETE_FLAG) !== 0;
13071
+ if (expect) {
13072
+ if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
13073
+ if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
13074
+ }
13075
+ if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
13076
+ if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
13077
+ if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
13078
+ throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
13079
+ }
13080
+ const items = [];
13081
+ const rawItems = [];
13082
+ const itemPositions = [];
13083
+ let skippedUnknown = 0;
13084
+ let skippedMalformed = 0;
13085
+ let offset = NOTE_INDEX_HEADER_LEN;
13086
+ for (let i = 0; i < count; i++) {
13087
+ if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
13088
+ const kind = bytes[offset];
13089
+ const bodyLen = view.getUint16(offset + 1, true);
13090
+ const bodyStart = offset + ITEM_HEADER_LEN;
13091
+ const bodyEnd = bodyStart + bodyLen;
13092
+ if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
13093
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
13094
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
13095
+ skippedUnknown++;
13096
+ offset = bodyEnd;
13097
+ continue;
13098
+ }
13099
+ let item;
13100
+ try {
13101
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
13102
+ } catch (error) {
13103
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
13104
+ skippedMalformed++;
13105
+ offset = bodyEnd;
13106
+ continue;
13107
+ }
13108
+ items.push(item);
13109
+ rawItems.push(bytes.slice(offset, bodyEnd));
13110
+ itemPositions.push(i);
13111
+ offset = bodyEnd;
13112
+ }
13113
+ if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
13114
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
13115
+ }
13116
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
13117
+ const bodyLen = bodyEnd - bodyStart;
13118
+ const r = new Reader(bytes, bodyStart, bodyEnd);
13119
+ let item;
13120
+ if (kind === NOTE_INDEX_KIND_TX) {
13121
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
13122
+ item = parseTx(r, bodyLen);
13123
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
13124
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
13125
+ item = parseDelivery(r);
13126
+ } else {
13127
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
13128
+ item = parseSwapRefund(r);
13129
+ }
13130
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
13131
+ return item;
13132
+ }
13133
+ function parseNoteIndexItem(raw) {
13134
+ if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
13135
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
13136
+ const kind = raw[0];
13137
+ const bodyLen = view.getUint16(1, true);
13138
+ if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
13139
+ const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
13140
+ let item;
13141
+ if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
13142
+ else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
13143
+ else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
13144
+ else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
13145
+ if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
13146
+ return item;
13147
+ }
13148
+ function computeNoteIndexChain(prevChain, pageBytes) {
13149
+ if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
13150
+ if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
13151
+ const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
13152
+ const input = new Uint8Array(32 + items.length);
13153
+ input.set(prevChain);
13154
+ input.set(items, 32);
13155
+ return (0, import_sha25.sha256)(input);
13156
+ }
13157
+ var Writer = class {
13158
+ constructor() {
13159
+ this.chunks = [];
13160
+ this.length = 0;
13161
+ }
13162
+ push(bytes) {
13163
+ this.chunks.push(bytes);
13164
+ this.length += bytes.length;
13165
+ }
13166
+ u8(v) {
13167
+ if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
13168
+ this.push(Uint8Array.of(v));
13169
+ }
13170
+ u16(v) {
13171
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
13172
+ const b = new Uint8Array(2);
13173
+ new DataView(b.buffer).setUint16(0, v, true);
13174
+ this.push(b);
13175
+ }
13176
+ u32(v) {
13177
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
13178
+ const b = new Uint8Array(4);
13179
+ new DataView(b.buffer).setUint32(0, v, true);
13180
+ this.push(b);
13181
+ }
13182
+ u64(v) {
13183
+ if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
13184
+ const b = new Uint8Array(8);
13185
+ new DataView(b.buffer).setBigUint64(0, v, true);
13186
+ this.push(b);
13187
+ }
13188
+ i64(v) {
13189
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
13190
+ const b = new Uint8Array(8);
13191
+ new DataView(b.buffer).setBigInt64(0, v, true);
13192
+ this.push(b);
13193
+ }
13194
+ fixed(bytes, len, label) {
13195
+ if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
13196
+ this.push(bytes);
13197
+ }
13198
+ finish() {
13199
+ const out = new Uint8Array(this.length);
13200
+ let off = 0;
13201
+ for (const c of this.chunks) {
13202
+ out.set(c, off);
13203
+ off += c.length;
13204
+ }
13205
+ return out;
13206
+ }
13207
+ };
13208
+ function encodeItemBody(item) {
13209
+ const w = new Writer();
13210
+ switch (item.kind) {
13211
+ case NOTE_INDEX_KIND_TX: {
13212
+ w.fixed(item.mint, 32, "mint");
13213
+ w.u64(item.slot);
13214
+ w.u32(item.blockPos);
13215
+ w.u8(item.ixTag);
13216
+ w.i64(item.publicAmount);
13217
+ w.fixed(item.nullifier0, 32, "nullifier0");
13218
+ w.fixed(item.nullifier1, 32, "nullifier1");
13219
+ w.fixed(item.comm0, 32, "comm0");
13220
+ w.u64(item.leaf0);
13221
+ w.fixed(item.comm1, 32, "comm1");
13222
+ w.u64(item.leaf1);
13223
+ w.u8(item.noteSource);
13224
+ const noteLen = item.note.length;
13225
+ if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
13226
+ throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
13227
+ }
13228
+ w.u8(noteLen);
13229
+ w.push(item.note);
13230
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13231
+ break;
13232
+ }
13233
+ case NOTE_INDEX_KIND_DELIVERY:
13234
+ w.fixed(item.mint, 32, "mint");
13235
+ w.u64(item.slot);
13236
+ w.fixed(item.commitment, 32, "commitment");
13237
+ w.u64(item.leaf);
13238
+ w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
13239
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13240
+ break;
13241
+ case NOTE_INDEX_KIND_SWAP_REFUND:
13242
+ w.fixed(item.mint, 32, "mint");
13243
+ w.u64(item.slot);
13244
+ w.fixed(item.commitment, 32, "commitment");
13245
+ w.u64(item.leaf);
13246
+ w.u64(item.amountAfterFee);
13247
+ w.fixed(item.nullifier0, 32, "nullifier0");
13248
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13249
+ break;
13250
+ default:
13251
+ throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
13252
+ }
13253
+ return w.finish();
13254
+ }
13255
+ function encodeNoteIndexItem(item) {
13256
+ const body = encodeItemBody(item);
13257
+ const w = new Writer();
13258
+ w.u8(item.kind);
13259
+ w.u16(body.length);
13260
+ w.push(body);
13261
+ return w.finish();
13262
+ }
13263
+ function encodeNoteIndexPage(params) {
13264
+ const items = params.items ?? [];
13265
+ if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
13266
+ const w = new Writer();
13267
+ w.push(NOTE_INDEX_MAGIC);
13268
+ w.u8(NOTE_INDEX_FORMAT_VERSION);
13269
+ w.u8(params.complete ? COMPLETE_FLAG : 0);
13270
+ w.u16(0);
13271
+ w.u64(BigInt(params.epoch));
13272
+ w.u64(BigInt(params.page));
13273
+ w.u64(BigInt(params.firstSeq));
13274
+ w.u32(items.length);
13275
+ w.fixed(params.prevChain, 32, "prevChain");
13276
+ for (const item of items) w.push(encodeNoteIndexItem(item));
13277
+ return w.finish();
13278
+ }
13279
+
13280
+ // src/relay/note-index-client.ts
13281
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
13282
+ var DEFAULT_MAX_RETRIES2 = 3;
13283
+ var RETRY_BASE_DELAY_MS = 500;
13284
+ var U64_MAX3 = (1n << 64n) - 1n;
13285
+ function joinPath(relayUrl, path) {
13286
+ const url = new URL(relayUrl);
13287
+ url.pathname = url.pathname.replace(/\/$/, "") + path;
13288
+ return url;
13289
+ }
13290
+ function abortError() {
13291
+ const error = new Error("Note index request aborted");
13292
+ error.name = "AbortError";
13293
+ return error;
13294
+ }
13295
+ function sleep4(ms, signal) {
13296
+ return new Promise((resolve, reject) => {
13297
+ if (signal?.aborted) return reject(abortError());
13298
+ const timer = setTimeout(() => {
13299
+ signal?.removeEventListener("abort", onAbort);
13300
+ resolve();
13301
+ }, ms);
13302
+ const onAbort = () => {
13303
+ clearTimeout(timer);
13304
+ reject(abortError());
13305
+ };
13306
+ signal?.addEventListener("abort", onAbort, { once: true });
13307
+ });
13308
+ }
13309
+ var RetryableStatusError = class extends Error {
13310
+ };
13311
+ var HttpStatusError = class extends Error {
13312
+ constructor(status, message) {
13313
+ super(message);
13314
+ this.status = status;
13315
+ this.name = "HttpStatusError";
13316
+ }
13317
+ };
13318
+ async function requestWithRetry(url, options, read) {
13319
+ assertAllowedRelayOrigin(url);
13320
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
13321
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
13322
+ let lastError;
13323
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
13324
+ if (options.signal?.aborted) throw abortError();
13325
+ const controller = new AbortController();
13326
+ const onAbort = () => controller.abort();
13327
+ options.signal?.addEventListener("abort", onAbort, { once: true });
13328
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
13329
+ try {
13330
+ const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
13331
+ if (response.status === 429 || response.status >= 500) {
13332
+ throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
13333
+ }
13334
+ return await read(response, controller.signal);
13335
+ } catch (error) {
13336
+ if (options.signal?.aborted) throw abortError();
13337
+ const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
13338
+ if (!retryable || attempt >= maxRetries) throw error;
13339
+ lastError = error;
13340
+ await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
13341
+ } finally {
13342
+ clearTimeout(timer);
13343
+ options.signal?.removeEventListener("abort", onAbort);
13344
+ }
13345
+ }
13346
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
13347
+ }
13348
+ async function readBoundedBody(response, maxBytes) {
13349
+ const declaredHeader = response.headers?.get?.("content-length") ?? null;
13350
+ const declared = declaredHeader === null ? NaN : Number(declaredHeader);
13351
+ if (Number.isFinite(declared) && declared > maxBytes) {
13352
+ throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
13353
+ }
13354
+ const reader = response.body?.getReader?.();
13355
+ if (!reader) {
13356
+ const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
13357
+ if (!Number.isSafeInteger(declared) || declared < 0) {
13358
+ throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
13359
+ }
13360
+ if (encoding !== "" && encoding !== "identity") {
13361
+ throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
13362
+ }
13363
+ const buffer = new Uint8Array(await response.arrayBuffer());
13364
+ if (buffer.length > maxBytes || buffer.length !== declared) {
13365
+ throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
13366
+ }
13367
+ return buffer;
13368
+ }
13369
+ const chunks = [];
13370
+ let total = 0;
13371
+ for (; ; ) {
13372
+ const { done, value } = await reader.read();
13373
+ if (done) break;
13374
+ total += value.length;
13375
+ if (total > maxBytes) {
13376
+ await reader.cancel().catch(() => void 0);
13377
+ throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
13378
+ }
13379
+ chunks.push(value);
13380
+ }
13381
+ const out = new Uint8Array(total);
13382
+ let off = 0;
13383
+ for (const c of chunks) {
13384
+ out.set(c, off);
13385
+ off += c.length;
13386
+ }
13387
+ return out;
13388
+ }
13389
+ function isNonNegativeSafeInteger(value) {
13390
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
13391
+ }
13392
+ async function fetchNoteIndexHead(relayUrl, options = {}) {
13393
+ const url = joinPath(relayUrl, "/note-index/v1/head").toString();
13394
+ const raw = await requestWithRetry(url, options, async (response) => {
13395
+ if (!response.ok) {
13396
+ throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
13397
+ }
13398
+ const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
13399
+ try {
13400
+ return JSON.parse(text);
13401
+ } catch {
13402
+ throw new NoteIndexFormatError("head is not JSON");
13403
+ }
13404
+ });
13405
+ if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
13406
+ if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
13407
+ throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
13408
+ }
13409
+ if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
13410
+ throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
13411
+ }
13412
+ if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
13413
+ throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
13414
+ }
13415
+ if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
13416
+ throw new NoteIndexFormatError(
13417
+ `complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
13418
+ );
13419
+ }
13420
+ if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
13421
+ throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
13422
+ }
13423
+ if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
13424
+ throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
13425
+ }
13426
+ return {
13427
+ format: 1,
13428
+ epoch: BigInt(raw.epoch),
13429
+ pageSize: NOTE_INDEX_PAGE_SIZE,
13430
+ watermark: raw.watermark,
13431
+ completePages: raw.complete_pages,
13432
+ chainTip: raw.chain_tip.toLowerCase()
13433
+ };
13434
+ }
13435
+ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
13436
+ if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
13437
+ if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
13438
+ const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
13439
+ return requestWithRetry(url, options, async (response) => {
13440
+ if (!response.ok) {
13441
+ throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
13442
+ }
13443
+ return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
13444
+ });
13445
+ }
13446
+
13447
+ // src/scanning/note-index.ts
13448
+ var import_bs584 = __toESM(require("bs58"), 1);
13449
+ var import_sha26 = require("@noble/hashes/sha2");
13450
+ init_address();
13451
+ init_utxo();
13452
+ var bs584 = import_bs584.default.default || import_bs584.default;
13453
+ var CURSOR_VERSION = 2;
13454
+ var DEFAULT_CONCURRENCY = 6;
13455
+ var MAX_CONCURRENCY = 32;
13456
+ var ITEM_BATCH = 64;
13457
+ var CURSOR_PAGE_ALIGN = 8;
13458
+ var MAX_PERSISTED_PENDING_LEAVES = 4096;
13459
+ var MAX_CARRIED_PENDING = 256;
13460
+ var MAX_REJECTED_IDS = 1024;
13461
+ var LEAF_WINDOW = 512;
13462
+ var MAX_OVERRIDES = 256;
13463
+ var MAX_CURSOR_OWN_ITEMS = 65536;
13464
+ var MAX_LEGACY_VIEWING_KEYS = 8;
13465
+ var MAX_CURSOR_KEYS = 131072;
13466
+ var MAX_CURSOR_POOLS = 256;
13467
+ var MAX_CURSOR_PAGE = 2 ** 32;
13468
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
13469
+ var ZERO_CHAIN = "00".repeat(32);
13470
+ var U64_MAX4 = (1n << 64n) - 1n;
13471
+ var NoteIndexHeadBehindError = class extends Error {
13472
+ constructor(cursorWatermark, headWatermark) {
13473
+ super(
13474
+ `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`
13475
+ );
13476
+ this.cursorWatermark = cursorWatermark;
13477
+ this.headWatermark = headWatermark;
13478
+ this.retryable = true;
13479
+ this.name = "NoteIndexHeadBehindError";
13480
+ }
13481
+ };
13482
+ var FullPassSignal = class {
13483
+ constructor(reason) {
13484
+ this.reason = reason;
13485
+ }
13486
+ };
13487
+ function abortError2() {
13488
+ const error = new Error("recoverNotesFromIndex aborted");
13489
+ error.name = "AbortError";
13490
+ return error;
13491
+ }
13492
+ function bytesToBigint3(bytes) {
13493
+ let v = 0n;
13494
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
13495
+ return v;
13496
+ }
13497
+ function toHex2(bytes) {
13498
+ let s = "";
13499
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
13500
+ return s;
13501
+ }
13502
+ function fromHex(hex) {
13503
+ return Uint8Array.from(Buffer.from(hex, "hex"));
13504
+ }
13505
+ function hex32(v) {
13506
+ return v.toString(16).padStart(64, "0");
13507
+ }
13508
+ function isAllZero3(bytes) {
13509
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
13510
+ return true;
13511
+ }
13512
+ function floorAlign(page) {
13513
+ return page - page % CURSOR_PAGE_ALIGN;
13514
+ }
13515
+ function verifiedKey(mint, leaf, commitment) {
13516
+ return `${mint}:${leaf}:${hex32(commitment)}`;
13517
+ }
13518
+ function itemIdentity(raw) {
13519
+ return toHex2((0, import_sha26.sha256)(raw).subarray(0, 16));
13520
+ }
13521
+ var LeafBuffer = class {
13522
+ constructor() {
13523
+ this.bytes = new Uint8Array(32 * 1024);
13524
+ this.view = new DataView(this.bytes.buffer);
13525
+ this.count = 0;
13526
+ }
13527
+ get length() {
13528
+ return this.count;
13529
+ }
13530
+ push(values) {
13531
+ const need = (this.count + values.length) * 32;
13532
+ if (need > this.bytes.length) {
13533
+ let size = this.bytes.length;
13534
+ while (size < need) size *= 2;
13535
+ const next = new Uint8Array(size);
13536
+ next.set(this.bytes.subarray(0, this.count * 32));
13537
+ this.bytes = next;
13538
+ this.view = new DataView(next.buffer);
13539
+ }
13540
+ for (const v of values) {
13541
+ const o = this.count * 32;
13542
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
13543
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
13544
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
13545
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
13546
+ this.count++;
13547
+ }
13548
+ }
13549
+ get(i) {
13550
+ if (i < 0 || i >= this.count) return void 0;
13551
+ const o = i * 32;
13552
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
13553
+ }
13554
+ };
13555
+ async function trialItem(item, trials) {
13556
+ for (const trial of trials) {
13557
+ if (trial.legacy && item.kind === 2) continue;
13558
+ const opened = await trialItemWith(item, trial);
13559
+ if (opened) return { ...opened, trial };
13560
+ }
13561
+ return null;
13562
+ }
13563
+ async function trialItemIsolated(item, trials, stats) {
13564
+ try {
13565
+ return await trialItem(item, trials);
13566
+ } catch {
13567
+ stats.skipped++;
13568
+ return null;
13569
+ }
13570
+ }
13571
+ async function trialItemWith(item, trial) {
13572
+ if (item.kind === 1) {
13573
+ if (item.note.length === 0) return null;
13574
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
13575
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
13576
+ return note ? { note } : null;
13577
+ }
13578
+ if (item.kind === 2) {
13579
+ const delivery = await trial.open(item.envelope);
13580
+ return delivery ? { delivery } : null;
13581
+ }
13582
+ if (item.amountAfterFee === 0n) return null;
13583
+ const refund = await matchSwapRefundLeaf({
13584
+ viewingKeyNk: trial.nk,
13585
+ inputNullifier: item.nullifier0,
13586
+ amountAfterFee: item.amountAfterFee,
13587
+ commitment: item.commitment,
13588
+ ownerUtxoKeypair: trial.owner
13589
+ });
13590
+ return refund ? { refund } : null;
13591
+ }
13592
+ function txOutputs(item) {
13593
+ const out = [toHex2(item.comm0)];
13594
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
13595
+ return out;
13596
+ }
13597
+ function leafOfTxOutput(item, commitment) {
13598
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint3(item.comm0)) return Number(item.leaf0);
13599
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
13600
+ return null;
13601
+ }
13602
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
13603
+ try {
13604
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
13605
+ } catch {
13606
+ return null;
13607
+ }
13608
+ }
13609
+ async function matchOwnItems(own, owner, onReject, onSkip) {
13610
+ const candidates = [];
13611
+ const claimed = /* @__PURE__ */ new Set();
13612
+ const byNullifier = /* @__PURE__ */ new Map();
13613
+ const legacyKeys = /* @__PURE__ */ new Map();
13614
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
13615
+ const spendsOf = /* @__PURE__ */ new Map();
13616
+ const byOutKey = /* @__PURE__ */ new Map();
13617
+ const index = (map, key, o) => {
13618
+ const list = map.get(key);
13619
+ if (list) list.push(o);
13620
+ else map.set(key, [o]);
13621
+ };
13622
+ for (const o of ownTxs) {
13623
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
13624
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
13625
+ }
13626
+ const queue = [];
13627
+ const queued = /* @__PURE__ */ new Set();
13628
+ const enqueue = (o) => {
13629
+ if (queued.has(o)) return;
13630
+ queued.add(o);
13631
+ queue.push(o);
13632
+ };
13633
+ const add = async (o, c) => {
13634
+ const nullifier = hex32(
13635
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
13636
+ );
13637
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
13638
+ candidates.push(full);
13639
+ if (!byNullifier.has(nullifier)) {
13640
+ byNullifier.set(nullifier, full);
13641
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
13642
+ }
13643
+ if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
13644
+ legacyKeys.set(c.keypair.publicKey, c.keypair);
13645
+ for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
13646
+ }
13647
+ };
13648
+ const tryDeposit = async (o, item, amount) => {
13649
+ const note = o.note;
13650
+ const mint = addressFromBytes(item.mint);
13651
+ const deposit = await matchDepositNote({
13652
+ viewingKeyNk: o.trial.nk,
13653
+ noteSalt: note.noteSalt,
13654
+ amount,
13655
+ mintAddress: mint,
13656
+ outputCommitments: txOutputs(item),
13657
+ ownerUtxoKeypair: owner
13658
+ });
13659
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
13660
+ if (!deposit || leaf === null) return false;
13661
+ await add(o, {
13662
+ kind: "deposit",
13663
+ atRisk: deposit.legacyExposed,
13664
+ amount: deposit.amount,
13665
+ blinding: deposit.blinding,
13666
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
13667
+ mint,
13668
+ commitment: deposit.commitment,
13669
+ leaf
13670
+ });
13671
+ return true;
13672
+ };
13673
+ const tryChange0 = async (o, item, keypair, atRisk) => {
13674
+ const note = o.note;
13675
+ const mint = addressFromBytes(item.mint);
13676
+ const change = await matchChangeNote({
13677
+ viewingKeyNk: o.trial.nk,
13678
+ noteSalt: note.noteSalt,
13679
+ amount: note.outAmount0,
13680
+ keypair,
13681
+ mintAddress: mint,
13682
+ outputIndex: 0,
13683
+ outputCommitments: [toHex2(item.comm0)],
13684
+ ownerUtxoPublicKey: owner.publicKey
13685
+ });
13686
+ if (!change) return false;
13687
+ await add(o, {
13688
+ kind: "change",
13689
+ atRisk,
13690
+ amount: change.amount,
13691
+ blinding: change.blinding,
13692
+ keypair,
13693
+ mint,
13694
+ commitment: change.commitment,
13695
+ leaf: Number(item.leaf0)
13696
+ });
13697
+ return true;
13698
+ };
13699
+ const direct = async (o) => {
13700
+ const item = o.item;
13701
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
13702
+ const note = o.note;
13703
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13704
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
13705
+ }
13706
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
13707
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
13708
+ }
13709
+ } else if (item.kind === 2 && o.delivery) {
13710
+ const mint = addressFromBytes(item.mint);
13711
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
13712
+ onReject(o);
13713
+ return;
13714
+ }
13715
+ const commitment = await computeCommitment2({
13716
+ amount: o.delivery.amount,
13717
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
13718
+ blinding: o.delivery.blinding,
13719
+ mintAddress: mint
13720
+ });
13721
+ if (commitment !== bytesToBigint3(item.commitment)) {
13722
+ onReject(o);
13723
+ return;
13724
+ }
13725
+ await add(o, {
13726
+ kind: "received",
13727
+ atRisk: false,
13728
+ amount: o.delivery.amount,
13729
+ blinding: o.delivery.blinding,
13730
+ keypair: owner,
13731
+ mint,
13732
+ commitment,
13733
+ leaf: Number(item.leaf)
13734
+ });
13735
+ } else if (item.kind === 3 && o.refund) {
13736
+ await add(o, {
13737
+ kind: "swap_refund",
13738
+ atRisk: o.refund.legacyExposed,
13739
+ amount: o.refund.amount,
13740
+ blinding: o.refund.blinding,
13741
+ // per-swap refunds carry their derived keypair; owner-shape ones carry the owner
13742
+ keypair: o.refund.keypair,
13743
+ mint: NATIVE_SOL_MINT,
13744
+ commitment: o.refund.commitment,
13745
+ leaf: Number(item.leaf)
13746
+ });
13747
+ }
13748
+ };
13749
+ for (const o of own) {
13750
+ try {
13751
+ await direct(o);
13752
+ } catch {
13753
+ onSkip(o);
13754
+ }
13755
+ }
13756
+ const processTx = async (o) => {
13757
+ const item = o.item;
13758
+ const note = o.note;
13759
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
13760
+ const legacy = legacyKeys.get(note.outPubkey0);
13761
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
13762
+ }
13763
+ const mint = addressFromBytes(item.mint);
13764
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
13765
+ if (inputs.length === 0) return;
13766
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
13767
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
13768
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
13769
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
13770
+ if (out1 > 0n && blinding === null) onSkip(o);
13771
+ else if (blinding !== null) {
13772
+ const owners = [{ keypair: owner, atRisk: false }];
13773
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
13774
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
13775
+ for (const { keypair, atRisk } of owners) {
13776
+ const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
13777
+ if (commitment !== bytesToBigint3(item.comm1)) continue;
13778
+ claimed.add(`${o.seq}:1`);
13779
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
13780
+ break;
13781
+ }
13782
+ }
13783
+ }
13784
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13785
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
13786
+ }
13787
+ };
13788
+ for (const o of ownTxs) enqueue(o);
13789
+ for (let i = 0; i < queue.length; i++) {
13790
+ const o = queue[i];
13791
+ queued.delete(o);
13792
+ try {
13793
+ await processTx(o);
13794
+ } catch {
13795
+ onSkip(o);
13796
+ }
13797
+ }
13798
+ return candidates;
13799
+ }
13800
+ async function replayStream(start, pages, overrides, chain, targetPage) {
13801
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
13802
+ const startN = frontier.nextIndex;
13803
+ const pending = new Map(start.pending);
13804
+ const flushed = new LeafBuffer();
13805
+ const corrections = /* @__PURE__ */ new Map();
13806
+ let conflicts = 0;
13807
+ let verifiedPrefix = 0;
13808
+ let mismatch = false;
13809
+ const checks = [];
13810
+ const setBits = [];
13811
+ if (chain && chain.nextIndex > 0) {
13812
+ const last = chain.nextIndex - 1;
13813
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
13814
+ for (const l of setBits) {
13815
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
13816
+ if (at >= startN) checks.push({ at, level: l });
13817
+ }
13818
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
13819
+ checks.sort((a, b) => a.at - b.at);
13820
+ }
13821
+ let nextCheck = 0;
13822
+ const runChecks = () => {
13823
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
13824
+ const { at, level } = checks[nextCheck++];
13825
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
13826
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
13827
+ else mismatch = true;
13828
+ }
13829
+ };
13830
+ const append = (values) => {
13831
+ let i = 0;
13832
+ while (i < values.length) {
13833
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
13834
+ const take = Math.min(values.length - i, room);
13835
+ if (take > 0) {
13836
+ const part = values.slice(i, i + take);
13837
+ frontier.append(part);
13838
+ flushed.push(part);
13839
+ i += take;
13840
+ }
13841
+ runChecks();
13842
+ }
13843
+ };
13844
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
13845
+ const flush = () => {
13846
+ const batch = [];
13847
+ let next = frontier.nextIndex;
13848
+ while (pending.has(next)) {
13849
+ batch.push(pending.get(next));
13850
+ pending.delete(next);
13851
+ next++;
13852
+ }
13853
+ if (batch.length > 0) append(batch);
13854
+ };
13855
+ let snapshot = null;
13856
+ let taken = false;
13857
+ const takeSnapshot = () => {
13858
+ taken = true;
13859
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
13860
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
13861
+ };
13862
+ runChecks();
13863
+ flush();
13864
+ for (const { page, entries } of pages) {
13865
+ if (!taken && page >= targetPage) takeSnapshot();
13866
+ for (const e of entries) {
13867
+ if (e.leaf < startN) continue;
13868
+ const prior = valueAt(e.leaf);
13869
+ if (prior !== void 0) {
13870
+ if (prior !== e.commitment) {
13871
+ conflicts++;
13872
+ corrections.set(e.leaf, e.commitment);
13873
+ }
13874
+ continue;
13875
+ }
13876
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
13877
+ }
13878
+ flush();
13879
+ }
13880
+ if (!taken) takeSnapshot();
13881
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
13882
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
13883
+ }
13884
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
13885
+ }
13886
+ var HEX64 = /^[0-9a-f]{64}$/;
13887
+ var HEX32 = /^[0-9a-f]{32}$/;
13888
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
13889
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
13890
+ function isRecord(v) {
13891
+ return typeof v === "object" && v !== null && !Array.isArray(v);
13892
+ }
13893
+ function isIntIn(v, min, max) {
13894
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
13895
+ }
13896
+ function isBoundedArray(v, max) {
13897
+ return Array.isArray(v) && v.length <= max;
13898
+ }
13899
+ function emptyStartTree() {
13900
+ return {
13901
+ frontier: null,
13902
+ nextIndex: 0,
13903
+ pending: /* @__PURE__ */ new Map(),
13904
+ window: [],
13905
+ windowStart: 0,
13906
+ verified: 0,
13907
+ overrides: /* @__PURE__ */ new Map(),
13908
+ mismatch: false,
13909
+ hiBefore: -1
13910
+ };
13911
+ }
13912
+ async function parseCursor(cursor, poolMints) {
13913
+ try {
13914
+ if (!isRecord(cursor)) return "not an object";
13915
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
13916
+ const c = cursor;
13917
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
13918
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
13919
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
13920
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
13921
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
13922
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
13923
+ const trees = /* @__PURE__ */ new Map();
13924
+ for (const mint of poolMints) {
13925
+ const t = c.trees[mint];
13926
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
13927
+ const tree = t;
13928
+ if (!isRecord(tree.frontier)) return "bad frontier";
13929
+ let frontier;
13930
+ try {
13931
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
13932
+ } catch {
13933
+ return "bad frontier";
13934
+ }
13935
+ const nextIndex = frontier.nextIndex;
13936
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
13937
+ const pending = /* @__PURE__ */ new Map();
13938
+ let hiBefore = nextIndex - 1;
13939
+ for (const entry of tree.pending) {
13940
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
13941
+ const [leaf, value] = entry;
13942
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
13943
+ return "bad pending leaves";
13944
+ }
13945
+ pending.set(leaf, BigInt("0x" + value));
13946
+ hiBefore = Math.max(hiBefore, leaf);
13947
+ }
13948
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
13949
+ const windowLen = tree.window.length / 64;
13950
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
13951
+ const window2 = [];
13952
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
13953
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
13954
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
13955
+ const overrides = /* @__PURE__ */ new Map();
13956
+ for (const entry of tree.overrides) {
13957
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
13958
+ const [leaf, value] = entry;
13959
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
13960
+ overrides.set(leaf, BigInt("0x" + value));
13961
+ }
13962
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
13963
+ trees.set(mint, {
13964
+ frontier: frontier.toState(),
13965
+ nextIndex,
13966
+ pending,
13967
+ window: window2,
13968
+ windowStart: nextIndex - windowLen,
13969
+ verified: tree.verified,
13970
+ overrides,
13971
+ mismatch: tree.mismatch,
13972
+ hiBefore
13973
+ });
13974
+ }
13975
+ const own = c.own;
13976
+ if (!isRecord(own)) return "bad own state";
13977
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
13978
+ const items = [];
13979
+ const seqs = /* @__PURE__ */ new Set();
13980
+ for (const entry of own.items) {
13981
+ if (!isRecord(entry)) return "bad own items";
13982
+ const { seq, item } = entry;
13983
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
13984
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
13985
+ seqs.add(seq);
13986
+ const raw = fromHex(item);
13987
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
13988
+ }
13989
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
13990
+ return "bad verified notes";
13991
+ }
13992
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
13993
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
13994
+ const pendingLeaves = /* @__PURE__ */ new Map();
13995
+ for (const entry of own.pendingLeaves) {
13996
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
13997
+ const [mint, leaf, value] = entry;
13998
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
13999
+ return "bad pending notes";
14000
+ }
14001
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
14002
+ }
14003
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
14004
+ return "bad rejected set";
14005
+ }
14006
+ return {
14007
+ raw: c,
14008
+ trees,
14009
+ items,
14010
+ verified: new Set(own.verified),
14011
+ spent: new Set(own.spent),
14012
+ pendingLeaves,
14013
+ rejected: own.rejected
14014
+ };
14015
+ } catch {
14016
+ return "unreadable state";
14017
+ }
14018
+ }
14019
+ async function recoverNotesFromIndex(params) {
14020
+ const startedAt = Date.now();
14021
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
14022
+ assertAllowedRelayOrigin(relayUrl);
14023
+ assertAllowedRpcConnection(connection);
14024
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
14025
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
14026
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
14027
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
14028
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
14029
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
14030
+ }
14031
+ if (params.signal?.aborted) throw abortError2();
14032
+ const stats = {
14033
+ pages: 0,
14034
+ items: 0,
14035
+ bytes: 0,
14036
+ rpcCalls: 0,
14037
+ ms: 0,
14038
+ dropped: 0,
14039
+ decrypted: 0,
14040
+ candidates: 0,
14041
+ spent: 0,
14042
+ conflicts: 0,
14043
+ pendingDropped: 0,
14044
+ skipped: 0
14045
+ };
14046
+ const rpc = new Proxy(connection, {
14047
+ get(target, prop, receiver) {
14048
+ const value = Reflect.get(target, prop, receiver);
14049
+ if (typeof value !== "function") return value;
14050
+ return (...args) => {
14051
+ const pending = value.apply(target, args);
14052
+ if (pending && typeof pending.send === "function") {
14053
+ const send = pending.send.bind(pending);
14054
+ return {
14055
+ ...pending,
14056
+ send: (...sendArgs) => {
14057
+ stats.rpcCalls++;
14058
+ return send(...sendArgs);
14059
+ }
14060
+ };
14061
+ }
14062
+ return pending;
14063
+ };
14064
+ }
14065
+ });
14066
+ const makeTrial = async (nk, legacy) => ({
14067
+ nk,
14068
+ legacy,
14069
+ owner,
14070
+ decrypt: await createCompactChainNoteDecryptor(nk),
14071
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
14072
+ });
14073
+ const trials = [await makeTrial(viewingKeyNk, false)];
14074
+ const legacyNks = params.legacyViewingKeyNks ?? [];
14075
+ if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
14076
+ if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
14077
+ const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
14078
+ for (const nk of legacyNks) {
14079
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
14080
+ const key = toHex2(nk);
14081
+ if (seenNks.has(key)) continue;
14082
+ seenNks.add(key);
14083
+ trials.push(await makeTrial(Uint8Array.from(nk), true));
14084
+ }
14085
+ const poolMints = Array.from(new Set(params.poolMints));
14086
+ const warnings = [];
14087
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
14088
+ let cursor;
14089
+ if (params.cursor !== void 0) {
14090
+ const checked = await parseCursor(params.cursor, poolMints);
14091
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
14092
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
14093
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
14094
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
14095
+ } else cursor = checked;
14096
+ }
14097
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
14098
+ let treeRead;
14099
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
14100
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
14101
+ return poolMints.map((_, i) => {
14102
+ const account = accounts[i];
14103
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
14104
+ return account && parsed ? { ...parsed, data: account.data } : null;
14105
+ });
14106
+ })());
14107
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
14108
+ let outcome = await runOnce(ctx, cursor);
14109
+ if (outcome instanceof FullPassSignal) {
14110
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
14111
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
14112
+ outcome = await runOnce(ctx, void 0);
14113
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
14114
+ }
14115
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
14116
+ stats.ms = Date.now() - startedAt;
14117
+ return { ...outcome, stats, warnings };
14118
+ }
14119
+ async function runOnce(ctx, cursor) {
14120
+ const { params, head, trials, owner, stats, poolMints } = ctx;
14121
+ const { relayUrl, onProgress } = params;
14122
+ const poolSet = new Set(poolMints);
14123
+ const startPage = cursor?.raw.page ?? 0;
14124
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
14125
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
14126
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
14127
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
14128
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
14129
+ const rejectedIds = new Set(cursor?.rejected ?? []);
14130
+ const controller = new AbortController();
14131
+ const onCallerAbort = () => controller.abort();
14132
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
14133
+ const signal = controller.signal;
14134
+ try {
14135
+ const pageData = /* @__PURE__ */ new Map();
14136
+ const ownItems = [];
14137
+ const nullifiers = /* @__PURE__ */ new Set();
14138
+ let fullPassReason = null;
14139
+ const lateReference = (mint, leaf, value, seq) => {
14140
+ if (!cursor || seq < fullPassSeq) return null;
14141
+ const t = startTrees.get(mint);
14142
+ if (leaf < t.nextIndex) {
14143
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
14144
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
14145
+ return null;
14146
+ }
14147
+ const held = t.pending.get(leaf);
14148
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
14149
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
14150
+ return null;
14151
+ };
14152
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
14153
+ const waiting = /* @__PURE__ */ new Map();
14154
+ let chainNext = startPage;
14155
+ let chainError = null;
14156
+ let wakers = [];
14157
+ const wakeAll = () => {
14158
+ const w = wakers;
14159
+ wakers = [];
14160
+ for (const f of w) f();
14161
+ };
14162
+ signal.addEventListener("abort", wakeAll);
14163
+ const advanceChain = () => {
14164
+ while (!chainError && waiting.has(chainNext)) {
14165
+ const w = waiting.get(chainNext);
14166
+ waiting.delete(chainNext);
14167
+ const expected = chainAt.get(chainNext);
14168
+ if (w.prevChain !== expected) {
14169
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
14170
+ controller.abort();
14171
+ return;
14172
+ }
14173
+ if (!w.complete) break;
14174
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
14175
+ chainNext++;
14176
+ }
14177
+ wakeAll();
14178
+ };
14179
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
14180
+ const lookahead = 2 * workerCount + 2;
14181
+ let nextToFetch = startPage;
14182
+ let pagesDone = 0;
14183
+ const worker = async () => {
14184
+ for (; ; ) {
14185
+ if (signal.aborted) throw abortError2();
14186
+ const pageNo = nextToFetch++;
14187
+ if (pageNo >= pagesTotal) return;
14188
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
14189
+ if (signal.aborted) throw abortError2();
14190
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
14191
+ stats.bytes += bytes.length;
14192
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
14193
+ if (pageNo < head.completePages && !page2.complete) {
14194
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
14195
+ }
14196
+ stats.pages++;
14197
+ stats.skipped += page2.skippedMalformed;
14198
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
14199
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
14200
+ advanceChain();
14201
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
14202
+ const late = (reason) => {
14203
+ if (reason && !fullPassReason) {
14204
+ fullPassReason = reason;
14205
+ controller.abort();
14206
+ }
14207
+ };
14208
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
14209
+ if (isAllZero3(commitment)) return;
14210
+ const mint = addressFromBytes(mintBytes);
14211
+ if (!poolSet.has(mint)) return;
14212
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint3(commitment) };
14213
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
14214
+ const list = data.leaves.get(mint);
14215
+ if (list) list.push(entry);
14216
+ else data.leaves.set(mint, [entry]);
14217
+ };
14218
+ page2.items.forEach((item, i) => {
14219
+ const seq = seqOf(i);
14220
+ if (item.kind === 1) {
14221
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
14222
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
14223
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
14224
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
14225
+ } else if (item.kind === 3) {
14226
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
14227
+ } else {
14228
+ const mint = addressFromBytes(item.mint);
14229
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
14230
+ }
14231
+ });
14232
+ if (signal.aborted) throw abortError2();
14233
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
14234
+ if (signal.aborted) throw abortError2();
14235
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
14236
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
14237
+ opened.forEach((o, k) => {
14238
+ if (!o) return;
14239
+ stats.decrypted++;
14240
+ const raw = page2.rawItems[i + k];
14241
+ const id = itemIdentity(raw);
14242
+ if (rejectedIds.has(id)) {
14243
+ stats.dropped++;
14244
+ return;
14245
+ }
14246
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
14247
+ });
14248
+ stats.items += batch.length;
14249
+ }
14250
+ pageData.set(pageNo, data);
14251
+ pagesDone++;
14252
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
14253
+ }
14254
+ };
14255
+ const workers = Array.from(
14256
+ { length: workerCount },
14257
+ () => worker().catch((error) => {
14258
+ controller.abort();
14259
+ throw error;
14260
+ })
14261
+ );
14262
+ const settled = await Promise.allSettled(workers);
14263
+ signal.removeEventListener("abort", wakeAll);
14264
+ if (params.signal?.aborted) throw abortError2();
14265
+ const lateReason = fullPassReason;
14266
+ if (lateReason) return new FullPassSignal(lateReason);
14267
+ const chainFailure = chainError;
14268
+ if (chainFailure) {
14269
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
14270
+ throw chainFailure;
14271
+ }
14272
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
14273
+ if (failure) throw failure.reason;
14274
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
14275
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
14276
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
14277
+ }
14278
+ for (const entry of cursor?.items ?? []) {
14279
+ const o = await trialItemIsolated(entry.item, trials, stats);
14280
+ if (!o) continue;
14281
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
14282
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
14283
+ if (entry.item.kind === 1) {
14284
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
14285
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
14286
+ }
14287
+ }
14288
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
14289
+ ownItems.sort((a, b) => a.seq - b.seq);
14290
+ const rejectedNow = /* @__PURE__ */ new Set();
14291
+ const skippedNow = /* @__PURE__ */ new Set();
14292
+ const allCandidates = await matchOwnItems(
14293
+ ownItems,
14294
+ owner,
14295
+ (o) => {
14296
+ stats.dropped++;
14297
+ rejectedNow.add(o.id);
14298
+ },
14299
+ (o) => {
14300
+ if (skippedNow.has(o)) return;
14301
+ skippedNow.add(o);
14302
+ stats.skipped++;
14303
+ }
14304
+ );
14305
+ stats.candidates = allCandidates.length;
14306
+ const cutoff = params.legacyCutoffLeaf ?? {};
14307
+ const candidates = allCandidates.filter((c) => {
14308
+ const limit = cutoff[c.mint];
14309
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
14310
+ stats.dropped++;
14311
+ return false;
14312
+ }
14313
+ return true;
14314
+ });
14315
+ const chainTrees = await ctx.readTrees();
14316
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
14317
+ const replays = /* @__PURE__ */ new Map();
14318
+ for (let i = 0; i < poolMints.length; i++) {
14319
+ const mint = poolMints[i];
14320
+ const start = startTrees.get(mint);
14321
+ const chainTree = chainTrees[i] ?? null;
14322
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
14323
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
14324
+ let overrides = start.overrides;
14325
+ stats.conflicts += r.conflicts;
14326
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
14327
+ const merged = new Map([...start.overrides, ...r.corrections]);
14328
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
14329
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
14330
+ r = alternative;
14331
+ overrides = merged;
14332
+ }
14333
+ }
14334
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
14335
+ replays.set(mint, { r, overrides });
14336
+ }
14337
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
14338
+ const streamValue = (mint, leaf) => {
14339
+ const v = replays.get(mint)?.r.valueAt(leaf);
14340
+ if (v !== void 0) return v;
14341
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
14342
+ if (carried !== void 0) return carried;
14343
+ const t = startTrees.get(mint);
14344
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
14345
+ return void 0;
14346
+ };
14347
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
14348
+ const verified = [];
14349
+ const pendingByKey = /* @__PURE__ */ new Map();
14350
+ const rejectedCandidates = /* @__PURE__ */ new Set();
14351
+ const outcomeOf = /* @__PURE__ */ new Map();
14352
+ const tally = (c, what) => {
14353
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
14354
+ t.total++;
14355
+ if (what === "kept") t.kept = true;
14356
+ if (what === "rejected") t.rejected++;
14357
+ outcomeOf.set(c.seq, t);
14358
+ };
14359
+ const pend = (c, rank) => {
14360
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
14361
+ const prior = pendingByKey.get(key);
14362
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
14363
+ };
14364
+ for (const c of candidates) {
14365
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
14366
+ verified.push(c);
14367
+ continue;
14368
+ }
14369
+ if (!poolSet.has(c.mint)) {
14370
+ pend(c, 3);
14371
+ continue;
14372
+ }
14373
+ const value = streamValue(c.mint, c.leaf);
14374
+ if (value === void 0) {
14375
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
14376
+ stats.dropped++;
14377
+ tally(c, "other");
14378
+ } else pend(c, 1);
14379
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
14380
+ pend(c, value === c.commitment ? 0 : 2);
14381
+ } else if (value === c.commitment) {
14382
+ verified.push(c);
14383
+ } else {
14384
+ stats.dropped++;
14385
+ rejectedCandidates.add(c);
14386
+ tally(c, "rejected");
14387
+ }
14388
+ }
14389
+ verified.sort((a, b) => a.seq - b.seq);
14390
+ const byLeaf = /* @__PURE__ */ new Map();
14391
+ for (const c of verified) {
14392
+ const key = `${c.mint}:${c.leaf}`;
14393
+ if (byLeaf.has(key)) {
14394
+ stats.dropped++;
14395
+ tally(c, "other");
14396
+ continue;
14397
+ }
14398
+ byLeaf.set(key, c);
14399
+ }
14400
+ const notes = [];
14401
+ const atRisk = [];
14402
+ const spentOut = new Set(knownSpent);
14403
+ const verifiedOut = new Set(knownVerified);
14404
+ const keyChecked = /* @__PURE__ */ new Map();
14405
+ for (const c of byLeaf.values()) {
14406
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
14407
+ keyChecked.set(c.keypair.privateKey, pubOk);
14408
+ const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
14409
+ if (!pubOk || !c.atRisk && !ownerOk) {
14410
+ stats.dropped++;
14411
+ tally(c, "rejected");
14412
+ continue;
14413
+ }
14414
+ tally(c, "kept");
14415
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
14416
+ const utxo = {
14417
+ amount: c.amount,
14418
+ keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
14419
+ blinding: c.blinding,
14420
+ mintAddress: c.mint,
14421
+ index: c.leaf,
14422
+ commitment: c.commitment
14423
+ };
14424
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
14425
+ stats.spent++;
14426
+ spentOut.add(c.nullifier);
14427
+ continue;
14428
+ }
14429
+ const note = {
14430
+ kind: c.kind,
14431
+ utxo,
14432
+ signature: bs584.encode(c.signature),
14433
+ legacyExposed: c.atRisk
14434
+ };
14435
+ (c.atRisk ? atRisk : notes).push(note);
14436
+ }
14437
+ 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);
14438
+ sortNotes(notes);
14439
+ sortNotes(atRisk);
14440
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
14441
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
14442
+ const overflow = pendingList.length - carriedPending.length;
14443
+ if (overflow > 0) {
14444
+ stats.pendingDropped += overflow;
14445
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
14446
+ }
14447
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
14448
+ for (const c of carriedPending) tally(c, "kept");
14449
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
14450
+ let page = targetPage;
14451
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
14452
+ const trees = {};
14453
+ const treeEnd = /* @__PURE__ */ new Map();
14454
+ for (const mint of poolMints) {
14455
+ const start = startTrees.get(mint);
14456
+ const { r, overrides } = replays.get(mint);
14457
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
14458
+ const n = snap.nextIndex;
14459
+ const window2 = [];
14460
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
14461
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
14462
+ if (v === void 0) break;
14463
+ window2.push(hex32(v));
14464
+ }
14465
+ window2.reverse();
14466
+ trees[mint] = {
14467
+ frontier: snap.frontier,
14468
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
14469
+ window: window2.join(""),
14470
+ verified: Math.min(verifiedUpTo(mint), n),
14471
+ 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)]),
14472
+ mismatch: r.mismatch
14473
+ };
14474
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
14475
+ }
14476
+ const pendingLeaves = [];
14477
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
14478
+ for (const c of carriedPending) {
14479
+ const end = treeEnd.get(c.mint);
14480
+ if (!end || c.leaf >= end.nextIndex) continue;
14481
+ const value = streamValue(c.mint, c.leaf);
14482
+ const key = `${c.mint}:${c.leaf}`;
14483
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
14484
+ pendingLeafSeen.add(key);
14485
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
14486
+ }
14487
+ const keptItems = [];
14488
+ const keptIds = /* @__PURE__ */ new Set();
14489
+ for (const o of ownItems) {
14490
+ const t = outcomeOf.get(o.seq);
14491
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
14492
+ rejectedNow.add(o.id);
14493
+ continue;
14494
+ }
14495
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
14496
+ keptIds.add(o.id);
14497
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
14498
+ }
14499
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
14500
+ const nextCursor = {
14501
+ v: CURSOR_VERSION,
14502
+ epoch: head.epoch.toString(10),
14503
+ page,
14504
+ chain: chainAt.get(page) ?? startChain,
14505
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
14506
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
14507
+ trees,
14508
+ own: {
14509
+ items: keptItems,
14510
+ verified: Array.from(verifiedOut),
14511
+ spent: Array.from(spentOut),
14512
+ pendingLeaves,
14513
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
14514
+ }
14515
+ };
14516
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
14517
+ } finally {
14518
+ params.signal?.removeEventListener("abort", onCallerAbort);
14519
+ }
14520
+ }
14521
+
12256
14522
  // src/wallet/utxo-wallet.ts
12257
14523
  init_address();
12258
14524
  init_utxo();
@@ -12912,7 +15178,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12912
15178
  })
12913
15179
  });
12914
15180
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12915
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
15181
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
12916
15182
  throw new Error(
12917
15183
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12918
15184
  );
@@ -12949,9 +15215,13 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12949
15215
  // src/bridge/derive.ts
12950
15216
  var import_hmac = require("@noble/hashes/hmac");
12951
15217
  var import_sha512 = require("@noble/hashes/sha512");
15218
+ var import_blake37 = require("@noble/hashes/blake3");
15219
+ init_utxo();
12952
15220
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
15221
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
15222
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
12953
15223
  var MAX_RECEIVER_INDEX = 1e4;
12954
- async function deriveBridgeReceiver(nk, index) {
15224
+ function assertReceiverIndex(index) {
12955
15225
  if (!Number.isInteger(index) || index < 0) {
12956
15226
  throw new Error(`index must be a non-negative integer, got ${index}`);
12957
15227
  }
@@ -12960,6 +15230,26 @@ async function deriveBridgeReceiver(nk, index) {
12960
15230
  `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
15231
  );
12962
15232
  }
15233
+ }
15234
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
15235
+ if (ownerUtxoKeypair instanceof Uint8Array) {
15236
+ throw new Error(
15237
+ "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."
15238
+ );
15239
+ }
15240
+ assertReceiverIndex(index);
15241
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
15242
+ const priv = bigintToBytes323(owner.privateKey);
15243
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
15244
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
15245
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
15246
+ const key = (0, import_blake37.blake3)(preimage);
15247
+ const h = (0, import_hmac.hmac)(import_sha512.sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
15248
+ return signerFromSecretKey(h.slice(0, 32));
15249
+ }
15250
+ async function deriveLegacyBridgeReceiver(nk, index) {
15251
+ assertReceiverIndex(index);
15252
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
12963
15253
  const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12964
15254
  return signerFromSecretKey(h.slice(0, 32));
12965
15255
  }
@@ -12970,13 +15260,44 @@ var import_token4 = require("@solana-program/token");
12970
15260
  function describeError(err) {
12971
15261
  return err instanceof Error ? err.message : String(err);
12972
15262
  }
12973
- async function listBridgeDeposits(rpc, nk, opts) {
15263
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
15264
+ if (ownerUtxoKeypair instanceof Uint8Array) {
15265
+ throw new Error(
15266
+ "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)."
15267
+ );
15268
+ }
15269
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
15270
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
15271
+ legacyExposed: false
15272
+ });
15273
+ if (opts.includeLegacy === false) return out;
15274
+ const nks = [];
15275
+ const seen = /* @__PURE__ */ new Set();
15276
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
15277
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
15278
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
15279
+ }
15280
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
15281
+ if (seen.has(key)) continue;
15282
+ seen.add(key);
15283
+ nks.push(nk);
15284
+ }
15285
+ for (const nk of nks) {
15286
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
15287
+ legacyExposed: true,
15288
+ legacyViewingKeyNk: nk
15289
+ });
15290
+ out.push(...legacy);
15291
+ }
15292
+ return out;
15293
+ }
15294
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12974
15295
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12975
15296
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12976
15297
  const out = [];
12977
15298
  let consecutiveUnused = 0;
12978
15299
  for (let index = 0; index < scanDepth; index++) {
12979
- const kp = await deriveBridgeReceiver(nk, index);
15300
+ const kp = await receiverAt(index);
12980
15301
  const receiver = kp.address;
12981
15302
  const [tokenAccount] = await (0, import_token4.findAssociatedTokenPda)({
12982
15303
  mint: opts.mint,
@@ -13028,7 +15349,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
13028
15349
  tokenBalance,
13029
15350
  lamports,
13030
15351
  shieldSignature,
13031
- ...indexReused ? { indexReused, shieldSignatures } : {}
15352
+ ...indexReused ? { indexReused, shieldSignatures } : {},
15353
+ ...provenance
13032
15354
  });
13033
15355
  } catch (err) {
13034
15356
  out.push({
@@ -13038,7 +15360,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
13038
15360
  state: "unknown",
13039
15361
  tokenBalance: 0n,
13040
15362
  lamports: 0n,
13041
- error: describeError(err)
15363
+ error: describeError(err),
15364
+ ...provenance
13042
15365
  });
13043
15366
  }
13044
15367
  }
@@ -13192,7 +15515,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13192
15515
  const signMessage = (m) => signMessageBytes(R, m);
13193
15516
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
13194
15517
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
13195
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
15518
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
15519
+ amount,
15520
+ viewingKeyNk: nk,
15521
+ ownerUtxoKeypair: utxoKeypair,
15522
+ mintAddress: mint
15523
+ });
13196
15524
  const zeroInput = await createZeroUtxo(mint);
13197
15525
  const rBefore = (await rpc.getBalance(R.address).send()).value;
13198
15526
  let result;
@@ -13211,6 +15539,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13211
15539
  signMessage,
13212
15540
  chainNoteViewingKeyNk: nk,
13213
15541
  chainNoteSalt: noteSalt,
15542
+ ownerUtxoKeypair: utxoKeypair,
13214
15543
  relaySupplementalAlt: true,
13215
15544
  onProgress: (s) => log(` \xB7 ${s}`)
13216
15545
  }
@@ -13398,13 +15727,13 @@ var DoNotRetry = class extends Error {
13398
15727
  };
13399
15728
  async function withShieldRetries(attempt, hooks = {}) {
13400
15729
  const attempts = hooks.attempts ?? 3;
13401
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
15730
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13402
15731
  let last = "";
13403
15732
  for (let n = 1; n <= attempts; n++) {
13404
15733
  if (n > 1) {
13405
15734
  const delay = retryDelayMs(n);
13406
15735
  hooks.onRetry?.(n, delay, last);
13407
- await sleep4(delay);
15736
+ await sleep5(delay);
13408
15737
  }
13409
15738
  try {
13410
15739
  return await attempt(n);
@@ -13424,6 +15753,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13424
15753
  0 && (module.exports = {
13425
15754
  AccountRole,
13426
15755
  BRIDGE_ESCROW_LABEL,
15756
+ BRIDGE_ESCROW_LABEL_V2,
13427
15757
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
13428
15758
  CHAIN_NOTE_SALT_BITS,
13429
15759
  CLEANUP_FEE_BUDGET,
@@ -13452,6 +15782,10 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13452
15782
  MemoryStorageAdapter,
13453
15783
  MerkleTree,
13454
15784
  NATIVE_SOL_MINT,
15785
+ NOTE_INDEX_NO_LEAF,
15786
+ NOTE_INDEX_PAGE_SIZE,
15787
+ NoteIndexFormatError,
15788
+ NoteIndexHeadBehindError,
13455
15789
  ONECLICK_PUBKEY_B58,
13456
15790
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
13457
15791
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -13528,6 +15862,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13528
15862
  computeChainNoteHash,
13529
15863
  computeExtDataHash,
13530
15864
  computeMerkleRoot,
15865
+ computeNoteIndexChain,
13531
15866
  computeProofForLatestDeposit,
13532
15867
  computeProofFromChain,
13533
15868
  computeSignature,
@@ -13552,14 +15887,19 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13552
15887
  depositFromDerivedKey,
13553
15888
  deriveBridgeReceiver,
13554
15889
  deriveChangeNoteBlinding,
13555
- deriveDepositNoteSecrets,
15890
+ deriveDepositNoteBlinding,
13556
15891
  deriveDiversifiedViewingKey,
13557
15892
  deriveDiversifier,
13558
15893
  deriveFundingTargets,
13559
15894
  deriveInputNullifierPdas,
15895
+ deriveLegacyBridgeReceiver,
15896
+ deriveLegacyDepositNoteSecrets,
15897
+ deriveLegacySwapRefundAuthorization,
13560
15898
  derivePublicKey,
13561
15899
  deriveSpendKey,
13562
15900
  deriveSwapRefundAuthorization,
15901
+ deriveSwapRefundBlinding,
15902
+ deriveSwapRefundKeypair,
13563
15903
  deriveUserCompliancePublicKey,
13564
15904
  deriveUserComplianceScalar,
13565
15905
  deriveUtxoKeypairFromSpendKey,
@@ -13572,6 +15912,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13572
15912
  discoverSwapRefunds,
13573
15913
  downloadNote,
13574
15914
  encodeDeliveryCarrierMemo,
15915
+ encodeNoteIndexItem,
15916
+ encodeNoteIndexPage,
13575
15917
  encodeNoteSimple,
13576
15918
  encodeRecipientDeliveryNote,
13577
15919
  encryptCompactChainNote,
@@ -13587,6 +15929,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13587
15929
  fetchCommitments,
13588
15930
  fetchLatestBlockhash,
13589
15931
  fetchLookupTables,
15932
+ fetchNoteIndexHead,
15933
+ fetchNoteIndexPage,
13590
15934
  fetchRiskQuoteInstruction,
13591
15935
  fetchRiskQuoteIx,
13592
15936
  fetchSignaturesForAddress,
@@ -13659,6 +16003,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13659
16003
  parseDeliveryCarrierMemo,
13660
16004
  parseError,
13661
16005
  parseNote,
16006
+ parseNoteIndexItem,
16007
+ parseNoteIndexPage,
13662
16008
  parseRelayErrorResponse,
13663
16009
  parseRelayErrorSignature,
13664
16010
  parseTransactionError,
@@ -13680,6 +16026,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13680
16026
  readMerkleTreeState,
13681
16027
  readRent,
13682
16028
  recipientDeliveryNoteToBase64,
16029
+ recoverNotesFromIndex,
13683
16030
  registerViewingKey,
13684
16031
  relayRequestDigestHex,
13685
16032
  removePendingDeposit,