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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -638,13 +638,16 @@ import { sha256 as sha2562 } from "@noble/hashes/sha2";
638
638
 
639
639
  // src/relay/viewing-key.ts
640
640
  var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
641
+ var VIEWING_KEY_CHALLENGE_READABLE_HEADER = "Cloak: Enable private transactions\n\nShares your viewing key with Cloak so you can transact privately. Signing this does not move any funds.\n\n";
642
+ var VIEWING_KEY_CHALLENGE_REQUEST_FORMAT = "readable";
641
643
  var UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
642
644
  var MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS = 300;
643
645
  function normalizeViewingKeyHex(viewingKeyHex) {
644
646
  return viewingKeyHex.replace(/^0x/i, "").toLowerCase();
645
647
  }
646
- function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex) {
647
- return [
648
+ function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format = "legacy") {
649
+ const header = format === "readable" ? VIEWING_KEY_CHALLENGE_READABLE_HEADER : "";
650
+ return header + [
648
651
  VIEWING_KEY_CHALLENGE_PREFIX,
649
652
  userPubkey,
650
653
  nonce,
@@ -659,17 +662,16 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
659
662
  const challenge = data;
660
663
  const nonce = typeof challenge.nonce === "string" ? challenge.nonce : "";
661
664
  const expiresInSeconds = challenge.expires_in_seconds;
662
- const expectedMessage = buildViewingKeyChallengeMessage(
663
- userPubkey,
664
- nonce,
665
- viewingKeyHex
665
+ const messageFormat = ["readable", "legacy"].find(
666
+ (format) => challenge.message === buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format)
666
667
  );
667
- if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || challenge.message !== expectedMessage) {
668
+ if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || messageFormat === void 0) {
668
669
  throw new Error("Relay returned an unsafe viewing-key challenge");
669
670
  }
670
671
  return {
671
672
  nonce,
672
- message: expectedMessage,
673
+ message: buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, messageFormat),
674
+ messageFormat,
673
675
  expiresInSeconds
674
676
  };
675
677
  }
@@ -753,6 +755,44 @@ function isLoopbackHost(value) {
753
755
  }
754
756
  var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
755
757
 
758
+ // src/relay/clock.ts
759
+ var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
760
+ var MAX_CLOCK_DIVERGENCE_MS = 2e3;
761
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
762
+ var sample = null;
763
+ function monotonicNowMs() {
764
+ const perf = globalThis.performance;
765
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
766
+ }
767
+ function observeRelayClock(response) {
768
+ const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
769
+ if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
770
+ const serverMs = Number(raw.trim());
771
+ const wallMs = Date.now();
772
+ const offsetMs = serverMs - wallMs;
773
+ if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
774
+ sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
775
+ }
776
+ function relayNowMs() {
777
+ const wallMs = Date.now();
778
+ if (!sample) return wallMs;
779
+ const wallElapsed = wallMs - sample.wallAtSampleMs;
780
+ const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
781
+ if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
782
+ sample = null;
783
+ return wallMs;
784
+ }
785
+ return wallMs + sample.offsetMs;
786
+ }
787
+ function hasRelayClockSample() {
788
+ if (!sample) return false;
789
+ relayNowMs();
790
+ return sample !== null;
791
+ }
792
+ function relayNowSeconds() {
793
+ return Math.floor(relayNowMs() / 1e3);
794
+ }
795
+
756
796
  // src/relay/endpoint.ts
757
797
  var ALLOWED_ORIGINS = new Set(
758
798
  RELAY_ORIGIN_ALLOWLIST.map((entry) => {
@@ -804,8 +844,9 @@ function assertAllowedRelayOrigin(value) {
804
844
  async function relayFetch(url, init, options) {
805
845
  assertAllowedRelayOrigin(url);
806
846
  const extra = sanitizeExtraHeaders(options?.extraHeaders);
807
- if (!extra) return fetch(url, init);
808
- return fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) });
847
+ const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
848
+ if (options?.observeClock !== false) observeRelayClock(response);
849
+ return response;
809
850
  }
810
851
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
811
852
  var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
@@ -1298,7 +1339,7 @@ ${digest}`
1298
1339
  }
1299
1340
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1300
1341
  const senderB58 = sender;
1301
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
1342
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
1302
1343
  const nonce = randomNonceUuid();
1303
1344
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
1304
1345
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -1377,7 +1418,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
1377
1418
  `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
1419
  );
1379
1420
  }
1380
- function explainRelayAuthRejection(responseText) {
1421
+ function explainRelayAuthRejection(responseText, context) {
1381
1422
  const text = String(responseText);
1382
1423
  const has = (needle) => text.includes(needle);
1383
1424
  if (has("issued too far in the future")) {
@@ -1387,7 +1428,9 @@ function explainRelayAuthRejection(responseText) {
1387
1428
  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
1429
  }
1389
1430
  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\`.`;
1431
+ 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\`.`;
1432
+ if (!context?.carriedAffiliateCode) return base;
1433
+ 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
1434
  }
1392
1435
  if (has("has no registered viewing key")) {
1393
1436
  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.`;
@@ -1593,7 +1636,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1593
1636
  headers: { "Content-Type": "application/json" },
1594
1637
  body: JSON.stringify({
1595
1638
  user_pubkey: userPubkey,
1596
- viewing_key: nkHex
1639
+ viewing_key: nkHex,
1640
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
1597
1641
  })
1598
1642
  });
1599
1643
  if (!challengeResponse.ok) {
@@ -1621,7 +1665,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1621
1665
  nonce: challenge.nonce,
1622
1666
  identifier: keyId,
1623
1667
  signature,
1624
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
1668
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
1669
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
1625
1670
  })
1626
1671
  });
1627
1672
  if (!response.ok) {
@@ -1904,6 +1949,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
1904
1949
  return false;
1905
1950
  }
1906
1951
  }
1952
+ function isRelayRequestInFlightResponse(responseText) {
1953
+ try {
1954
+ const parsed = JSON.parse(responseText);
1955
+ return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
1956
+ } catch {
1957
+ return false;
1958
+ }
1959
+ }
1907
1960
  function classifyRelayError(responseText, httpStatus) {
1908
1961
  let inner = "";
1909
1962
  try {
@@ -3442,7 +3495,11 @@ var RelayService = class {
3442
3495
  const challengeRes = await relayFetch(`${this.baseUrl}/viewing-key/challenge`, {
3443
3496
  method: "POST",
3444
3497
  headers: { "Content-Type": "application/json" },
3445
- body: JSON.stringify({ user_pubkey: userPubkey, viewing_key: viewingKey })
3498
+ body: JSON.stringify({
3499
+ user_pubkey: userPubkey,
3500
+ viewing_key: viewingKey,
3501
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
3502
+ })
3446
3503
  });
3447
3504
  if (!challengeRes.ok) {
3448
3505
  const error = await challengeRes.text();
@@ -3467,7 +3524,8 @@ var RelayService = class {
3467
3524
  nonce: challenge.nonce,
3468
3525
  identifier,
3469
3526
  signature,
3470
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
3527
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
3528
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
3471
3529
  })
3472
3530
  });
3473
3531
  if (!response.ok) {
@@ -3929,6 +3987,27 @@ function isRootAccepted(data, rootHex) {
3929
3987
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3930
3988
  return readRootHistory(data).some((r) => r === want);
3931
3989
  }
3990
+ function treeAccountAcceptsRoot(data, rootHex) {
3991
+ const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3992
+ if (data.length >= ROOT_OFFSET + 32) {
3993
+ const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
3994
+ if (current === want) return true;
3995
+ }
3996
+ return isRootAccepted(data, want);
3997
+ }
3998
+ function readTreeAccountFrontier(data) {
3999
+ if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
4000
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
4001
+ const next = readBigUInt64LE(buf, 32);
4002
+ if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
4003
+ const subtrees = [];
4004
+ for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
4005
+ const offset = SUBTREES_OFFSET + level * 32;
4006
+ subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
4007
+ }
4008
+ const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
4009
+ return { nextIndex: Number(next), subtrees, root };
4010
+ }
3932
4011
 
3933
4012
  // src/proving/merkle.ts
3934
4013
  import { buildPoseidon } from "circomlibjs";
@@ -4088,6 +4167,89 @@ var MerkleTree = class _MerkleTree {
4088
4167
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4089
4168
  return MerkleTree.create(height, commitments);
4090
4169
  }
4170
+ var MerkleFrontier = class _MerkleFrontier {
4171
+ constructor(levels, zeros, poseidon2, count, left) {
4172
+ this.levels = levels;
4173
+ this.zeros = zeros;
4174
+ this.poseidon = poseidon2;
4175
+ this.count = count;
4176
+ this.left = left;
4177
+ }
4178
+ static async create(state, levels = MERKLE_TREE_HEIGHT2) {
4179
+ const zeros = await getZeroValues();
4180
+ const poseidon2 = await getPoseidon();
4181
+ const left = new Array(levels).fill(null);
4182
+ let count = 0;
4183
+ if (state) {
4184
+ if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
4185
+ throw new Error("MerkleFrontierState.nextIndex out of range");
4186
+ }
4187
+ if (!Array.isArray(state.left) || state.left.length !== levels) {
4188
+ throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
4189
+ }
4190
+ count = state.nextIndex;
4191
+ for (let l = 0; l < levels; l++) {
4192
+ const odd = Math.floor(count / 2 ** l) % 2 === 1;
4193
+ const entry = state.left[l];
4194
+ if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
4195
+ if (odd) {
4196
+ if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
4197
+ left[l] = BigInt("0x" + entry);
4198
+ }
4199
+ }
4200
+ }
4201
+ return new _MerkleFrontier(levels, zeros, poseidon2, count, left);
4202
+ }
4203
+ get nextIndex() {
4204
+ return this.count;
4205
+ }
4206
+ /**
4207
+ * The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
4208
+ * present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
4209
+ * With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
4210
+ */
4211
+ leftAt(level) {
4212
+ if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
4213
+ return this.left[level];
4214
+ }
4215
+ hash(a, b) {
4216
+ return this.poseidon.F.toObject(this.poseidon([a, b]));
4217
+ }
4218
+ /** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
4219
+ append(leaves) {
4220
+ if (leaves.length === 0) return;
4221
+ if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
4222
+ let nodes = leaves;
4223
+ for (let l = 0; l < this.levels && nodes.length > 0; l++) {
4224
+ const before = Math.floor(this.count / 2 ** l);
4225
+ const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
4226
+ const parents = [];
4227
+ for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
4228
+ this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
4229
+ nodes = parents;
4230
+ }
4231
+ this.count += leaves.length;
4232
+ }
4233
+ /** The root of the first `nextIndex` leaves, zero-padded to the right. */
4234
+ root() {
4235
+ let partial = this.zeros[0];
4236
+ for (let l = 0; l < this.levels; l++) {
4237
+ const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
4238
+ if (odd) partial = this.hash(this.left[l], partial);
4239
+ else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
4240
+ }
4241
+ return partial;
4242
+ }
4243
+ toState() {
4244
+ return {
4245
+ nextIndex: this.count,
4246
+ left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
4247
+ };
4248
+ }
4249
+ clone() {
4250
+ return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
4251
+ }
4252
+ };
4091
4253
 
4092
4254
  // src/config/transaction-version.ts
4093
4255
  var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
@@ -4236,6 +4398,7 @@ async function fetchWithRetry(url, options = {}) {
4236
4398
  try {
4237
4399
  const response = await fetch(url, { signal: controller.signal });
4238
4400
  clearTimeout(timeoutId);
4401
+ observeRelayClock(response);
4239
4402
  return response;
4240
4403
  } finally {
4241
4404
  clearTimeout(timeoutId);
@@ -4599,38 +4762,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
4599
4762
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
4600
4763
  return new Uint8Array(plaintext);
4601
4764
  }
4602
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
4765
+ async function importNkHkdfKey(nk) {
4603
4766
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4604
4767
  throw new Error("nk must be 32 bytes");
4605
4768
  }
4769
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
4770
+ }
4771
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
4606
4772
  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
- );
4773
+ const [keyBits, nonceBits] = await Promise.all([
4774
+ subtle.deriveBits(
4775
+ {
4776
+ name: "HKDF",
4777
+ hash: "SHA-256",
4778
+ salt: toArrayBuffer2(salt),
4779
+ info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
4780
+ },
4781
+ ikm,
4782
+ 256
4783
+ ),
4784
+ subtle.deriveBits(
4785
+ {
4786
+ name: "HKDF",
4787
+ hash: "SHA-256",
4788
+ salt: toArrayBuffer2(salt),
4789
+ info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
4790
+ },
4791
+ ikm,
4792
+ 96
4793
+ )
4794
+ ]);
4629
4795
  return {
4630
4796
  key: new Uint8Array(keyBits),
4631
4797
  nonce: new Uint8Array(nonceBits)
4632
4798
  };
4633
4799
  }
4800
+ async function deriveAesKeyAndNonce(nk, commitmentHex) {
4801
+ const ikm = await importNkHkdfKey(nk);
4802
+ return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
4803
+ }
4804
+ function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
4805
+ if (version === NOTE_VERSION_V4) {
4806
+ if (plaintext.length !== PLAINTEXT_LEN_V4) {
4807
+ throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
4808
+ }
4809
+ return {
4810
+ timestamp: readU64LE(plaintext, 0),
4811
+ commitment: commitmentHex.toLowerCase(),
4812
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
4813
+ outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
4814
+ outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
4815
+ isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
4816
+ };
4817
+ }
4818
+ if (version === NOTE_VERSION_V3) {
4819
+ if (plaintext.length !== PLAINTEXT_LEN_V3) {
4820
+ throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
4821
+ }
4822
+ return {
4823
+ timestamp: readU64LE(plaintext, 0),
4824
+ commitment: commitmentHex.toLowerCase(),
4825
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
4826
+ };
4827
+ }
4828
+ if (plaintext.length !== PLAINTEXT_LEN_V2) {
4829
+ throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
4830
+ }
4831
+ return {
4832
+ timestamp: readU64LE(plaintext, 0),
4833
+ commitment: commitmentHex.toLowerCase()
4834
+ };
4835
+ }
4634
4836
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
4635
4837
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4636
4838
  throw new Error("nk must be 32 bytes");
@@ -4694,36 +4896,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4694
4896
  try {
4695
4897
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
4696
4898
  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
- };
4899
+ return decodeChainNotePlaintext(version, plaintext, commitment);
4727
4900
  } catch (error) {
4728
4901
  lastError = error;
4729
4902
  }
@@ -4732,6 +4905,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4732
4905
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
4733
4906
  );
4734
4907
  }
4908
+ async function createCompactChainNoteDecryptor(nk) {
4909
+ const ikm = await importNkHkdfKey(nk);
4910
+ return async (noteBytes, commitment) => {
4911
+ if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
4912
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
4913
+ const version = noteBytes[0];
4914
+ if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
4915
+ return null;
4916
+ }
4917
+ try {
4918
+ const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
4919
+ const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
4920
+ let hex = "";
4921
+ for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
4922
+ return decodeChainNotePlaintext(version, plaintext, hex);
4923
+ } catch {
4924
+ return null;
4925
+ }
4926
+ };
4927
+ }
4735
4928
  function chainNoteToBase64(noteBytes) {
4736
4929
  return Buffer.from(noteBytes).toString("base64");
4737
4930
  }
@@ -4828,6 +5021,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4828
5021
  return null;
4829
5022
  }
4830
5023
  }
5024
+ var X25519_PKCS8_PREFIX = Uint8Array.from([
5025
+ 48,
5026
+ 46,
5027
+ 2,
5028
+ 1,
5029
+ 0,
5030
+ 48,
5031
+ 5,
5032
+ 6,
5033
+ 3,
5034
+ 43,
5035
+ 101,
5036
+ 110,
5037
+ 4,
5038
+ 34,
5039
+ 4,
5040
+ 32
5041
+ ]);
5042
+ var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
5043
+ function decodeOpened(plaintext) {
5044
+ if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5045
+ return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5046
+ }
5047
+ async function createRecipientDeliveryOpener(viewingSecretKey) {
5048
+ if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
5049
+ throw new Error("viewingSecretKey must be 32 bytes");
5050
+ }
5051
+ const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5052
+ const subtle = globalThis.crypto?.subtle;
5053
+ const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
5054
+ if (!subtle || typeof hsalsa !== "function") return slow;
5055
+ let privateKey;
5056
+ const sharedKey = async (ephemeralPk) => {
5057
+ const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
5058
+ const shared = new Uint8Array(
5059
+ await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
5060
+ );
5061
+ const key = new Uint8Array(32);
5062
+ hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
5063
+ return key;
5064
+ };
5065
+ try {
5066
+ const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
5067
+ pkcs8.set(X25519_PKCS8_PREFIX);
5068
+ pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5069
+ privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5070
+ const probe = nacl4.box.keyPair().publicKey;
5071
+ const fast = await sharedKey(probe);
5072
+ const reference = nacl4.box.before(probe, viewingSecretKey);
5073
+ if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5074
+ } catch {
5075
+ return slow;
5076
+ }
5077
+ return async (envelope) => {
5078
+ if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
5079
+ const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
5080
+ const nonce = envelope.subarray(
5081
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
5082
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5083
+ );
5084
+ const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
5085
+ let key;
5086
+ try {
5087
+ key = await sharedKey(ephemeralPk);
5088
+ } catch {
5089
+ return openRecipientDeliveryNote(envelope, viewingSecretKey);
5090
+ }
5091
+ try {
5092
+ return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
5093
+ } catch {
5094
+ return null;
5095
+ }
5096
+ };
5097
+ }
4831
5098
  function recipientDeliveryNoteToBase64(envelope) {
4832
5099
  return Buffer.from(envelope).toString("base64");
4833
5100
  }
@@ -4880,9 +5147,43 @@ function parseDeliveryCarrierMemo(data) {
4880
5147
  // src/notes/swap-refund.ts
4881
5148
  import { blake3 as blake33 } from "@noble/hashes/blake3";
4882
5149
  import _bs582 from "bs58";
5150
+
5151
+ // src/notes/owner-key.ts
5152
+ var FIELD_MODULUS = BigInt(
5153
+ "21888242871839275222246405745257275088548364400416034343698204186575808495617"
5154
+ );
5155
+ async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
5156
+ if (!keypair || typeof keypair !== "object") {
5157
+ throw new Error(
5158
+ `${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.`
5159
+ );
5160
+ }
5161
+ const { privateKey, publicKey } = keypair;
5162
+ if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS) {
5163
+ throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
5164
+ }
5165
+ if (typeof publicKey !== "bigint" || publicKey === 0n) {
5166
+ throw new Error(`${label}.publicKey must be a non-zero bigint`);
5167
+ }
5168
+ if (await derivePublicKey(privateKey) !== publicKey) {
5169
+ throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
5170
+ }
5171
+ return { privateKey, publicKey };
5172
+ }
5173
+ function normalizeOwnerPublicKey(publicKey, label) {
5174
+ if (publicKey === void 0 || publicKey === null) return void 0;
5175
+ if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS) {
5176
+ throw new Error(`${label} must be a non-zero field element (bigint)`);
5177
+ }
5178
+ return publicKey;
5179
+ }
5180
+
5181
+ // src/notes/swap-refund.ts
4883
5182
  var bs582 = _bs582.default || _bs582;
4884
5183
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
4885
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5184
+ var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
5185
+ var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
5186
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
4886
5187
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
4887
5188
  function normalizeNullifier(inputNullifier) {
4888
5189
  if (inputNullifier instanceof Uint8Array) {
@@ -4916,13 +5217,51 @@ function derive(nk, nullifier, info) {
4916
5217
  preimage.set(info, off);
4917
5218
  return blake33(preimage);
4918
5219
  }
4919
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5220
+ function assertNk(viewingKeyNk) {
4920
5221
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
4921
5222
  throw new Error("viewingKeyNk must be 32 bytes");
4922
5223
  }
5224
+ return viewingKeyNk;
5225
+ }
5226
+ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
5227
+ const nk = assertNk(viewingKeyNk);
5228
+ return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
5229
+ }
5230
+ function privateKeyBytes(privateKey) {
5231
+ return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
5232
+ }
5233
+ async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
5234
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5235
+ const nullifier = normalizeNullifier(inputNullifier);
5236
+ const preimage = new Uint8Array(
5237
+ REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
5238
+ );
5239
+ let off = 0;
5240
+ preimage.set(REFUND_KEY_DOMAIN_V2, off);
5241
+ off += REFUND_KEY_DOMAIN_V2.length;
5242
+ preimage.set(privateKeyBytes(owner.privateKey), off);
5243
+ off += 32;
5244
+ preimage.set(nullifier, off);
5245
+ off += nullifier.length;
5246
+ preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
5247
+ const privateKey = toFieldSecret(blake33(preimage));
5248
+ const publicKey = await derivePublicKey(privateKey);
5249
+ if (publicKey === 0n) throw new Error("refund authorization is degenerate");
5250
+ return { privateKey, publicKey };
5251
+ }
5252
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
5253
+ const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5254
+ const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
5255
+ if (keypair.publicKey === 0n || blinding === 0n) {
5256
+ throw new Error("refund authorization is degenerate");
5257
+ }
5258
+ return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
5259
+ }
5260
+ async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5261
+ const nk = assertNk(viewingKeyNk);
4923
5262
  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));
5263
+ const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
5264
+ const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
4926
5265
  const publicKey = await derivePublicKey(privateKey);
4927
5266
  if (publicKey === 0n || blinding === 0n) {
4928
5267
  throw new Error("derived refund authorization is degenerate");
@@ -4937,22 +5276,90 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
4937
5276
  mintAddress: NATIVE_SOL_MINT
4938
5277
  });
4939
5278
  }
5279
+ function toField(value) {
5280
+ return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
5281
+ }
4940
5282
  async function matchSwapRefundLeaf(params) {
4941
5283
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
4942
- const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
4943
- let auth;
5284
+ const expected = toField(params.commitment);
5285
+ let blinding;
5286
+ try {
5287
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5288
+ } catch {
5289
+ return null;
5290
+ }
5291
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5292
+ const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
5293
+ let perSwapPub;
5294
+ let perSwapPriv = 0n;
5295
+ if (ownerPriv > 0n && ownerPub !== void 0) {
5296
+ try {
5297
+ const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
5298
+ perSwapPub = kp.publicKey;
5299
+ perSwapPriv = kp.privateKey;
5300
+ } catch {
5301
+ return null;
5302
+ }
5303
+ }
5304
+ if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
5305
+ const published = toField(params.publishedRefundPubkey);
5306
+ const publishedBlinding = toField(params.publishedRefundBlinding);
5307
+ if (published !== 0n && publishedBlinding === blinding) {
5308
+ if (perSwapPub === void 0 || perSwapPub === published) {
5309
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
5310
+ if (candidate === expected && published !== ownerPub) {
5311
+ return {
5312
+ keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
5313
+ shape: "per-swap",
5314
+ blinding,
5315
+ amount: amountAfterFee,
5316
+ commitment: candidate,
5317
+ legacyExposed: false
5318
+ };
5319
+ }
5320
+ }
5321
+ }
5322
+ } else if (perSwapPub !== void 0) {
5323
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
5324
+ if (candidate === expected) {
5325
+ return {
5326
+ keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
5327
+ shape: "per-swap",
5328
+ blinding,
5329
+ amount: amountAfterFee,
5330
+ commitment: candidate,
5331
+ legacyExposed: false
5332
+ };
5333
+ }
5334
+ }
5335
+ if (ownerPub !== void 0) {
5336
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
5337
+ if (candidate === expected) {
5338
+ return {
5339
+ keypair: { privateKey: ownerPriv, publicKey: ownerPub },
5340
+ shape: "owner",
5341
+ blinding,
5342
+ amount: amountAfterFee,
5343
+ commitment: candidate,
5344
+ legacyExposed: false
5345
+ };
5346
+ }
5347
+ }
5348
+ let legacy;
4944
5349
  try {
4945
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
5350
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
4946
5351
  } catch {
4947
5352
  return null;
4948
5353
  }
4949
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
4950
- if (candidate !== expected) return null;
5354
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
5355
+ if (legacyCandidate !== expected) return null;
4951
5356
  return {
4952
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
4953
- blinding: auth.blinding,
5357
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
5358
+ shape: "legacy-nk",
5359
+ blinding: legacy.blinding,
4954
5360
  amount: amountAfterFee,
4955
- commitment: candidate
5361
+ commitment: legacyCandidate,
5362
+ legacyExposed: true
4956
5363
  };
4957
5364
  }
4958
5365
  var TRANSACT_SWAP_TAG2 = 1;
@@ -4960,6 +5367,9 @@ var PROOF_LEN2 = 256;
4960
5367
  var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
4961
5368
  var PUBLIC_INPUTS_LEN2 = 264;
4962
5369
  var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
5370
+ var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
5371
+ var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
5372
+ var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
4963
5373
  function toBase58(key) {
4964
5374
  if (!key) return void 0;
4965
5375
  if (typeof key === "string") return key;
@@ -5016,10 +5426,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
5016
5426
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
5017
5427
  return out;
5018
5428
  }
5019
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
5429
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
5020
5430
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5021
5431
  throw new Error("viewingKeyNk must be 32 bytes");
5022
5432
  }
5433
+ if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
5434
+ throw new Error(
5435
+ "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): per-swap and owner-key refund leaves are matched against it, and nk alone can only find legacy refunds."
5436
+ );
5437
+ }
5438
+ const ownerUtxoKeypair = options.ownerUtxoKeypair;
5023
5439
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5024
5440
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5025
5441
  const programIdBase58 = programId;
@@ -5076,7 +5492,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5076
5492
  programId
5077
5493
  );
5078
5494
  const key = swapState;
5079
- if (!nullifierBySwapState.has(key)) nullifierBySwapState.set(key, { nullifier, signature });
5495
+ const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
5496
+ if (!nullifierBySwapState.has(key)) {
5497
+ nullifierBySwapState.set(key, {
5498
+ nullifier,
5499
+ signature,
5500
+ refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
5501
+ refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
5502
+ });
5503
+ }
5080
5504
  }
5081
5505
  const logs = tx.meta?.logMessages;
5082
5506
  const scan = scanRefundLeafEvents(logs, programIdBase58);
@@ -5094,7 +5518,10 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5094
5518
  viewingKeyNk,
5095
5519
  inputNullifier: candidate.nullifier,
5096
5520
  amountAfterFee: event.amountAfterFee,
5097
- commitment: event.commitmentField
5521
+ commitment: event.commitmentField,
5522
+ ownerUtxoKeypair,
5523
+ publishedRefundPubkey: candidate.refundPubkey,
5524
+ publishedRefundBlinding: candidate.refundBlinding
5098
5525
  });
5099
5526
  if (!recovered) continue;
5100
5527
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5118,7 +5545,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5118
5545
  // src/notes/deposit-note.ts
5119
5546
  import { blake3 as blake34 } from "@noble/hashes/blake3";
5120
5547
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5121
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5548
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5122
5549
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5123
5550
  var CHAIN_NOTE_SALT_BITS = 96;
5124
5551
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -5154,30 +5581,47 @@ function derive2(nk, salt, info) {
5154
5581
  preimage.set(info, off);
5155
5582
  return blake34(preimage);
5156
5583
  }
5584
+ function assertNk2(viewingKeyNk) {
5585
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5586
+ throw new Error("viewingKeyNk must be 32 bytes");
5587
+ }
5588
+ return viewingKeyNk;
5589
+ }
5157
5590
  function randomDepositNoteSalt() {
5158
5591
  const bytes = randomBytes(12);
5159
5592
  let v = 0n;
5160
5593
  for (const b of bytes) v = v << 8n | BigInt(b);
5161
5594
  return v === 0n ? 1n : v;
5162
5595
  }
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
- }
5596
+ function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
5597
+ const nk = assertNk2(viewingKeyNk);
5598
+ return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
5599
+ }
5600
+ async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
5601
+ const nk = assertNk2(viewingKeyNk);
5167
5602
  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));
5603
+ const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
5604
+ const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
5170
5605
  const publicKey = await derivePublicKey(privateKey);
5171
5606
  if (publicKey === 0n || blinding === 0n) {
5172
5607
  throw new Error("derived deposit note secrets are degenerate");
5173
5608
  }
5174
5609
  return { keypair: { privateKey, publicKey }, blinding };
5175
5610
  }
5176
- async function createRecoverableDepositUtxo(amount, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomDepositNoteSalt()) {
5611
+ async function createRecoverableDepositUtxo(params) {
5612
+ if (!params || typeof params !== "object" || params instanceof Uint8Array) {
5613
+ throw new Error(
5614
+ "createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
5615
+ );
5616
+ }
5617
+ const { amount, viewingKeyNk } = params;
5177
5618
  if (typeof amount !== "bigint" || amount <= 0n) {
5178
5619
  throw new Error("amount must be a positive bigint");
5179
5620
  }
5180
- const { keypair, blinding } = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5621
+ const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
5622
+ const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
5623
+ const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
5624
+ const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5181
5625
  const utxo = { amount, keypair, blinding, mintAddress };
5182
5626
  utxo.commitment = await computeCommitment(utxo);
5183
5627
  return { utxo, noteSalt };
@@ -5192,21 +5636,46 @@ function normalizeCommitment(value) {
5192
5636
  async function matchDepositNote(params) {
5193
5637
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
5194
5638
  if (typeof amount !== "bigint" || amount <= 0n) return null;
5195
- let secrets;
5639
+ let blinding;
5640
+ try {
5641
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5642
+ } catch {
5643
+ return null;
5644
+ }
5645
+ const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
5646
+ if (published.length === 0) return null;
5647
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5648
+ if (ownerPub !== void 0) {
5649
+ const keypair = {
5650
+ privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
5651
+ publicKey: ownerPub
5652
+ };
5653
+ const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5654
+ if (published.some((value) => value === candidate)) {
5655
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
5656
+ }
5657
+ }
5658
+ let legacy;
5196
5659
  try {
5197
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5660
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
5198
5661
  } catch {
5199
5662
  return null;
5200
5663
  }
5201
- const candidate = await computeCommitment({
5664
+ const legacyCandidate = await computeCommitment({
5202
5665
  amount,
5203
- keypair: secrets.keypair,
5204
- blinding: secrets.blinding,
5666
+ keypair: legacy.keypair,
5667
+ blinding: legacy.blinding,
5205
5668
  mintAddress
5206
5669
  });
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 };
5670
+ if (!published.some((value) => value === legacyCandidate)) return null;
5671
+ return {
5672
+ ...legacy,
5673
+ amount,
5674
+ mintAddress,
5675
+ commitment: legacyCandidate,
5676
+ noteSalt,
5677
+ legacyExposed: true
5678
+ };
5210
5679
  }
5211
5680
 
5212
5681
  // src/notes/change-note.ts
@@ -5262,10 +5731,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
5262
5731
  preimage.set(CHANGE_BLINDING_INFO, off);
5263
5732
  return toFieldSecret3(blake35(preimage));
5264
5733
  }
5265
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5734
+ async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5266
5735
  if (typeof amount !== "bigint" || amount <= 0n) {
5267
5736
  throw new Error("amount must be a positive bigint");
5268
5737
  }
5738
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5269
5739
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5270
5740
  const utxo = { amount, keypair, blinding, mintAddress };
5271
5741
  utxo.commitment = await computeCommitment(utxo);
@@ -5291,13 +5761,27 @@ async function matchChangeNote(params) {
5291
5761
  const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5292
5762
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
5293
5763
  if (!published.some((value) => value === candidate)) return null;
5294
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
5764
+ const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
5765
+ const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
5766
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
5295
5767
  }
5296
5768
 
5297
5769
  // src/flows/transact.ts
5298
5770
  import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
5299
5771
  import nacl5 from "tweetnacl";
5300
5772
 
5773
+ // src/relay/chain-note-time.ts
5774
+ async function relayChainNoteTimestampMs(relayUrl) {
5775
+ if (relayUrl && !hasRelayClockSample()) {
5776
+ try {
5777
+ const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
5778
+ await response.body?.cancel?.().catch(() => void 0);
5779
+ } catch {
5780
+ }
5781
+ }
5782
+ return BigInt(relayNowMs());
5783
+ }
5784
+
5301
5785
  // src/proving/artifacts.ts
5302
5786
  import { sha256 as sha2564 } from "@noble/hashes/sha2";
5303
5787
 
@@ -5584,6 +6068,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
5584
6068
  var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
5585
6069
  var DEFAULT_RELAY_NETWORK_RETRIES = 6;
5586
6070
  var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
6071
+ var RELAY_SOURCE_LEASE_MS = 18e4;
6072
+ var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
6073
+ var MAX_LEASE_EXPIRY_REPLAYS = 2;
6074
+ var RELAY_IN_FLIGHT_POLL_MS = 5e3;
6075
+ var RELAY_LANDED_POLL_MS = 1e3;
6076
+ var MAX_LANDED_POLLS = 5;
5587
6077
  function parseMissingRelayIndexError(message) {
5588
6078
  const match = message.match(
5589
6079
  /Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
@@ -5934,6 +6424,33 @@ function parseNkInput(input) {
5934
6424
  }
5935
6425
  return Uint8Array.from(Buffer.from(clean, "hex"));
5936
6426
  }
6427
+ async function resolveWalletNk(options) {
6428
+ const explicit = await resolveChainNoteNk(options);
6429
+ if (explicit) return explicit;
6430
+ if (options.ownerUtxoKeypair) {
6431
+ const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
6432
+ return getNkFromUtxoPrivateKey(owner.privateKey);
6433
+ }
6434
+ return null;
6435
+ }
6436
+ function missingWalletNkError(flow) {
6437
+ return new Error(
6438
+ `${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.`
6439
+ );
6440
+ }
6441
+ async function requireWalletNk(options, flow) {
6442
+ const nk = await resolveWalletNk(options);
6443
+ if (nk) return nk;
6444
+ throw missingWalletNkError(flow);
6445
+ }
6446
+ async function requireOwnerUtxoKeypair(options, flow) {
6447
+ if (!options.ownerUtxoKeypair) {
6448
+ throw new Error(
6449
+ `${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].`
6450
+ );
6451
+ }
6452
+ return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
6453
+ }
5937
6454
  async function resolveChainNoteNk(options) {
5938
6455
  if (options.chainNoteViewingKeyNk) {
5939
6456
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -5951,7 +6468,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
5951
6468
  function toHex(bytes) {
5952
6469
  return Buffer.from(bytes).toString("hex");
5953
6470
  }
5954
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6471
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
5955
6472
  if (options.enforceViewingKeyRegistration === false) {
5956
6473
  return;
5957
6474
  }
@@ -5965,7 +6482,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5965
6482
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
5966
6483
  );
5967
6484
  }
5968
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
6485
+ const nk = walletNk;
5969
6486
  if (!nk || nk.length !== 32) {
5970
6487
  throw new Error(
5971
6488
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6001,7 +6518,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6001
6518
  headers: { "Content-Type": "application/json" },
6002
6519
  body: JSON.stringify({
6003
6520
  user_pubkey: userPubkey,
6004
- viewing_key: viewingKeyHex
6521
+ viewing_key: viewingKeyHex,
6522
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
6005
6523
  })
6006
6524
  });
6007
6525
  if (!challengeResponse.ok) {
@@ -6048,7 +6566,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6048
6566
  viewing_key: viewingKeyHex,
6049
6567
  nonce: challenge.nonce,
6050
6568
  signature: signatureBase64,
6051
- ...authMode === "transaction" ? { auth_mode: authMode } : {}
6569
+ ...authMode === "transaction" ? { auth_mode: authMode } : {},
6570
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
6052
6571
  })
6053
6572
  });
6054
6573
  if (!response.ok) {
@@ -6107,10 +6626,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6107
6626
  result.set(bigintToBytes322(BigInt(publicSignals[0])), offset);
6108
6627
  offset += 32;
6109
6628
  let amount = BigInt(publicSignals[1]);
6110
- const FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6111
- const HALF_FIELD = FIELD_MODULUS / BigInt(2);
6629
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6630
+ const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
6112
6631
  if (amount > HALF_FIELD) {
6113
- amount = amount - FIELD_MODULUS;
6632
+ amount = amount - FIELD_MODULUS2;
6114
6633
  }
6115
6634
  const amountBytes = new Uint8Array(8);
6116
6635
  let amountValue = amount;
@@ -7057,8 +7576,9 @@ function chargeWalletApproval(used, budget, lastError) {
7057
7576
  }
7058
7577
  return used + 1;
7059
7578
  }
7060
- function relayFailureMessage(prefix, responseText) {
7061
- const explanation = explainRelayAuthRejection(responseText);
7579
+ function relayFailureMessage(prefix, responseText, requestBody) {
7580
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
7581
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7062
7582
  return explanation ? `${prefix}: ${responseText}
7063
7583
 
7064
7584
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -7140,6 +7660,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
7140
7660
  function sleep2(ms) {
7141
7661
  return new Promise((resolve) => setTimeout(resolve, ms));
7142
7662
  }
7663
+ function sleepUnlessAborted(ms, signal) {
7664
+ if (signal?.aborted) return Promise.resolve(false);
7665
+ return new Promise((resolve) => {
7666
+ const onAbort = () => {
7667
+ clearTimeout(timer);
7668
+ resolve(false);
7669
+ };
7670
+ const timer = setTimeout(() => {
7671
+ signal?.removeEventListener("abort", onAbort);
7672
+ resolve(true);
7673
+ }, ms);
7674
+ signal?.addEventListener("abort", onAbort, { once: true });
7675
+ });
7676
+ }
7143
7677
  function hexToBytes2(hex) {
7144
7678
  const bytes = new Uint8Array(hex.length / 2);
7145
7679
  for (let i = 0; i < hex.length; i += 2) {
@@ -7374,6 +7908,9 @@ async function submitTransactToRelay(args) {
7374
7908
  let unknownOutcomeSignature = null;
7375
7909
  let possiblySubmitted = false;
7376
7910
  let networkRetry = 0;
7911
+ let leaseReplays = 0;
7912
+ let landedPolls = 0;
7913
+ let leaseBaseMs = null;
7377
7914
  const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
7378
7915
  connection: settlement.connection,
7379
7916
  programId: settlement.programId,
@@ -7429,6 +7966,7 @@ async function submitTransactToRelay(args) {
7429
7966
  const controller = new AbortController();
7430
7967
  const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
7431
7968
  let response;
7969
+ leaseBaseMs ?? (leaseBaseMs = Date.now());
7432
7970
  try {
7433
7971
  response = await doFetch(`${relayUrl}/transact`, {
7434
7972
  method: "POST",
@@ -7436,6 +7974,7 @@ async function submitTransactToRelay(args) {
7436
7974
  body: requestPayload,
7437
7975
  signal: controller.signal
7438
7976
  });
7977
+ observeRelayClock(response);
7439
7978
  } finally {
7440
7979
  clearTimeout(timeoutId);
7441
7980
  }
@@ -7446,6 +7985,49 @@ async function submitTransactToRelay(args) {
7446
7985
  if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
7447
7986
  possiblySubmitted = true;
7448
7987
  }
7988
+ if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
7989
+ networkRetry = 0;
7990
+ const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
7991
+ const polling = Date.now() < leaseEndsMs;
7992
+ const probe = await verifySettlement(
7993
+ unknownOutcomeSignature,
7994
+ polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
7995
+ );
7996
+ if (probe.status === "landed") {
7997
+ landedPolls++;
7998
+ if (!polling || landedPolls > MAX_LANDED_POLLS) {
7999
+ return await resolveFailure(
8000
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8001
+ );
8002
+ }
8003
+ if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
8004
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8005
+ }
8006
+ continue;
8007
+ }
8008
+ if (polling) {
8009
+ onProgress?.("Relay is still processing this request; checking again shortly...");
8010
+ const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
8011
+ if (!await sleepUnlessAborted(pollMs, args.signal)) {
8012
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8013
+ }
8014
+ continue;
8015
+ }
8016
+ leaseReplays++;
8017
+ const waitMs = Math.max(
8018
+ 0,
8019
+ (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
8020
+ );
8021
+ onProgress?.(
8022
+ `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})...`
8023
+ );
8024
+ if (!await sleepUnlessAborted(waitMs, args.signal)) {
8025
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8026
+ }
8027
+ networkRetry = 0;
8028
+ leaseBaseMs = null;
8029
+ continue;
8030
+ }
7449
8031
  if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
7450
8032
  networkRetry++;
7451
8033
  const delay = relayBackoffMs(networkRetry);
@@ -7466,7 +8048,9 @@ async function submitTransactToRelay(args) {
7466
8048
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
7467
8049
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
7468
8050
  }
7469
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
8051
+ return await resolveFailure(
8052
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8053
+ );
7470
8054
  }
7471
8055
  const apiResponse = JSON.parse(responseText);
7472
8056
  if (!apiResponse.success || !apiResponse.data) {
@@ -7483,7 +8067,7 @@ async function submitTransactToRelay(args) {
7483
8067
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
7484
8068
  }
7485
8069
  return await resolveFailure(
7486
- new Error(relayFailureMessage("Relay returned error", errorStr))
8070
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
7487
8071
  );
7488
8072
  }
7489
8073
  const result = apiResponse.data;
@@ -7591,34 +8175,37 @@ async function transact(params, options) {
7591
8175
  );
7592
8176
  }
7593
8177
  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) {
8178
+ const walletNk = await resolveWalletNk(options);
8179
+ const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
8180
+ if (options.chainNoteSalt !== void 0 && !walletNk) {
7599
8181
  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."
8182
+ "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
8183
  );
7602
8184
  }
7603
8185
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
7604
8186
  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));
8187
+ if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
8188
+ throw missingWalletNkError("transact");
8189
+ }
8190
+ if (walletNk && chainNoteWillCarrySalt) {
8191
+ const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8192
+ if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
8193
+ const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
7607
8194
  for (let i = 0; i < outputUtxos.length; i++) {
7608
8195
  const out = outputUtxos[i];
7609
8196
  if (!out || out.amount <= BigInt(0)) continue;
7610
- if (!inputOwners.has(out.keypair.publicKey)) continue;
7611
- if (out.blinding !== deriveChangeNoteBlinding(explicitChainNoteNk, chainNoteSalt, i)) {
8197
+ if (!selfOwners.has(out.keypair.publicKey)) continue;
8198
+ if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
7612
8199
  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.`
8200
+ `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
8201
  );
7615
8202
  }
7616
8203
  }
7617
8204
  }
7618
8205
  assertAllowedRpcConnection(connection);
7619
8206
  assertInputMints(inputUtxos, options.expectedMint);
7620
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
7621
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
8207
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
8208
+ const resolvedChainNoteNk = walletNk;
7622
8209
  if (inputUtxos.length > 2) {
7623
8210
  throw new Error("Maximum 2 input UTXOs allowed");
7624
8211
  }
@@ -7992,7 +8579,7 @@ async function transact(params, options) {
7992
8579
  }
7993
8580
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
7994
8581
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
7995
- const chainNoteTimestamp = BigInt(Date.now());
8582
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
7996
8583
  const mintField = pubkeyToFieldElement(mint);
7997
8584
  let signature = "pending-" + Date.now().toString();
7998
8585
  let commitmentIndices = [-1, -1];
@@ -8088,9 +8675,9 @@ async function transact(params, options) {
8088
8675
  ]));
8089
8676
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8090
8677
  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()}`);
8678
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8679
+ if (chainNoteHash >= FIELD_MODULUS2) {
8680
+ throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
8094
8681
  }
8095
8682
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8096
8683
  const totalInputs = 1 + // root
@@ -8512,7 +9099,8 @@ async function transact(params, options) {
8512
9099
  throw lastError;
8513
9100
  }
8514
9101
  const classified = classifyRelayError(lastError.message);
8515
- const isMerkleClass = !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9102
+ const isDepositSubmission = externalAmount > BigInt(0);
9103
+ const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
8516
9104
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
8517
9105
  onProgress?.(
8518
9106
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -8661,54 +9249,83 @@ async function transact(params, options) {
8661
9249
  };
8662
9250
  }
8663
9251
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
9252
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
9253
+ const transferNk = await requireWalletNk(options, "transfer");
8664
9254
  const inputSum = sumUtxoAmounts(inputUtxos);
8665
9255
  if (inputSum < amount) {
8666
9256
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
8667
9257
  }
8668
9258
  const change = inputSum - amount;
8669
- const myKeypair = inputUtxos[0].keypair;
8670
9259
  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);
9260
+ let spendInputs = [
9261
+ ...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
9262
+ ...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
9263
+ ];
9264
+ let spendOptions = options;
9265
+ if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
9266
+ if (spendInputs.length > 2) {
9267
+ throw new Error(
9268
+ `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.`
9269
+ );
9270
+ }
9271
+ if (options.relayAuthBatch) {
9272
+ throw new Error(
9273
+ "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."
9274
+ );
9275
+ }
9276
+ options.onProgress?.("Moving notes under the wallet key before the transfer...");
9277
+ const migrationSalt = randomChangeNoteSalt();
9278
+ const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
9279
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
9280
+ void _recipientViewingPublicKey;
9281
+ const migration = await transact(
9282
+ { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
9283
+ { ...migrationOptions, chainNoteSalt: migrationSalt }
9284
+ );
9285
+ const migratedNote = migration.outputUtxos?.[0] ?? migrated;
9286
+ if (migration.commitmentIndices?.[0] >= 0) {
9287
+ migratedNote.index = migration.commitmentIndices[0];
9288
+ }
9289
+ spendInputs = [migratedNote];
9290
+ spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
9291
+ }
9292
+ const changeNoteSalt = randomChangeNoteSalt();
9293
+ const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
8674
9294
  const recipientKeypair = {
8675
9295
  privateKey: BigInt(0),
8676
9296
  // Recipient's private key unknown
8677
9297
  publicKey: recipientPubkey
8678
9298
  };
8679
- const recipientUtxo = transferNk && isSendToSelf ? (await createRecoverableChangeUtxo(amount, myKeypair, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
9299
+ const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
8680
9300
  const outputUtxos = [recipientUtxo];
8681
9301
  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
- }
9302
+ const { utxo } = await createRecoverableChangeUtxo(
9303
+ change,
9304
+ owner,
9305
+ transferNk,
9306
+ mint,
9307
+ changeNoteSalt,
9308
+ 1
9309
+ );
9310
+ outputUtxos.push(utxo);
8695
9311
  }
8696
9312
  return transact(
8697
9313
  {
8698
- inputUtxos,
9314
+ inputUtxos: spendInputs,
8699
9315
  outputUtxos,
8700
9316
  externalAmount: BigInt(0)
8701
9317
  // Pure shield-to-shield
8702
9318
  },
8703
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
9319
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
8704
9320
  );
8705
9321
  }
8706
9322
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9323
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
9324
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
8707
9325
  const inputSum = sumUtxoAmounts(inputUtxos);
8708
9326
  if (inputSum < withdrawAmount) {
8709
9327
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
8710
9328
  }
8711
- const myKeypair = inputUtxos[0].keypair;
8712
9329
  const mint = inputUtxos[0].mintAddress;
8713
9330
  let utxos = [...inputUtxos];
8714
9331
  let cachedTree = options.cachedMerkleTree;
@@ -8717,9 +9334,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8717
9334
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
8718
9335
  const [small1, small2, ...rest] = utxos;
8719
9336
  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);
9337
+ const mergeSalt = randomChangeNoteSalt();
9338
+ const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
8723
9339
  const mergeResult = await transact(
8724
9340
  {
8725
9341
  inputUtxos: [small1, small2],
@@ -8730,7 +9346,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8730
9346
  {
8731
9347
  ...options,
8732
9348
  cachedMerkleTree: cachedTree,
8733
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
9349
+ chainNoteSalt: mergeSalt
8734
9350
  }
8735
9351
  );
8736
9352
  cachedTree = mergeResult.merkleTree;
@@ -8745,23 +9361,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8745
9361
  const outputUtxos = [];
8746
9362
  let changeNoteSalt;
8747
9363
  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
- }
9364
+ const salt = randomChangeNoteSalt();
9365
+ const { utxo } = await createRecoverableChangeUtxo(
9366
+ change,
9367
+ owner,
9368
+ walletNk,
9369
+ mint,
9370
+ salt,
9371
+ 0
9372
+ // partialWithdraw puts change at output 0
9373
+ );
9374
+ outputUtxos.push(utxo);
9375
+ changeNoteSalt = salt;
8765
9376
  }
8766
9377
  return transact(
8767
9378
  {
@@ -8884,6 +9495,8 @@ async function swapUtxo(params, options) {
8884
9495
  if (relayUrl) {
8885
9496
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
8886
9497
  }
9498
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
9499
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
8887
9500
  if (inputUtxos.length === 0) {
8888
9501
  throw new Error("At least one input UTXO required");
8889
9502
  }
@@ -8909,15 +9522,12 @@ async function swapUtxo(params, options) {
8909
9522
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
8910
9523
  }
8911
9524
  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;
9525
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
8916
9526
  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)) {
9527
+ if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
9528
+ if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
8919
9529
  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.`
9530
+ `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
9531
  );
8922
9532
  }
8923
9533
  }
@@ -8941,24 +9551,18 @@ async function swapUtxo(params, options) {
8941
9551
  );
8942
9552
  }
8943
9553
  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
- }
9554
+ const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
9555
+ const refundAuthorization = await deriveSwapRefundAuthorization(
9556
+ resolvedSwapChainNoteNk,
9557
+ refundNullifier,
9558
+ swapOwner
9559
+ );
9560
+ const refundKeypair = {
9561
+ privateKey: refundAuthorization.privateKey,
9562
+ publicKey: refundAuthorization.publicKey
9563
+ };
9564
+ const refundBlinding = refundAuthorization.blinding;
9565
+ const refundDerivedFromNk = true;
8962
9566
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
8963
9567
  throw new Error(
8964
9568
  "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 +9888,7 @@ async function swapUtxo(params, options) {
9284
9888
  for (const utxo of paddedOutputs) {
9285
9889
  outputCommitments.push(await computeCommitment(utxo));
9286
9890
  }
9287
- const chainNoteTimestamp = BigInt(Date.now());
9891
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
9288
9892
  onProgress?.("Computing external data hash...");
9289
9893
  const mint = swapPoolMint;
9290
9894
  const mintField = pubkeyToFieldElement(mint);
@@ -9598,7 +10202,7 @@ async function swapUtxo(params, options) {
9598
10202
  forceChainIndexing = !relayUrl;
9599
10203
  continue;
9600
10204
  }
9601
- throw new Error(relayFailureMessage("Relay error", responseText));
10205
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
9602
10206
  }
9603
10207
  const apiResponse = JSON.parse(responseText);
9604
10208
  if (!apiResponse.success || !apiResponse.data) {
@@ -9734,7 +10338,6 @@ async function swapUtxo(params, options) {
9734
10338
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
9735
10339
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
9736
10340
  refund: {
9737
- privateKey: Buffer.from(bigintToBytes322(refundKeypair.privateKey)).toString("hex"),
9738
10341
  publicKey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("hex"),
9739
10342
  blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("hex"),
9740
10343
  derivedFromNk: refundDerivedFromNk
@@ -9742,6 +10345,7 @@ async function swapUtxo(params, options) {
9742
10345
  };
9743
10346
  }
9744
10347
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
10348
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
9745
10349
  const totalInput = sumUtxoAmounts(inputUtxos);
9746
10350
  const change = totalInput - swapAmount;
9747
10351
  if (change < BigInt(0)) {
@@ -9750,16 +10354,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
9750
10354
  let changeUtxo;
9751
10355
  let changeNoteSalt;
9752
10356
  if (change > BigInt(0)) {
9753
- const myKeypair = inputUtxos[0].keypair;
9754
10357
  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
- }
10358
+ const changeNk = await requireWalletNk(options, "swapWithChange");
10359
+ const salt = randomChangeNoteSalt();
10360
+ changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
10361
+ changeNoteSalt = salt;
9763
10362
  }
9764
10363
  return swapUtxo(
9765
10364
  {
@@ -10082,7 +10681,7 @@ var RelayBatchAuthCoordinator = class {
10082
10681
  throw new Error("Every item of a batch must target the same program id.");
10083
10682
  }
10084
10683
  }
10085
- const nowSeconds = Math.floor(Date.now() / 1e3);
10684
+ const nowSeconds = relayNowSeconds();
10086
10685
  const preimages = waiting.map(
10087
10686
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10088
10687
  );
@@ -10520,7 +11119,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
10520
11119
  const cached = depositSecretsCache.get(key);
10521
11120
  if (cached) return cached;
10522
11121
  try {
10523
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
11122
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
10524
11123
  if (depositSecretsCache.size >= 4096) {
10525
11124
  const oldest = depositSecretsCache.keys().next();
10526
11125
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11103,6 +11702,7 @@ async function scanTransactions(opts) {
11103
11702
  } else {
11104
11703
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11105
11704
  const candidateKeys = [
11705
+ opts.ownerUtxoPublicKey,
11106
11706
  derived?.keypair.publicKey,
11107
11707
  opts.ownUtxoPublicKey,
11108
11708
  BigInt(0)
@@ -11156,6 +11756,7 @@ async function scanTransactions(opts) {
11156
11756
  try {
11157
11757
  const recoveredDeposit = await matchDepositNote({
11158
11758
  viewingKeyNk,
11759
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
11159
11760
  noteSalt: compactNote.noteSalt,
11160
11761
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
11161
11762
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -11190,7 +11791,8 @@ async function scanTransactions(opts) {
11190
11791
  mintAddress: address(asset.mint),
11191
11792
  outputIndex: 0,
11192
11793
  // v4 describes output 0, which is where change lands
11193
- outputCommitments: ixCtx.outputCommitments ?? []
11794
+ outputCommitments: ixCtx.outputCommitments ?? [],
11795
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
11194
11796
  });
11195
11797
  if (recoveredChange) {
11196
11798
  recoveredChangeNotes.push({
@@ -11300,6 +11902,17 @@ async function scanTransactions(opts) {
11300
11902
  runningByAsset.set(key, running);
11301
11903
  tx.runningBalance = running;
11302
11904
  }
11905
+ const legacyKeys = /* @__PURE__ */ new Map();
11906
+ for (const note of recoveredDepositNotes) {
11907
+ if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
11908
+ }
11909
+ for (const change of recoveredChangeNotes) {
11910
+ const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
11911
+ if (legacyPrivateKey !== void 0) {
11912
+ change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
11913
+ change.legacyExposed = true;
11914
+ }
11915
+ }
11303
11916
  return {
11304
11917
  transactions: txs,
11305
11918
  summary: {
@@ -11379,6 +11992,1634 @@ function formatComplianceCsv(report) {
11379
11992
  return header + rows;
11380
11993
  }
11381
11994
 
11995
+ // src/relay/note-index-format.ts
11996
+ import { sha256 as sha2565 } from "@noble/hashes/sha2";
11997
+ var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
11998
+ var NOTE_INDEX_FORMAT_VERSION = 1;
11999
+ var NOTE_INDEX_PAGE_SIZE = 1024;
12000
+ var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
12001
+ var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
12002
+ var NOTE_INDEX_HEADER_LEN = 68;
12003
+ var NOTE_INDEX_KIND_TX = 1;
12004
+ var NOTE_INDEX_KIND_DELIVERY = 2;
12005
+ var NOTE_INDEX_KIND_SWAP_REFUND = 3;
12006
+ var NOTE_SOURCE_NONE = 0;
12007
+ var NOTE_SOURCE_CARRIER = 2;
12008
+ var ITEM_HEADER_LEN = 3;
12009
+ var TX_FIXED_LEN = 263;
12010
+ var DELIVERY_BODY_LEN = 256;
12011
+ var SWAP_REFUND_BODY_LEN = 184;
12012
+ var MAX_UNKNOWN_BODY_LEN = 1024;
12013
+ var DELIVERY_ENVELOPE_LEN = 112;
12014
+ var SIGNATURE_LEN = 64;
12015
+ var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
12016
+ [25, 2],
12017
+ [57, 3],
12018
+ [98, 4]
12019
+ ]);
12020
+ var COMPLETE_FLAG = 1;
12021
+ var U64_MAX2 = (1n << 64n) - 1n;
12022
+ var U32_MAX = 4294967295;
12023
+ var MAX_LEAF_INDEX = (1n << 32n) - 1n;
12024
+ var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
12025
+ var NoteIndexFormatError = class extends Error {
12026
+ constructor(message) {
12027
+ super(`Note index format error: ${message}`);
12028
+ this.name = "NoteIndexFormatError";
12029
+ }
12030
+ };
12031
+ function isAllZero2(bytes) {
12032
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12033
+ return true;
12034
+ }
12035
+ function bytesEqual(a, b) {
12036
+ if (a.length !== b.length) return false;
12037
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
12038
+ return true;
12039
+ }
12040
+ function checkLeafPair(commitment, leaf, label) {
12041
+ if (isAllZero2(commitment)) {
12042
+ if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
12043
+ return;
12044
+ }
12045
+ if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
12046
+ }
12047
+ var Reader = class {
12048
+ constructor(bytes, start, end) {
12049
+ this.bytes = bytes;
12050
+ this.end = end;
12051
+ this.offset = start;
12052
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12053
+ }
12054
+ take(len) {
12055
+ if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
12056
+ const at = this.offset;
12057
+ this.offset += len;
12058
+ return at;
12059
+ }
12060
+ u8() {
12061
+ return this.bytes[this.take(1)];
12062
+ }
12063
+ u32() {
12064
+ return this.view.getUint32(this.take(4), true);
12065
+ }
12066
+ u64() {
12067
+ return this.view.getBigUint64(this.take(8), true);
12068
+ }
12069
+ i64() {
12070
+ return this.view.getBigInt64(this.take(8), true);
12071
+ }
12072
+ raw(len) {
12073
+ const at = this.take(len);
12074
+ return this.bytes.slice(at, at + len);
12075
+ }
12076
+ get position() {
12077
+ return this.offset;
12078
+ }
12079
+ };
12080
+ function parseTx(r, bodyLen) {
12081
+ const mint = r.raw(32);
12082
+ const slot = r.u64();
12083
+ const blockPos = r.u32();
12084
+ const ixTag = r.u8();
12085
+ if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
12086
+ const publicAmount = r.i64();
12087
+ const nullifier0 = r.raw(32);
12088
+ const nullifier1 = r.raw(32);
12089
+ const comm0 = r.raw(32);
12090
+ const leaf0 = r.u64();
12091
+ const comm1 = r.raw(32);
12092
+ const leaf1 = r.u64();
12093
+ const noteSource = r.u8();
12094
+ if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
12095
+ const noteLen = r.u8();
12096
+ if (noteSource === NOTE_SOURCE_NONE) {
12097
+ if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
12098
+ } else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
12099
+ throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
12100
+ }
12101
+ if (bodyLen !== TX_FIXED_LEN + noteLen) {
12102
+ throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
12103
+ }
12104
+ const note = r.raw(noteLen);
12105
+ if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
12106
+ throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
12107
+ }
12108
+ const signature = r.raw(SIGNATURE_LEN);
12109
+ checkLeafPair(comm0, leaf0, "TX comm0");
12110
+ checkLeafPair(comm1, leaf1, "TX comm1");
12111
+ return {
12112
+ kind: 1,
12113
+ mint,
12114
+ slot,
12115
+ blockPos,
12116
+ ixTag,
12117
+ publicAmount,
12118
+ nullifier0,
12119
+ nullifier1,
12120
+ comm0,
12121
+ leaf0,
12122
+ comm1,
12123
+ leaf1,
12124
+ noteSource,
12125
+ note,
12126
+ signature
12127
+ };
12128
+ }
12129
+ function parseDelivery(r) {
12130
+ const mint = r.raw(32);
12131
+ const slot = r.u64();
12132
+ const commitment = r.raw(32);
12133
+ const leaf = r.u64();
12134
+ const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
12135
+ const signature = r.raw(SIGNATURE_LEN);
12136
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
12137
+ checkLeafPair(commitment, leaf, "DELIVERY");
12138
+ return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
12139
+ }
12140
+ function parseSwapRefund(r) {
12141
+ const mint = r.raw(32);
12142
+ if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
12143
+ const slot = r.u64();
12144
+ const commitment = r.raw(32);
12145
+ const leaf = r.u64();
12146
+ const amountAfterFee = r.u64();
12147
+ const nullifier0 = r.raw(32);
12148
+ const signature = r.raw(SIGNATURE_LEN);
12149
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
12150
+ checkLeafPair(commitment, leaf, "SWAP_REFUND");
12151
+ return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
12152
+ }
12153
+ function parseNoteIndexPage(bytes, expect, options = {}) {
12154
+ if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
12155
+ if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
12156
+ throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
12157
+ }
12158
+ if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12159
+ for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
12160
+ if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
12161
+ }
12162
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12163
+ const version = bytes[4];
12164
+ if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
12165
+ const flags = bytes[5];
12166
+ if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
12167
+ if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
12168
+ const epoch = view.getBigUint64(8, true);
12169
+ const page = view.getBigUint64(16, true);
12170
+ const firstSeq = view.getBigUint64(24, true);
12171
+ const count = view.getUint32(32, true);
12172
+ const prevChain = bytes.slice(36, 68);
12173
+ const complete = (flags & COMPLETE_FLAG) !== 0;
12174
+ if (expect) {
12175
+ if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
12176
+ if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
12177
+ }
12178
+ if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12179
+ if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
12180
+ if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
12181
+ throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
12182
+ }
12183
+ const items = [];
12184
+ const rawItems = [];
12185
+ const itemPositions = [];
12186
+ let skippedUnknown = 0;
12187
+ let skippedMalformed = 0;
12188
+ let offset = NOTE_INDEX_HEADER_LEN;
12189
+ for (let i = 0; i < count; i++) {
12190
+ if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
12191
+ const kind = bytes[offset];
12192
+ const bodyLen = view.getUint16(offset + 1, true);
12193
+ const bodyStart = offset + ITEM_HEADER_LEN;
12194
+ const bodyEnd = bodyStart + bodyLen;
12195
+ if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12196
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
12197
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12198
+ skippedUnknown++;
12199
+ offset = bodyEnd;
12200
+ continue;
12201
+ }
12202
+ let item;
12203
+ try {
12204
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
12205
+ } catch (error) {
12206
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
12207
+ skippedMalformed++;
12208
+ offset = bodyEnd;
12209
+ continue;
12210
+ }
12211
+ items.push(item);
12212
+ rawItems.push(bytes.slice(offset, bodyEnd));
12213
+ itemPositions.push(i);
12214
+ offset = bodyEnd;
12215
+ }
12216
+ if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12217
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
12218
+ }
12219
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
12220
+ const bodyLen = bodyEnd - bodyStart;
12221
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12222
+ let item;
12223
+ if (kind === NOTE_INDEX_KIND_TX) {
12224
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12225
+ item = parseTx(r, bodyLen);
12226
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
12227
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12228
+ item = parseDelivery(r);
12229
+ } else {
12230
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12231
+ item = parseSwapRefund(r);
12232
+ }
12233
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12234
+ return item;
12235
+ }
12236
+ function parseNoteIndexItem(raw) {
12237
+ if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
12238
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
12239
+ const kind = raw[0];
12240
+ const bodyLen = view.getUint16(1, true);
12241
+ if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
12242
+ const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
12243
+ let item;
12244
+ if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
12245
+ else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
12246
+ else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
12247
+ else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
12248
+ if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
12249
+ return item;
12250
+ }
12251
+ function computeNoteIndexChain(prevChain, pageBytes) {
12252
+ if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
12253
+ if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12254
+ const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
12255
+ const input = new Uint8Array(32 + items.length);
12256
+ input.set(prevChain);
12257
+ input.set(items, 32);
12258
+ return sha2565(input);
12259
+ }
12260
+ var Writer = class {
12261
+ constructor() {
12262
+ this.chunks = [];
12263
+ this.length = 0;
12264
+ }
12265
+ push(bytes) {
12266
+ this.chunks.push(bytes);
12267
+ this.length += bytes.length;
12268
+ }
12269
+ u8(v) {
12270
+ if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
12271
+ this.push(Uint8Array.of(v));
12272
+ }
12273
+ u16(v) {
12274
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
12275
+ const b = new Uint8Array(2);
12276
+ new DataView(b.buffer).setUint16(0, v, true);
12277
+ this.push(b);
12278
+ }
12279
+ u32(v) {
12280
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
12281
+ const b = new Uint8Array(4);
12282
+ new DataView(b.buffer).setUint32(0, v, true);
12283
+ this.push(b);
12284
+ }
12285
+ u64(v) {
12286
+ if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
12287
+ const b = new Uint8Array(8);
12288
+ new DataView(b.buffer).setBigUint64(0, v, true);
12289
+ this.push(b);
12290
+ }
12291
+ i64(v) {
12292
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
12293
+ const b = new Uint8Array(8);
12294
+ new DataView(b.buffer).setBigInt64(0, v, true);
12295
+ this.push(b);
12296
+ }
12297
+ fixed(bytes, len, label) {
12298
+ if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
12299
+ this.push(bytes);
12300
+ }
12301
+ finish() {
12302
+ const out = new Uint8Array(this.length);
12303
+ let off = 0;
12304
+ for (const c of this.chunks) {
12305
+ out.set(c, off);
12306
+ off += c.length;
12307
+ }
12308
+ return out;
12309
+ }
12310
+ };
12311
+ function encodeItemBody(item) {
12312
+ const w = new Writer();
12313
+ switch (item.kind) {
12314
+ case NOTE_INDEX_KIND_TX: {
12315
+ w.fixed(item.mint, 32, "mint");
12316
+ w.u64(item.slot);
12317
+ w.u32(item.blockPos);
12318
+ w.u8(item.ixTag);
12319
+ w.i64(item.publicAmount);
12320
+ w.fixed(item.nullifier0, 32, "nullifier0");
12321
+ w.fixed(item.nullifier1, 32, "nullifier1");
12322
+ w.fixed(item.comm0, 32, "comm0");
12323
+ w.u64(item.leaf0);
12324
+ w.fixed(item.comm1, 32, "comm1");
12325
+ w.u64(item.leaf1);
12326
+ w.u8(item.noteSource);
12327
+ const noteLen = item.note.length;
12328
+ if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
12329
+ throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
12330
+ }
12331
+ w.u8(noteLen);
12332
+ w.push(item.note);
12333
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12334
+ break;
12335
+ }
12336
+ case NOTE_INDEX_KIND_DELIVERY:
12337
+ w.fixed(item.mint, 32, "mint");
12338
+ w.u64(item.slot);
12339
+ w.fixed(item.commitment, 32, "commitment");
12340
+ w.u64(item.leaf);
12341
+ w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
12342
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12343
+ break;
12344
+ case NOTE_INDEX_KIND_SWAP_REFUND:
12345
+ w.fixed(item.mint, 32, "mint");
12346
+ w.u64(item.slot);
12347
+ w.fixed(item.commitment, 32, "commitment");
12348
+ w.u64(item.leaf);
12349
+ w.u64(item.amountAfterFee);
12350
+ w.fixed(item.nullifier0, 32, "nullifier0");
12351
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12352
+ break;
12353
+ default:
12354
+ throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
12355
+ }
12356
+ return w.finish();
12357
+ }
12358
+ function encodeNoteIndexItem(item) {
12359
+ const body = encodeItemBody(item);
12360
+ const w = new Writer();
12361
+ w.u8(item.kind);
12362
+ w.u16(body.length);
12363
+ w.push(body);
12364
+ return w.finish();
12365
+ }
12366
+ function encodeNoteIndexPage(params) {
12367
+ const items = params.items ?? [];
12368
+ if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12369
+ const w = new Writer();
12370
+ w.push(NOTE_INDEX_MAGIC);
12371
+ w.u8(NOTE_INDEX_FORMAT_VERSION);
12372
+ w.u8(params.complete ? COMPLETE_FLAG : 0);
12373
+ w.u16(0);
12374
+ w.u64(BigInt(params.epoch));
12375
+ w.u64(BigInt(params.page));
12376
+ w.u64(BigInt(params.firstSeq));
12377
+ w.u32(items.length);
12378
+ w.fixed(params.prevChain, 32, "prevChain");
12379
+ for (const item of items) w.push(encodeNoteIndexItem(item));
12380
+ return w.finish();
12381
+ }
12382
+
12383
+ // src/relay/note-index-client.ts
12384
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
12385
+ var DEFAULT_MAX_RETRIES2 = 3;
12386
+ var RETRY_BASE_DELAY_MS = 500;
12387
+ var U64_MAX3 = (1n << 64n) - 1n;
12388
+ function joinPath(relayUrl, path) {
12389
+ const url = new URL(relayUrl);
12390
+ url.pathname = url.pathname.replace(/\/$/, "") + path;
12391
+ return url;
12392
+ }
12393
+ function abortError() {
12394
+ const error = new Error("Note index request aborted");
12395
+ error.name = "AbortError";
12396
+ return error;
12397
+ }
12398
+ function sleep4(ms, signal) {
12399
+ return new Promise((resolve, reject) => {
12400
+ if (signal?.aborted) return reject(abortError());
12401
+ const timer = setTimeout(() => {
12402
+ signal?.removeEventListener("abort", onAbort);
12403
+ resolve();
12404
+ }, ms);
12405
+ const onAbort = () => {
12406
+ clearTimeout(timer);
12407
+ reject(abortError());
12408
+ };
12409
+ signal?.addEventListener("abort", onAbort, { once: true });
12410
+ });
12411
+ }
12412
+ var RetryableStatusError = class extends Error {
12413
+ };
12414
+ var HttpStatusError = class extends Error {
12415
+ constructor(status, message) {
12416
+ super(message);
12417
+ this.status = status;
12418
+ this.name = "HttpStatusError";
12419
+ }
12420
+ };
12421
+ async function requestWithRetry(url, options, read) {
12422
+ assertAllowedRelayOrigin(url);
12423
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
12424
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
12425
+ let lastError;
12426
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
12427
+ if (options.signal?.aborted) throw abortError();
12428
+ const controller = new AbortController();
12429
+ const onAbort = () => controller.abort();
12430
+ options.signal?.addEventListener("abort", onAbort, { once: true });
12431
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
12432
+ try {
12433
+ const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
12434
+ if (response.status === 429 || response.status >= 500) {
12435
+ throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
12436
+ }
12437
+ return await read(response, controller.signal);
12438
+ } catch (error) {
12439
+ if (options.signal?.aborted) throw abortError();
12440
+ const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
12441
+ if (!retryable || attempt >= maxRetries) throw error;
12442
+ lastError = error;
12443
+ await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
12444
+ } finally {
12445
+ clearTimeout(timer);
12446
+ options.signal?.removeEventListener("abort", onAbort);
12447
+ }
12448
+ }
12449
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
12450
+ }
12451
+ async function readBoundedBody(response, maxBytes) {
12452
+ const declaredHeader = response.headers?.get?.("content-length") ?? null;
12453
+ const declared = declaredHeader === null ? NaN : Number(declaredHeader);
12454
+ if (Number.isFinite(declared) && declared > maxBytes) {
12455
+ throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
12456
+ }
12457
+ const reader = response.body?.getReader?.();
12458
+ if (!reader) {
12459
+ const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
12460
+ if (!Number.isSafeInteger(declared) || declared < 0) {
12461
+ throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
12462
+ }
12463
+ if (encoding !== "" && encoding !== "identity") {
12464
+ throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
12465
+ }
12466
+ const buffer = new Uint8Array(await response.arrayBuffer());
12467
+ if (buffer.length > maxBytes || buffer.length !== declared) {
12468
+ throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
12469
+ }
12470
+ return buffer;
12471
+ }
12472
+ const chunks = [];
12473
+ let total = 0;
12474
+ for (; ; ) {
12475
+ const { done, value } = await reader.read();
12476
+ if (done) break;
12477
+ total += value.length;
12478
+ if (total > maxBytes) {
12479
+ await reader.cancel().catch(() => void 0);
12480
+ throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
12481
+ }
12482
+ chunks.push(value);
12483
+ }
12484
+ const out = new Uint8Array(total);
12485
+ let off = 0;
12486
+ for (const c of chunks) {
12487
+ out.set(c, off);
12488
+ off += c.length;
12489
+ }
12490
+ return out;
12491
+ }
12492
+ function isNonNegativeSafeInteger(value) {
12493
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12494
+ }
12495
+ async function fetchNoteIndexHead(relayUrl, options = {}) {
12496
+ const url = joinPath(relayUrl, "/note-index/v1/head").toString();
12497
+ const raw = await requestWithRetry(url, options, async (response) => {
12498
+ if (!response.ok) {
12499
+ throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
12500
+ }
12501
+ const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
12502
+ try {
12503
+ return JSON.parse(text);
12504
+ } catch {
12505
+ throw new NoteIndexFormatError("head is not JSON");
12506
+ }
12507
+ });
12508
+ if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
12509
+ if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
12510
+ throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
12511
+ }
12512
+ if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
12513
+ throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
12514
+ }
12515
+ if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
12516
+ throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
12517
+ }
12518
+ if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
12519
+ throw new NoteIndexFormatError(
12520
+ `complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
12521
+ );
12522
+ }
12523
+ if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
12524
+ throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
12525
+ }
12526
+ if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
12527
+ throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
12528
+ }
12529
+ return {
12530
+ format: 1,
12531
+ epoch: BigInt(raw.epoch),
12532
+ pageSize: NOTE_INDEX_PAGE_SIZE,
12533
+ watermark: raw.watermark,
12534
+ completePages: raw.complete_pages,
12535
+ chainTip: raw.chain_tip.toLowerCase()
12536
+ };
12537
+ }
12538
+ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
12539
+ if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
12540
+ if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
12541
+ const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
12542
+ return requestWithRetry(url, options, async (response) => {
12543
+ if (!response.ok) {
12544
+ throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
12545
+ }
12546
+ return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
12547
+ });
12548
+ }
12549
+
12550
+ // src/scanning/note-index.ts
12551
+ import _bs584 from "bs58";
12552
+ import { sha256 as sha2566 } from "@noble/hashes/sha2";
12553
+ var bs584 = _bs584.default || _bs584;
12554
+ var CURSOR_VERSION = 2;
12555
+ var DEFAULT_CONCURRENCY = 6;
12556
+ var MAX_CONCURRENCY = 32;
12557
+ var ITEM_BATCH = 64;
12558
+ var CURSOR_PAGE_ALIGN = 8;
12559
+ var MAX_PERSISTED_PENDING_LEAVES = 4096;
12560
+ var MAX_CARRIED_PENDING = 256;
12561
+ var MAX_REJECTED_IDS = 1024;
12562
+ var LEAF_WINDOW = 512;
12563
+ var MAX_OVERRIDES = 256;
12564
+ var MAX_CURSOR_OWN_ITEMS = 65536;
12565
+ var MAX_LEGACY_VIEWING_KEYS = 8;
12566
+ var MAX_CURSOR_KEYS = 131072;
12567
+ var MAX_CURSOR_POOLS = 256;
12568
+ var MAX_CURSOR_PAGE = 2 ** 32;
12569
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
12570
+ var ZERO_CHAIN = "00".repeat(32);
12571
+ var U64_MAX4 = (1n << 64n) - 1n;
12572
+ var NoteIndexHeadBehindError = class extends Error {
12573
+ constructor(cursorWatermark, headWatermark) {
12574
+ super(
12575
+ `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`
12576
+ );
12577
+ this.cursorWatermark = cursorWatermark;
12578
+ this.headWatermark = headWatermark;
12579
+ this.retryable = true;
12580
+ this.name = "NoteIndexHeadBehindError";
12581
+ }
12582
+ };
12583
+ var FullPassSignal = class {
12584
+ constructor(reason) {
12585
+ this.reason = reason;
12586
+ }
12587
+ };
12588
+ function abortError2() {
12589
+ const error = new Error("recoverNotesFromIndex aborted");
12590
+ error.name = "AbortError";
12591
+ return error;
12592
+ }
12593
+ function bytesToBigint2(bytes) {
12594
+ let v = 0n;
12595
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
12596
+ return v;
12597
+ }
12598
+ function toHex2(bytes) {
12599
+ let s = "";
12600
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
12601
+ return s;
12602
+ }
12603
+ function fromHex(hex) {
12604
+ return Uint8Array.from(Buffer.from(hex, "hex"));
12605
+ }
12606
+ function hex32(v) {
12607
+ return v.toString(16).padStart(64, "0");
12608
+ }
12609
+ function isAllZero3(bytes) {
12610
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12611
+ return true;
12612
+ }
12613
+ function floorAlign(page) {
12614
+ return page - page % CURSOR_PAGE_ALIGN;
12615
+ }
12616
+ function verifiedKey(mint, leaf, commitment) {
12617
+ return `${mint}:${leaf}:${hex32(commitment)}`;
12618
+ }
12619
+ function itemIdentity(raw) {
12620
+ return toHex2(sha2566(raw).subarray(0, 16));
12621
+ }
12622
+ var LeafBuffer = class {
12623
+ constructor() {
12624
+ this.bytes = new Uint8Array(32 * 1024);
12625
+ this.view = new DataView(this.bytes.buffer);
12626
+ this.count = 0;
12627
+ }
12628
+ get length() {
12629
+ return this.count;
12630
+ }
12631
+ push(values) {
12632
+ const need = (this.count + values.length) * 32;
12633
+ if (need > this.bytes.length) {
12634
+ let size = this.bytes.length;
12635
+ while (size < need) size *= 2;
12636
+ const next = new Uint8Array(size);
12637
+ next.set(this.bytes.subarray(0, this.count * 32));
12638
+ this.bytes = next;
12639
+ this.view = new DataView(next.buffer);
12640
+ }
12641
+ for (const v of values) {
12642
+ const o = this.count * 32;
12643
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
12644
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
12645
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
12646
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
12647
+ this.count++;
12648
+ }
12649
+ }
12650
+ get(i) {
12651
+ if (i < 0 || i >= this.count) return void 0;
12652
+ const o = i * 32;
12653
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
12654
+ }
12655
+ };
12656
+ async function trialItem(item, trials) {
12657
+ for (const trial of trials) {
12658
+ if (trial.legacy && item.kind === 2) continue;
12659
+ const opened = await trialItemWith(item, trial);
12660
+ if (opened) return { ...opened, trial };
12661
+ }
12662
+ return null;
12663
+ }
12664
+ async function trialItemIsolated(item, trials, stats) {
12665
+ try {
12666
+ return await trialItem(item, trials);
12667
+ } catch {
12668
+ stats.skipped++;
12669
+ return null;
12670
+ }
12671
+ }
12672
+ async function trialItemWith(item, trial) {
12673
+ if (item.kind === 1) {
12674
+ if (item.note.length === 0) return null;
12675
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
12676
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
12677
+ return note ? { note } : null;
12678
+ }
12679
+ if (item.kind === 2) {
12680
+ const delivery = await trial.open(item.envelope);
12681
+ return delivery ? { delivery } : null;
12682
+ }
12683
+ if (item.amountAfterFee === 0n) return null;
12684
+ const refund = await matchSwapRefundLeaf({
12685
+ viewingKeyNk: trial.nk,
12686
+ inputNullifier: item.nullifier0,
12687
+ amountAfterFee: item.amountAfterFee,
12688
+ commitment: item.commitment,
12689
+ ownerUtxoKeypair: trial.owner
12690
+ });
12691
+ return refund ? { refund } : null;
12692
+ }
12693
+ function txOutputs(item) {
12694
+ const out = [toHex2(item.comm0)];
12695
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
12696
+ return out;
12697
+ }
12698
+ function leafOfTxOutput(item, commitment) {
12699
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint2(item.comm0)) return Number(item.leaf0);
12700
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
12701
+ return null;
12702
+ }
12703
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
12704
+ try {
12705
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
12706
+ } catch {
12707
+ return null;
12708
+ }
12709
+ }
12710
+ async function matchOwnItems(own, owner, onReject, onSkip) {
12711
+ const candidates = [];
12712
+ const claimed = /* @__PURE__ */ new Set();
12713
+ const byNullifier = /* @__PURE__ */ new Map();
12714
+ const legacyKeys = /* @__PURE__ */ new Map();
12715
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
12716
+ const spendsOf = /* @__PURE__ */ new Map();
12717
+ const byOutKey = /* @__PURE__ */ new Map();
12718
+ const index = (map, key, o) => {
12719
+ const list = map.get(key);
12720
+ if (list) list.push(o);
12721
+ else map.set(key, [o]);
12722
+ };
12723
+ for (const o of ownTxs) {
12724
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
12725
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
12726
+ }
12727
+ const queue = [];
12728
+ const queued = /* @__PURE__ */ new Set();
12729
+ const enqueue = (o) => {
12730
+ if (queued.has(o)) return;
12731
+ queued.add(o);
12732
+ queue.push(o);
12733
+ };
12734
+ const add = async (o, c) => {
12735
+ const nullifier = hex32(
12736
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
12737
+ );
12738
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
12739
+ candidates.push(full);
12740
+ if (!byNullifier.has(nullifier)) {
12741
+ byNullifier.set(nullifier, full);
12742
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
12743
+ }
12744
+ if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
12745
+ legacyKeys.set(c.keypair.publicKey, c.keypair);
12746
+ for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
12747
+ }
12748
+ };
12749
+ const tryDeposit = async (o, item, amount) => {
12750
+ const note = o.note;
12751
+ const mint = addressFromBytes(item.mint);
12752
+ const deposit = await matchDepositNote({
12753
+ viewingKeyNk: o.trial.nk,
12754
+ noteSalt: note.noteSalt,
12755
+ amount,
12756
+ mintAddress: mint,
12757
+ outputCommitments: txOutputs(item),
12758
+ ownerUtxoKeypair: owner
12759
+ });
12760
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
12761
+ if (!deposit || leaf === null) return false;
12762
+ await add(o, {
12763
+ kind: "deposit",
12764
+ atRisk: deposit.legacyExposed,
12765
+ amount: deposit.amount,
12766
+ blinding: deposit.blinding,
12767
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
12768
+ mint,
12769
+ commitment: deposit.commitment,
12770
+ leaf
12771
+ });
12772
+ return true;
12773
+ };
12774
+ const tryChange0 = async (o, item, keypair, atRisk) => {
12775
+ const note = o.note;
12776
+ const mint = addressFromBytes(item.mint);
12777
+ const change = await matchChangeNote({
12778
+ viewingKeyNk: o.trial.nk,
12779
+ noteSalt: note.noteSalt,
12780
+ amount: note.outAmount0,
12781
+ keypair,
12782
+ mintAddress: mint,
12783
+ outputIndex: 0,
12784
+ outputCommitments: [toHex2(item.comm0)],
12785
+ ownerUtxoPublicKey: owner.publicKey
12786
+ });
12787
+ if (!change) return false;
12788
+ await add(o, {
12789
+ kind: "change",
12790
+ atRisk,
12791
+ amount: change.amount,
12792
+ blinding: change.blinding,
12793
+ keypair,
12794
+ mint,
12795
+ commitment: change.commitment,
12796
+ leaf: Number(item.leaf0)
12797
+ });
12798
+ return true;
12799
+ };
12800
+ const direct = async (o) => {
12801
+ const item = o.item;
12802
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
12803
+ const note = o.note;
12804
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12805
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
12806
+ }
12807
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
12808
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
12809
+ }
12810
+ } else if (item.kind === 2 && o.delivery) {
12811
+ const mint = addressFromBytes(item.mint);
12812
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
12813
+ onReject(o);
12814
+ return;
12815
+ }
12816
+ const commitment = await computeCommitment({
12817
+ amount: o.delivery.amount,
12818
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
12819
+ blinding: o.delivery.blinding,
12820
+ mintAddress: mint
12821
+ });
12822
+ if (commitment !== bytesToBigint2(item.commitment)) {
12823
+ onReject(o);
12824
+ return;
12825
+ }
12826
+ await add(o, {
12827
+ kind: "received",
12828
+ atRisk: false,
12829
+ amount: o.delivery.amount,
12830
+ blinding: o.delivery.blinding,
12831
+ keypair: owner,
12832
+ mint,
12833
+ commitment,
12834
+ leaf: Number(item.leaf)
12835
+ });
12836
+ } else if (item.kind === 3 && o.refund) {
12837
+ await add(o, {
12838
+ kind: "swap_refund",
12839
+ atRisk: o.refund.legacyExposed,
12840
+ amount: o.refund.amount,
12841
+ blinding: o.refund.blinding,
12842
+ // per-swap refunds carry their derived keypair; owner-shape ones carry the owner
12843
+ keypair: o.refund.keypair,
12844
+ mint: NATIVE_SOL_MINT,
12845
+ commitment: o.refund.commitment,
12846
+ leaf: Number(item.leaf)
12847
+ });
12848
+ }
12849
+ };
12850
+ for (const o of own) {
12851
+ try {
12852
+ await direct(o);
12853
+ } catch {
12854
+ onSkip(o);
12855
+ }
12856
+ }
12857
+ const processTx = async (o) => {
12858
+ const item = o.item;
12859
+ const note = o.note;
12860
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
12861
+ const legacy = legacyKeys.get(note.outPubkey0);
12862
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
12863
+ }
12864
+ const mint = addressFromBytes(item.mint);
12865
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
12866
+ if (inputs.length === 0) return;
12867
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
12868
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
12869
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
12870
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
12871
+ if (out1 > 0n && blinding === null) onSkip(o);
12872
+ else if (blinding !== null) {
12873
+ const owners = [{ keypair: owner, atRisk: false }];
12874
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
12875
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
12876
+ for (const { keypair, atRisk } of owners) {
12877
+ const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
12878
+ if (commitment !== bytesToBigint2(item.comm1)) continue;
12879
+ claimed.add(`${o.seq}:1`);
12880
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
12881
+ break;
12882
+ }
12883
+ }
12884
+ }
12885
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12886
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
12887
+ }
12888
+ };
12889
+ for (const o of ownTxs) enqueue(o);
12890
+ for (let i = 0; i < queue.length; i++) {
12891
+ const o = queue[i];
12892
+ queued.delete(o);
12893
+ try {
12894
+ await processTx(o);
12895
+ } catch {
12896
+ onSkip(o);
12897
+ }
12898
+ }
12899
+ return candidates;
12900
+ }
12901
+ async function replayStream(start, pages, overrides, chain, targetPage) {
12902
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
12903
+ const startN = frontier.nextIndex;
12904
+ const pending = new Map(start.pending);
12905
+ const flushed = new LeafBuffer();
12906
+ const corrections = /* @__PURE__ */ new Map();
12907
+ let conflicts = 0;
12908
+ let verifiedPrefix = 0;
12909
+ let mismatch = false;
12910
+ const checks = [];
12911
+ const setBits = [];
12912
+ if (chain && chain.nextIndex > 0) {
12913
+ const last = chain.nextIndex - 1;
12914
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
12915
+ for (const l of setBits) {
12916
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
12917
+ if (at >= startN) checks.push({ at, level: l });
12918
+ }
12919
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
12920
+ checks.sort((a, b) => a.at - b.at);
12921
+ }
12922
+ let nextCheck = 0;
12923
+ const runChecks = () => {
12924
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
12925
+ const { at, level } = checks[nextCheck++];
12926
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
12927
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
12928
+ else mismatch = true;
12929
+ }
12930
+ };
12931
+ const append = (values) => {
12932
+ let i = 0;
12933
+ while (i < values.length) {
12934
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
12935
+ const take = Math.min(values.length - i, room);
12936
+ if (take > 0) {
12937
+ const part = values.slice(i, i + take);
12938
+ frontier.append(part);
12939
+ flushed.push(part);
12940
+ i += take;
12941
+ }
12942
+ runChecks();
12943
+ }
12944
+ };
12945
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
12946
+ const flush = () => {
12947
+ const batch = [];
12948
+ let next = frontier.nextIndex;
12949
+ while (pending.has(next)) {
12950
+ batch.push(pending.get(next));
12951
+ pending.delete(next);
12952
+ next++;
12953
+ }
12954
+ if (batch.length > 0) append(batch);
12955
+ };
12956
+ let snapshot = null;
12957
+ let taken = false;
12958
+ const takeSnapshot = () => {
12959
+ taken = true;
12960
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
12961
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
12962
+ };
12963
+ runChecks();
12964
+ flush();
12965
+ for (const { page, entries } of pages) {
12966
+ if (!taken && page >= targetPage) takeSnapshot();
12967
+ for (const e of entries) {
12968
+ if (e.leaf < startN) continue;
12969
+ const prior = valueAt(e.leaf);
12970
+ if (prior !== void 0) {
12971
+ if (prior !== e.commitment) {
12972
+ conflicts++;
12973
+ corrections.set(e.leaf, e.commitment);
12974
+ }
12975
+ continue;
12976
+ }
12977
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
12978
+ }
12979
+ flush();
12980
+ }
12981
+ if (!taken) takeSnapshot();
12982
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
12983
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
12984
+ }
12985
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
12986
+ }
12987
+ var HEX64 = /^[0-9a-f]{64}$/;
12988
+ var HEX32 = /^[0-9a-f]{32}$/;
12989
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
12990
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
12991
+ function isRecord(v) {
12992
+ return typeof v === "object" && v !== null && !Array.isArray(v);
12993
+ }
12994
+ function isIntIn(v, min, max) {
12995
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
12996
+ }
12997
+ function isBoundedArray(v, max) {
12998
+ return Array.isArray(v) && v.length <= max;
12999
+ }
13000
+ function emptyStartTree() {
13001
+ return {
13002
+ frontier: null,
13003
+ nextIndex: 0,
13004
+ pending: /* @__PURE__ */ new Map(),
13005
+ window: [],
13006
+ windowStart: 0,
13007
+ verified: 0,
13008
+ overrides: /* @__PURE__ */ new Map(),
13009
+ mismatch: false,
13010
+ hiBefore: -1
13011
+ };
13012
+ }
13013
+ async function parseCursor(cursor, poolMints) {
13014
+ try {
13015
+ if (!isRecord(cursor)) return "not an object";
13016
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
13017
+ const c = cursor;
13018
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
13019
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
13020
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
13021
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
13022
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
13023
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
13024
+ const trees = /* @__PURE__ */ new Map();
13025
+ for (const mint of poolMints) {
13026
+ const t = c.trees[mint];
13027
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
13028
+ const tree = t;
13029
+ if (!isRecord(tree.frontier)) return "bad frontier";
13030
+ let frontier;
13031
+ try {
13032
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
13033
+ } catch {
13034
+ return "bad frontier";
13035
+ }
13036
+ const nextIndex = frontier.nextIndex;
13037
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
13038
+ const pending = /* @__PURE__ */ new Map();
13039
+ let hiBefore = nextIndex - 1;
13040
+ for (const entry of tree.pending) {
13041
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
13042
+ const [leaf, value] = entry;
13043
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
13044
+ return "bad pending leaves";
13045
+ }
13046
+ pending.set(leaf, BigInt("0x" + value));
13047
+ hiBefore = Math.max(hiBefore, leaf);
13048
+ }
13049
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
13050
+ const windowLen = tree.window.length / 64;
13051
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
13052
+ const window2 = [];
13053
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
13054
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
13055
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
13056
+ const overrides = /* @__PURE__ */ new Map();
13057
+ for (const entry of tree.overrides) {
13058
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
13059
+ const [leaf, value] = entry;
13060
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
13061
+ overrides.set(leaf, BigInt("0x" + value));
13062
+ }
13063
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
13064
+ trees.set(mint, {
13065
+ frontier: frontier.toState(),
13066
+ nextIndex,
13067
+ pending,
13068
+ window: window2,
13069
+ windowStart: nextIndex - windowLen,
13070
+ verified: tree.verified,
13071
+ overrides,
13072
+ mismatch: tree.mismatch,
13073
+ hiBefore
13074
+ });
13075
+ }
13076
+ const own = c.own;
13077
+ if (!isRecord(own)) return "bad own state";
13078
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
13079
+ const items = [];
13080
+ const seqs = /* @__PURE__ */ new Set();
13081
+ for (const entry of own.items) {
13082
+ if (!isRecord(entry)) return "bad own items";
13083
+ const { seq, item } = entry;
13084
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
13085
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
13086
+ seqs.add(seq);
13087
+ const raw = fromHex(item);
13088
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
13089
+ }
13090
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
13091
+ return "bad verified notes";
13092
+ }
13093
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
13094
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
13095
+ const pendingLeaves = /* @__PURE__ */ new Map();
13096
+ for (const entry of own.pendingLeaves) {
13097
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
13098
+ const [mint, leaf, value] = entry;
13099
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
13100
+ return "bad pending notes";
13101
+ }
13102
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
13103
+ }
13104
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
13105
+ return "bad rejected set";
13106
+ }
13107
+ return {
13108
+ raw: c,
13109
+ trees,
13110
+ items,
13111
+ verified: new Set(own.verified),
13112
+ spent: new Set(own.spent),
13113
+ pendingLeaves,
13114
+ rejected: own.rejected
13115
+ };
13116
+ } catch {
13117
+ return "unreadable state";
13118
+ }
13119
+ }
13120
+ async function recoverNotesFromIndex(params) {
13121
+ const startedAt = Date.now();
13122
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
13123
+ assertAllowedRelayOrigin(relayUrl);
13124
+ assertAllowedRpcConnection(connection);
13125
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
13126
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
13127
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
13128
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
13129
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
13130
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
13131
+ }
13132
+ if (params.signal?.aborted) throw abortError2();
13133
+ const stats = {
13134
+ pages: 0,
13135
+ items: 0,
13136
+ bytes: 0,
13137
+ rpcCalls: 0,
13138
+ ms: 0,
13139
+ dropped: 0,
13140
+ decrypted: 0,
13141
+ candidates: 0,
13142
+ spent: 0,
13143
+ conflicts: 0,
13144
+ pendingDropped: 0,
13145
+ skipped: 0
13146
+ };
13147
+ const rpc = new Proxy(connection, {
13148
+ get(target, prop, receiver) {
13149
+ const value = Reflect.get(target, prop, receiver);
13150
+ if (typeof value !== "function") return value;
13151
+ return (...args) => {
13152
+ const pending = value.apply(target, args);
13153
+ if (pending && typeof pending.send === "function") {
13154
+ const send = pending.send.bind(pending);
13155
+ return {
13156
+ ...pending,
13157
+ send: (...sendArgs) => {
13158
+ stats.rpcCalls++;
13159
+ return send(...sendArgs);
13160
+ }
13161
+ };
13162
+ }
13163
+ return pending;
13164
+ };
13165
+ }
13166
+ });
13167
+ const makeTrial = async (nk, legacy) => ({
13168
+ nk,
13169
+ legacy,
13170
+ owner,
13171
+ decrypt: await createCompactChainNoteDecryptor(nk),
13172
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
13173
+ });
13174
+ const trials = [await makeTrial(viewingKeyNk, false)];
13175
+ const legacyNks = params.legacyViewingKeyNks ?? [];
13176
+ if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
13177
+ if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
13178
+ const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
13179
+ for (const nk of legacyNks) {
13180
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
13181
+ const key = toHex2(nk);
13182
+ if (seenNks.has(key)) continue;
13183
+ seenNks.add(key);
13184
+ trials.push(await makeTrial(Uint8Array.from(nk), true));
13185
+ }
13186
+ const poolMints = Array.from(new Set(params.poolMints));
13187
+ const warnings = [];
13188
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
13189
+ let cursor;
13190
+ if (params.cursor !== void 0) {
13191
+ const checked = await parseCursor(params.cursor, poolMints);
13192
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
13193
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
13194
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
13195
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
13196
+ } else cursor = checked;
13197
+ }
13198
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
13199
+ let treeRead;
13200
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
13201
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
13202
+ return poolMints.map((_, i) => {
13203
+ const account = accounts[i];
13204
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
13205
+ return account && parsed ? { ...parsed, data: account.data } : null;
13206
+ });
13207
+ })());
13208
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
13209
+ let outcome = await runOnce(ctx, cursor);
13210
+ if (outcome instanceof FullPassSignal) {
13211
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
13212
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
13213
+ outcome = await runOnce(ctx, void 0);
13214
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13215
+ }
13216
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
13217
+ stats.ms = Date.now() - startedAt;
13218
+ return { ...outcome, stats, warnings };
13219
+ }
13220
+ async function runOnce(ctx, cursor) {
13221
+ const { params, head, trials, owner, stats, poolMints } = ctx;
13222
+ const { relayUrl, onProgress } = params;
13223
+ const poolSet = new Set(poolMints);
13224
+ const startPage = cursor?.raw.page ?? 0;
13225
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
13226
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
13227
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
13228
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
13229
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
13230
+ const rejectedIds = new Set(cursor?.rejected ?? []);
13231
+ const controller = new AbortController();
13232
+ const onCallerAbort = () => controller.abort();
13233
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
13234
+ const signal = controller.signal;
13235
+ try {
13236
+ const pageData = /* @__PURE__ */ new Map();
13237
+ const ownItems = [];
13238
+ const nullifiers = /* @__PURE__ */ new Set();
13239
+ let fullPassReason = null;
13240
+ const lateReference = (mint, leaf, value, seq) => {
13241
+ if (!cursor || seq < fullPassSeq) return null;
13242
+ const t = startTrees.get(mint);
13243
+ if (leaf < t.nextIndex) {
13244
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
13245
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
13246
+ return null;
13247
+ }
13248
+ const held = t.pending.get(leaf);
13249
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
13250
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
13251
+ return null;
13252
+ };
13253
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
13254
+ const waiting = /* @__PURE__ */ new Map();
13255
+ let chainNext = startPage;
13256
+ let chainError = null;
13257
+ let wakers = [];
13258
+ const wakeAll = () => {
13259
+ const w = wakers;
13260
+ wakers = [];
13261
+ for (const f of w) f();
13262
+ };
13263
+ signal.addEventListener("abort", wakeAll);
13264
+ const advanceChain = () => {
13265
+ while (!chainError && waiting.has(chainNext)) {
13266
+ const w = waiting.get(chainNext);
13267
+ waiting.delete(chainNext);
13268
+ const expected = chainAt.get(chainNext);
13269
+ if (w.prevChain !== expected) {
13270
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
13271
+ controller.abort();
13272
+ return;
13273
+ }
13274
+ if (!w.complete) break;
13275
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
13276
+ chainNext++;
13277
+ }
13278
+ wakeAll();
13279
+ };
13280
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
13281
+ const lookahead = 2 * workerCount + 2;
13282
+ let nextToFetch = startPage;
13283
+ let pagesDone = 0;
13284
+ const worker = async () => {
13285
+ for (; ; ) {
13286
+ if (signal.aborted) throw abortError2();
13287
+ const pageNo = nextToFetch++;
13288
+ if (pageNo >= pagesTotal) return;
13289
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
13290
+ if (signal.aborted) throw abortError2();
13291
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13292
+ stats.bytes += bytes.length;
13293
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
13294
+ if (pageNo < head.completePages && !page2.complete) {
13295
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13296
+ }
13297
+ stats.pages++;
13298
+ stats.skipped += page2.skippedMalformed;
13299
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
13300
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13301
+ advanceChain();
13302
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
13303
+ const late = (reason) => {
13304
+ if (reason && !fullPassReason) {
13305
+ fullPassReason = reason;
13306
+ controller.abort();
13307
+ }
13308
+ };
13309
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
13310
+ if (isAllZero3(commitment)) return;
13311
+ const mint = addressFromBytes(mintBytes);
13312
+ if (!poolSet.has(mint)) return;
13313
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint2(commitment) };
13314
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
13315
+ const list = data.leaves.get(mint);
13316
+ if (list) list.push(entry);
13317
+ else data.leaves.set(mint, [entry]);
13318
+ };
13319
+ page2.items.forEach((item, i) => {
13320
+ const seq = seqOf(i);
13321
+ if (item.kind === 1) {
13322
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
13323
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
13324
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
13325
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
13326
+ } else if (item.kind === 3) {
13327
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
13328
+ } else {
13329
+ const mint = addressFromBytes(item.mint);
13330
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
13331
+ }
13332
+ });
13333
+ if (signal.aborted) throw abortError2();
13334
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
13335
+ if (signal.aborted) throw abortError2();
13336
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
13337
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
13338
+ opened.forEach((o, k) => {
13339
+ if (!o) return;
13340
+ stats.decrypted++;
13341
+ const raw = page2.rawItems[i + k];
13342
+ const id = itemIdentity(raw);
13343
+ if (rejectedIds.has(id)) {
13344
+ stats.dropped++;
13345
+ return;
13346
+ }
13347
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
13348
+ });
13349
+ stats.items += batch.length;
13350
+ }
13351
+ pageData.set(pageNo, data);
13352
+ pagesDone++;
13353
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
13354
+ }
13355
+ };
13356
+ const workers = Array.from(
13357
+ { length: workerCount },
13358
+ () => worker().catch((error) => {
13359
+ controller.abort();
13360
+ throw error;
13361
+ })
13362
+ );
13363
+ const settled = await Promise.allSettled(workers);
13364
+ signal.removeEventListener("abort", wakeAll);
13365
+ if (params.signal?.aborted) throw abortError2();
13366
+ const lateReason = fullPassReason;
13367
+ if (lateReason) return new FullPassSignal(lateReason);
13368
+ const chainFailure = chainError;
13369
+ if (chainFailure) {
13370
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
13371
+ throw chainFailure;
13372
+ }
13373
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
13374
+ if (failure) throw failure.reason;
13375
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
13376
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
13377
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
13378
+ }
13379
+ for (const entry of cursor?.items ?? []) {
13380
+ const o = await trialItemIsolated(entry.item, trials, stats);
13381
+ if (!o) continue;
13382
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
13383
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
13384
+ if (entry.item.kind === 1) {
13385
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
13386
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
13387
+ }
13388
+ }
13389
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
13390
+ ownItems.sort((a, b) => a.seq - b.seq);
13391
+ const rejectedNow = /* @__PURE__ */ new Set();
13392
+ const skippedNow = /* @__PURE__ */ new Set();
13393
+ const allCandidates = await matchOwnItems(
13394
+ ownItems,
13395
+ owner,
13396
+ (o) => {
13397
+ stats.dropped++;
13398
+ rejectedNow.add(o.id);
13399
+ },
13400
+ (o) => {
13401
+ if (skippedNow.has(o)) return;
13402
+ skippedNow.add(o);
13403
+ stats.skipped++;
13404
+ }
13405
+ );
13406
+ stats.candidates = allCandidates.length;
13407
+ const cutoff = params.legacyCutoffLeaf ?? {};
13408
+ const candidates = allCandidates.filter((c) => {
13409
+ const limit = cutoff[c.mint];
13410
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
13411
+ stats.dropped++;
13412
+ return false;
13413
+ }
13414
+ return true;
13415
+ });
13416
+ const chainTrees = await ctx.readTrees();
13417
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
13418
+ const replays = /* @__PURE__ */ new Map();
13419
+ for (let i = 0; i < poolMints.length; i++) {
13420
+ const mint = poolMints[i];
13421
+ const start = startTrees.get(mint);
13422
+ const chainTree = chainTrees[i] ?? null;
13423
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
13424
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
13425
+ let overrides = start.overrides;
13426
+ stats.conflicts += r.conflicts;
13427
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
13428
+ const merged = new Map([...start.overrides, ...r.corrections]);
13429
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
13430
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
13431
+ r = alternative;
13432
+ overrides = merged;
13433
+ }
13434
+ }
13435
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
13436
+ replays.set(mint, { r, overrides });
13437
+ }
13438
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
13439
+ const streamValue = (mint, leaf) => {
13440
+ const v = replays.get(mint)?.r.valueAt(leaf);
13441
+ if (v !== void 0) return v;
13442
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
13443
+ if (carried !== void 0) return carried;
13444
+ const t = startTrees.get(mint);
13445
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
13446
+ return void 0;
13447
+ };
13448
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
13449
+ const verified = [];
13450
+ const pendingByKey = /* @__PURE__ */ new Map();
13451
+ const rejectedCandidates = /* @__PURE__ */ new Set();
13452
+ const outcomeOf = /* @__PURE__ */ new Map();
13453
+ const tally = (c, what) => {
13454
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
13455
+ t.total++;
13456
+ if (what === "kept") t.kept = true;
13457
+ if (what === "rejected") t.rejected++;
13458
+ outcomeOf.set(c.seq, t);
13459
+ };
13460
+ const pend = (c, rank) => {
13461
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
13462
+ const prior = pendingByKey.get(key);
13463
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
13464
+ };
13465
+ for (const c of candidates) {
13466
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
13467
+ verified.push(c);
13468
+ continue;
13469
+ }
13470
+ if (!poolSet.has(c.mint)) {
13471
+ pend(c, 3);
13472
+ continue;
13473
+ }
13474
+ const value = streamValue(c.mint, c.leaf);
13475
+ if (value === void 0) {
13476
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
13477
+ stats.dropped++;
13478
+ tally(c, "other");
13479
+ } else pend(c, 1);
13480
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
13481
+ pend(c, value === c.commitment ? 0 : 2);
13482
+ } else if (value === c.commitment) {
13483
+ verified.push(c);
13484
+ } else {
13485
+ stats.dropped++;
13486
+ rejectedCandidates.add(c);
13487
+ tally(c, "rejected");
13488
+ }
13489
+ }
13490
+ verified.sort((a, b) => a.seq - b.seq);
13491
+ const byLeaf = /* @__PURE__ */ new Map();
13492
+ for (const c of verified) {
13493
+ const key = `${c.mint}:${c.leaf}`;
13494
+ if (byLeaf.has(key)) {
13495
+ stats.dropped++;
13496
+ tally(c, "other");
13497
+ continue;
13498
+ }
13499
+ byLeaf.set(key, c);
13500
+ }
13501
+ const notes = [];
13502
+ const atRisk = [];
13503
+ const spentOut = new Set(knownSpent);
13504
+ const verifiedOut = new Set(knownVerified);
13505
+ const keyChecked = /* @__PURE__ */ new Map();
13506
+ for (const c of byLeaf.values()) {
13507
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
13508
+ keyChecked.set(c.keypair.privateKey, pubOk);
13509
+ const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
13510
+ if (!pubOk || !c.atRisk && !ownerOk) {
13511
+ stats.dropped++;
13512
+ tally(c, "rejected");
13513
+ continue;
13514
+ }
13515
+ tally(c, "kept");
13516
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
13517
+ const utxo = {
13518
+ amount: c.amount,
13519
+ keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
13520
+ blinding: c.blinding,
13521
+ mintAddress: c.mint,
13522
+ index: c.leaf,
13523
+ commitment: c.commitment
13524
+ };
13525
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
13526
+ stats.spent++;
13527
+ spentOut.add(c.nullifier);
13528
+ continue;
13529
+ }
13530
+ const note = {
13531
+ kind: c.kind,
13532
+ utxo,
13533
+ signature: bs584.encode(c.signature),
13534
+ legacyExposed: c.atRisk
13535
+ };
13536
+ (c.atRisk ? atRisk : notes).push(note);
13537
+ }
13538
+ 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);
13539
+ sortNotes(notes);
13540
+ sortNotes(atRisk);
13541
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
13542
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
13543
+ const overflow = pendingList.length - carriedPending.length;
13544
+ if (overflow > 0) {
13545
+ stats.pendingDropped += overflow;
13546
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
13547
+ }
13548
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
13549
+ for (const c of carriedPending) tally(c, "kept");
13550
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
13551
+ let page = targetPage;
13552
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
13553
+ const trees = {};
13554
+ const treeEnd = /* @__PURE__ */ new Map();
13555
+ for (const mint of poolMints) {
13556
+ const start = startTrees.get(mint);
13557
+ const { r, overrides } = replays.get(mint);
13558
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
13559
+ const n = snap.nextIndex;
13560
+ const window2 = [];
13561
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
13562
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
13563
+ if (v === void 0) break;
13564
+ window2.push(hex32(v));
13565
+ }
13566
+ window2.reverse();
13567
+ trees[mint] = {
13568
+ frontier: snap.frontier,
13569
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
13570
+ window: window2.join(""),
13571
+ verified: Math.min(verifiedUpTo(mint), n),
13572
+ 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)]),
13573
+ mismatch: r.mismatch
13574
+ };
13575
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
13576
+ }
13577
+ const pendingLeaves = [];
13578
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
13579
+ for (const c of carriedPending) {
13580
+ const end = treeEnd.get(c.mint);
13581
+ if (!end || c.leaf >= end.nextIndex) continue;
13582
+ const value = streamValue(c.mint, c.leaf);
13583
+ const key = `${c.mint}:${c.leaf}`;
13584
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
13585
+ pendingLeafSeen.add(key);
13586
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
13587
+ }
13588
+ const keptItems = [];
13589
+ const keptIds = /* @__PURE__ */ new Set();
13590
+ for (const o of ownItems) {
13591
+ const t = outcomeOf.get(o.seq);
13592
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
13593
+ rejectedNow.add(o.id);
13594
+ continue;
13595
+ }
13596
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
13597
+ keptIds.add(o.id);
13598
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
13599
+ }
13600
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
13601
+ const nextCursor = {
13602
+ v: CURSOR_VERSION,
13603
+ epoch: head.epoch.toString(10),
13604
+ page,
13605
+ chain: chainAt.get(page) ?? startChain,
13606
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
13607
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
13608
+ trees,
13609
+ own: {
13610
+ items: keptItems,
13611
+ verified: Array.from(verifiedOut),
13612
+ spent: Array.from(spentOut),
13613
+ pendingLeaves,
13614
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
13615
+ }
13616
+ };
13617
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
13618
+ } finally {
13619
+ params.signal?.removeEventListener("abort", onCallerAbort);
13620
+ }
13621
+ }
13622
+
11382
13623
  // src/wallet/utxo-wallet.ts
11383
13624
  var UtxoWallet = class _UtxoWallet {
11384
13625
  constructor(viewingKey) {
@@ -11733,7 +13974,7 @@ async function loadWeb3() {
11733
13974
 
11734
13975
  // src/bridge/rail-verify.ts
11735
13976
  import nacl6 from "tweetnacl";
11736
- import { sha256 as sha2565 } from "@noble/hashes/sha256";
13977
+ import { sha256 as sha2567 } from "@noble/hashes/sha256";
11737
13978
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
11738
13979
  var b58 = /* @__PURE__ */ (() => {
11739
13980
  const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -11839,7 +14080,7 @@ function canonicalPayloadString(resp) {
11839
14080
  function verifyQuoteSignature(resp) {
11840
14081
  if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
11841
14082
  const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
11842
- const digest = sha2565(new TextEncoder().encode(stable(payload)));
14083
+ const digest = sha2567(new TextEncoder().encode(stable(payload)));
11843
14084
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
11844
14085
  const sig = resp.signature.replace(/^ed25519:/, "");
11845
14086
  try {
@@ -12034,7 +14275,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12034
14275
  })
12035
14276
  });
12036
14277
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12037
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
14278
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
12038
14279
  throw new Error(
12039
14280
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12040
14281
  );
@@ -12071,9 +14312,12 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12071
14312
  // src/bridge/derive.ts
12072
14313
  import { hmac } from "@noble/hashes/hmac";
12073
14314
  import { sha512 } from "@noble/hashes/sha512";
14315
+ import { blake3 as blake36 } from "@noble/hashes/blake3";
12074
14316
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
14317
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
14318
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
12075
14319
  var MAX_RECEIVER_INDEX = 1e4;
12076
- async function deriveBridgeReceiver(nk, index) {
14320
+ function assertReceiverIndex(index) {
12077
14321
  if (!Number.isInteger(index) || index < 0) {
12078
14322
  throw new Error(`index must be a non-negative integer, got ${index}`);
12079
14323
  }
@@ -12082,6 +14326,26 @@ async function deriveBridgeReceiver(nk, index) {
12082
14326
  `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
14327
  );
12084
14328
  }
14329
+ }
14330
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
14331
+ if (ownerUtxoKeypair instanceof Uint8Array) {
14332
+ throw new Error(
14333
+ "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."
14334
+ );
14335
+ }
14336
+ assertReceiverIndex(index);
14337
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
14338
+ const priv = bigintToBytes322(owner.privateKey);
14339
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
14340
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
14341
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
14342
+ const key = blake36(preimage);
14343
+ const h = hmac(sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
14344
+ return signerFromSecretKey(h.slice(0, 32));
14345
+ }
14346
+ async function deriveLegacyBridgeReceiver(nk, index) {
14347
+ assertReceiverIndex(index);
14348
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
12085
14349
  const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12086
14350
  return signerFromSecretKey(h.slice(0, 32));
12087
14351
  }
@@ -12092,13 +14356,44 @@ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS4, findAssociatedTokenPda
12092
14356
  function describeError(err) {
12093
14357
  return err instanceof Error ? err.message : String(err);
12094
14358
  }
12095
- async function listBridgeDeposits(rpc, nk, opts) {
14359
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
14360
+ if (ownerUtxoKeypair instanceof Uint8Array) {
14361
+ throw new Error(
14362
+ "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)."
14363
+ );
14364
+ }
14365
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
14366
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
14367
+ legacyExposed: false
14368
+ });
14369
+ if (opts.includeLegacy === false) return out;
14370
+ const nks = [];
14371
+ const seen = /* @__PURE__ */ new Set();
14372
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
14373
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
14374
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
14375
+ }
14376
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
14377
+ if (seen.has(key)) continue;
14378
+ seen.add(key);
14379
+ nks.push(nk);
14380
+ }
14381
+ for (const nk of nks) {
14382
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
14383
+ legacyExposed: true,
14384
+ legacyViewingKeyNk: nk
14385
+ });
14386
+ out.push(...legacy);
14387
+ }
14388
+ return out;
14389
+ }
14390
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12096
14391
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12097
14392
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12098
14393
  const out = [];
12099
14394
  let consecutiveUnused = 0;
12100
14395
  for (let index = 0; index < scanDepth; index++) {
12101
- const kp = await deriveBridgeReceiver(nk, index);
14396
+ const kp = await receiverAt(index);
12102
14397
  const receiver = kp.address;
12103
14398
  const [tokenAccount] = await findAssociatedTokenPda4({
12104
14399
  mint: opts.mint,
@@ -12150,7 +14445,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12150
14445
  tokenBalance,
12151
14446
  lamports,
12152
14447
  shieldSignature,
12153
- ...indexReused ? { indexReused, shieldSignatures } : {}
14448
+ ...indexReused ? { indexReused, shieldSignatures } : {},
14449
+ ...provenance
12154
14450
  });
12155
14451
  } catch (err) {
12156
14452
  out.push({
@@ -12160,7 +14456,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12160
14456
  state: "unknown",
12161
14457
  tokenBalance: 0n,
12162
14458
  lamports: 0n,
12163
- error: describeError(err)
14459
+ error: describeError(err),
14460
+ ...provenance
12164
14461
  });
12165
14462
  }
12166
14463
  }
@@ -12315,7 +14612,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12315
14612
  const signMessage = (m) => signMessageBytes(R, m);
12316
14613
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
12317
14614
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
12318
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
14615
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
14616
+ amount,
14617
+ viewingKeyNk: nk,
14618
+ ownerUtxoKeypair: utxoKeypair,
14619
+ mintAddress: mint
14620
+ });
12319
14621
  const zeroInput = await createZeroUtxo(mint);
12320
14622
  const rBefore = (await rpc.getBalance(R.address).send()).value;
12321
14623
  let result;
@@ -12334,6 +14636,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12334
14636
  signMessage,
12335
14637
  chainNoteViewingKeyNk: nk,
12336
14638
  chainNoteSalt: noteSalt,
14639
+ ownerUtxoKeypair: utxoKeypair,
12337
14640
  relaySupplementalAlt: true,
12338
14641
  onProgress: (s) => log(` \xB7 ${s}`)
12339
14642
  }
@@ -12527,13 +14830,13 @@ var DoNotRetry = class extends Error {
12527
14830
  };
12528
14831
  async function withShieldRetries(attempt, hooks = {}) {
12529
14832
  const attempts = hooks.attempts ?? 3;
12530
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
14833
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
12531
14834
  let last = "";
12532
14835
  for (let n = 1; n <= attempts; n++) {
12533
14836
  if (n > 1) {
12534
14837
  const delay = retryDelayMs(n);
12535
14838
  hooks.onRetry?.(n, delay, last);
12536
- await sleep4(delay);
14839
+ await sleep5(delay);
12537
14840
  }
12538
14841
  try {
12539
14842
  return await attempt(n);
@@ -12552,6 +14855,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12552
14855
  export {
12553
14856
  AccountRole,
12554
14857
  BRIDGE_ESCROW_LABEL,
14858
+ BRIDGE_ESCROW_LABEL_V2,
12555
14859
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
12556
14860
  CHAIN_NOTE_SALT_BITS,
12557
14861
  CLEANUP_FEE_BUDGET,
@@ -12580,6 +14884,10 @@ export {
12580
14884
  MemoryStorageAdapter,
12581
14885
  MerkleTree,
12582
14886
  NATIVE_SOL_MINT,
14887
+ NOTE_INDEX_NO_LEAF,
14888
+ NOTE_INDEX_PAGE_SIZE,
14889
+ NoteIndexFormatError,
14890
+ NoteIndexHeadBehindError,
12583
14891
  ONECLICK_PUBKEY_B58,
12584
14892
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
12585
14893
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -12656,6 +14964,7 @@ export {
12656
14964
  computeChainNoteHash,
12657
14965
  computeExtDataHash,
12658
14966
  computeMerkleRoot,
14967
+ computeNoteIndexChain,
12659
14968
  computeProofForLatestDeposit,
12660
14969
  computeProofFromChain,
12661
14970
  computeSignature,
@@ -12680,14 +14989,19 @@ export {
12680
14989
  depositFromDerivedKey,
12681
14990
  deriveBridgeReceiver,
12682
14991
  deriveChangeNoteBlinding,
12683
- deriveDepositNoteSecrets,
14992
+ deriveDepositNoteBlinding,
12684
14993
  deriveDiversifiedViewingKey,
12685
14994
  deriveDiversifier,
12686
14995
  deriveFundingTargets,
12687
14996
  deriveInputNullifierPdas,
14997
+ deriveLegacyBridgeReceiver,
14998
+ deriveLegacyDepositNoteSecrets,
14999
+ deriveLegacySwapRefundAuthorization,
12688
15000
  derivePublicKey,
12689
15001
  deriveSpendKey,
12690
15002
  deriveSwapRefundAuthorization,
15003
+ deriveSwapRefundBlinding,
15004
+ deriveSwapRefundKeypair,
12691
15005
  deriveUserCompliancePublicKey,
12692
15006
  deriveUserComplianceScalar,
12693
15007
  deriveUtxoKeypairFromSpendKey,
@@ -12700,6 +15014,8 @@ export {
12700
15014
  discoverSwapRefunds,
12701
15015
  downloadNote,
12702
15016
  encodeDeliveryCarrierMemo,
15017
+ encodeNoteIndexItem,
15018
+ encodeNoteIndexPage,
12703
15019
  encodeNoteSimple,
12704
15020
  encodeRecipientDeliveryNote,
12705
15021
  encryptCompactChainNote,
@@ -12715,6 +15031,8 @@ export {
12715
15031
  fetchCommitments,
12716
15032
  fetchLatestBlockhash,
12717
15033
  fetchLookupTables,
15034
+ fetchNoteIndexHead,
15035
+ fetchNoteIndexPage,
12718
15036
  fetchRiskQuoteInstruction,
12719
15037
  fetchRiskQuoteIx,
12720
15038
  fetchSignaturesForAddress,
@@ -12787,6 +15105,8 @@ export {
12787
15105
  parseDeliveryCarrierMemo,
12788
15106
  parseError,
12789
15107
  parseNote2 as parseNote,
15108
+ parseNoteIndexItem,
15109
+ parseNoteIndexPage,
12790
15110
  parseRelayErrorResponse,
12791
15111
  parseRelayErrorSignature,
12792
15112
  parseTransactionError,
@@ -12808,6 +15128,7 @@ export {
12808
15128
  readMerkleTreeState,
12809
15129
  readRent,
12810
15130
  recipientDeliveryNoteToBase64,
15131
+ recoverNotesFromIndex,
12811
15132
  registerViewingKey,
12812
15133
  relayRequestDigestHex,
12813
15134
  removePendingDeposit,