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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -753,6 +753,44 @@ function isLoopbackHost(value) {
753
753
  }
754
754
  var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
755
755
 
756
+ // src/relay/clock.ts
757
+ var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
758
+ var MAX_CLOCK_DIVERGENCE_MS = 2e3;
759
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
760
+ var sample = null;
761
+ function monotonicNowMs() {
762
+ const perf = globalThis.performance;
763
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
764
+ }
765
+ function observeRelayClock(response) {
766
+ const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
767
+ if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
768
+ const serverMs = Number(raw.trim());
769
+ const wallMs = Date.now();
770
+ const offsetMs = serverMs - wallMs;
771
+ if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
772
+ sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
773
+ }
774
+ function relayNowMs() {
775
+ const wallMs = Date.now();
776
+ if (!sample) return wallMs;
777
+ const wallElapsed = wallMs - sample.wallAtSampleMs;
778
+ const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
779
+ if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
780
+ sample = null;
781
+ return wallMs;
782
+ }
783
+ return wallMs + sample.offsetMs;
784
+ }
785
+ function hasRelayClockSample() {
786
+ if (!sample) return false;
787
+ relayNowMs();
788
+ return sample !== null;
789
+ }
790
+ function relayNowSeconds() {
791
+ return Math.floor(relayNowMs() / 1e3);
792
+ }
793
+
756
794
  // src/relay/endpoint.ts
757
795
  var ALLOWED_ORIGINS = new Set(
758
796
  RELAY_ORIGIN_ALLOWLIST.map((entry) => {
@@ -804,8 +842,9 @@ function assertAllowedRelayOrigin(value) {
804
842
  async function relayFetch(url, init, options) {
805
843
  assertAllowedRelayOrigin(url);
806
844
  const extra = sanitizeExtraHeaders(options?.extraHeaders);
807
- if (!extra) return fetch(url, init);
808
- return fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) });
845
+ const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
846
+ if (options?.observeClock !== false) observeRelayClock(response);
847
+ return response;
809
848
  }
810
849
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
811
850
  var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
@@ -1298,7 +1337,7 @@ ${digest}`
1298
1337
  }
1299
1338
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1300
1339
  const senderB58 = sender;
1301
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
1340
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
1302
1341
  const nonce = randomNonceUuid();
1303
1342
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
1304
1343
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -1377,7 +1416,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
1377
1416
  `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.`
1378
1417
  );
1379
1418
  }
1380
- function explainRelayAuthRejection(responseText) {
1419
+ function explainRelayAuthRejection(responseText, context) {
1381
1420
  const text = String(responseText);
1382
1421
  const has = (needle) => text.includes(needle);
1383
1422
  if (has("issued too far in the future")) {
@@ -1387,7 +1426,9 @@ function explainRelayAuthRejection(responseText) {
1387
1426
  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.`;
1388
1427
  }
1389
1428
  if (has("does not match the exact request")) {
1390
- 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\`.`;
1429
+ 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\`.`;
1430
+ if (!context?.carriedAffiliateCode) return base;
1431
+ 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\`.`;
1391
1432
  }
1392
1433
  if (has("has no registered viewing key")) {
1393
1434
  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.`;
@@ -1904,6 +1945,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
1904
1945
  return false;
1905
1946
  }
1906
1947
  }
1948
+ function isRelayRequestInFlightResponse(responseText) {
1949
+ try {
1950
+ const parsed = JSON.parse(responseText);
1951
+ return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
1952
+ } catch {
1953
+ return false;
1954
+ }
1955
+ }
1907
1956
  function classifyRelayError(responseText, httpStatus) {
1908
1957
  let inner = "";
1909
1958
  try {
@@ -3929,6 +3978,27 @@ function isRootAccepted(data, rootHex) {
3929
3978
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3930
3979
  return readRootHistory(data).some((r) => r === want);
3931
3980
  }
3981
+ function treeAccountAcceptsRoot(data, rootHex) {
3982
+ const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3983
+ if (data.length >= ROOT_OFFSET + 32) {
3984
+ const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
3985
+ if (current === want) return true;
3986
+ }
3987
+ return isRootAccepted(data, want);
3988
+ }
3989
+ function readTreeAccountFrontier(data) {
3990
+ if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
3991
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
3992
+ const next = readBigUInt64LE(buf, 32);
3993
+ if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
3994
+ const subtrees = [];
3995
+ for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
3996
+ const offset = SUBTREES_OFFSET + level * 32;
3997
+ subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
3998
+ }
3999
+ const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
4000
+ return { nextIndex: Number(next), subtrees, root };
4001
+ }
3932
4002
 
3933
4003
  // src/proving/merkle.ts
3934
4004
  import { buildPoseidon } from "circomlibjs";
@@ -4088,6 +4158,89 @@ var MerkleTree = class _MerkleTree {
4088
4158
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4089
4159
  return MerkleTree.create(height, commitments);
4090
4160
  }
4161
+ var MerkleFrontier = class _MerkleFrontier {
4162
+ constructor(levels, zeros, poseidon2, count, left) {
4163
+ this.levels = levels;
4164
+ this.zeros = zeros;
4165
+ this.poseidon = poseidon2;
4166
+ this.count = count;
4167
+ this.left = left;
4168
+ }
4169
+ static async create(state, levels = MERKLE_TREE_HEIGHT2) {
4170
+ const zeros = await getZeroValues();
4171
+ const poseidon2 = await getPoseidon();
4172
+ const left = new Array(levels).fill(null);
4173
+ let count = 0;
4174
+ if (state) {
4175
+ if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
4176
+ throw new Error("MerkleFrontierState.nextIndex out of range");
4177
+ }
4178
+ if (!Array.isArray(state.left) || state.left.length !== levels) {
4179
+ throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
4180
+ }
4181
+ count = state.nextIndex;
4182
+ for (let l = 0; l < levels; l++) {
4183
+ const odd = Math.floor(count / 2 ** l) % 2 === 1;
4184
+ const entry = state.left[l];
4185
+ if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
4186
+ if (odd) {
4187
+ if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
4188
+ left[l] = BigInt("0x" + entry);
4189
+ }
4190
+ }
4191
+ }
4192
+ return new _MerkleFrontier(levels, zeros, poseidon2, count, left);
4193
+ }
4194
+ get nextIndex() {
4195
+ return this.count;
4196
+ }
4197
+ /**
4198
+ * The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
4199
+ * present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
4200
+ * With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
4201
+ */
4202
+ leftAt(level) {
4203
+ if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
4204
+ return this.left[level];
4205
+ }
4206
+ hash(a, b) {
4207
+ return this.poseidon.F.toObject(this.poseidon([a, b]));
4208
+ }
4209
+ /** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
4210
+ append(leaves) {
4211
+ if (leaves.length === 0) return;
4212
+ if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
4213
+ let nodes = leaves;
4214
+ for (let l = 0; l < this.levels && nodes.length > 0; l++) {
4215
+ const before = Math.floor(this.count / 2 ** l);
4216
+ const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
4217
+ const parents = [];
4218
+ for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
4219
+ this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
4220
+ nodes = parents;
4221
+ }
4222
+ this.count += leaves.length;
4223
+ }
4224
+ /** The root of the first `nextIndex` leaves, zero-padded to the right. */
4225
+ root() {
4226
+ let partial = this.zeros[0];
4227
+ for (let l = 0; l < this.levels; l++) {
4228
+ const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
4229
+ if (odd) partial = this.hash(this.left[l], partial);
4230
+ else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
4231
+ }
4232
+ return partial;
4233
+ }
4234
+ toState() {
4235
+ return {
4236
+ nextIndex: this.count,
4237
+ left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
4238
+ };
4239
+ }
4240
+ clone() {
4241
+ return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
4242
+ }
4243
+ };
4091
4244
 
4092
4245
  // src/config/transaction-version.ts
4093
4246
  var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
@@ -4236,6 +4389,7 @@ async function fetchWithRetry(url, options = {}) {
4236
4389
  try {
4237
4390
  const response = await fetch(url, { signal: controller.signal });
4238
4391
  clearTimeout(timeoutId);
4392
+ observeRelayClock(response);
4239
4393
  return response;
4240
4394
  } finally {
4241
4395
  clearTimeout(timeoutId);
@@ -4599,38 +4753,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
4599
4753
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
4600
4754
  return new Uint8Array(plaintext);
4601
4755
  }
4602
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
4756
+ async function importNkHkdfKey(nk) {
4603
4757
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4604
4758
  throw new Error("nk must be 32 bytes");
4605
4759
  }
4760
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
4761
+ }
4762
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
4606
4763
  const subtle = getSubtleCrypto2();
4607
- const ikm = await subtle.importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
4608
- const salt = hexToBytes32(commitmentHex);
4609
- const keyBits = await subtle.deriveBits(
4610
- {
4611
- name: "HKDF",
4612
- hash: "SHA-256",
4613
- salt: toArrayBuffer2(salt),
4614
- info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
4615
- },
4616
- ikm,
4617
- 256
4618
- );
4619
- const nonceBits = await subtle.deriveBits(
4620
- {
4621
- name: "HKDF",
4622
- hash: "SHA-256",
4623
- salt: toArrayBuffer2(salt),
4624
- info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
4625
- },
4626
- ikm,
4627
- 96
4628
- );
4764
+ const [keyBits, nonceBits] = await Promise.all([
4765
+ subtle.deriveBits(
4766
+ {
4767
+ name: "HKDF",
4768
+ hash: "SHA-256",
4769
+ salt: toArrayBuffer2(salt),
4770
+ info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
4771
+ },
4772
+ ikm,
4773
+ 256
4774
+ ),
4775
+ subtle.deriveBits(
4776
+ {
4777
+ name: "HKDF",
4778
+ hash: "SHA-256",
4779
+ salt: toArrayBuffer2(salt),
4780
+ info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
4781
+ },
4782
+ ikm,
4783
+ 96
4784
+ )
4785
+ ]);
4629
4786
  return {
4630
4787
  key: new Uint8Array(keyBits),
4631
4788
  nonce: new Uint8Array(nonceBits)
4632
4789
  };
4633
4790
  }
4791
+ async function deriveAesKeyAndNonce(nk, commitmentHex) {
4792
+ const ikm = await importNkHkdfKey(nk);
4793
+ return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
4794
+ }
4795
+ function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
4796
+ if (version === NOTE_VERSION_V4) {
4797
+ if (plaintext.length !== PLAINTEXT_LEN_V4) {
4798
+ throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
4799
+ }
4800
+ return {
4801
+ timestamp: readU64LE(plaintext, 0),
4802
+ commitment: commitmentHex.toLowerCase(),
4803
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
4804
+ outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
4805
+ outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
4806
+ isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
4807
+ };
4808
+ }
4809
+ if (version === NOTE_VERSION_V3) {
4810
+ if (plaintext.length !== PLAINTEXT_LEN_V3) {
4811
+ throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
4812
+ }
4813
+ return {
4814
+ timestamp: readU64LE(plaintext, 0),
4815
+ commitment: commitmentHex.toLowerCase(),
4816
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
4817
+ };
4818
+ }
4819
+ if (plaintext.length !== PLAINTEXT_LEN_V2) {
4820
+ throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
4821
+ }
4822
+ return {
4823
+ timestamp: readU64LE(plaintext, 0),
4824
+ commitment: commitmentHex.toLowerCase()
4825
+ };
4826
+ }
4634
4827
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
4635
4828
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4636
4829
  throw new Error("nk must be 32 bytes");
@@ -4694,36 +4887,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4694
4887
  try {
4695
4888
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
4696
4889
  const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
4697
- if (version === NOTE_VERSION_V4) {
4698
- if (plaintext.length !== PLAINTEXT_LEN_V4) {
4699
- throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
4700
- }
4701
- return {
4702
- timestamp: readU64LE(plaintext, 0),
4703
- commitment: commitment.toLowerCase(),
4704
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
4705
- outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
4706
- outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
4707
- isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
4708
- };
4709
- }
4710
- if (version === NOTE_VERSION_V3) {
4711
- if (plaintext.length !== PLAINTEXT_LEN_V3) {
4712
- throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
4713
- }
4714
- return {
4715
- timestamp: readU64LE(plaintext, 0),
4716
- commitment: commitment.toLowerCase(),
4717
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
4718
- };
4719
- }
4720
- if (plaintext.length !== PLAINTEXT_LEN_V2) {
4721
- throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
4722
- }
4723
- return {
4724
- timestamp: readU64LE(plaintext, 0),
4725
- commitment: commitment.toLowerCase()
4726
- };
4890
+ return decodeChainNotePlaintext(version, plaintext, commitment);
4727
4891
  } catch (error) {
4728
4892
  lastError = error;
4729
4893
  }
@@ -4732,6 +4896,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4732
4896
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
4733
4897
  );
4734
4898
  }
4899
+ async function createCompactChainNoteDecryptor(nk) {
4900
+ const ikm = await importNkHkdfKey(nk);
4901
+ return async (noteBytes, commitment) => {
4902
+ if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
4903
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
4904
+ const version = noteBytes[0];
4905
+ if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
4906
+ return null;
4907
+ }
4908
+ try {
4909
+ const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
4910
+ const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
4911
+ let hex = "";
4912
+ for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
4913
+ return decodeChainNotePlaintext(version, plaintext, hex);
4914
+ } catch {
4915
+ return null;
4916
+ }
4917
+ };
4918
+ }
4735
4919
  function chainNoteToBase64(noteBytes) {
4736
4920
  return Buffer.from(noteBytes).toString("base64");
4737
4921
  }
@@ -4828,6 +5012,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4828
5012
  return null;
4829
5013
  }
4830
5014
  }
5015
+ var X25519_PKCS8_PREFIX = Uint8Array.from([
5016
+ 48,
5017
+ 46,
5018
+ 2,
5019
+ 1,
5020
+ 0,
5021
+ 48,
5022
+ 5,
5023
+ 6,
5024
+ 3,
5025
+ 43,
5026
+ 101,
5027
+ 110,
5028
+ 4,
5029
+ 34,
5030
+ 4,
5031
+ 32
5032
+ ]);
5033
+ var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
5034
+ function decodeOpened(plaintext) {
5035
+ if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5036
+ return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5037
+ }
5038
+ async function createRecipientDeliveryOpener(viewingSecretKey) {
5039
+ if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
5040
+ throw new Error("viewingSecretKey must be 32 bytes");
5041
+ }
5042
+ const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5043
+ const subtle = globalThis.crypto?.subtle;
5044
+ const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
5045
+ if (!subtle || typeof hsalsa !== "function") return slow;
5046
+ let privateKey;
5047
+ const sharedKey = async (ephemeralPk) => {
5048
+ const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
5049
+ const shared = new Uint8Array(
5050
+ await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
5051
+ );
5052
+ const key = new Uint8Array(32);
5053
+ hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
5054
+ return key;
5055
+ };
5056
+ try {
5057
+ const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
5058
+ pkcs8.set(X25519_PKCS8_PREFIX);
5059
+ pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5060
+ privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5061
+ const probe = nacl4.box.keyPair().publicKey;
5062
+ const fast = await sharedKey(probe);
5063
+ const reference = nacl4.box.before(probe, viewingSecretKey);
5064
+ if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5065
+ } catch {
5066
+ return slow;
5067
+ }
5068
+ return async (envelope) => {
5069
+ if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
5070
+ const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
5071
+ const nonce = envelope.subarray(
5072
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
5073
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5074
+ );
5075
+ const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
5076
+ let key;
5077
+ try {
5078
+ key = await sharedKey(ephemeralPk);
5079
+ } catch {
5080
+ return openRecipientDeliveryNote(envelope, viewingSecretKey);
5081
+ }
5082
+ try {
5083
+ return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
5084
+ } catch {
5085
+ return null;
5086
+ }
5087
+ };
5088
+ }
4831
5089
  function recipientDeliveryNoteToBase64(envelope) {
4832
5090
  return Buffer.from(envelope).toString("base64");
4833
5091
  }
@@ -4880,9 +5138,41 @@ function parseDeliveryCarrierMemo(data) {
4880
5138
  // src/notes/swap-refund.ts
4881
5139
  import { blake3 as blake33 } from "@noble/hashes/blake3";
4882
5140
  import _bs582 from "bs58";
5141
+
5142
+ // src/notes/owner-key.ts
5143
+ var FIELD_MODULUS = BigInt(
5144
+ "21888242871839275222246405745257275088548364400416034343698204186575808495617"
5145
+ );
5146
+ async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
5147
+ if (!keypair || typeof keypair !== "object") {
5148
+ throw new Error(
5149
+ `${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.`
5150
+ );
5151
+ }
5152
+ const { privateKey, publicKey } = keypair;
5153
+ if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS) {
5154
+ throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
5155
+ }
5156
+ if (typeof publicKey !== "bigint" || publicKey === 0n) {
5157
+ throw new Error(`${label}.publicKey must be a non-zero bigint`);
5158
+ }
5159
+ if (await derivePublicKey(privateKey) !== publicKey) {
5160
+ throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
5161
+ }
5162
+ return { privateKey, publicKey };
5163
+ }
5164
+ function normalizeOwnerPublicKey(publicKey, label) {
5165
+ if (publicKey === void 0 || publicKey === null) return void 0;
5166
+ if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS) {
5167
+ throw new Error(`${label} must be a non-zero field element (bigint)`);
5168
+ }
5169
+ return publicKey;
5170
+ }
5171
+
5172
+ // src/notes/swap-refund.ts
4883
5173
  var bs582 = _bs582.default || _bs582;
4884
5174
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
4885
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5175
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
4886
5176
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
4887
5177
  function normalizeNullifier(inputNullifier) {
4888
5178
  if (inputNullifier instanceof Uint8Array) {
@@ -4916,13 +5206,29 @@ function derive(nk, nullifier, info) {
4916
5206
  preimage.set(info, off);
4917
5207
  return blake33(preimage);
4918
5208
  }
4919
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5209
+ function assertNk(viewingKeyNk) {
4920
5210
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
4921
5211
  throw new Error("viewingKeyNk must be 32 bytes");
4922
5212
  }
5213
+ return viewingKeyNk;
5214
+ }
5215
+ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
5216
+ const nk = assertNk(viewingKeyNk);
5217
+ return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
5218
+ }
5219
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
5220
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5221
+ const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5222
+ if (owner.publicKey === 0n || blinding === 0n) {
5223
+ throw new Error("refund authorization is degenerate");
5224
+ }
5225
+ return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
5226
+ }
5227
+ async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5228
+ const nk = assertNk(viewingKeyNk);
4923
5229
  const nullifier = normalizeNullifier(inputNullifier);
4924
- const privateKey = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_PRIVATE_KEY_INFO));
4925
- const blinding = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_BLINDING_INFO));
5230
+ const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
5231
+ const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
4926
5232
  const publicKey = await derivePublicKey(privateKey);
4927
5233
  if (publicKey === 0n || blinding === 0n) {
4928
5234
  throw new Error("derived refund authorization is degenerate");
@@ -4940,19 +5246,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
4940
5246
  async function matchSwapRefundLeaf(params) {
4941
5247
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
4942
5248
  const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
4943
- let auth;
5249
+ let blinding;
5250
+ try {
5251
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5252
+ } catch {
5253
+ return null;
5254
+ }
5255
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5256
+ if (ownerPub !== void 0) {
5257
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
5258
+ if (candidate === expected) {
5259
+ return {
5260
+ keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
5261
+ blinding,
5262
+ amount: amountAfterFee,
5263
+ commitment: candidate,
5264
+ legacyExposed: false
5265
+ };
5266
+ }
5267
+ }
5268
+ let legacy;
4944
5269
  try {
4945
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
5270
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
4946
5271
  } catch {
4947
5272
  return null;
4948
5273
  }
4949
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
4950
- if (candidate !== expected) return null;
5274
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
5275
+ if (legacyCandidate !== expected) return null;
4951
5276
  return {
4952
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
4953
- blinding: auth.blinding,
5277
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
5278
+ blinding: legacy.blinding,
4954
5279
  amount: amountAfterFee,
4955
- commitment: candidate
5280
+ commitment: legacyCandidate,
5281
+ legacyExposed: true
4956
5282
  };
4957
5283
  }
4958
5284
  var TRANSACT_SWAP_TAG2 = 1;
@@ -5016,10 +5342,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
5016
5342
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
5017
5343
  return out;
5018
5344
  }
5019
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
5345
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
5020
5346
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5021
5347
  throw new Error("viewingKeyNk must be 32 bytes");
5022
5348
  }
5349
+ if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
5350
+ throw new Error(
5351
+ "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are owned by it, and nk alone can only find legacy refunds."
5352
+ );
5353
+ }
5354
+ const ownerUtxoKeypair = options.ownerUtxoKeypair;
5023
5355
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5024
5356
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5025
5357
  const programIdBase58 = programId;
@@ -5094,7 +5426,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5094
5426
  viewingKeyNk,
5095
5427
  inputNullifier: candidate.nullifier,
5096
5428
  amountAfterFee: event.amountAfterFee,
5097
- commitment: event.commitmentField
5429
+ commitment: event.commitmentField,
5430
+ ownerUtxoKeypair
5098
5431
  });
5099
5432
  if (!recovered) continue;
5100
5433
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5118,7 +5451,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5118
5451
  // src/notes/deposit-note.ts
5119
5452
  import { blake3 as blake34 } from "@noble/hashes/blake3";
5120
5453
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5121
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5454
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5122
5455
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5123
5456
  var CHAIN_NOTE_SALT_BITS = 96;
5124
5457
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -5154,30 +5487,47 @@ function derive2(nk, salt, info) {
5154
5487
  preimage.set(info, off);
5155
5488
  return blake34(preimage);
5156
5489
  }
5490
+ function assertNk2(viewingKeyNk) {
5491
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5492
+ throw new Error("viewingKeyNk must be 32 bytes");
5493
+ }
5494
+ return viewingKeyNk;
5495
+ }
5157
5496
  function randomDepositNoteSalt() {
5158
5497
  const bytes = randomBytes(12);
5159
5498
  let v = 0n;
5160
5499
  for (const b of bytes) v = v << 8n | BigInt(b);
5161
5500
  return v === 0n ? 1n : v;
5162
5501
  }
5163
- async function deriveDepositNoteSecrets(viewingKeyNk, noteSalt) {
5164
- if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5165
- throw new Error("viewingKeyNk must be 32 bytes");
5166
- }
5502
+ function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
5503
+ const nk = assertNk2(viewingKeyNk);
5504
+ return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
5505
+ }
5506
+ async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
5507
+ const nk = assertNk2(viewingKeyNk);
5167
5508
  const salt = saltToBytes(noteSalt);
5168
- const privateKey = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_PRIVATE_KEY_INFO));
5169
- const blinding = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_BLINDING_INFO));
5509
+ const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
5510
+ const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
5170
5511
  const publicKey = await derivePublicKey(privateKey);
5171
5512
  if (publicKey === 0n || blinding === 0n) {
5172
5513
  throw new Error("derived deposit note secrets are degenerate");
5173
5514
  }
5174
5515
  return { keypair: { privateKey, publicKey }, blinding };
5175
5516
  }
5176
- async function createRecoverableDepositUtxo(amount, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomDepositNoteSalt()) {
5517
+ async function createRecoverableDepositUtxo(params) {
5518
+ if (!params || typeof params !== "object" || params instanceof Uint8Array) {
5519
+ throw new Error(
5520
+ "createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
5521
+ );
5522
+ }
5523
+ const { amount, viewingKeyNk } = params;
5177
5524
  if (typeof amount !== "bigint" || amount <= 0n) {
5178
5525
  throw new Error("amount must be a positive bigint");
5179
5526
  }
5180
- const { keypair, blinding } = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5527
+ const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
5528
+ const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
5529
+ const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
5530
+ const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5181
5531
  const utxo = { amount, keypair, blinding, mintAddress };
5182
5532
  utxo.commitment = await computeCommitment(utxo);
5183
5533
  return { utxo, noteSalt };
@@ -5192,21 +5542,46 @@ function normalizeCommitment(value) {
5192
5542
  async function matchDepositNote(params) {
5193
5543
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
5194
5544
  if (typeof amount !== "bigint" || amount <= 0n) return null;
5195
- let secrets;
5545
+ let blinding;
5546
+ try {
5547
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5548
+ } catch {
5549
+ return null;
5550
+ }
5551
+ const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
5552
+ if (published.length === 0) return null;
5553
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5554
+ if (ownerPub !== void 0) {
5555
+ const keypair = {
5556
+ privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
5557
+ publicKey: ownerPub
5558
+ };
5559
+ const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5560
+ if (published.some((value) => value === candidate)) {
5561
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
5562
+ }
5563
+ }
5564
+ let legacy;
5196
5565
  try {
5197
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5566
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
5198
5567
  } catch {
5199
5568
  return null;
5200
5569
  }
5201
- const candidate = await computeCommitment({
5570
+ const legacyCandidate = await computeCommitment({
5202
5571
  amount,
5203
- keypair: secrets.keypair,
5204
- blinding: secrets.blinding,
5572
+ keypair: legacy.keypair,
5573
+ blinding: legacy.blinding,
5205
5574
  mintAddress
5206
5575
  });
5207
- const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
5208
- if (!published.some((value) => value === candidate)) return null;
5209
- return { ...secrets, amount, mintAddress, commitment: candidate, noteSalt };
5576
+ if (!published.some((value) => value === legacyCandidate)) return null;
5577
+ return {
5578
+ ...legacy,
5579
+ amount,
5580
+ mintAddress,
5581
+ commitment: legacyCandidate,
5582
+ noteSalt,
5583
+ legacyExposed: true
5584
+ };
5210
5585
  }
5211
5586
 
5212
5587
  // src/notes/change-note.ts
@@ -5262,10 +5637,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
5262
5637
  preimage.set(CHANGE_BLINDING_INFO, off);
5263
5638
  return toFieldSecret3(blake35(preimage));
5264
5639
  }
5265
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5640
+ async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5266
5641
  if (typeof amount !== "bigint" || amount <= 0n) {
5267
5642
  throw new Error("amount must be a positive bigint");
5268
5643
  }
5644
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5269
5645
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5270
5646
  const utxo = { amount, keypair, blinding, mintAddress };
5271
5647
  utxo.commitment = await computeCommitment(utxo);
@@ -5291,13 +5667,27 @@ async function matchChangeNote(params) {
5291
5667
  const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5292
5668
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
5293
5669
  if (!published.some((value) => value === candidate)) return null;
5294
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
5670
+ const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
5671
+ const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
5672
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
5295
5673
  }
5296
5674
 
5297
5675
  // src/flows/transact.ts
5298
5676
  import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
5299
5677
  import nacl5 from "tweetnacl";
5300
5678
 
5679
+ // src/relay/chain-note-time.ts
5680
+ async function relayChainNoteTimestampMs(relayUrl) {
5681
+ if (relayUrl && !hasRelayClockSample()) {
5682
+ try {
5683
+ const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
5684
+ await response.body?.cancel?.().catch(() => void 0);
5685
+ } catch {
5686
+ }
5687
+ }
5688
+ return BigInt(relayNowMs());
5689
+ }
5690
+
5301
5691
  // src/proving/artifacts.ts
5302
5692
  import { sha256 as sha2564 } from "@noble/hashes/sha2";
5303
5693
 
@@ -5584,6 +5974,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
5584
5974
  var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
5585
5975
  var DEFAULT_RELAY_NETWORK_RETRIES = 6;
5586
5976
  var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
5977
+ var RELAY_SOURCE_LEASE_MS = 18e4;
5978
+ var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
5979
+ var MAX_LEASE_EXPIRY_REPLAYS = 2;
5980
+ var RELAY_IN_FLIGHT_POLL_MS = 5e3;
5981
+ var RELAY_LANDED_POLL_MS = 1e3;
5982
+ var MAX_LANDED_POLLS = 5;
5587
5983
  function parseMissingRelayIndexError(message) {
5588
5984
  const match = message.match(
5589
5985
  /Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
@@ -5934,6 +6330,33 @@ function parseNkInput(input) {
5934
6330
  }
5935
6331
  return Uint8Array.from(Buffer.from(clean, "hex"));
5936
6332
  }
6333
+ async function resolveWalletNk(options) {
6334
+ const explicit = await resolveChainNoteNk(options);
6335
+ if (explicit) return explicit;
6336
+ if (options.ownerUtxoKeypair) {
6337
+ const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
6338
+ return getNkFromUtxoPrivateKey(owner.privateKey);
6339
+ }
6340
+ return null;
6341
+ }
6342
+ function missingWalletNkError(flow) {
6343
+ return new Error(
6344
+ `${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.`
6345
+ );
6346
+ }
6347
+ async function requireWalletNk(options, flow) {
6348
+ const nk = await resolveWalletNk(options);
6349
+ if (nk) return nk;
6350
+ throw missingWalletNkError(flow);
6351
+ }
6352
+ async function requireOwnerUtxoKeypair(options, flow) {
6353
+ if (!options.ownerUtxoKeypair) {
6354
+ throw new Error(
6355
+ `${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].`
6356
+ );
6357
+ }
6358
+ return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
6359
+ }
5937
6360
  async function resolveChainNoteNk(options) {
5938
6361
  if (options.chainNoteViewingKeyNk) {
5939
6362
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -5951,7 +6374,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
5951
6374
  function toHex(bytes) {
5952
6375
  return Buffer.from(bytes).toString("hex");
5953
6376
  }
5954
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6377
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
5955
6378
  if (options.enforceViewingKeyRegistration === false) {
5956
6379
  return;
5957
6380
  }
@@ -5965,7 +6388,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5965
6388
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
5966
6389
  );
5967
6390
  }
5968
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
6391
+ const nk = walletNk;
5969
6392
  if (!nk || nk.length !== 32) {
5970
6393
  throw new Error(
5971
6394
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6107,10 +6530,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6107
6530
  result.set(bigintToBytes322(BigInt(publicSignals[0])), offset);
6108
6531
  offset += 32;
6109
6532
  let amount = BigInt(publicSignals[1]);
6110
- const FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6111
- const HALF_FIELD = FIELD_MODULUS / BigInt(2);
6533
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6534
+ const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
6112
6535
  if (amount > HALF_FIELD) {
6113
- amount = amount - FIELD_MODULUS;
6536
+ amount = amount - FIELD_MODULUS2;
6114
6537
  }
6115
6538
  const amountBytes = new Uint8Array(8);
6116
6539
  let amountValue = amount;
@@ -7057,8 +7480,9 @@ function chargeWalletApproval(used, budget, lastError) {
7057
7480
  }
7058
7481
  return used + 1;
7059
7482
  }
7060
- function relayFailureMessage(prefix, responseText) {
7061
- const explanation = explainRelayAuthRejection(responseText);
7483
+ function relayFailureMessage(prefix, responseText, requestBody) {
7484
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
7485
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7062
7486
  return explanation ? `${prefix}: ${responseText}
7063
7487
 
7064
7488
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -7140,6 +7564,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
7140
7564
  function sleep2(ms) {
7141
7565
  return new Promise((resolve) => setTimeout(resolve, ms));
7142
7566
  }
7567
+ function sleepUnlessAborted(ms, signal) {
7568
+ if (signal?.aborted) return Promise.resolve(false);
7569
+ return new Promise((resolve) => {
7570
+ const onAbort = () => {
7571
+ clearTimeout(timer);
7572
+ resolve(false);
7573
+ };
7574
+ const timer = setTimeout(() => {
7575
+ signal?.removeEventListener("abort", onAbort);
7576
+ resolve(true);
7577
+ }, ms);
7578
+ signal?.addEventListener("abort", onAbort, { once: true });
7579
+ });
7580
+ }
7143
7581
  function hexToBytes2(hex) {
7144
7582
  const bytes = new Uint8Array(hex.length / 2);
7145
7583
  for (let i = 0; i < hex.length; i += 2) {
@@ -7374,6 +7812,9 @@ async function submitTransactToRelay(args) {
7374
7812
  let unknownOutcomeSignature = null;
7375
7813
  let possiblySubmitted = false;
7376
7814
  let networkRetry = 0;
7815
+ let leaseReplays = 0;
7816
+ let landedPolls = 0;
7817
+ let leaseBaseMs = null;
7377
7818
  const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
7378
7819
  connection: settlement.connection,
7379
7820
  programId: settlement.programId,
@@ -7429,6 +7870,7 @@ async function submitTransactToRelay(args) {
7429
7870
  const controller = new AbortController();
7430
7871
  const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
7431
7872
  let response;
7873
+ leaseBaseMs ?? (leaseBaseMs = Date.now());
7432
7874
  try {
7433
7875
  response = await doFetch(`${relayUrl}/transact`, {
7434
7876
  method: "POST",
@@ -7436,6 +7878,7 @@ async function submitTransactToRelay(args) {
7436
7878
  body: requestPayload,
7437
7879
  signal: controller.signal
7438
7880
  });
7881
+ observeRelayClock(response);
7439
7882
  } finally {
7440
7883
  clearTimeout(timeoutId);
7441
7884
  }
@@ -7446,6 +7889,49 @@ async function submitTransactToRelay(args) {
7446
7889
  if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
7447
7890
  possiblySubmitted = true;
7448
7891
  }
7892
+ if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
7893
+ networkRetry = 0;
7894
+ const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
7895
+ const polling = Date.now() < leaseEndsMs;
7896
+ const probe = await verifySettlement(
7897
+ unknownOutcomeSignature,
7898
+ polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
7899
+ );
7900
+ if (probe.status === "landed") {
7901
+ landedPolls++;
7902
+ if (!polling || landedPolls > MAX_LANDED_POLLS) {
7903
+ return await resolveFailure(
7904
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
7905
+ );
7906
+ }
7907
+ if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
7908
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
7909
+ }
7910
+ continue;
7911
+ }
7912
+ if (polling) {
7913
+ onProgress?.("Relay is still processing this request; checking again shortly...");
7914
+ const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
7915
+ if (!await sleepUnlessAborted(pollMs, args.signal)) {
7916
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
7917
+ }
7918
+ continue;
7919
+ }
7920
+ leaseReplays++;
7921
+ const waitMs = Math.max(
7922
+ 0,
7923
+ (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
7924
+ );
7925
+ onProgress?.(
7926
+ `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})...`
7927
+ );
7928
+ if (!await sleepUnlessAborted(waitMs, args.signal)) {
7929
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
7930
+ }
7931
+ networkRetry = 0;
7932
+ leaseBaseMs = null;
7933
+ continue;
7934
+ }
7449
7935
  if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
7450
7936
  networkRetry++;
7451
7937
  const delay = relayBackoffMs(networkRetry);
@@ -7466,7 +7952,9 @@ async function submitTransactToRelay(args) {
7466
7952
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
7467
7953
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
7468
7954
  }
7469
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
7955
+ return await resolveFailure(
7956
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
7957
+ );
7470
7958
  }
7471
7959
  const apiResponse = JSON.parse(responseText);
7472
7960
  if (!apiResponse.success || !apiResponse.data) {
@@ -7483,7 +7971,7 @@ async function submitTransactToRelay(args) {
7483
7971
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
7484
7972
  }
7485
7973
  return await resolveFailure(
7486
- new Error(relayFailureMessage("Relay returned error", errorStr))
7974
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
7487
7975
  );
7488
7976
  }
7489
7977
  const result = apiResponse.data;
@@ -7591,34 +8079,37 @@ async function transact(params, options) {
7591
8079
  );
7592
8080
  }
7593
8081
  onProgress?.("Validating transaction parameters...");
7594
- const firstInputWithAmount = inputUtxos.find((u) => u.amount > BigInt(0));
7595
- const firstOutputWithAmount = outputUtxos.find((u) => u.amount > BigInt(0));
7596
- const fallbackNk = firstOutputWithAmount ? getNkFromUtxoPrivateKey(firstOutputWithAmount.keypair.privateKey) : firstInputWithAmount ? getNkFromUtxoPrivateKey(firstInputWithAmount.keypair.privateKey) : void 0;
7597
- const explicitChainNoteNk = await resolveChainNoteNk(options);
7598
- if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
8082
+ const walletNk = await resolveWalletNk(options);
8083
+ const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
8084
+ if (options.chainNoteSalt !== void 0 && !walletNk) {
7599
8085
  throw new Error(
7600
- "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."
8086
+ "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."
7601
8087
  );
7602
8088
  }
7603
8089
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
7604
8090
  const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
7605
- if (explicitChainNoteNk && chainNoteWillCarrySalt) {
7606
- const inputOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8091
+ if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
8092
+ throw missingWalletNkError("transact");
8093
+ }
8094
+ if (walletNk && chainNoteWillCarrySalt) {
8095
+ const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8096
+ if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
8097
+ const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
7607
8098
  for (let i = 0; i < outputUtxos.length; i++) {
7608
8099
  const out = outputUtxos[i];
7609
8100
  if (!out || out.amount <= BigInt(0)) continue;
7610
- if (!inputOwners.has(out.keypair.publicKey)) continue;
7611
- if (out.blinding !== deriveChangeNoteBlinding(explicitChainNoteNk, chainNoteSalt, i)) {
8101
+ if (!selfOwners.has(out.keypair.publicKey)) continue;
8102
+ if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
7612
8103
  throw new Error(
7613
- `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.`
8104
+ `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.`
7614
8105
  );
7615
8106
  }
7616
8107
  }
7617
8108
  }
7618
8109
  assertAllowedRpcConnection(connection);
7619
8110
  assertInputMints(inputUtxos, options.expectedMint);
7620
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
7621
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
8111
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
8112
+ const resolvedChainNoteNk = walletNk;
7622
8113
  if (inputUtxos.length > 2) {
7623
8114
  throw new Error("Maximum 2 input UTXOs allowed");
7624
8115
  }
@@ -7992,7 +8483,7 @@ async function transact(params, options) {
7992
8483
  }
7993
8484
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
7994
8485
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
7995
- const chainNoteTimestamp = BigInt(Date.now());
8486
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
7996
8487
  const mintField = pubkeyToFieldElement(mint);
7997
8488
  let signature = "pending-" + Date.now().toString();
7998
8489
  let commitmentIndices = [-1, -1];
@@ -8088,9 +8579,9 @@ async function transact(params, options) {
8088
8579
  ]));
8089
8580
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8090
8581
  const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
8091
- const FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8092
- if (chainNoteHash >= FIELD_MODULUS) {
8093
- throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS.toString()}`);
8582
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8583
+ if (chainNoteHash >= FIELD_MODULUS2) {
8584
+ throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
8094
8585
  }
8095
8586
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8096
8587
  const totalInputs = 1 + // root
@@ -8512,7 +9003,8 @@ async function transact(params, options) {
8512
9003
  throw lastError;
8513
9004
  }
8514
9005
  const classified = classifyRelayError(lastError.message);
8515
- const isMerkleClass = !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9006
+ const isDepositSubmission = externalAmount > BigInt(0);
9007
+ const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
8516
9008
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
8517
9009
  onProgress?.(
8518
9010
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -8661,54 +9153,83 @@ async function transact(params, options) {
8661
9153
  };
8662
9154
  }
8663
9155
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
9156
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
9157
+ const transferNk = await requireWalletNk(options, "transfer");
8664
9158
  const inputSum = sumUtxoAmounts(inputUtxos);
8665
9159
  if (inputSum < amount) {
8666
9160
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
8667
9161
  }
8668
9162
  const change = inputSum - amount;
8669
- const myKeypair = inputUtxos[0].keypair;
8670
9163
  const mint = inputUtxos[0].mintAddress;
8671
- const transferNk = await resolveChainNoteNk(options);
8672
- const changeNoteSalt = transferNk ? randomChangeNoteSalt() : void 0;
8673
- const isSendToSelf = inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
9164
+ let spendInputs = [
9165
+ ...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
9166
+ ...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
9167
+ ];
9168
+ let spendOptions = options;
9169
+ if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
9170
+ if (spendInputs.length > 2) {
9171
+ throw new Error(
9172
+ `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.`
9173
+ );
9174
+ }
9175
+ if (options.relayAuthBatch) {
9176
+ throw new Error(
9177
+ "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."
9178
+ );
9179
+ }
9180
+ options.onProgress?.("Moving notes under the wallet key before the transfer...");
9181
+ const migrationSalt = randomChangeNoteSalt();
9182
+ const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
9183
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
9184
+ void _recipientViewingPublicKey;
9185
+ const migration = await transact(
9186
+ { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
9187
+ { ...migrationOptions, chainNoteSalt: migrationSalt }
9188
+ );
9189
+ const migratedNote = migration.outputUtxos?.[0] ?? migrated;
9190
+ if (migration.commitmentIndices?.[0] >= 0) {
9191
+ migratedNote.index = migration.commitmentIndices[0];
9192
+ }
9193
+ spendInputs = [migratedNote];
9194
+ spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
9195
+ }
9196
+ const changeNoteSalt = randomChangeNoteSalt();
9197
+ const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
8674
9198
  const recipientKeypair = {
8675
9199
  privateKey: BigInt(0),
8676
9200
  // Recipient's private key unknown
8677
9201
  publicKey: recipientPubkey
8678
9202
  };
8679
- const recipientUtxo = transferNk && isSendToSelf ? (await createRecoverableChangeUtxo(amount, myKeypair, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
9203
+ const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
8680
9204
  const outputUtxos = [recipientUtxo];
8681
9205
  if (change > BigInt(0)) {
8682
- if (transferNk) {
8683
- const { utxo } = await createRecoverableChangeUtxo(
8684
- change,
8685
- myKeypair,
8686
- transferNk,
8687
- mint,
8688
- changeNoteSalt,
8689
- 1
8690
- );
8691
- outputUtxos.push(utxo);
8692
- } else {
8693
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
8694
- }
9206
+ const { utxo } = await createRecoverableChangeUtxo(
9207
+ change,
9208
+ owner,
9209
+ transferNk,
9210
+ mint,
9211
+ changeNoteSalt,
9212
+ 1
9213
+ );
9214
+ outputUtxos.push(utxo);
8695
9215
  }
8696
9216
  return transact(
8697
9217
  {
8698
- inputUtxos,
9218
+ inputUtxos: spendInputs,
8699
9219
  outputUtxos,
8700
9220
  externalAmount: BigInt(0)
8701
9221
  // Pure shield-to-shield
8702
9222
  },
8703
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
9223
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
8704
9224
  );
8705
9225
  }
8706
9226
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9227
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
9228
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
8707
9229
  const inputSum = sumUtxoAmounts(inputUtxos);
8708
9230
  if (inputSum < withdrawAmount) {
8709
9231
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
8710
9232
  }
8711
- const myKeypair = inputUtxos[0].keypair;
8712
9233
  const mint = inputUtxos[0].mintAddress;
8713
9234
  let utxos = [...inputUtxos];
8714
9235
  let cachedTree = options.cachedMerkleTree;
@@ -8717,9 +9238,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8717
9238
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
8718
9239
  const [small1, small2, ...rest] = utxos;
8719
9240
  const mergedAmount = small1.amount + small2.amount;
8720
- const mergeNk = await resolveChainNoteNk(options);
8721
- const mergeSalt = mergeNk ? randomChangeNoteSalt() : void 0;
8722
- const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
9241
+ const mergeSalt = randomChangeNoteSalt();
9242
+ const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
8723
9243
  const mergeResult = await transact(
8724
9244
  {
8725
9245
  inputUtxos: [small1, small2],
@@ -8730,7 +9250,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8730
9250
  {
8731
9251
  ...options,
8732
9252
  cachedMerkleTree: cachedTree,
8733
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
9253
+ chainNoteSalt: mergeSalt
8734
9254
  }
8735
9255
  );
8736
9256
  cachedTree = mergeResult.merkleTree;
@@ -8745,23 +9265,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8745
9265
  const outputUtxos = [];
8746
9266
  let changeNoteSalt;
8747
9267
  if (change > BigInt(0)) {
8748
- const changeNk = await resolveChainNoteNk(options);
8749
- if (changeNk) {
8750
- const salt = randomChangeNoteSalt();
8751
- const { utxo } = await createRecoverableChangeUtxo(
8752
- change,
8753
- myKeypair,
8754
- changeNk,
8755
- mint,
8756
- salt,
8757
- 0
8758
- // partialWithdraw puts change at output 0
8759
- );
8760
- outputUtxos.push(utxo);
8761
- changeNoteSalt = salt;
8762
- } else {
8763
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
8764
- }
9268
+ const salt = randomChangeNoteSalt();
9269
+ const { utxo } = await createRecoverableChangeUtxo(
9270
+ change,
9271
+ owner,
9272
+ walletNk,
9273
+ mint,
9274
+ salt,
9275
+ 0
9276
+ // partialWithdraw puts change at output 0
9277
+ );
9278
+ outputUtxos.push(utxo);
9279
+ changeNoteSalt = salt;
8765
9280
  }
8766
9281
  return transact(
8767
9282
  {
@@ -8884,6 +9399,8 @@ async function swapUtxo(params, options) {
8884
9399
  if (relayUrl) {
8885
9400
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
8886
9401
  }
9402
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
9403
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
8887
9404
  if (inputUtxos.length === 0) {
8888
9405
  throw new Error("At least one input UTXO required");
8889
9406
  }
@@ -8909,15 +9426,12 @@ async function swapUtxo(params, options) {
8909
9426
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
8910
9427
  }
8911
9428
  onProgress?.("Validating transaction parameters...");
8912
- const swapFallbackNk = getNkFromUtxoPrivateKey(inputUtxos[0].keypair.privateKey);
8913
- await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
8914
- const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
8915
- const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
9429
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
8916
9430
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
8917
- if (explicitSwapChainNoteNk && changeUtxo && changeUtxo.amount > BigInt(0) && inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey)) {
8918
- if (changeUtxo.blinding !== deriveChangeNoteBlinding(explicitSwapChainNoteNk, chainNoteSalt, 0)) {
9431
+ if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
9432
+ if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
8919
9433
  throw new Error(
8920
- `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.`
9434
+ `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.`
8921
9435
  );
8922
9436
  }
8923
9437
  }
@@ -8941,24 +9455,18 @@ async function swapUtxo(params, options) {
8941
9455
  );
8942
9456
  }
8943
9457
  const externalAmount = -swapAmount;
8944
- let refundKeypair;
8945
- let refundBlinding;
8946
- let refundDerivedFromNk = false;
8947
- if (resolvedSwapChainNoteNk) {
8948
- try {
8949
- const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
8950
- const derived = await deriveSwapRefundAuthorization(resolvedSwapChainNoteNk, refundNullifier);
8951
- refundKeypair = { privateKey: derived.privateKey, publicKey: derived.publicKey };
8952
- refundBlinding = derived.blinding;
8953
- refundDerivedFromNk = true;
8954
- } catch {
8955
- refundKeypair = await generateUtxoKeypair();
8956
- refundBlinding = randomFieldElement();
8957
- }
8958
- } else {
8959
- refundKeypair = await generateUtxoKeypair();
8960
- refundBlinding = randomFieldElement();
8961
- }
9458
+ const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
9459
+ const refundAuthorization = await deriveSwapRefundAuthorization(
9460
+ resolvedSwapChainNoteNk,
9461
+ refundNullifier,
9462
+ swapOwner
9463
+ );
9464
+ const refundKeypair = {
9465
+ privateKey: refundAuthorization.privateKey,
9466
+ publicKey: refundAuthorization.publicKey
9467
+ };
9468
+ const refundBlinding = refundAuthorization.blinding;
9469
+ const refundDerivedFromNk = true;
8962
9470
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
8963
9471
  throw new Error(
8964
9472
  "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."
@@ -9284,7 +9792,7 @@ async function swapUtxo(params, options) {
9284
9792
  for (const utxo of paddedOutputs) {
9285
9793
  outputCommitments.push(await computeCommitment(utxo));
9286
9794
  }
9287
- const chainNoteTimestamp = BigInt(Date.now());
9795
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
9288
9796
  onProgress?.("Computing external data hash...");
9289
9797
  const mint = swapPoolMint;
9290
9798
  const mintField = pubkeyToFieldElement(mint);
@@ -9598,7 +10106,7 @@ async function swapUtxo(params, options) {
9598
10106
  forceChainIndexing = !relayUrl;
9599
10107
  continue;
9600
10108
  }
9601
- throw new Error(relayFailureMessage("Relay error", responseText));
10109
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
9602
10110
  }
9603
10111
  const apiResponse = JSON.parse(responseText);
9604
10112
  if (!apiResponse.success || !apiResponse.data) {
@@ -9734,7 +10242,6 @@ async function swapUtxo(params, options) {
9734
10242
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
9735
10243
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
9736
10244
  refund: {
9737
- privateKey: Buffer.from(bigintToBytes322(refundKeypair.privateKey)).toString("hex"),
9738
10245
  publicKey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("hex"),
9739
10246
  blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("hex"),
9740
10247
  derivedFromNk: refundDerivedFromNk
@@ -9742,6 +10249,7 @@ async function swapUtxo(params, options) {
9742
10249
  };
9743
10250
  }
9744
10251
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
10252
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
9745
10253
  const totalInput = sumUtxoAmounts(inputUtxos);
9746
10254
  const change = totalInput - swapAmount;
9747
10255
  if (change < BigInt(0)) {
@@ -9750,16 +10258,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
9750
10258
  let changeUtxo;
9751
10259
  let changeNoteSalt;
9752
10260
  if (change > BigInt(0)) {
9753
- const myKeypair = inputUtxos[0].keypair;
9754
10261
  const mint = inputUtxos[0].mintAddress;
9755
- const changeNk = await resolveChainNoteNk(options);
9756
- if (changeNk) {
9757
- const salt = randomChangeNoteSalt();
9758
- changeUtxo = (await createRecoverableChangeUtxo(change, myKeypair, changeNk, mint, salt, 0)).utxo;
9759
- changeNoteSalt = salt;
9760
- } else {
9761
- changeUtxo = await createUtxo(change, myKeypair, mint);
9762
- }
10262
+ const changeNk = await requireWalletNk(options, "swapWithChange");
10263
+ const salt = randomChangeNoteSalt();
10264
+ changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
10265
+ changeNoteSalt = salt;
9763
10266
  }
9764
10267
  return swapUtxo(
9765
10268
  {
@@ -10082,7 +10585,7 @@ var RelayBatchAuthCoordinator = class {
10082
10585
  throw new Error("Every item of a batch must target the same program id.");
10083
10586
  }
10084
10587
  }
10085
- const nowSeconds = Math.floor(Date.now() / 1e3);
10588
+ const nowSeconds = relayNowSeconds();
10086
10589
  const preimages = waiting.map(
10087
10590
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10088
10591
  );
@@ -10520,7 +11023,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
10520
11023
  const cached = depositSecretsCache.get(key);
10521
11024
  if (cached) return cached;
10522
11025
  try {
10523
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
11026
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
10524
11027
  if (depositSecretsCache.size >= 4096) {
10525
11028
  const oldest = depositSecretsCache.keys().next();
10526
11029
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11103,6 +11606,7 @@ async function scanTransactions(opts) {
11103
11606
  } else {
11104
11607
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11105
11608
  const candidateKeys = [
11609
+ opts.ownerUtxoPublicKey,
11106
11610
  derived?.keypair.publicKey,
11107
11611
  opts.ownUtxoPublicKey,
11108
11612
  BigInt(0)
@@ -11156,6 +11660,7 @@ async function scanTransactions(opts) {
11156
11660
  try {
11157
11661
  const recoveredDeposit = await matchDepositNote({
11158
11662
  viewingKeyNk,
11663
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
11159
11664
  noteSalt: compactNote.noteSalt,
11160
11665
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
11161
11666
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -11190,7 +11695,8 @@ async function scanTransactions(opts) {
11190
11695
  mintAddress: address(asset.mint),
11191
11696
  outputIndex: 0,
11192
11697
  // v4 describes output 0, which is where change lands
11193
- outputCommitments: ixCtx.outputCommitments ?? []
11698
+ outputCommitments: ixCtx.outputCommitments ?? [],
11699
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
11194
11700
  });
11195
11701
  if (recoveredChange) {
11196
11702
  recoveredChangeNotes.push({
@@ -11300,6 +11806,17 @@ async function scanTransactions(opts) {
11300
11806
  runningByAsset.set(key, running);
11301
11807
  tx.runningBalance = running;
11302
11808
  }
11809
+ const legacyKeys = /* @__PURE__ */ new Map();
11810
+ for (const note of recoveredDepositNotes) {
11811
+ if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
11812
+ }
11813
+ for (const change of recoveredChangeNotes) {
11814
+ const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
11815
+ if (legacyPrivateKey !== void 0) {
11816
+ change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
11817
+ change.legacyExposed = true;
11818
+ }
11819
+ }
11303
11820
  return {
11304
11821
  transactions: txs,
11305
11822
  summary: {
@@ -11379,31 +11896,1657 @@ function formatComplianceCsv(report) {
11379
11896
  return header + rows;
11380
11897
  }
11381
11898
 
11382
- // src/wallet/utxo-wallet.ts
11383
- var UtxoWallet = class _UtxoWallet {
11384
- constructor(viewingKey) {
11385
- this.wallets = /* @__PURE__ */ new Map();
11386
- this.viewingKey = viewingKey;
11899
+ // src/relay/note-index-format.ts
11900
+ import { sha256 as sha2565 } from "@noble/hashes/sha2";
11901
+ var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
11902
+ var NOTE_INDEX_FORMAT_VERSION = 1;
11903
+ var NOTE_INDEX_PAGE_SIZE = 1024;
11904
+ var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
11905
+ var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
11906
+ var NOTE_INDEX_HEADER_LEN = 68;
11907
+ var NOTE_INDEX_KIND_TX = 1;
11908
+ var NOTE_INDEX_KIND_DELIVERY = 2;
11909
+ var NOTE_INDEX_KIND_SWAP_REFUND = 3;
11910
+ var NOTE_SOURCE_NONE = 0;
11911
+ var NOTE_SOURCE_CARRIER = 2;
11912
+ var ITEM_HEADER_LEN = 3;
11913
+ var TX_FIXED_LEN = 263;
11914
+ var DELIVERY_BODY_LEN = 256;
11915
+ var SWAP_REFUND_BODY_LEN = 184;
11916
+ var MAX_UNKNOWN_BODY_LEN = 1024;
11917
+ var DELIVERY_ENVELOPE_LEN = 112;
11918
+ var SIGNATURE_LEN = 64;
11919
+ var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
11920
+ [25, 2],
11921
+ [57, 3],
11922
+ [98, 4]
11923
+ ]);
11924
+ var COMPLETE_FLAG = 1;
11925
+ var U64_MAX2 = (1n << 64n) - 1n;
11926
+ var U32_MAX = 4294967295;
11927
+ var MAX_LEAF_INDEX = (1n << 32n) - 1n;
11928
+ var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
11929
+ var NoteIndexFormatError = class extends Error {
11930
+ constructor(message) {
11931
+ super(`Note index format error: ${message}`);
11932
+ this.name = "NoteIndexFormatError";
11387
11933
  }
11388
- /**
11389
- * Add a UTXO to the wallet (discovered from chain or created)
11390
- */
11391
- addUtxo(utxo, mint = NATIVE_SOL_MINT) {
11392
- const mintKey = mint;
11393
- if (!this.wallets.has(mintKey)) {
11394
- this.wallets.set(mintKey, {
11395
- mint,
11396
- utxos: []
11397
- });
11398
- }
11399
- const wallet = this.wallets.get(mintKey);
11400
- const exists = wallet.utxos.some(
11401
- (u) => u.amount === utxo.amount && u.keypair.publicKey === utxo.keypair.publicKey && u.blinding === utxo.blinding
11402
- );
11403
- if (!exists) {
11404
- wallet.utxos.push({
11405
- ...utxo,
11406
- discoveredAt: Date.now(),
11934
+ };
11935
+ function isAllZero2(bytes) {
11936
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
11937
+ return true;
11938
+ }
11939
+ function bytesEqual(a, b) {
11940
+ if (a.length !== b.length) return false;
11941
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
11942
+ return true;
11943
+ }
11944
+ function checkLeafPair(commitment, leaf, label) {
11945
+ if (isAllZero2(commitment)) {
11946
+ if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
11947
+ return;
11948
+ }
11949
+ if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
11950
+ }
11951
+ var Reader = class {
11952
+ constructor(bytes, start, end) {
11953
+ this.bytes = bytes;
11954
+ this.end = end;
11955
+ this.offset = start;
11956
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11957
+ }
11958
+ take(len) {
11959
+ if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
11960
+ const at = this.offset;
11961
+ this.offset += len;
11962
+ return at;
11963
+ }
11964
+ u8() {
11965
+ return this.bytes[this.take(1)];
11966
+ }
11967
+ u32() {
11968
+ return this.view.getUint32(this.take(4), true);
11969
+ }
11970
+ u64() {
11971
+ return this.view.getBigUint64(this.take(8), true);
11972
+ }
11973
+ i64() {
11974
+ return this.view.getBigInt64(this.take(8), true);
11975
+ }
11976
+ raw(len) {
11977
+ const at = this.take(len);
11978
+ return this.bytes.slice(at, at + len);
11979
+ }
11980
+ get position() {
11981
+ return this.offset;
11982
+ }
11983
+ };
11984
+ function parseTx(r, bodyLen) {
11985
+ const mint = r.raw(32);
11986
+ const slot = r.u64();
11987
+ const blockPos = r.u32();
11988
+ const ixTag = r.u8();
11989
+ if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
11990
+ const publicAmount = r.i64();
11991
+ const nullifier0 = r.raw(32);
11992
+ const nullifier1 = r.raw(32);
11993
+ const comm0 = r.raw(32);
11994
+ const leaf0 = r.u64();
11995
+ const comm1 = r.raw(32);
11996
+ const leaf1 = r.u64();
11997
+ const noteSource = r.u8();
11998
+ if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
11999
+ const noteLen = r.u8();
12000
+ if (noteSource === NOTE_SOURCE_NONE) {
12001
+ if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
12002
+ } else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
12003
+ throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
12004
+ }
12005
+ if (bodyLen !== TX_FIXED_LEN + noteLen) {
12006
+ throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
12007
+ }
12008
+ const note = r.raw(noteLen);
12009
+ if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
12010
+ throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
12011
+ }
12012
+ const signature = r.raw(SIGNATURE_LEN);
12013
+ checkLeafPair(comm0, leaf0, "TX comm0");
12014
+ checkLeafPair(comm1, leaf1, "TX comm1");
12015
+ return {
12016
+ kind: 1,
12017
+ mint,
12018
+ slot,
12019
+ blockPos,
12020
+ ixTag,
12021
+ publicAmount,
12022
+ nullifier0,
12023
+ nullifier1,
12024
+ comm0,
12025
+ leaf0,
12026
+ comm1,
12027
+ leaf1,
12028
+ noteSource,
12029
+ note,
12030
+ signature
12031
+ };
12032
+ }
12033
+ function parseDelivery(r) {
12034
+ const mint = r.raw(32);
12035
+ const slot = r.u64();
12036
+ const commitment = r.raw(32);
12037
+ const leaf = r.u64();
12038
+ const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
12039
+ const signature = r.raw(SIGNATURE_LEN);
12040
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
12041
+ checkLeafPair(commitment, leaf, "DELIVERY");
12042
+ return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
12043
+ }
12044
+ function parseSwapRefund(r) {
12045
+ const mint = r.raw(32);
12046
+ if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
12047
+ const slot = r.u64();
12048
+ const commitment = r.raw(32);
12049
+ const leaf = r.u64();
12050
+ const amountAfterFee = r.u64();
12051
+ const nullifier0 = r.raw(32);
12052
+ const signature = r.raw(SIGNATURE_LEN);
12053
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
12054
+ checkLeafPair(commitment, leaf, "SWAP_REFUND");
12055
+ return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
12056
+ }
12057
+ function parseNoteIndexPage(bytes, expect, options = {}) {
12058
+ if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
12059
+ if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
12060
+ throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
12061
+ }
12062
+ if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12063
+ for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
12064
+ if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
12065
+ }
12066
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12067
+ const version = bytes[4];
12068
+ if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
12069
+ const flags = bytes[5];
12070
+ if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
12071
+ if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
12072
+ const epoch = view.getBigUint64(8, true);
12073
+ const page = view.getBigUint64(16, true);
12074
+ const firstSeq = view.getBigUint64(24, true);
12075
+ const count = view.getUint32(32, true);
12076
+ const prevChain = bytes.slice(36, 68);
12077
+ const complete = (flags & COMPLETE_FLAG) !== 0;
12078
+ if (expect) {
12079
+ if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
12080
+ if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
12081
+ }
12082
+ if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12083
+ if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
12084
+ if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
12085
+ throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
12086
+ }
12087
+ const items = [];
12088
+ const rawItems = [];
12089
+ const itemPositions = [];
12090
+ let skippedUnknown = 0;
12091
+ let skippedMalformed = 0;
12092
+ let offset = NOTE_INDEX_HEADER_LEN;
12093
+ for (let i = 0; i < count; i++) {
12094
+ if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
12095
+ const kind = bytes[offset];
12096
+ const bodyLen = view.getUint16(offset + 1, true);
12097
+ const bodyStart = offset + ITEM_HEADER_LEN;
12098
+ const bodyEnd = bodyStart + bodyLen;
12099
+ if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12100
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
12101
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12102
+ skippedUnknown++;
12103
+ offset = bodyEnd;
12104
+ continue;
12105
+ }
12106
+ let item;
12107
+ try {
12108
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
12109
+ } catch (error) {
12110
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
12111
+ skippedMalformed++;
12112
+ offset = bodyEnd;
12113
+ continue;
12114
+ }
12115
+ items.push(item);
12116
+ rawItems.push(bytes.slice(offset, bodyEnd));
12117
+ itemPositions.push(i);
12118
+ offset = bodyEnd;
12119
+ }
12120
+ if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12121
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
12122
+ }
12123
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
12124
+ const bodyLen = bodyEnd - bodyStart;
12125
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12126
+ let item;
12127
+ if (kind === NOTE_INDEX_KIND_TX) {
12128
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12129
+ item = parseTx(r, bodyLen);
12130
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
12131
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12132
+ item = parseDelivery(r);
12133
+ } else {
12134
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12135
+ item = parseSwapRefund(r);
12136
+ }
12137
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12138
+ return item;
12139
+ }
12140
+ function parseNoteIndexItem(raw) {
12141
+ if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
12142
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
12143
+ const kind = raw[0];
12144
+ const bodyLen = view.getUint16(1, true);
12145
+ if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
12146
+ const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
12147
+ let item;
12148
+ if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
12149
+ else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
12150
+ else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
12151
+ else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
12152
+ if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
12153
+ return item;
12154
+ }
12155
+ function computeNoteIndexChain(prevChain, pageBytes) {
12156
+ if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
12157
+ if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12158
+ const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
12159
+ const input = new Uint8Array(32 + items.length);
12160
+ input.set(prevChain);
12161
+ input.set(items, 32);
12162
+ return sha2565(input);
12163
+ }
12164
+ var Writer = class {
12165
+ constructor() {
12166
+ this.chunks = [];
12167
+ this.length = 0;
12168
+ }
12169
+ push(bytes) {
12170
+ this.chunks.push(bytes);
12171
+ this.length += bytes.length;
12172
+ }
12173
+ u8(v) {
12174
+ if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
12175
+ this.push(Uint8Array.of(v));
12176
+ }
12177
+ u16(v) {
12178
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
12179
+ const b = new Uint8Array(2);
12180
+ new DataView(b.buffer).setUint16(0, v, true);
12181
+ this.push(b);
12182
+ }
12183
+ u32(v) {
12184
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
12185
+ const b = new Uint8Array(4);
12186
+ new DataView(b.buffer).setUint32(0, v, true);
12187
+ this.push(b);
12188
+ }
12189
+ u64(v) {
12190
+ if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
12191
+ const b = new Uint8Array(8);
12192
+ new DataView(b.buffer).setBigUint64(0, v, true);
12193
+ this.push(b);
12194
+ }
12195
+ i64(v) {
12196
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
12197
+ const b = new Uint8Array(8);
12198
+ new DataView(b.buffer).setBigInt64(0, v, true);
12199
+ this.push(b);
12200
+ }
12201
+ fixed(bytes, len, label) {
12202
+ if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
12203
+ this.push(bytes);
12204
+ }
12205
+ finish() {
12206
+ const out = new Uint8Array(this.length);
12207
+ let off = 0;
12208
+ for (const c of this.chunks) {
12209
+ out.set(c, off);
12210
+ off += c.length;
12211
+ }
12212
+ return out;
12213
+ }
12214
+ };
12215
+ function encodeItemBody(item) {
12216
+ const w = new Writer();
12217
+ switch (item.kind) {
12218
+ case NOTE_INDEX_KIND_TX: {
12219
+ w.fixed(item.mint, 32, "mint");
12220
+ w.u64(item.slot);
12221
+ w.u32(item.blockPos);
12222
+ w.u8(item.ixTag);
12223
+ w.i64(item.publicAmount);
12224
+ w.fixed(item.nullifier0, 32, "nullifier0");
12225
+ w.fixed(item.nullifier1, 32, "nullifier1");
12226
+ w.fixed(item.comm0, 32, "comm0");
12227
+ w.u64(item.leaf0);
12228
+ w.fixed(item.comm1, 32, "comm1");
12229
+ w.u64(item.leaf1);
12230
+ w.u8(item.noteSource);
12231
+ const noteLen = item.note.length;
12232
+ if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
12233
+ throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
12234
+ }
12235
+ w.u8(noteLen);
12236
+ w.push(item.note);
12237
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12238
+ break;
12239
+ }
12240
+ case NOTE_INDEX_KIND_DELIVERY:
12241
+ w.fixed(item.mint, 32, "mint");
12242
+ w.u64(item.slot);
12243
+ w.fixed(item.commitment, 32, "commitment");
12244
+ w.u64(item.leaf);
12245
+ w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
12246
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12247
+ break;
12248
+ case NOTE_INDEX_KIND_SWAP_REFUND:
12249
+ w.fixed(item.mint, 32, "mint");
12250
+ w.u64(item.slot);
12251
+ w.fixed(item.commitment, 32, "commitment");
12252
+ w.u64(item.leaf);
12253
+ w.u64(item.amountAfterFee);
12254
+ w.fixed(item.nullifier0, 32, "nullifier0");
12255
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12256
+ break;
12257
+ default:
12258
+ throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
12259
+ }
12260
+ return w.finish();
12261
+ }
12262
+ function encodeNoteIndexItem(item) {
12263
+ const body = encodeItemBody(item);
12264
+ const w = new Writer();
12265
+ w.u8(item.kind);
12266
+ w.u16(body.length);
12267
+ w.push(body);
12268
+ return w.finish();
12269
+ }
12270
+ function encodeNoteIndexPage(params) {
12271
+ const items = params.items ?? [];
12272
+ if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12273
+ const w = new Writer();
12274
+ w.push(NOTE_INDEX_MAGIC);
12275
+ w.u8(NOTE_INDEX_FORMAT_VERSION);
12276
+ w.u8(params.complete ? COMPLETE_FLAG : 0);
12277
+ w.u16(0);
12278
+ w.u64(BigInt(params.epoch));
12279
+ w.u64(BigInt(params.page));
12280
+ w.u64(BigInt(params.firstSeq));
12281
+ w.u32(items.length);
12282
+ w.fixed(params.prevChain, 32, "prevChain");
12283
+ for (const item of items) w.push(encodeNoteIndexItem(item));
12284
+ return w.finish();
12285
+ }
12286
+
12287
+ // src/relay/note-index-client.ts
12288
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
12289
+ var DEFAULT_MAX_RETRIES2 = 3;
12290
+ var RETRY_BASE_DELAY_MS = 500;
12291
+ var U64_MAX3 = (1n << 64n) - 1n;
12292
+ function joinPath(relayUrl, path) {
12293
+ const url = new URL(relayUrl);
12294
+ url.pathname = url.pathname.replace(/\/$/, "") + path;
12295
+ return url;
12296
+ }
12297
+ function abortError() {
12298
+ const error = new Error("Note index request aborted");
12299
+ error.name = "AbortError";
12300
+ return error;
12301
+ }
12302
+ function sleep4(ms, signal) {
12303
+ return new Promise((resolve, reject) => {
12304
+ if (signal?.aborted) return reject(abortError());
12305
+ const timer = setTimeout(() => {
12306
+ signal?.removeEventListener("abort", onAbort);
12307
+ resolve();
12308
+ }, ms);
12309
+ const onAbort = () => {
12310
+ clearTimeout(timer);
12311
+ reject(abortError());
12312
+ };
12313
+ signal?.addEventListener("abort", onAbort, { once: true });
12314
+ });
12315
+ }
12316
+ var RetryableStatusError = class extends Error {
12317
+ };
12318
+ var HttpStatusError = class extends Error {
12319
+ constructor(status, message) {
12320
+ super(message);
12321
+ this.status = status;
12322
+ this.name = "HttpStatusError";
12323
+ }
12324
+ };
12325
+ async function requestWithRetry(url, options, read) {
12326
+ assertAllowedRelayOrigin(url);
12327
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
12328
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
12329
+ let lastError;
12330
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
12331
+ if (options.signal?.aborted) throw abortError();
12332
+ const controller = new AbortController();
12333
+ const onAbort = () => controller.abort();
12334
+ options.signal?.addEventListener("abort", onAbort, { once: true });
12335
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
12336
+ try {
12337
+ const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
12338
+ if (response.status === 429 || response.status >= 500) {
12339
+ throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
12340
+ }
12341
+ return await read(response, controller.signal);
12342
+ } catch (error) {
12343
+ if (options.signal?.aborted) throw abortError();
12344
+ const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
12345
+ if (!retryable || attempt >= maxRetries) throw error;
12346
+ lastError = error;
12347
+ await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
12348
+ } finally {
12349
+ clearTimeout(timer);
12350
+ options.signal?.removeEventListener("abort", onAbort);
12351
+ }
12352
+ }
12353
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
12354
+ }
12355
+ async function readBoundedBody(response, maxBytes) {
12356
+ const declaredHeader = response.headers?.get?.("content-length") ?? null;
12357
+ const declared = declaredHeader === null ? NaN : Number(declaredHeader);
12358
+ if (Number.isFinite(declared) && declared > maxBytes) {
12359
+ throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
12360
+ }
12361
+ const reader = response.body?.getReader?.();
12362
+ if (!reader) {
12363
+ const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
12364
+ if (!Number.isSafeInteger(declared) || declared < 0) {
12365
+ throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
12366
+ }
12367
+ if (encoding !== "" && encoding !== "identity") {
12368
+ throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
12369
+ }
12370
+ const buffer = new Uint8Array(await response.arrayBuffer());
12371
+ if (buffer.length > maxBytes || buffer.length !== declared) {
12372
+ throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
12373
+ }
12374
+ return buffer;
12375
+ }
12376
+ const chunks = [];
12377
+ let total = 0;
12378
+ for (; ; ) {
12379
+ const { done, value } = await reader.read();
12380
+ if (done) break;
12381
+ total += value.length;
12382
+ if (total > maxBytes) {
12383
+ await reader.cancel().catch(() => void 0);
12384
+ throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
12385
+ }
12386
+ chunks.push(value);
12387
+ }
12388
+ const out = new Uint8Array(total);
12389
+ let off = 0;
12390
+ for (const c of chunks) {
12391
+ out.set(c, off);
12392
+ off += c.length;
12393
+ }
12394
+ return out;
12395
+ }
12396
+ function isNonNegativeSafeInteger(value) {
12397
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12398
+ }
12399
+ async function fetchNoteIndexHead(relayUrl, options = {}) {
12400
+ const url = joinPath(relayUrl, "/note-index/v1/head").toString();
12401
+ const raw = await requestWithRetry(url, options, async (response) => {
12402
+ if (!response.ok) {
12403
+ throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
12404
+ }
12405
+ const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
12406
+ try {
12407
+ return JSON.parse(text);
12408
+ } catch {
12409
+ throw new NoteIndexFormatError("head is not JSON");
12410
+ }
12411
+ });
12412
+ if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
12413
+ if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
12414
+ throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
12415
+ }
12416
+ if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
12417
+ throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
12418
+ }
12419
+ if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
12420
+ throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
12421
+ }
12422
+ if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
12423
+ throw new NoteIndexFormatError(
12424
+ `complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
12425
+ );
12426
+ }
12427
+ if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
12428
+ throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
12429
+ }
12430
+ if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
12431
+ throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
12432
+ }
12433
+ return {
12434
+ format: 1,
12435
+ epoch: BigInt(raw.epoch),
12436
+ pageSize: NOTE_INDEX_PAGE_SIZE,
12437
+ watermark: raw.watermark,
12438
+ completePages: raw.complete_pages,
12439
+ chainTip: raw.chain_tip.toLowerCase()
12440
+ };
12441
+ }
12442
+ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
12443
+ if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
12444
+ if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
12445
+ const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
12446
+ return requestWithRetry(url, options, async (response) => {
12447
+ if (!response.ok) {
12448
+ throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
12449
+ }
12450
+ return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
12451
+ });
12452
+ }
12453
+
12454
+ // src/scanning/note-index.ts
12455
+ import _bs584 from "bs58";
12456
+ import { sha256 as sha2566 } from "@noble/hashes/sha2";
12457
+ var bs584 = _bs584.default || _bs584;
12458
+ var CURSOR_VERSION = 2;
12459
+ var DEFAULT_CONCURRENCY = 6;
12460
+ var MAX_CONCURRENCY = 32;
12461
+ var ITEM_BATCH = 64;
12462
+ var CURSOR_PAGE_ALIGN = 8;
12463
+ var MAX_PERSISTED_PENDING_LEAVES = 4096;
12464
+ var MAX_CARRIED_PENDING = 256;
12465
+ var MAX_REJECTED_IDS = 1024;
12466
+ var LEAF_WINDOW = 512;
12467
+ var MAX_OVERRIDES = 256;
12468
+ var MAX_CURSOR_OWN_ITEMS = 65536;
12469
+ var MAX_LEGACY_VIEWING_KEYS = 8;
12470
+ var MAX_CURSOR_KEYS = 131072;
12471
+ var MAX_CURSOR_POOLS = 256;
12472
+ var MAX_CURSOR_PAGE = 2 ** 32;
12473
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
12474
+ var ZERO_CHAIN = "00".repeat(32);
12475
+ var U64_MAX4 = (1n << 64n) - 1n;
12476
+ var NoteIndexHeadBehindError = class extends Error {
12477
+ constructor(cursorWatermark, headWatermark) {
12478
+ super(
12479
+ `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`
12480
+ );
12481
+ this.cursorWatermark = cursorWatermark;
12482
+ this.headWatermark = headWatermark;
12483
+ this.retryable = true;
12484
+ this.name = "NoteIndexHeadBehindError";
12485
+ }
12486
+ };
12487
+ var FullPassSignal = class {
12488
+ constructor(reason) {
12489
+ this.reason = reason;
12490
+ }
12491
+ };
12492
+ function abortError2() {
12493
+ const error = new Error("recoverNotesFromIndex aborted");
12494
+ error.name = "AbortError";
12495
+ return error;
12496
+ }
12497
+ function bytesToBigint2(bytes) {
12498
+ let v = 0n;
12499
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
12500
+ return v;
12501
+ }
12502
+ function toHex2(bytes) {
12503
+ let s = "";
12504
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
12505
+ return s;
12506
+ }
12507
+ function fromHex(hex) {
12508
+ return Uint8Array.from(Buffer.from(hex, "hex"));
12509
+ }
12510
+ function hex32(v) {
12511
+ return v.toString(16).padStart(64, "0");
12512
+ }
12513
+ function isAllZero3(bytes) {
12514
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12515
+ return true;
12516
+ }
12517
+ function floorAlign(page) {
12518
+ return page - page % CURSOR_PAGE_ALIGN;
12519
+ }
12520
+ function verifiedKey(mint, leaf, commitment) {
12521
+ return `${mint}:${leaf}:${hex32(commitment)}`;
12522
+ }
12523
+ function itemIdentity(raw) {
12524
+ return toHex2(sha2566(raw).subarray(0, 16));
12525
+ }
12526
+ var LeafBuffer = class {
12527
+ constructor() {
12528
+ this.bytes = new Uint8Array(32 * 1024);
12529
+ this.view = new DataView(this.bytes.buffer);
12530
+ this.count = 0;
12531
+ }
12532
+ get length() {
12533
+ return this.count;
12534
+ }
12535
+ push(values) {
12536
+ const need = (this.count + values.length) * 32;
12537
+ if (need > this.bytes.length) {
12538
+ let size = this.bytes.length;
12539
+ while (size < need) size *= 2;
12540
+ const next = new Uint8Array(size);
12541
+ next.set(this.bytes.subarray(0, this.count * 32));
12542
+ this.bytes = next;
12543
+ this.view = new DataView(next.buffer);
12544
+ }
12545
+ for (const v of values) {
12546
+ const o = this.count * 32;
12547
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
12548
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
12549
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
12550
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
12551
+ this.count++;
12552
+ }
12553
+ }
12554
+ get(i) {
12555
+ if (i < 0 || i >= this.count) return void 0;
12556
+ const o = i * 32;
12557
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
12558
+ }
12559
+ };
12560
+ async function trialItem(item, trials) {
12561
+ for (const trial of trials) {
12562
+ if (trial.legacy && item.kind === 2) continue;
12563
+ const opened = await trialItemWith(item, trial);
12564
+ if (opened) return { ...opened, trial };
12565
+ }
12566
+ return null;
12567
+ }
12568
+ async function trialItemIsolated(item, trials, stats) {
12569
+ try {
12570
+ return await trialItem(item, trials);
12571
+ } catch {
12572
+ stats.skipped++;
12573
+ return null;
12574
+ }
12575
+ }
12576
+ async function trialItemWith(item, trial) {
12577
+ if (item.kind === 1) {
12578
+ if (item.note.length === 0) return null;
12579
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
12580
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
12581
+ return note ? { note } : null;
12582
+ }
12583
+ if (item.kind === 2) {
12584
+ const delivery = await trial.open(item.envelope);
12585
+ return delivery ? { delivery } : null;
12586
+ }
12587
+ if (item.amountAfterFee === 0n) return null;
12588
+ const refund = await matchSwapRefundLeaf({
12589
+ viewingKeyNk: trial.nk,
12590
+ inputNullifier: item.nullifier0,
12591
+ amountAfterFee: item.amountAfterFee,
12592
+ commitment: item.commitment,
12593
+ ownerUtxoKeypair: trial.owner
12594
+ });
12595
+ return refund ? { refund } : null;
12596
+ }
12597
+ function txOutputs(item) {
12598
+ const out = [toHex2(item.comm0)];
12599
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
12600
+ return out;
12601
+ }
12602
+ function leafOfTxOutput(item, commitment) {
12603
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint2(item.comm0)) return Number(item.leaf0);
12604
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
12605
+ return null;
12606
+ }
12607
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
12608
+ try {
12609
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
12610
+ } catch {
12611
+ return null;
12612
+ }
12613
+ }
12614
+ async function matchOwnItems(own, owner, onReject, onSkip) {
12615
+ const candidates = [];
12616
+ const claimed = /* @__PURE__ */ new Set();
12617
+ const byNullifier = /* @__PURE__ */ new Map();
12618
+ const legacyKeys = /* @__PURE__ */ new Map();
12619
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
12620
+ const spendsOf = /* @__PURE__ */ new Map();
12621
+ const byOutKey = /* @__PURE__ */ new Map();
12622
+ const index = (map, key, o) => {
12623
+ const list = map.get(key);
12624
+ if (list) list.push(o);
12625
+ else map.set(key, [o]);
12626
+ };
12627
+ for (const o of ownTxs) {
12628
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
12629
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
12630
+ }
12631
+ const queue = [];
12632
+ const queued = /* @__PURE__ */ new Set();
12633
+ const enqueue = (o) => {
12634
+ if (queued.has(o)) return;
12635
+ queued.add(o);
12636
+ queue.push(o);
12637
+ };
12638
+ const add = async (o, c) => {
12639
+ const nullifier = hex32(
12640
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
12641
+ );
12642
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
12643
+ candidates.push(full);
12644
+ if (!byNullifier.has(nullifier)) {
12645
+ byNullifier.set(nullifier, full);
12646
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
12647
+ }
12648
+ if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
12649
+ legacyKeys.set(c.keypair.publicKey, c.keypair);
12650
+ for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
12651
+ }
12652
+ };
12653
+ const tryDeposit = async (o, item, amount) => {
12654
+ const note = o.note;
12655
+ const mint = addressFromBytes(item.mint);
12656
+ const deposit = await matchDepositNote({
12657
+ viewingKeyNk: o.trial.nk,
12658
+ noteSalt: note.noteSalt,
12659
+ amount,
12660
+ mintAddress: mint,
12661
+ outputCommitments: txOutputs(item),
12662
+ ownerUtxoKeypair: owner
12663
+ });
12664
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
12665
+ if (!deposit || leaf === null) return false;
12666
+ await add(o, {
12667
+ kind: "deposit",
12668
+ atRisk: deposit.legacyExposed,
12669
+ amount: deposit.amount,
12670
+ blinding: deposit.blinding,
12671
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
12672
+ mint,
12673
+ commitment: deposit.commitment,
12674
+ leaf
12675
+ });
12676
+ return true;
12677
+ };
12678
+ const tryChange0 = async (o, item, keypair, atRisk) => {
12679
+ const note = o.note;
12680
+ const mint = addressFromBytes(item.mint);
12681
+ const change = await matchChangeNote({
12682
+ viewingKeyNk: o.trial.nk,
12683
+ noteSalt: note.noteSalt,
12684
+ amount: note.outAmount0,
12685
+ keypair,
12686
+ mintAddress: mint,
12687
+ outputIndex: 0,
12688
+ outputCommitments: [toHex2(item.comm0)],
12689
+ ownerUtxoPublicKey: owner.publicKey
12690
+ });
12691
+ if (!change) return false;
12692
+ await add(o, {
12693
+ kind: "change",
12694
+ atRisk,
12695
+ amount: change.amount,
12696
+ blinding: change.blinding,
12697
+ keypair,
12698
+ mint,
12699
+ commitment: change.commitment,
12700
+ leaf: Number(item.leaf0)
12701
+ });
12702
+ return true;
12703
+ };
12704
+ const direct = async (o) => {
12705
+ const item = o.item;
12706
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
12707
+ const note = o.note;
12708
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12709
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
12710
+ }
12711
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
12712
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
12713
+ }
12714
+ } else if (item.kind === 2 && o.delivery) {
12715
+ const mint = addressFromBytes(item.mint);
12716
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
12717
+ onReject(o);
12718
+ return;
12719
+ }
12720
+ const commitment = await computeCommitment({
12721
+ amount: o.delivery.amount,
12722
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
12723
+ blinding: o.delivery.blinding,
12724
+ mintAddress: mint
12725
+ });
12726
+ if (commitment !== bytesToBigint2(item.commitment)) {
12727
+ onReject(o);
12728
+ return;
12729
+ }
12730
+ await add(o, {
12731
+ kind: "received",
12732
+ atRisk: false,
12733
+ amount: o.delivery.amount,
12734
+ blinding: o.delivery.blinding,
12735
+ keypair: owner,
12736
+ mint,
12737
+ commitment,
12738
+ leaf: Number(item.leaf)
12739
+ });
12740
+ } else if (item.kind === 3 && o.refund) {
12741
+ await add(o, {
12742
+ kind: "swap_refund",
12743
+ atRisk: o.refund.legacyExposed,
12744
+ amount: o.refund.amount,
12745
+ blinding: o.refund.blinding,
12746
+ keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
12747
+ mint: NATIVE_SOL_MINT,
12748
+ commitment: o.refund.commitment,
12749
+ leaf: Number(item.leaf)
12750
+ });
12751
+ }
12752
+ };
12753
+ for (const o of own) {
12754
+ try {
12755
+ await direct(o);
12756
+ } catch {
12757
+ onSkip(o);
12758
+ }
12759
+ }
12760
+ const processTx = async (o) => {
12761
+ const item = o.item;
12762
+ const note = o.note;
12763
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
12764
+ const legacy = legacyKeys.get(note.outPubkey0);
12765
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
12766
+ }
12767
+ const mint = addressFromBytes(item.mint);
12768
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
12769
+ if (inputs.length === 0) return;
12770
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
12771
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
12772
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
12773
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
12774
+ if (out1 > 0n && blinding === null) onSkip(o);
12775
+ else if (blinding !== null) {
12776
+ const owners = [{ keypair: owner, atRisk: false }];
12777
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
12778
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
12779
+ for (const { keypair, atRisk } of owners) {
12780
+ const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
12781
+ if (commitment !== bytesToBigint2(item.comm1)) continue;
12782
+ claimed.add(`${o.seq}:1`);
12783
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
12784
+ break;
12785
+ }
12786
+ }
12787
+ }
12788
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12789
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
12790
+ }
12791
+ };
12792
+ for (const o of ownTxs) enqueue(o);
12793
+ for (let i = 0; i < queue.length; i++) {
12794
+ const o = queue[i];
12795
+ queued.delete(o);
12796
+ try {
12797
+ await processTx(o);
12798
+ } catch {
12799
+ onSkip(o);
12800
+ }
12801
+ }
12802
+ return candidates;
12803
+ }
12804
+ async function replayStream(start, pages, overrides, chain, targetPage) {
12805
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
12806
+ const startN = frontier.nextIndex;
12807
+ const pending = new Map(start.pending);
12808
+ const flushed = new LeafBuffer();
12809
+ const corrections = /* @__PURE__ */ new Map();
12810
+ let conflicts = 0;
12811
+ let verifiedPrefix = 0;
12812
+ let mismatch = false;
12813
+ const checks = [];
12814
+ const setBits = [];
12815
+ if (chain && chain.nextIndex > 0) {
12816
+ const last = chain.nextIndex - 1;
12817
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
12818
+ for (const l of setBits) {
12819
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
12820
+ if (at >= startN) checks.push({ at, level: l });
12821
+ }
12822
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
12823
+ checks.sort((a, b) => a.at - b.at);
12824
+ }
12825
+ let nextCheck = 0;
12826
+ const runChecks = () => {
12827
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
12828
+ const { at, level } = checks[nextCheck++];
12829
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
12830
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
12831
+ else mismatch = true;
12832
+ }
12833
+ };
12834
+ const append = (values) => {
12835
+ let i = 0;
12836
+ while (i < values.length) {
12837
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
12838
+ const take = Math.min(values.length - i, room);
12839
+ if (take > 0) {
12840
+ const part = values.slice(i, i + take);
12841
+ frontier.append(part);
12842
+ flushed.push(part);
12843
+ i += take;
12844
+ }
12845
+ runChecks();
12846
+ }
12847
+ };
12848
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
12849
+ const flush = () => {
12850
+ const batch = [];
12851
+ let next = frontier.nextIndex;
12852
+ while (pending.has(next)) {
12853
+ batch.push(pending.get(next));
12854
+ pending.delete(next);
12855
+ next++;
12856
+ }
12857
+ if (batch.length > 0) append(batch);
12858
+ };
12859
+ let snapshot = null;
12860
+ let taken = false;
12861
+ const takeSnapshot = () => {
12862
+ taken = true;
12863
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
12864
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
12865
+ };
12866
+ runChecks();
12867
+ flush();
12868
+ for (const { page, entries } of pages) {
12869
+ if (!taken && page >= targetPage) takeSnapshot();
12870
+ for (const e of entries) {
12871
+ if (e.leaf < startN) continue;
12872
+ const prior = valueAt(e.leaf);
12873
+ if (prior !== void 0) {
12874
+ if (prior !== e.commitment) {
12875
+ conflicts++;
12876
+ corrections.set(e.leaf, e.commitment);
12877
+ }
12878
+ continue;
12879
+ }
12880
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
12881
+ }
12882
+ flush();
12883
+ }
12884
+ if (!taken) takeSnapshot();
12885
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
12886
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
12887
+ }
12888
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
12889
+ }
12890
+ var HEX64 = /^[0-9a-f]{64}$/;
12891
+ var HEX32 = /^[0-9a-f]{32}$/;
12892
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
12893
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
12894
+ function isRecord(v) {
12895
+ return typeof v === "object" && v !== null && !Array.isArray(v);
12896
+ }
12897
+ function isIntIn(v, min, max) {
12898
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
12899
+ }
12900
+ function isBoundedArray(v, max) {
12901
+ return Array.isArray(v) && v.length <= max;
12902
+ }
12903
+ function emptyStartTree() {
12904
+ return {
12905
+ frontier: null,
12906
+ nextIndex: 0,
12907
+ pending: /* @__PURE__ */ new Map(),
12908
+ window: [],
12909
+ windowStart: 0,
12910
+ verified: 0,
12911
+ overrides: /* @__PURE__ */ new Map(),
12912
+ mismatch: false,
12913
+ hiBefore: -1
12914
+ };
12915
+ }
12916
+ async function parseCursor(cursor, poolMints) {
12917
+ try {
12918
+ if (!isRecord(cursor)) return "not an object";
12919
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
12920
+ const c = cursor;
12921
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
12922
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
12923
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
12924
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
12925
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
12926
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
12927
+ const trees = /* @__PURE__ */ new Map();
12928
+ for (const mint of poolMints) {
12929
+ const t = c.trees[mint];
12930
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
12931
+ const tree = t;
12932
+ if (!isRecord(tree.frontier)) return "bad frontier";
12933
+ let frontier;
12934
+ try {
12935
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
12936
+ } catch {
12937
+ return "bad frontier";
12938
+ }
12939
+ const nextIndex = frontier.nextIndex;
12940
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
12941
+ const pending = /* @__PURE__ */ new Map();
12942
+ let hiBefore = nextIndex - 1;
12943
+ for (const entry of tree.pending) {
12944
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
12945
+ const [leaf, value] = entry;
12946
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
12947
+ return "bad pending leaves";
12948
+ }
12949
+ pending.set(leaf, BigInt("0x" + value));
12950
+ hiBefore = Math.max(hiBefore, leaf);
12951
+ }
12952
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
12953
+ const windowLen = tree.window.length / 64;
12954
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
12955
+ const window2 = [];
12956
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
12957
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
12958
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
12959
+ const overrides = /* @__PURE__ */ new Map();
12960
+ for (const entry of tree.overrides) {
12961
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
12962
+ const [leaf, value] = entry;
12963
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
12964
+ overrides.set(leaf, BigInt("0x" + value));
12965
+ }
12966
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
12967
+ trees.set(mint, {
12968
+ frontier: frontier.toState(),
12969
+ nextIndex,
12970
+ pending,
12971
+ window: window2,
12972
+ windowStart: nextIndex - windowLen,
12973
+ verified: tree.verified,
12974
+ overrides,
12975
+ mismatch: tree.mismatch,
12976
+ hiBefore
12977
+ });
12978
+ }
12979
+ const own = c.own;
12980
+ if (!isRecord(own)) return "bad own state";
12981
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
12982
+ const items = [];
12983
+ const seqs = /* @__PURE__ */ new Set();
12984
+ for (const entry of own.items) {
12985
+ if (!isRecord(entry)) return "bad own items";
12986
+ const { seq, item } = entry;
12987
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
12988
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
12989
+ seqs.add(seq);
12990
+ const raw = fromHex(item);
12991
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
12992
+ }
12993
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
12994
+ return "bad verified notes";
12995
+ }
12996
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
12997
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
12998
+ const pendingLeaves = /* @__PURE__ */ new Map();
12999
+ for (const entry of own.pendingLeaves) {
13000
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
13001
+ const [mint, leaf, value] = entry;
13002
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
13003
+ return "bad pending notes";
13004
+ }
13005
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
13006
+ }
13007
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
13008
+ return "bad rejected set";
13009
+ }
13010
+ return {
13011
+ raw: c,
13012
+ trees,
13013
+ items,
13014
+ verified: new Set(own.verified),
13015
+ spent: new Set(own.spent),
13016
+ pendingLeaves,
13017
+ rejected: own.rejected
13018
+ };
13019
+ } catch {
13020
+ return "unreadable state";
13021
+ }
13022
+ }
13023
+ async function recoverNotesFromIndex(params) {
13024
+ const startedAt = Date.now();
13025
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
13026
+ assertAllowedRelayOrigin(relayUrl);
13027
+ assertAllowedRpcConnection(connection);
13028
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
13029
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
13030
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
13031
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
13032
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
13033
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
13034
+ }
13035
+ if (params.signal?.aborted) throw abortError2();
13036
+ const stats = {
13037
+ pages: 0,
13038
+ items: 0,
13039
+ bytes: 0,
13040
+ rpcCalls: 0,
13041
+ ms: 0,
13042
+ dropped: 0,
13043
+ decrypted: 0,
13044
+ candidates: 0,
13045
+ spent: 0,
13046
+ conflicts: 0,
13047
+ pendingDropped: 0,
13048
+ skipped: 0
13049
+ };
13050
+ const rpc = new Proxy(connection, {
13051
+ get(target, prop, receiver) {
13052
+ const value = Reflect.get(target, prop, receiver);
13053
+ if (typeof value !== "function") return value;
13054
+ return (...args) => {
13055
+ const pending = value.apply(target, args);
13056
+ if (pending && typeof pending.send === "function") {
13057
+ const send = pending.send.bind(pending);
13058
+ return {
13059
+ ...pending,
13060
+ send: (...sendArgs) => {
13061
+ stats.rpcCalls++;
13062
+ return send(...sendArgs);
13063
+ }
13064
+ };
13065
+ }
13066
+ return pending;
13067
+ };
13068
+ }
13069
+ });
13070
+ const makeTrial = async (nk, legacy) => ({
13071
+ nk,
13072
+ legacy,
13073
+ owner,
13074
+ decrypt: await createCompactChainNoteDecryptor(nk),
13075
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
13076
+ });
13077
+ const trials = [await makeTrial(viewingKeyNk, false)];
13078
+ const legacyNks = params.legacyViewingKeyNks ?? [];
13079
+ if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
13080
+ if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
13081
+ const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
13082
+ for (const nk of legacyNks) {
13083
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
13084
+ const key = toHex2(nk);
13085
+ if (seenNks.has(key)) continue;
13086
+ seenNks.add(key);
13087
+ trials.push(await makeTrial(Uint8Array.from(nk), true));
13088
+ }
13089
+ const poolMints = Array.from(new Set(params.poolMints));
13090
+ const warnings = [];
13091
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
13092
+ let cursor;
13093
+ if (params.cursor !== void 0) {
13094
+ const checked = await parseCursor(params.cursor, poolMints);
13095
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
13096
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
13097
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
13098
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
13099
+ } else cursor = checked;
13100
+ }
13101
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
13102
+ let treeRead;
13103
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
13104
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
13105
+ return poolMints.map((_, i) => {
13106
+ const account = accounts[i];
13107
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
13108
+ return account && parsed ? { ...parsed, data: account.data } : null;
13109
+ });
13110
+ })());
13111
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
13112
+ let outcome = await runOnce(ctx, cursor);
13113
+ if (outcome instanceof FullPassSignal) {
13114
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
13115
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
13116
+ outcome = await runOnce(ctx, void 0);
13117
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13118
+ }
13119
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
13120
+ stats.ms = Date.now() - startedAt;
13121
+ return { ...outcome, stats, warnings };
13122
+ }
13123
+ async function runOnce(ctx, cursor) {
13124
+ const { params, head, trials, owner, stats, poolMints } = ctx;
13125
+ const { relayUrl, onProgress } = params;
13126
+ const poolSet = new Set(poolMints);
13127
+ const startPage = cursor?.raw.page ?? 0;
13128
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
13129
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
13130
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
13131
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
13132
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
13133
+ const rejectedIds = new Set(cursor?.rejected ?? []);
13134
+ const controller = new AbortController();
13135
+ const onCallerAbort = () => controller.abort();
13136
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
13137
+ const signal = controller.signal;
13138
+ try {
13139
+ const pageData = /* @__PURE__ */ new Map();
13140
+ const ownItems = [];
13141
+ const nullifiers = /* @__PURE__ */ new Set();
13142
+ let fullPassReason = null;
13143
+ const lateReference = (mint, leaf, value, seq) => {
13144
+ if (!cursor || seq < fullPassSeq) return null;
13145
+ const t = startTrees.get(mint);
13146
+ if (leaf < t.nextIndex) {
13147
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
13148
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
13149
+ return null;
13150
+ }
13151
+ const held = t.pending.get(leaf);
13152
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
13153
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
13154
+ return null;
13155
+ };
13156
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
13157
+ const waiting = /* @__PURE__ */ new Map();
13158
+ let chainNext = startPage;
13159
+ let chainError = null;
13160
+ let wakers = [];
13161
+ const wakeAll = () => {
13162
+ const w = wakers;
13163
+ wakers = [];
13164
+ for (const f of w) f();
13165
+ };
13166
+ signal.addEventListener("abort", wakeAll);
13167
+ const advanceChain = () => {
13168
+ while (!chainError && waiting.has(chainNext)) {
13169
+ const w = waiting.get(chainNext);
13170
+ waiting.delete(chainNext);
13171
+ const expected = chainAt.get(chainNext);
13172
+ if (w.prevChain !== expected) {
13173
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
13174
+ controller.abort();
13175
+ return;
13176
+ }
13177
+ if (!w.complete) break;
13178
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
13179
+ chainNext++;
13180
+ }
13181
+ wakeAll();
13182
+ };
13183
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
13184
+ const lookahead = 2 * workerCount + 2;
13185
+ let nextToFetch = startPage;
13186
+ let pagesDone = 0;
13187
+ const worker = async () => {
13188
+ for (; ; ) {
13189
+ if (signal.aborted) throw abortError2();
13190
+ const pageNo = nextToFetch++;
13191
+ if (pageNo >= pagesTotal) return;
13192
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
13193
+ if (signal.aborted) throw abortError2();
13194
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13195
+ stats.bytes += bytes.length;
13196
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
13197
+ if (pageNo < head.completePages && !page2.complete) {
13198
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13199
+ }
13200
+ stats.pages++;
13201
+ stats.skipped += page2.skippedMalformed;
13202
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
13203
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13204
+ advanceChain();
13205
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
13206
+ const late = (reason) => {
13207
+ if (reason && !fullPassReason) {
13208
+ fullPassReason = reason;
13209
+ controller.abort();
13210
+ }
13211
+ };
13212
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
13213
+ if (isAllZero3(commitment)) return;
13214
+ const mint = addressFromBytes(mintBytes);
13215
+ if (!poolSet.has(mint)) return;
13216
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint2(commitment) };
13217
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
13218
+ const list = data.leaves.get(mint);
13219
+ if (list) list.push(entry);
13220
+ else data.leaves.set(mint, [entry]);
13221
+ };
13222
+ page2.items.forEach((item, i) => {
13223
+ const seq = seqOf(i);
13224
+ if (item.kind === 1) {
13225
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
13226
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
13227
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
13228
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
13229
+ } else if (item.kind === 3) {
13230
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
13231
+ } else {
13232
+ const mint = addressFromBytes(item.mint);
13233
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
13234
+ }
13235
+ });
13236
+ if (signal.aborted) throw abortError2();
13237
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
13238
+ if (signal.aborted) throw abortError2();
13239
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
13240
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
13241
+ opened.forEach((o, k) => {
13242
+ if (!o) return;
13243
+ stats.decrypted++;
13244
+ const raw = page2.rawItems[i + k];
13245
+ const id = itemIdentity(raw);
13246
+ if (rejectedIds.has(id)) {
13247
+ stats.dropped++;
13248
+ return;
13249
+ }
13250
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
13251
+ });
13252
+ stats.items += batch.length;
13253
+ }
13254
+ pageData.set(pageNo, data);
13255
+ pagesDone++;
13256
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
13257
+ }
13258
+ };
13259
+ const workers = Array.from(
13260
+ { length: workerCount },
13261
+ () => worker().catch((error) => {
13262
+ controller.abort();
13263
+ throw error;
13264
+ })
13265
+ );
13266
+ const settled = await Promise.allSettled(workers);
13267
+ signal.removeEventListener("abort", wakeAll);
13268
+ if (params.signal?.aborted) throw abortError2();
13269
+ const lateReason = fullPassReason;
13270
+ if (lateReason) return new FullPassSignal(lateReason);
13271
+ const chainFailure = chainError;
13272
+ if (chainFailure) {
13273
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
13274
+ throw chainFailure;
13275
+ }
13276
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
13277
+ if (failure) throw failure.reason;
13278
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
13279
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
13280
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
13281
+ }
13282
+ for (const entry of cursor?.items ?? []) {
13283
+ const o = await trialItemIsolated(entry.item, trials, stats);
13284
+ if (!o) continue;
13285
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
13286
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
13287
+ if (entry.item.kind === 1) {
13288
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
13289
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
13290
+ }
13291
+ }
13292
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
13293
+ ownItems.sort((a, b) => a.seq - b.seq);
13294
+ const rejectedNow = /* @__PURE__ */ new Set();
13295
+ const skippedNow = /* @__PURE__ */ new Set();
13296
+ const allCandidates = await matchOwnItems(
13297
+ ownItems,
13298
+ owner,
13299
+ (o) => {
13300
+ stats.dropped++;
13301
+ rejectedNow.add(o.id);
13302
+ },
13303
+ (o) => {
13304
+ if (skippedNow.has(o)) return;
13305
+ skippedNow.add(o);
13306
+ stats.skipped++;
13307
+ }
13308
+ );
13309
+ stats.candidates = allCandidates.length;
13310
+ const cutoff = params.legacyCutoffLeaf ?? {};
13311
+ const candidates = allCandidates.filter((c) => {
13312
+ const limit = cutoff[c.mint];
13313
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
13314
+ stats.dropped++;
13315
+ return false;
13316
+ }
13317
+ return true;
13318
+ });
13319
+ const chainTrees = await ctx.readTrees();
13320
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
13321
+ const replays = /* @__PURE__ */ new Map();
13322
+ for (let i = 0; i < poolMints.length; i++) {
13323
+ const mint = poolMints[i];
13324
+ const start = startTrees.get(mint);
13325
+ const chainTree = chainTrees[i] ?? null;
13326
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
13327
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
13328
+ let overrides = start.overrides;
13329
+ stats.conflicts += r.conflicts;
13330
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
13331
+ const merged = new Map([...start.overrides, ...r.corrections]);
13332
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
13333
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
13334
+ r = alternative;
13335
+ overrides = merged;
13336
+ }
13337
+ }
13338
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
13339
+ replays.set(mint, { r, overrides });
13340
+ }
13341
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
13342
+ const streamValue = (mint, leaf) => {
13343
+ const v = replays.get(mint)?.r.valueAt(leaf);
13344
+ if (v !== void 0) return v;
13345
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
13346
+ if (carried !== void 0) return carried;
13347
+ const t = startTrees.get(mint);
13348
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
13349
+ return void 0;
13350
+ };
13351
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
13352
+ const verified = [];
13353
+ const pendingByKey = /* @__PURE__ */ new Map();
13354
+ const rejectedCandidates = /* @__PURE__ */ new Set();
13355
+ const outcomeOf = /* @__PURE__ */ new Map();
13356
+ const tally = (c, what) => {
13357
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
13358
+ t.total++;
13359
+ if (what === "kept") t.kept = true;
13360
+ if (what === "rejected") t.rejected++;
13361
+ outcomeOf.set(c.seq, t);
13362
+ };
13363
+ const pend = (c, rank) => {
13364
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
13365
+ const prior = pendingByKey.get(key);
13366
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
13367
+ };
13368
+ for (const c of candidates) {
13369
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
13370
+ verified.push(c);
13371
+ continue;
13372
+ }
13373
+ if (!poolSet.has(c.mint)) {
13374
+ pend(c, 3);
13375
+ continue;
13376
+ }
13377
+ const value = streamValue(c.mint, c.leaf);
13378
+ if (value === void 0) {
13379
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
13380
+ stats.dropped++;
13381
+ tally(c, "other");
13382
+ } else pend(c, 1);
13383
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
13384
+ pend(c, value === c.commitment ? 0 : 2);
13385
+ } else if (value === c.commitment) {
13386
+ verified.push(c);
13387
+ } else {
13388
+ stats.dropped++;
13389
+ rejectedCandidates.add(c);
13390
+ tally(c, "rejected");
13391
+ }
13392
+ }
13393
+ verified.sort((a, b) => a.seq - b.seq);
13394
+ const byLeaf = /* @__PURE__ */ new Map();
13395
+ for (const c of verified) {
13396
+ const key = `${c.mint}:${c.leaf}`;
13397
+ if (byLeaf.has(key)) {
13398
+ stats.dropped++;
13399
+ tally(c, "other");
13400
+ continue;
13401
+ }
13402
+ byLeaf.set(key, c);
13403
+ }
13404
+ const notes = [];
13405
+ const atRisk = [];
13406
+ const spentOut = new Set(knownSpent);
13407
+ const verifiedOut = new Set(knownVerified);
13408
+ const keyChecked = /* @__PURE__ */ new Map();
13409
+ for (const c of byLeaf.values()) {
13410
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
13411
+ keyChecked.set(c.keypair.privateKey, pubOk);
13412
+ if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
13413
+ stats.dropped++;
13414
+ tally(c, "rejected");
13415
+ continue;
13416
+ }
13417
+ tally(c, "kept");
13418
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
13419
+ const utxo = {
13420
+ amount: c.amount,
13421
+ keypair: c.atRisk ? { ...c.keypair } : owner,
13422
+ blinding: c.blinding,
13423
+ mintAddress: c.mint,
13424
+ index: c.leaf,
13425
+ commitment: c.commitment
13426
+ };
13427
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
13428
+ stats.spent++;
13429
+ spentOut.add(c.nullifier);
13430
+ continue;
13431
+ }
13432
+ const note = {
13433
+ kind: c.kind,
13434
+ utxo,
13435
+ signature: bs584.encode(c.signature),
13436
+ legacyExposed: c.atRisk
13437
+ };
13438
+ (c.atRisk ? atRisk : notes).push(note);
13439
+ }
13440
+ 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);
13441
+ sortNotes(notes);
13442
+ sortNotes(atRisk);
13443
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
13444
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
13445
+ const overflow = pendingList.length - carriedPending.length;
13446
+ if (overflow > 0) {
13447
+ stats.pendingDropped += overflow;
13448
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
13449
+ }
13450
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
13451
+ for (const c of carriedPending) tally(c, "kept");
13452
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
13453
+ let page = targetPage;
13454
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
13455
+ const trees = {};
13456
+ const treeEnd = /* @__PURE__ */ new Map();
13457
+ for (const mint of poolMints) {
13458
+ const start = startTrees.get(mint);
13459
+ const { r, overrides } = replays.get(mint);
13460
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
13461
+ const n = snap.nextIndex;
13462
+ const window2 = [];
13463
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
13464
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
13465
+ if (v === void 0) break;
13466
+ window2.push(hex32(v));
13467
+ }
13468
+ window2.reverse();
13469
+ trees[mint] = {
13470
+ frontier: snap.frontier,
13471
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
13472
+ window: window2.join(""),
13473
+ verified: Math.min(verifiedUpTo(mint), n),
13474
+ 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)]),
13475
+ mismatch: r.mismatch
13476
+ };
13477
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
13478
+ }
13479
+ const pendingLeaves = [];
13480
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
13481
+ for (const c of carriedPending) {
13482
+ const end = treeEnd.get(c.mint);
13483
+ if (!end || c.leaf >= end.nextIndex) continue;
13484
+ const value = streamValue(c.mint, c.leaf);
13485
+ const key = `${c.mint}:${c.leaf}`;
13486
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
13487
+ pendingLeafSeen.add(key);
13488
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
13489
+ }
13490
+ const keptItems = [];
13491
+ const keptIds = /* @__PURE__ */ new Set();
13492
+ for (const o of ownItems) {
13493
+ const t = outcomeOf.get(o.seq);
13494
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
13495
+ rejectedNow.add(o.id);
13496
+ continue;
13497
+ }
13498
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
13499
+ keptIds.add(o.id);
13500
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
13501
+ }
13502
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
13503
+ const nextCursor = {
13504
+ v: CURSOR_VERSION,
13505
+ epoch: head.epoch.toString(10),
13506
+ page,
13507
+ chain: chainAt.get(page) ?? startChain,
13508
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
13509
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
13510
+ trees,
13511
+ own: {
13512
+ items: keptItems,
13513
+ verified: Array.from(verifiedOut),
13514
+ spent: Array.from(spentOut),
13515
+ pendingLeaves,
13516
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
13517
+ }
13518
+ };
13519
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
13520
+ } finally {
13521
+ params.signal?.removeEventListener("abort", onCallerAbort);
13522
+ }
13523
+ }
13524
+
13525
+ // src/wallet/utxo-wallet.ts
13526
+ var UtxoWallet = class _UtxoWallet {
13527
+ constructor(viewingKey) {
13528
+ this.wallets = /* @__PURE__ */ new Map();
13529
+ this.viewingKey = viewingKey;
13530
+ }
13531
+ /**
13532
+ * Add a UTXO to the wallet (discovered from chain or created)
13533
+ */
13534
+ addUtxo(utxo, mint = NATIVE_SOL_MINT) {
13535
+ const mintKey = mint;
13536
+ if (!this.wallets.has(mintKey)) {
13537
+ this.wallets.set(mintKey, {
13538
+ mint,
13539
+ utxos: []
13540
+ });
13541
+ }
13542
+ const wallet = this.wallets.get(mintKey);
13543
+ const exists = wallet.utxos.some(
13544
+ (u) => u.amount === utxo.amount && u.keypair.publicKey === utxo.keypair.publicKey && u.blinding === utxo.blinding
13545
+ );
13546
+ if (!exists) {
13547
+ wallet.utxos.push({
13548
+ ...utxo,
13549
+ discoveredAt: Date.now(),
11407
13550
  index: utxo.index,
11408
13551
  isSpent: false
11409
13552
  });
@@ -11733,7 +13876,7 @@ async function loadWeb3() {
11733
13876
 
11734
13877
  // src/bridge/rail-verify.ts
11735
13878
  import nacl6 from "tweetnacl";
11736
- import { sha256 as sha2565 } from "@noble/hashes/sha256";
13879
+ import { sha256 as sha2567 } from "@noble/hashes/sha256";
11737
13880
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
11738
13881
  var b58 = /* @__PURE__ */ (() => {
11739
13882
  const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -11839,7 +13982,7 @@ function canonicalPayloadString(resp) {
11839
13982
  function verifyQuoteSignature(resp) {
11840
13983
  if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
11841
13984
  const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
11842
- const digest = sha2565(new TextEncoder().encode(stable(payload)));
13985
+ const digest = sha2567(new TextEncoder().encode(stable(payload)));
11843
13986
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
11844
13987
  const sig = resp.signature.replace(/^ed25519:/, "");
11845
13988
  try {
@@ -12034,7 +14177,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12034
14177
  })
12035
14178
  });
12036
14179
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12037
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
14180
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
12038
14181
  throw new Error(
12039
14182
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12040
14183
  );
@@ -12071,9 +14214,12 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12071
14214
  // src/bridge/derive.ts
12072
14215
  import { hmac } from "@noble/hashes/hmac";
12073
14216
  import { sha512 } from "@noble/hashes/sha512";
14217
+ import { blake3 as blake36 } from "@noble/hashes/blake3";
12074
14218
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
14219
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
14220
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
12075
14221
  var MAX_RECEIVER_INDEX = 1e4;
12076
- async function deriveBridgeReceiver(nk, index) {
14222
+ function assertReceiverIndex(index) {
12077
14223
  if (!Number.isInteger(index) || index < 0) {
12078
14224
  throw new Error(`index must be a non-negative integer, got ${index}`);
12079
14225
  }
@@ -12082,6 +14228,26 @@ async function deriveBridgeReceiver(nk, index) {
12082
14228
  `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.`
12083
14229
  );
12084
14230
  }
14231
+ }
14232
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
14233
+ if (ownerUtxoKeypair instanceof Uint8Array) {
14234
+ throw new Error(
14235
+ "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."
14236
+ );
14237
+ }
14238
+ assertReceiverIndex(index);
14239
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
14240
+ const priv = bigintToBytes322(owner.privateKey);
14241
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
14242
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
14243
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
14244
+ const key = blake36(preimage);
14245
+ const h = hmac(sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
14246
+ return signerFromSecretKey(h.slice(0, 32));
14247
+ }
14248
+ async function deriveLegacyBridgeReceiver(nk, index) {
14249
+ assertReceiverIndex(index);
14250
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
12085
14251
  const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12086
14252
  return signerFromSecretKey(h.slice(0, 32));
12087
14253
  }
@@ -12092,13 +14258,44 @@ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS4, findAssociatedTokenPda
12092
14258
  function describeError(err) {
12093
14259
  return err instanceof Error ? err.message : String(err);
12094
14260
  }
12095
- async function listBridgeDeposits(rpc, nk, opts) {
14261
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
14262
+ if (ownerUtxoKeypair instanceof Uint8Array) {
14263
+ throw new Error(
14264
+ "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)."
14265
+ );
14266
+ }
14267
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
14268
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
14269
+ legacyExposed: false
14270
+ });
14271
+ if (opts.includeLegacy === false) return out;
14272
+ const nks = [];
14273
+ const seen = /* @__PURE__ */ new Set();
14274
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
14275
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
14276
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
14277
+ }
14278
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
14279
+ if (seen.has(key)) continue;
14280
+ seen.add(key);
14281
+ nks.push(nk);
14282
+ }
14283
+ for (const nk of nks) {
14284
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
14285
+ legacyExposed: true,
14286
+ legacyViewingKeyNk: nk
14287
+ });
14288
+ out.push(...legacy);
14289
+ }
14290
+ return out;
14291
+ }
14292
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12096
14293
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12097
14294
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12098
14295
  const out = [];
12099
14296
  let consecutiveUnused = 0;
12100
14297
  for (let index = 0; index < scanDepth; index++) {
12101
- const kp = await deriveBridgeReceiver(nk, index);
14298
+ const kp = await receiverAt(index);
12102
14299
  const receiver = kp.address;
12103
14300
  const [tokenAccount] = await findAssociatedTokenPda4({
12104
14301
  mint: opts.mint,
@@ -12150,7 +14347,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12150
14347
  tokenBalance,
12151
14348
  lamports,
12152
14349
  shieldSignature,
12153
- ...indexReused ? { indexReused, shieldSignatures } : {}
14350
+ ...indexReused ? { indexReused, shieldSignatures } : {},
14351
+ ...provenance
12154
14352
  });
12155
14353
  } catch (err) {
12156
14354
  out.push({
@@ -12160,7 +14358,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12160
14358
  state: "unknown",
12161
14359
  tokenBalance: 0n,
12162
14360
  lamports: 0n,
12163
- error: describeError(err)
14361
+ error: describeError(err),
14362
+ ...provenance
12164
14363
  });
12165
14364
  }
12166
14365
  }
@@ -12315,7 +14514,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12315
14514
  const signMessage = (m) => signMessageBytes(R, m);
12316
14515
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
12317
14516
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
12318
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
14517
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
14518
+ amount,
14519
+ viewingKeyNk: nk,
14520
+ ownerUtxoKeypair: utxoKeypair,
14521
+ mintAddress: mint
14522
+ });
12319
14523
  const zeroInput = await createZeroUtxo(mint);
12320
14524
  const rBefore = (await rpc.getBalance(R.address).send()).value;
12321
14525
  let result;
@@ -12334,6 +14538,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12334
14538
  signMessage,
12335
14539
  chainNoteViewingKeyNk: nk,
12336
14540
  chainNoteSalt: noteSalt,
14541
+ ownerUtxoKeypair: utxoKeypair,
12337
14542
  relaySupplementalAlt: true,
12338
14543
  onProgress: (s) => log(` \xB7 ${s}`)
12339
14544
  }
@@ -12527,13 +14732,13 @@ var DoNotRetry = class extends Error {
12527
14732
  };
12528
14733
  async function withShieldRetries(attempt, hooks = {}) {
12529
14734
  const attempts = hooks.attempts ?? 3;
12530
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
14735
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
12531
14736
  let last = "";
12532
14737
  for (let n = 1; n <= attempts; n++) {
12533
14738
  if (n > 1) {
12534
14739
  const delay = retryDelayMs(n);
12535
14740
  hooks.onRetry?.(n, delay, last);
12536
- await sleep4(delay);
14741
+ await sleep5(delay);
12537
14742
  }
12538
14743
  try {
12539
14744
  return await attempt(n);
@@ -12552,6 +14757,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12552
14757
  export {
12553
14758
  AccountRole,
12554
14759
  BRIDGE_ESCROW_LABEL,
14760
+ BRIDGE_ESCROW_LABEL_V2,
12555
14761
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
12556
14762
  CHAIN_NOTE_SALT_BITS,
12557
14763
  CLEANUP_FEE_BUDGET,
@@ -12580,6 +14786,10 @@ export {
12580
14786
  MemoryStorageAdapter,
12581
14787
  MerkleTree,
12582
14788
  NATIVE_SOL_MINT,
14789
+ NOTE_INDEX_NO_LEAF,
14790
+ NOTE_INDEX_PAGE_SIZE,
14791
+ NoteIndexFormatError,
14792
+ NoteIndexHeadBehindError,
12583
14793
  ONECLICK_PUBKEY_B58,
12584
14794
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
12585
14795
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -12656,6 +14866,7 @@ export {
12656
14866
  computeChainNoteHash,
12657
14867
  computeExtDataHash,
12658
14868
  computeMerkleRoot,
14869
+ computeNoteIndexChain,
12659
14870
  computeProofForLatestDeposit,
12660
14871
  computeProofFromChain,
12661
14872
  computeSignature,
@@ -12680,14 +14891,18 @@ export {
12680
14891
  depositFromDerivedKey,
12681
14892
  deriveBridgeReceiver,
12682
14893
  deriveChangeNoteBlinding,
12683
- deriveDepositNoteSecrets,
14894
+ deriveDepositNoteBlinding,
12684
14895
  deriveDiversifiedViewingKey,
12685
14896
  deriveDiversifier,
12686
14897
  deriveFundingTargets,
12687
14898
  deriveInputNullifierPdas,
14899
+ deriveLegacyBridgeReceiver,
14900
+ deriveLegacyDepositNoteSecrets,
14901
+ deriveLegacySwapRefundAuthorization,
12688
14902
  derivePublicKey,
12689
14903
  deriveSpendKey,
12690
14904
  deriveSwapRefundAuthorization,
14905
+ deriveSwapRefundBlinding,
12691
14906
  deriveUserCompliancePublicKey,
12692
14907
  deriveUserComplianceScalar,
12693
14908
  deriveUtxoKeypairFromSpendKey,
@@ -12700,6 +14915,8 @@ export {
12700
14915
  discoverSwapRefunds,
12701
14916
  downloadNote,
12702
14917
  encodeDeliveryCarrierMemo,
14918
+ encodeNoteIndexItem,
14919
+ encodeNoteIndexPage,
12703
14920
  encodeNoteSimple,
12704
14921
  encodeRecipientDeliveryNote,
12705
14922
  encryptCompactChainNote,
@@ -12715,6 +14932,8 @@ export {
12715
14932
  fetchCommitments,
12716
14933
  fetchLatestBlockhash,
12717
14934
  fetchLookupTables,
14935
+ fetchNoteIndexHead,
14936
+ fetchNoteIndexPage,
12718
14937
  fetchRiskQuoteInstruction,
12719
14938
  fetchRiskQuoteIx,
12720
14939
  fetchSignaturesForAddress,
@@ -12787,6 +15006,8 @@ export {
12787
15006
  parseDeliveryCarrierMemo,
12788
15007
  parseError,
12789
15008
  parseNote2 as parseNote,
15009
+ parseNoteIndexItem,
15010
+ parseNoteIndexPage,
12790
15011
  parseRelayErrorResponse,
12791
15012
  parseRelayErrorSignature,
12792
15013
  parseTransactionError,
@@ -12808,6 +15029,7 @@ export {
12808
15029
  readMerkleTreeState,
12809
15030
  readRent,
12810
15031
  recipientDeliveryNoteToBase64,
15032
+ recoverNotesFromIndex,
12811
15033
  registerViewingKey,
12812
15034
  relayRequestDigestHex,
12813
15035
  removePendingDeposit,