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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -753,6 +753,44 @@ function isLoopbackHost(value) {
753
753
  }
754
754
  var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
755
755
 
756
+ // src/relay/clock.ts
757
+ var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
758
+ var MAX_CLOCK_DIVERGENCE_MS = 2e3;
759
+ var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
760
+ var sample = null;
761
+ function monotonicNowMs() {
762
+ const perf = globalThis.performance;
763
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
764
+ }
765
+ function observeRelayClock(response) {
766
+ const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
767
+ if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
768
+ const serverMs = Number(raw.trim());
769
+ const wallMs = Date.now();
770
+ const offsetMs = serverMs - wallMs;
771
+ if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
772
+ sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
773
+ }
774
+ function relayNowMs() {
775
+ const wallMs = Date.now();
776
+ if (!sample) return wallMs;
777
+ const wallElapsed = wallMs - sample.wallAtSampleMs;
778
+ const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
779
+ if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
780
+ sample = null;
781
+ return wallMs;
782
+ }
783
+ return wallMs + sample.offsetMs;
784
+ }
785
+ function hasRelayClockSample() {
786
+ if (!sample) return false;
787
+ relayNowMs();
788
+ return sample !== null;
789
+ }
790
+ function relayNowSeconds() {
791
+ return Math.floor(relayNowMs() / 1e3);
792
+ }
793
+
756
794
  // src/relay/endpoint.ts
757
795
  var ALLOWED_ORIGINS = new Set(
758
796
  RELAY_ORIGIN_ALLOWLIST.map((entry) => {
@@ -804,8 +842,9 @@ function assertAllowedRelayOrigin(value) {
804
842
  async function relayFetch(url, init, options) {
805
843
  assertAllowedRelayOrigin(url);
806
844
  const extra = sanitizeExtraHeaders(options?.extraHeaders);
807
- if (!extra) return fetch(url, init);
808
- return fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) });
845
+ const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
846
+ if (options?.observeClock !== false) observeRelayClock(response);
847
+ return response;
809
848
  }
810
849
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
811
850
  var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
@@ -1298,7 +1337,7 @@ ${digest}`
1298
1337
  }
1299
1338
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1300
1339
  const senderB58 = sender;
1301
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
1340
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
1302
1341
  const nonce = randomNonceUuid();
1303
1342
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
1304
1343
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -1377,7 +1416,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
1377
1416
  `The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${maxAgeSeconds} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
1378
1417
  );
1379
1418
  }
1380
- function explainRelayAuthRejection(responseText) {
1419
+ function explainRelayAuthRejection(responseText, context) {
1381
1420
  const text = String(responseText);
1382
1421
  const has = (needle) => text.includes(needle);
1383
1422
  if (has("issued too far in the future")) {
@@ -1387,7 +1426,9 @@ function explainRelayAuthRejection(responseText) {
1387
1426
  return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
1388
1427
  }
1389
1428
  if (has("does not match the exact request")) {
1390
- return `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
1429
+ const base = `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
1430
+ if (!context?.carriedAffiliateCode) return base;
1431
+ return `${base} This request carried \`affiliate_code\`, which is signed with the rest of the body. A relay that predates the affiliate release (REL-010/REL-011) ignores that field and leaves it out of its digest, which produces exactly this mismatch. Upgrade the relay, or send the request without \`affiliateCode\`.`;
1391
1432
  }
1392
1433
  if (has("has no registered viewing key")) {
1393
1434
  return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
@@ -3929,6 +3970,27 @@ function isRootAccepted(data, rootHex) {
3929
3970
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3930
3971
  return readRootHistory(data).some((r) => r === want);
3931
3972
  }
3973
+ function treeAccountAcceptsRoot(data, rootHex) {
3974
+ const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3975
+ if (data.length >= ROOT_OFFSET + 32) {
3976
+ const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
3977
+ if (current === want) return true;
3978
+ }
3979
+ return isRootAccepted(data, want);
3980
+ }
3981
+ function readTreeAccountFrontier(data) {
3982
+ if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
3983
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
3984
+ const next = readBigUInt64LE(buf, 32);
3985
+ if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
3986
+ const subtrees = [];
3987
+ for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
3988
+ const offset = SUBTREES_OFFSET + level * 32;
3989
+ subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
3990
+ }
3991
+ const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
3992
+ return { nextIndex: Number(next), subtrees, root };
3993
+ }
3932
3994
 
3933
3995
  // src/proving/merkle.ts
3934
3996
  import { buildPoseidon } from "circomlibjs";
@@ -4088,6 +4150,89 @@ var MerkleTree = class _MerkleTree {
4088
4150
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4089
4151
  return MerkleTree.create(height, commitments);
4090
4152
  }
4153
+ var MerkleFrontier = class _MerkleFrontier {
4154
+ constructor(levels, zeros, poseidon2, count, left) {
4155
+ this.levels = levels;
4156
+ this.zeros = zeros;
4157
+ this.poseidon = poseidon2;
4158
+ this.count = count;
4159
+ this.left = left;
4160
+ }
4161
+ static async create(state, levels = MERKLE_TREE_HEIGHT2) {
4162
+ const zeros = await getZeroValues();
4163
+ const poseidon2 = await getPoseidon();
4164
+ const left = new Array(levels).fill(null);
4165
+ let count = 0;
4166
+ if (state) {
4167
+ if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
4168
+ throw new Error("MerkleFrontierState.nextIndex out of range");
4169
+ }
4170
+ if (!Array.isArray(state.left) || state.left.length !== levels) {
4171
+ throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
4172
+ }
4173
+ count = state.nextIndex;
4174
+ for (let l = 0; l < levels; l++) {
4175
+ const odd = Math.floor(count / 2 ** l) % 2 === 1;
4176
+ const entry = state.left[l];
4177
+ if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
4178
+ if (odd) {
4179
+ if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
4180
+ left[l] = BigInt("0x" + entry);
4181
+ }
4182
+ }
4183
+ }
4184
+ return new _MerkleFrontier(levels, zeros, poseidon2, count, left);
4185
+ }
4186
+ get nextIndex() {
4187
+ return this.count;
4188
+ }
4189
+ /**
4190
+ * The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
4191
+ * present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
4192
+ * With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
4193
+ */
4194
+ leftAt(level) {
4195
+ if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
4196
+ return this.left[level];
4197
+ }
4198
+ hash(a, b) {
4199
+ return this.poseidon.F.toObject(this.poseidon([a, b]));
4200
+ }
4201
+ /** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
4202
+ append(leaves) {
4203
+ if (leaves.length === 0) return;
4204
+ if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
4205
+ let nodes = leaves;
4206
+ for (let l = 0; l < this.levels && nodes.length > 0; l++) {
4207
+ const before = Math.floor(this.count / 2 ** l);
4208
+ const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
4209
+ const parents = [];
4210
+ for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
4211
+ this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
4212
+ nodes = parents;
4213
+ }
4214
+ this.count += leaves.length;
4215
+ }
4216
+ /** The root of the first `nextIndex` leaves, zero-padded to the right. */
4217
+ root() {
4218
+ let partial = this.zeros[0];
4219
+ for (let l = 0; l < this.levels; l++) {
4220
+ const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
4221
+ if (odd) partial = this.hash(this.left[l], partial);
4222
+ else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
4223
+ }
4224
+ return partial;
4225
+ }
4226
+ toState() {
4227
+ return {
4228
+ nextIndex: this.count,
4229
+ left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
4230
+ };
4231
+ }
4232
+ clone() {
4233
+ return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
4234
+ }
4235
+ };
4091
4236
 
4092
4237
  // src/config/transaction-version.ts
4093
4238
  var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
@@ -4236,6 +4381,7 @@ async function fetchWithRetry(url, options = {}) {
4236
4381
  try {
4237
4382
  const response = await fetch(url, { signal: controller.signal });
4238
4383
  clearTimeout(timeoutId);
4384
+ observeRelayClock(response);
4239
4385
  return response;
4240
4386
  } finally {
4241
4387
  clearTimeout(timeoutId);
@@ -4599,38 +4745,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
4599
4745
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
4600
4746
  return new Uint8Array(plaintext);
4601
4747
  }
4602
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
4748
+ async function importNkHkdfKey(nk) {
4603
4749
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4604
4750
  throw new Error("nk must be 32 bytes");
4605
4751
  }
4752
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
4753
+ }
4754
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
4606
4755
  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
- );
4756
+ const [keyBits, nonceBits] = await Promise.all([
4757
+ subtle.deriveBits(
4758
+ {
4759
+ name: "HKDF",
4760
+ hash: "SHA-256",
4761
+ salt: toArrayBuffer2(salt),
4762
+ info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
4763
+ },
4764
+ ikm,
4765
+ 256
4766
+ ),
4767
+ subtle.deriveBits(
4768
+ {
4769
+ name: "HKDF",
4770
+ hash: "SHA-256",
4771
+ salt: toArrayBuffer2(salt),
4772
+ info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
4773
+ },
4774
+ ikm,
4775
+ 96
4776
+ )
4777
+ ]);
4629
4778
  return {
4630
4779
  key: new Uint8Array(keyBits),
4631
4780
  nonce: new Uint8Array(nonceBits)
4632
4781
  };
4633
4782
  }
4783
+ async function deriveAesKeyAndNonce(nk, commitmentHex) {
4784
+ const ikm = await importNkHkdfKey(nk);
4785
+ return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
4786
+ }
4787
+ function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
4788
+ if (version === NOTE_VERSION_V4) {
4789
+ if (plaintext.length !== PLAINTEXT_LEN_V4) {
4790
+ throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
4791
+ }
4792
+ return {
4793
+ timestamp: readU64LE(plaintext, 0),
4794
+ commitment: commitmentHex.toLowerCase(),
4795
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
4796
+ outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
4797
+ outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
4798
+ isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
4799
+ };
4800
+ }
4801
+ if (version === NOTE_VERSION_V3) {
4802
+ if (plaintext.length !== PLAINTEXT_LEN_V3) {
4803
+ throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
4804
+ }
4805
+ return {
4806
+ timestamp: readU64LE(plaintext, 0),
4807
+ commitment: commitmentHex.toLowerCase(),
4808
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
4809
+ };
4810
+ }
4811
+ if (plaintext.length !== PLAINTEXT_LEN_V2) {
4812
+ throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
4813
+ }
4814
+ return {
4815
+ timestamp: readU64LE(plaintext, 0),
4816
+ commitment: commitmentHex.toLowerCase()
4817
+ };
4818
+ }
4634
4819
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
4635
4820
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4636
4821
  throw new Error("nk must be 32 bytes");
@@ -4694,36 +4879,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4694
4879
  try {
4695
4880
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
4696
4881
  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
- };
4882
+ return decodeChainNotePlaintext(version, plaintext, commitment);
4727
4883
  } catch (error) {
4728
4884
  lastError = error;
4729
4885
  }
@@ -4732,6 +4888,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4732
4888
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
4733
4889
  );
4734
4890
  }
4891
+ async function createCompactChainNoteDecryptor(nk) {
4892
+ const ikm = await importNkHkdfKey(nk);
4893
+ return async (noteBytes, commitment) => {
4894
+ if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
4895
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
4896
+ const version = noteBytes[0];
4897
+ if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
4898
+ return null;
4899
+ }
4900
+ try {
4901
+ const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
4902
+ const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
4903
+ let hex = "";
4904
+ for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
4905
+ return decodeChainNotePlaintext(version, plaintext, hex);
4906
+ } catch {
4907
+ return null;
4908
+ }
4909
+ };
4910
+ }
4735
4911
  function chainNoteToBase64(noteBytes) {
4736
4912
  return Buffer.from(noteBytes).toString("base64");
4737
4913
  }
@@ -4828,6 +5004,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4828
5004
  return null;
4829
5005
  }
4830
5006
  }
5007
+ var X25519_PKCS8_PREFIX = Uint8Array.from([
5008
+ 48,
5009
+ 46,
5010
+ 2,
5011
+ 1,
5012
+ 0,
5013
+ 48,
5014
+ 5,
5015
+ 6,
5016
+ 3,
5017
+ 43,
5018
+ 101,
5019
+ 110,
5020
+ 4,
5021
+ 34,
5022
+ 4,
5023
+ 32
5024
+ ]);
5025
+ var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
5026
+ function decodeOpened(plaintext) {
5027
+ if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5028
+ return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5029
+ }
5030
+ async function createRecipientDeliveryOpener(viewingSecretKey) {
5031
+ if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
5032
+ throw new Error("viewingSecretKey must be 32 bytes");
5033
+ }
5034
+ const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5035
+ const subtle = globalThis.crypto?.subtle;
5036
+ const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
5037
+ if (!subtle || typeof hsalsa !== "function") return slow;
5038
+ let privateKey;
5039
+ const sharedKey = async (ephemeralPk) => {
5040
+ const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
5041
+ const shared = new Uint8Array(
5042
+ await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
5043
+ );
5044
+ const key = new Uint8Array(32);
5045
+ hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
5046
+ return key;
5047
+ };
5048
+ try {
5049
+ const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
5050
+ pkcs8.set(X25519_PKCS8_PREFIX);
5051
+ pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5052
+ privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5053
+ const probe = nacl4.box.keyPair().publicKey;
5054
+ const fast = await sharedKey(probe);
5055
+ const reference = nacl4.box.before(probe, viewingSecretKey);
5056
+ if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5057
+ } catch {
5058
+ return slow;
5059
+ }
5060
+ return async (envelope) => {
5061
+ if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
5062
+ const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
5063
+ const nonce = envelope.subarray(
5064
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
5065
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5066
+ );
5067
+ const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
5068
+ let key;
5069
+ try {
5070
+ key = await sharedKey(ephemeralPk);
5071
+ } catch {
5072
+ return openRecipientDeliveryNote(envelope, viewingSecretKey);
5073
+ }
5074
+ try {
5075
+ return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
5076
+ } catch {
5077
+ return null;
5078
+ }
5079
+ };
5080
+ }
4831
5081
  function recipientDeliveryNoteToBase64(envelope) {
4832
5082
  return Buffer.from(envelope).toString("base64");
4833
5083
  }
@@ -4880,9 +5130,41 @@ function parseDeliveryCarrierMemo(data) {
4880
5130
  // src/notes/swap-refund.ts
4881
5131
  import { blake3 as blake33 } from "@noble/hashes/blake3";
4882
5132
  import _bs582 from "bs58";
5133
+
5134
+ // src/notes/owner-key.ts
5135
+ var FIELD_MODULUS = BigInt(
5136
+ "21888242871839275222246405745257275088548364400416034343698204186575808495617"
5137
+ );
5138
+ async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
5139
+ if (!keypair || typeof keypair !== "object") {
5140
+ throw new Error(
5141
+ `${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.`
5142
+ );
5143
+ }
5144
+ const { privateKey, publicKey } = keypair;
5145
+ if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS) {
5146
+ throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
5147
+ }
5148
+ if (typeof publicKey !== "bigint" || publicKey === 0n) {
5149
+ throw new Error(`${label}.publicKey must be a non-zero bigint`);
5150
+ }
5151
+ if (await derivePublicKey(privateKey) !== publicKey) {
5152
+ throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
5153
+ }
5154
+ return { privateKey, publicKey };
5155
+ }
5156
+ function normalizeOwnerPublicKey(publicKey, label) {
5157
+ if (publicKey === void 0 || publicKey === null) return void 0;
5158
+ if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS) {
5159
+ throw new Error(`${label} must be a non-zero field element (bigint)`);
5160
+ }
5161
+ return publicKey;
5162
+ }
5163
+
5164
+ // src/notes/swap-refund.ts
4883
5165
  var bs582 = _bs582.default || _bs582;
4884
5166
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
4885
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5167
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
4886
5168
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
4887
5169
  function normalizeNullifier(inputNullifier) {
4888
5170
  if (inputNullifier instanceof Uint8Array) {
@@ -4916,13 +5198,29 @@ function derive(nk, nullifier, info) {
4916
5198
  preimage.set(info, off);
4917
5199
  return blake33(preimage);
4918
5200
  }
4919
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5201
+ function assertNk(viewingKeyNk) {
4920
5202
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
4921
5203
  throw new Error("viewingKeyNk must be 32 bytes");
4922
5204
  }
5205
+ return viewingKeyNk;
5206
+ }
5207
+ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
5208
+ const nk = assertNk(viewingKeyNk);
5209
+ return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
5210
+ }
5211
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
5212
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5213
+ const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5214
+ if (owner.publicKey === 0n || blinding === 0n) {
5215
+ throw new Error("refund authorization is degenerate");
5216
+ }
5217
+ return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
5218
+ }
5219
+ async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5220
+ const nk = assertNk(viewingKeyNk);
4923
5221
  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));
5222
+ const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
5223
+ const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
4926
5224
  const publicKey = await derivePublicKey(privateKey);
4927
5225
  if (publicKey === 0n || blinding === 0n) {
4928
5226
  throw new Error("derived refund authorization is degenerate");
@@ -4940,19 +5238,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
4940
5238
  async function matchSwapRefundLeaf(params) {
4941
5239
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
4942
5240
  const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
4943
- let auth;
5241
+ let blinding;
4944
5242
  try {
4945
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
5243
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
4946
5244
  } catch {
4947
5245
  return null;
4948
5246
  }
4949
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
4950
- if (candidate !== expected) return null;
5247
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5248
+ if (ownerPub !== void 0) {
5249
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
5250
+ if (candidate === expected) {
5251
+ return {
5252
+ keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
5253
+ blinding,
5254
+ amount: amountAfterFee,
5255
+ commitment: candidate,
5256
+ legacyExposed: false
5257
+ };
5258
+ }
5259
+ }
5260
+ let legacy;
5261
+ try {
5262
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
5263
+ } catch {
5264
+ return null;
5265
+ }
5266
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
5267
+ if (legacyCandidate !== expected) return null;
4951
5268
  return {
4952
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
4953
- blinding: auth.blinding,
5269
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
5270
+ blinding: legacy.blinding,
4954
5271
  amount: amountAfterFee,
4955
- commitment: candidate
5272
+ commitment: legacyCandidate,
5273
+ legacyExposed: true
4956
5274
  };
4957
5275
  }
4958
5276
  var TRANSACT_SWAP_TAG2 = 1;
@@ -5016,10 +5334,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
5016
5334
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
5017
5335
  return out;
5018
5336
  }
5019
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
5337
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
5020
5338
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5021
5339
  throw new Error("viewingKeyNk must be 32 bytes");
5022
5340
  }
5341
+ if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
5342
+ throw new Error(
5343
+ "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are owned by it, and nk alone can only find legacy refunds."
5344
+ );
5345
+ }
5346
+ const ownerUtxoKeypair = options.ownerUtxoKeypair;
5023
5347
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5024
5348
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5025
5349
  const programIdBase58 = programId;
@@ -5094,7 +5418,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5094
5418
  viewingKeyNk,
5095
5419
  inputNullifier: candidate.nullifier,
5096
5420
  amountAfterFee: event.amountAfterFee,
5097
- commitment: event.commitmentField
5421
+ commitment: event.commitmentField,
5422
+ ownerUtxoKeypair
5098
5423
  });
5099
5424
  if (!recovered) continue;
5100
5425
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5118,7 +5443,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5118
5443
  // src/notes/deposit-note.ts
5119
5444
  import { blake3 as blake34 } from "@noble/hashes/blake3";
5120
5445
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5121
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5446
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5122
5447
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5123
5448
  var CHAIN_NOTE_SALT_BITS = 96;
5124
5449
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -5154,30 +5479,47 @@ function derive2(nk, salt, info) {
5154
5479
  preimage.set(info, off);
5155
5480
  return blake34(preimage);
5156
5481
  }
5482
+ function assertNk2(viewingKeyNk) {
5483
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5484
+ throw new Error("viewingKeyNk must be 32 bytes");
5485
+ }
5486
+ return viewingKeyNk;
5487
+ }
5157
5488
  function randomDepositNoteSalt() {
5158
5489
  const bytes = randomBytes(12);
5159
5490
  let v = 0n;
5160
5491
  for (const b of bytes) v = v << 8n | BigInt(b);
5161
5492
  return v === 0n ? 1n : v;
5162
5493
  }
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
- }
5494
+ function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
5495
+ const nk = assertNk2(viewingKeyNk);
5496
+ return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
5497
+ }
5498
+ async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
5499
+ const nk = assertNk2(viewingKeyNk);
5167
5500
  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));
5501
+ const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
5502
+ const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
5170
5503
  const publicKey = await derivePublicKey(privateKey);
5171
5504
  if (publicKey === 0n || blinding === 0n) {
5172
5505
  throw new Error("derived deposit note secrets are degenerate");
5173
5506
  }
5174
5507
  return { keypair: { privateKey, publicKey }, blinding };
5175
5508
  }
5176
- async function createRecoverableDepositUtxo(amount, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomDepositNoteSalt()) {
5509
+ async function createRecoverableDepositUtxo(params) {
5510
+ if (!params || typeof params !== "object" || params instanceof Uint8Array) {
5511
+ throw new Error(
5512
+ "createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
5513
+ );
5514
+ }
5515
+ const { amount, viewingKeyNk } = params;
5177
5516
  if (typeof amount !== "bigint" || amount <= 0n) {
5178
5517
  throw new Error("amount must be a positive bigint");
5179
5518
  }
5180
- const { keypair, blinding } = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5519
+ const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
5520
+ const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
5521
+ const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
5522
+ const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5181
5523
  const utxo = { amount, keypair, blinding, mintAddress };
5182
5524
  utxo.commitment = await computeCommitment(utxo);
5183
5525
  return { utxo, noteSalt };
@@ -5192,21 +5534,46 @@ function normalizeCommitment(value) {
5192
5534
  async function matchDepositNote(params) {
5193
5535
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
5194
5536
  if (typeof amount !== "bigint" || amount <= 0n) return null;
5195
- let secrets;
5537
+ let blinding;
5196
5538
  try {
5197
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5539
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5198
5540
  } catch {
5199
5541
  return null;
5200
5542
  }
5201
- const candidate = await computeCommitment({
5543
+ const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
5544
+ if (published.length === 0) return null;
5545
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5546
+ if (ownerPub !== void 0) {
5547
+ const keypair = {
5548
+ privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
5549
+ publicKey: ownerPub
5550
+ };
5551
+ const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5552
+ if (published.some((value) => value === candidate)) {
5553
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
5554
+ }
5555
+ }
5556
+ let legacy;
5557
+ try {
5558
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
5559
+ } catch {
5560
+ return null;
5561
+ }
5562
+ const legacyCandidate = await computeCommitment({
5202
5563
  amount,
5203
- keypair: secrets.keypair,
5204
- blinding: secrets.blinding,
5564
+ keypair: legacy.keypair,
5565
+ blinding: legacy.blinding,
5205
5566
  mintAddress
5206
5567
  });
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 };
5568
+ if (!published.some((value) => value === legacyCandidate)) return null;
5569
+ return {
5570
+ ...legacy,
5571
+ amount,
5572
+ mintAddress,
5573
+ commitment: legacyCandidate,
5574
+ noteSalt,
5575
+ legacyExposed: true
5576
+ };
5210
5577
  }
5211
5578
 
5212
5579
  // src/notes/change-note.ts
@@ -5262,10 +5629,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
5262
5629
  preimage.set(CHANGE_BLINDING_INFO, off);
5263
5630
  return toFieldSecret3(blake35(preimage));
5264
5631
  }
5265
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5632
+ async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5266
5633
  if (typeof amount !== "bigint" || amount <= 0n) {
5267
5634
  throw new Error("amount must be a positive bigint");
5268
5635
  }
5636
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5269
5637
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5270
5638
  const utxo = { amount, keypair, blinding, mintAddress };
5271
5639
  utxo.commitment = await computeCommitment(utxo);
@@ -5291,13 +5659,27 @@ async function matchChangeNote(params) {
5291
5659
  const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5292
5660
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
5293
5661
  if (!published.some((value) => value === candidate)) return null;
5294
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
5662
+ const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
5663
+ const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
5664
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
5295
5665
  }
5296
5666
 
5297
5667
  // src/flows/transact.ts
5298
5668
  import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
5299
5669
  import nacl5 from "tweetnacl";
5300
5670
 
5671
+ // src/relay/chain-note-time.ts
5672
+ async function relayChainNoteTimestampMs(relayUrl) {
5673
+ if (relayUrl && !hasRelayClockSample()) {
5674
+ try {
5675
+ const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
5676
+ await response.body?.cancel?.().catch(() => void 0);
5677
+ } catch {
5678
+ }
5679
+ }
5680
+ return BigInt(relayNowMs());
5681
+ }
5682
+
5301
5683
  // src/proving/artifacts.ts
5302
5684
  import { sha256 as sha2564 } from "@noble/hashes/sha2";
5303
5685
 
@@ -5934,6 +6316,33 @@ function parseNkInput(input) {
5934
6316
  }
5935
6317
  return Uint8Array.from(Buffer.from(clean, "hex"));
5936
6318
  }
6319
+ async function resolveWalletNk(options) {
6320
+ const explicit = await resolveChainNoteNk(options);
6321
+ if (explicit) return explicit;
6322
+ if (options.ownerUtxoKeypair) {
6323
+ const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
6324
+ return getNkFromUtxoPrivateKey(owner.privateKey);
6325
+ }
6326
+ return null;
6327
+ }
6328
+ function missingWalletNkError(flow) {
6329
+ return new Error(
6330
+ `${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.`
6331
+ );
6332
+ }
6333
+ async function requireWalletNk(options, flow) {
6334
+ const nk = await resolveWalletNk(options);
6335
+ if (nk) return nk;
6336
+ throw missingWalletNkError(flow);
6337
+ }
6338
+ async function requireOwnerUtxoKeypair(options, flow) {
6339
+ if (!options.ownerUtxoKeypair) {
6340
+ throw new Error(
6341
+ `${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].`
6342
+ );
6343
+ }
6344
+ return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
6345
+ }
5937
6346
  async function resolveChainNoteNk(options) {
5938
6347
  if (options.chainNoteViewingKeyNk) {
5939
6348
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -5951,7 +6360,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
5951
6360
  function toHex(bytes) {
5952
6361
  return Buffer.from(bytes).toString("hex");
5953
6362
  }
5954
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6363
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
5955
6364
  if (options.enforceViewingKeyRegistration === false) {
5956
6365
  return;
5957
6366
  }
@@ -5965,7 +6374,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5965
6374
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
5966
6375
  );
5967
6376
  }
5968
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
6377
+ const nk = walletNk;
5969
6378
  if (!nk || nk.length !== 32) {
5970
6379
  throw new Error(
5971
6380
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6107,10 +6516,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6107
6516
  result.set(bigintToBytes322(BigInt(publicSignals[0])), offset);
6108
6517
  offset += 32;
6109
6518
  let amount = BigInt(publicSignals[1]);
6110
- const FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6111
- const HALF_FIELD = FIELD_MODULUS / BigInt(2);
6519
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6520
+ const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
6112
6521
  if (amount > HALF_FIELD) {
6113
- amount = amount - FIELD_MODULUS;
6522
+ amount = amount - FIELD_MODULUS2;
6114
6523
  }
6115
6524
  const amountBytes = new Uint8Array(8);
6116
6525
  let amountValue = amount;
@@ -7057,8 +7466,9 @@ function chargeWalletApproval(used, budget, lastError) {
7057
7466
  }
7058
7467
  return used + 1;
7059
7468
  }
7060
- function relayFailureMessage(prefix, responseText) {
7061
- const explanation = explainRelayAuthRejection(responseText);
7469
+ function relayFailureMessage(prefix, responseText, requestBody) {
7470
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
7471
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7062
7472
  return explanation ? `${prefix}: ${responseText}
7063
7473
 
7064
7474
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -7436,6 +7846,7 @@ async function submitTransactToRelay(args) {
7436
7846
  body: requestPayload,
7437
7847
  signal: controller.signal
7438
7848
  });
7849
+ observeRelayClock(response);
7439
7850
  } finally {
7440
7851
  clearTimeout(timeoutId);
7441
7852
  }
@@ -7466,7 +7877,9 @@ async function submitTransactToRelay(args) {
7466
7877
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
7467
7878
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
7468
7879
  }
7469
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
7880
+ return await resolveFailure(
7881
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
7882
+ );
7470
7883
  }
7471
7884
  const apiResponse = JSON.parse(responseText);
7472
7885
  if (!apiResponse.success || !apiResponse.data) {
@@ -7483,7 +7896,7 @@ async function submitTransactToRelay(args) {
7483
7896
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
7484
7897
  }
7485
7898
  return await resolveFailure(
7486
- new Error(relayFailureMessage("Relay returned error", errorStr))
7899
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
7487
7900
  );
7488
7901
  }
7489
7902
  const result = apiResponse.data;
@@ -7591,34 +8004,37 @@ async function transact(params, options) {
7591
8004
  );
7592
8005
  }
7593
8006
  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) {
8007
+ const walletNk = await resolveWalletNk(options);
8008
+ const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
8009
+ if (options.chainNoteSalt !== void 0 && !walletNk) {
7599
8010
  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."
8011
+ "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
8012
  );
7602
8013
  }
7603
8014
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
7604
8015
  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));
8016
+ if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
8017
+ throw missingWalletNkError("transact");
8018
+ }
8019
+ if (walletNk && chainNoteWillCarrySalt) {
8020
+ const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8021
+ if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
8022
+ const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
7607
8023
  for (let i = 0; i < outputUtxos.length; i++) {
7608
8024
  const out = outputUtxos[i];
7609
8025
  if (!out || out.amount <= BigInt(0)) continue;
7610
- if (!inputOwners.has(out.keypair.publicKey)) continue;
7611
- if (out.blinding !== deriveChangeNoteBlinding(explicitChainNoteNk, chainNoteSalt, i)) {
8026
+ if (!selfOwners.has(out.keypair.publicKey)) continue;
8027
+ if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
7612
8028
  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.`
8029
+ `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
8030
  );
7615
8031
  }
7616
8032
  }
7617
8033
  }
7618
8034
  assertAllowedRpcConnection(connection);
7619
8035
  assertInputMints(inputUtxos, options.expectedMint);
7620
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
7621
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
8036
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
8037
+ const resolvedChainNoteNk = walletNk;
7622
8038
  if (inputUtxos.length > 2) {
7623
8039
  throw new Error("Maximum 2 input UTXOs allowed");
7624
8040
  }
@@ -7992,7 +8408,7 @@ async function transact(params, options) {
7992
8408
  }
7993
8409
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
7994
8410
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
7995
- const chainNoteTimestamp = BigInt(Date.now());
8411
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
7996
8412
  const mintField = pubkeyToFieldElement(mint);
7997
8413
  let signature = "pending-" + Date.now().toString();
7998
8414
  let commitmentIndices = [-1, -1];
@@ -8088,9 +8504,9 @@ async function transact(params, options) {
8088
8504
  ]));
8089
8505
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8090
8506
  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()}`);
8507
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8508
+ if (chainNoteHash >= FIELD_MODULUS2) {
8509
+ throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
8094
8510
  }
8095
8511
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8096
8512
  const totalInputs = 1 + // root
@@ -8512,7 +8928,8 @@ async function transact(params, options) {
8512
8928
  throw lastError;
8513
8929
  }
8514
8930
  const classified = classifyRelayError(lastError.message);
8515
- const isMerkleClass = !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
8931
+ const isDepositSubmission = externalAmount > BigInt(0);
8932
+ const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
8516
8933
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
8517
8934
  onProgress?.(
8518
8935
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -8661,54 +9078,83 @@ async function transact(params, options) {
8661
9078
  };
8662
9079
  }
8663
9080
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
9081
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
9082
+ const transferNk = await requireWalletNk(options, "transfer");
8664
9083
  const inputSum = sumUtxoAmounts(inputUtxos);
8665
9084
  if (inputSum < amount) {
8666
9085
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
8667
9086
  }
8668
9087
  const change = inputSum - amount;
8669
- const myKeypair = inputUtxos[0].keypair;
8670
9088
  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);
9089
+ let spendInputs = [
9090
+ ...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
9091
+ ...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
9092
+ ];
9093
+ let spendOptions = options;
9094
+ if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
9095
+ if (spendInputs.length > 2) {
9096
+ throw new Error(
9097
+ `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.`
9098
+ );
9099
+ }
9100
+ if (options.relayAuthBatch) {
9101
+ throw new Error(
9102
+ "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."
9103
+ );
9104
+ }
9105
+ options.onProgress?.("Moving notes under the wallet key before the transfer...");
9106
+ const migrationSalt = randomChangeNoteSalt();
9107
+ const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
9108
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
9109
+ void _recipientViewingPublicKey;
9110
+ const migration = await transact(
9111
+ { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
9112
+ { ...migrationOptions, chainNoteSalt: migrationSalt }
9113
+ );
9114
+ const migratedNote = migration.outputUtxos?.[0] ?? migrated;
9115
+ if (migration.commitmentIndices?.[0] >= 0) {
9116
+ migratedNote.index = migration.commitmentIndices[0];
9117
+ }
9118
+ spendInputs = [migratedNote];
9119
+ spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
9120
+ }
9121
+ const changeNoteSalt = randomChangeNoteSalt();
9122
+ const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
8674
9123
  const recipientKeypair = {
8675
9124
  privateKey: BigInt(0),
8676
9125
  // Recipient's private key unknown
8677
9126
  publicKey: recipientPubkey
8678
9127
  };
8679
- const recipientUtxo = transferNk && isSendToSelf ? (await createRecoverableChangeUtxo(amount, myKeypair, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
9128
+ const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
8680
9129
  const outputUtxos = [recipientUtxo];
8681
9130
  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
- }
9131
+ const { utxo } = await createRecoverableChangeUtxo(
9132
+ change,
9133
+ owner,
9134
+ transferNk,
9135
+ mint,
9136
+ changeNoteSalt,
9137
+ 1
9138
+ );
9139
+ outputUtxos.push(utxo);
8695
9140
  }
8696
9141
  return transact(
8697
9142
  {
8698
- inputUtxos,
9143
+ inputUtxos: spendInputs,
8699
9144
  outputUtxos,
8700
9145
  externalAmount: BigInt(0)
8701
9146
  // Pure shield-to-shield
8702
9147
  },
8703
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
9148
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
8704
9149
  );
8705
9150
  }
8706
9151
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9152
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
9153
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
8707
9154
  const inputSum = sumUtxoAmounts(inputUtxos);
8708
9155
  if (inputSum < withdrawAmount) {
8709
9156
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
8710
9157
  }
8711
- const myKeypair = inputUtxos[0].keypair;
8712
9158
  const mint = inputUtxos[0].mintAddress;
8713
9159
  let utxos = [...inputUtxos];
8714
9160
  let cachedTree = options.cachedMerkleTree;
@@ -8717,9 +9163,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8717
9163
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
8718
9164
  const [small1, small2, ...rest] = utxos;
8719
9165
  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);
9166
+ const mergeSalt = randomChangeNoteSalt();
9167
+ const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
8723
9168
  const mergeResult = await transact(
8724
9169
  {
8725
9170
  inputUtxos: [small1, small2],
@@ -8730,7 +9175,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8730
9175
  {
8731
9176
  ...options,
8732
9177
  cachedMerkleTree: cachedTree,
8733
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
9178
+ chainNoteSalt: mergeSalt
8734
9179
  }
8735
9180
  );
8736
9181
  cachedTree = mergeResult.merkleTree;
@@ -8745,23 +9190,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8745
9190
  const outputUtxos = [];
8746
9191
  let changeNoteSalt;
8747
9192
  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
- }
9193
+ const salt = randomChangeNoteSalt();
9194
+ const { utxo } = await createRecoverableChangeUtxo(
9195
+ change,
9196
+ owner,
9197
+ walletNk,
9198
+ mint,
9199
+ salt,
9200
+ 0
9201
+ // partialWithdraw puts change at output 0
9202
+ );
9203
+ outputUtxos.push(utxo);
9204
+ changeNoteSalt = salt;
8765
9205
  }
8766
9206
  return transact(
8767
9207
  {
@@ -8884,6 +9324,8 @@ async function swapUtxo(params, options) {
8884
9324
  if (relayUrl) {
8885
9325
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
8886
9326
  }
9327
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
9328
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
8887
9329
  if (inputUtxos.length === 0) {
8888
9330
  throw new Error("At least one input UTXO required");
8889
9331
  }
@@ -8909,15 +9351,12 @@ async function swapUtxo(params, options) {
8909
9351
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
8910
9352
  }
8911
9353
  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;
9354
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
8916
9355
  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)) {
9356
+ if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
9357
+ if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
8919
9358
  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.`
9359
+ `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
9360
  );
8922
9361
  }
8923
9362
  }
@@ -8941,24 +9380,18 @@ async function swapUtxo(params, options) {
8941
9380
  );
8942
9381
  }
8943
9382
  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
- }
9383
+ const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
9384
+ const refundAuthorization = await deriveSwapRefundAuthorization(
9385
+ resolvedSwapChainNoteNk,
9386
+ refundNullifier,
9387
+ swapOwner
9388
+ );
9389
+ const refundKeypair = {
9390
+ privateKey: refundAuthorization.privateKey,
9391
+ publicKey: refundAuthorization.publicKey
9392
+ };
9393
+ const refundBlinding = refundAuthorization.blinding;
9394
+ const refundDerivedFromNk = true;
8962
9395
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
8963
9396
  throw new Error(
8964
9397
  "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 +9717,7 @@ async function swapUtxo(params, options) {
9284
9717
  for (const utxo of paddedOutputs) {
9285
9718
  outputCommitments.push(await computeCommitment(utxo));
9286
9719
  }
9287
- const chainNoteTimestamp = BigInt(Date.now());
9720
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
9288
9721
  onProgress?.("Computing external data hash...");
9289
9722
  const mint = swapPoolMint;
9290
9723
  const mintField = pubkeyToFieldElement(mint);
@@ -9598,7 +10031,7 @@ async function swapUtxo(params, options) {
9598
10031
  forceChainIndexing = !relayUrl;
9599
10032
  continue;
9600
10033
  }
9601
- throw new Error(relayFailureMessage("Relay error", responseText));
10034
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
9602
10035
  }
9603
10036
  const apiResponse = JSON.parse(responseText);
9604
10037
  if (!apiResponse.success || !apiResponse.data) {
@@ -9734,7 +10167,6 @@ async function swapUtxo(params, options) {
9734
10167
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
9735
10168
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
9736
10169
  refund: {
9737
- privateKey: Buffer.from(bigintToBytes322(refundKeypair.privateKey)).toString("hex"),
9738
10170
  publicKey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("hex"),
9739
10171
  blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("hex"),
9740
10172
  derivedFromNk: refundDerivedFromNk
@@ -9742,6 +10174,7 @@ async function swapUtxo(params, options) {
9742
10174
  };
9743
10175
  }
9744
10176
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
10177
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
9745
10178
  const totalInput = sumUtxoAmounts(inputUtxos);
9746
10179
  const change = totalInput - swapAmount;
9747
10180
  if (change < BigInt(0)) {
@@ -9750,16 +10183,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
9750
10183
  let changeUtxo;
9751
10184
  let changeNoteSalt;
9752
10185
  if (change > BigInt(0)) {
9753
- const myKeypair = inputUtxos[0].keypair;
9754
10186
  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
- }
10187
+ const changeNk = await requireWalletNk(options, "swapWithChange");
10188
+ const salt = randomChangeNoteSalt();
10189
+ changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
10190
+ changeNoteSalt = salt;
9763
10191
  }
9764
10192
  return swapUtxo(
9765
10193
  {
@@ -10082,7 +10510,7 @@ var RelayBatchAuthCoordinator = class {
10082
10510
  throw new Error("Every item of a batch must target the same program id.");
10083
10511
  }
10084
10512
  }
10085
- const nowSeconds = Math.floor(Date.now() / 1e3);
10513
+ const nowSeconds = relayNowSeconds();
10086
10514
  const preimages = waiting.map(
10087
10515
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10088
10516
  );
@@ -10520,7 +10948,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
10520
10948
  const cached = depositSecretsCache.get(key);
10521
10949
  if (cached) return cached;
10522
10950
  try {
10523
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
10951
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
10524
10952
  if (depositSecretsCache.size >= 4096) {
10525
10953
  const oldest = depositSecretsCache.keys().next();
10526
10954
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11103,6 +11531,7 @@ async function scanTransactions(opts) {
11103
11531
  } else {
11104
11532
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11105
11533
  const candidateKeys = [
11534
+ opts.ownerUtxoPublicKey,
11106
11535
  derived?.keypair.publicKey,
11107
11536
  opts.ownUtxoPublicKey,
11108
11537
  BigInt(0)
@@ -11156,6 +11585,7 @@ async function scanTransactions(opts) {
11156
11585
  try {
11157
11586
  const recoveredDeposit = await matchDepositNote({
11158
11587
  viewingKeyNk,
11588
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
11159
11589
  noteSalt: compactNote.noteSalt,
11160
11590
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
11161
11591
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -11190,7 +11620,8 @@ async function scanTransactions(opts) {
11190
11620
  mintAddress: address(asset.mint),
11191
11621
  outputIndex: 0,
11192
11622
  // v4 describes output 0, which is where change lands
11193
- outputCommitments: ixCtx.outputCommitments ?? []
11623
+ outputCommitments: ixCtx.outputCommitments ?? [],
11624
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
11194
11625
  });
11195
11626
  if (recoveredChange) {
11196
11627
  recoveredChangeNotes.push({
@@ -11300,6 +11731,17 @@ async function scanTransactions(opts) {
11300
11731
  runningByAsset.set(key, running);
11301
11732
  tx.runningBalance = running;
11302
11733
  }
11734
+ const legacyKeys = /* @__PURE__ */ new Map();
11735
+ for (const note of recoveredDepositNotes) {
11736
+ if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
11737
+ }
11738
+ for (const change of recoveredChangeNotes) {
11739
+ const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
11740
+ if (legacyPrivateKey !== void 0) {
11741
+ change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
11742
+ change.legacyExposed = true;
11743
+ }
11744
+ }
11303
11745
  return {
11304
11746
  transactions: txs,
11305
11747
  summary: {
@@ -11379,6 +11821,1563 @@ function formatComplianceCsv(report) {
11379
11821
  return header + rows;
11380
11822
  }
11381
11823
 
11824
+ // src/relay/note-index-format.ts
11825
+ import { sha256 as sha2565 } from "@noble/hashes/sha2";
11826
+ var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
11827
+ var NOTE_INDEX_FORMAT_VERSION = 1;
11828
+ var NOTE_INDEX_PAGE_SIZE = 1024;
11829
+ var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
11830
+ var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
11831
+ var NOTE_INDEX_HEADER_LEN = 68;
11832
+ var NOTE_INDEX_KIND_TX = 1;
11833
+ var NOTE_INDEX_KIND_DELIVERY = 2;
11834
+ var NOTE_INDEX_KIND_SWAP_REFUND = 3;
11835
+ var NOTE_SOURCE_NONE = 0;
11836
+ var NOTE_SOURCE_CARRIER = 2;
11837
+ var ITEM_HEADER_LEN = 3;
11838
+ var TX_FIXED_LEN = 263;
11839
+ var DELIVERY_BODY_LEN = 256;
11840
+ var SWAP_REFUND_BODY_LEN = 184;
11841
+ var MAX_UNKNOWN_BODY_LEN = 1024;
11842
+ var DELIVERY_ENVELOPE_LEN = 112;
11843
+ var SIGNATURE_LEN = 64;
11844
+ var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
11845
+ [25, 2],
11846
+ [57, 3],
11847
+ [98, 4]
11848
+ ]);
11849
+ var COMPLETE_FLAG = 1;
11850
+ var U64_MAX2 = (1n << 64n) - 1n;
11851
+ var U32_MAX = 4294967295;
11852
+ var MAX_LEAF_INDEX = (1n << 32n) - 1n;
11853
+ var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
11854
+ var NoteIndexFormatError = class extends Error {
11855
+ constructor(message) {
11856
+ super(`Note index format error: ${message}`);
11857
+ this.name = "NoteIndexFormatError";
11858
+ }
11859
+ };
11860
+ function isAllZero2(bytes) {
11861
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
11862
+ return true;
11863
+ }
11864
+ function bytesEqual(a, b) {
11865
+ if (a.length !== b.length) return false;
11866
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
11867
+ return true;
11868
+ }
11869
+ function checkLeafPair(commitment, leaf, label) {
11870
+ if (isAllZero2(commitment)) {
11871
+ if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
11872
+ return;
11873
+ }
11874
+ if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
11875
+ }
11876
+ var Reader = class {
11877
+ constructor(bytes, start, end) {
11878
+ this.bytes = bytes;
11879
+ this.end = end;
11880
+ this.offset = start;
11881
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11882
+ }
11883
+ take(len) {
11884
+ if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
11885
+ const at = this.offset;
11886
+ this.offset += len;
11887
+ return at;
11888
+ }
11889
+ u8() {
11890
+ return this.bytes[this.take(1)];
11891
+ }
11892
+ u32() {
11893
+ return this.view.getUint32(this.take(4), true);
11894
+ }
11895
+ u64() {
11896
+ return this.view.getBigUint64(this.take(8), true);
11897
+ }
11898
+ i64() {
11899
+ return this.view.getBigInt64(this.take(8), true);
11900
+ }
11901
+ raw(len) {
11902
+ const at = this.take(len);
11903
+ return this.bytes.slice(at, at + len);
11904
+ }
11905
+ get position() {
11906
+ return this.offset;
11907
+ }
11908
+ };
11909
+ function parseTx(r, bodyLen) {
11910
+ const mint = r.raw(32);
11911
+ const slot = r.u64();
11912
+ const blockPos = r.u32();
11913
+ const ixTag = r.u8();
11914
+ if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
11915
+ const publicAmount = r.i64();
11916
+ const nullifier0 = r.raw(32);
11917
+ const nullifier1 = r.raw(32);
11918
+ const comm0 = r.raw(32);
11919
+ const leaf0 = r.u64();
11920
+ const comm1 = r.raw(32);
11921
+ const leaf1 = r.u64();
11922
+ const noteSource = r.u8();
11923
+ if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
11924
+ const noteLen = r.u8();
11925
+ if (noteSource === NOTE_SOURCE_NONE) {
11926
+ if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
11927
+ } else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
11928
+ throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
11929
+ }
11930
+ if (bodyLen !== TX_FIXED_LEN + noteLen) {
11931
+ throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
11932
+ }
11933
+ const note = r.raw(noteLen);
11934
+ if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
11935
+ throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
11936
+ }
11937
+ const signature = r.raw(SIGNATURE_LEN);
11938
+ checkLeafPair(comm0, leaf0, "TX comm0");
11939
+ checkLeafPair(comm1, leaf1, "TX comm1");
11940
+ return {
11941
+ kind: 1,
11942
+ mint,
11943
+ slot,
11944
+ blockPos,
11945
+ ixTag,
11946
+ publicAmount,
11947
+ nullifier0,
11948
+ nullifier1,
11949
+ comm0,
11950
+ leaf0,
11951
+ comm1,
11952
+ leaf1,
11953
+ noteSource,
11954
+ note,
11955
+ signature
11956
+ };
11957
+ }
11958
+ function parseDelivery(r) {
11959
+ const mint = r.raw(32);
11960
+ const slot = r.u64();
11961
+ const commitment = r.raw(32);
11962
+ const leaf = r.u64();
11963
+ const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
11964
+ const signature = r.raw(SIGNATURE_LEN);
11965
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
11966
+ checkLeafPair(commitment, leaf, "DELIVERY");
11967
+ return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
11968
+ }
11969
+ function parseSwapRefund(r) {
11970
+ const mint = r.raw(32);
11971
+ if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
11972
+ const slot = r.u64();
11973
+ const commitment = r.raw(32);
11974
+ const leaf = r.u64();
11975
+ const amountAfterFee = r.u64();
11976
+ const nullifier0 = r.raw(32);
11977
+ const signature = r.raw(SIGNATURE_LEN);
11978
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
11979
+ checkLeafPair(commitment, leaf, "SWAP_REFUND");
11980
+ return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
11981
+ }
11982
+ function parseNoteIndexPage(bytes, expect) {
11983
+ if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
11984
+ if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
11985
+ throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
11986
+ }
11987
+ if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
11988
+ for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
11989
+ if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
11990
+ }
11991
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11992
+ const version = bytes[4];
11993
+ if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
11994
+ const flags = bytes[5];
11995
+ if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
11996
+ if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
11997
+ const epoch = view.getBigUint64(8, true);
11998
+ const page = view.getBigUint64(16, true);
11999
+ const firstSeq = view.getBigUint64(24, true);
12000
+ const count = view.getUint32(32, true);
12001
+ const prevChain = bytes.slice(36, 68);
12002
+ const complete = (flags & COMPLETE_FLAG) !== 0;
12003
+ if (expect) {
12004
+ if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
12005
+ if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
12006
+ }
12007
+ if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12008
+ if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
12009
+ if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
12010
+ throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
12011
+ }
12012
+ const items = [];
12013
+ const rawItems = [];
12014
+ let skippedUnknown = 0;
12015
+ let offset = NOTE_INDEX_HEADER_LEN;
12016
+ for (let i = 0; i < count; i++) {
12017
+ if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
12018
+ const kind = bytes[offset];
12019
+ const bodyLen = view.getUint16(offset + 1, true);
12020
+ const bodyStart = offset + ITEM_HEADER_LEN;
12021
+ const bodyEnd = bodyStart + bodyLen;
12022
+ if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12023
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12024
+ let item;
12025
+ switch (kind) {
12026
+ case NOTE_INDEX_KIND_TX:
12027
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12028
+ item = parseTx(r, bodyLen);
12029
+ break;
12030
+ case NOTE_INDEX_KIND_DELIVERY:
12031
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12032
+ item = parseDelivery(r);
12033
+ break;
12034
+ case NOTE_INDEX_KIND_SWAP_REFUND:
12035
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12036
+ item = parseSwapRefund(r);
12037
+ break;
12038
+ default:
12039
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12040
+ skippedUnknown++;
12041
+ offset = bodyEnd;
12042
+ continue;
12043
+ }
12044
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12045
+ items.push(item);
12046
+ rawItems.push(bytes.slice(offset, bodyEnd));
12047
+ offset = bodyEnd;
12048
+ }
12049
+ if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12050
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown };
12051
+ }
12052
+ function parseNoteIndexItem(raw) {
12053
+ if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
12054
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
12055
+ const kind = raw[0];
12056
+ const bodyLen = view.getUint16(1, true);
12057
+ if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
12058
+ const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
12059
+ let item;
12060
+ if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
12061
+ else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
12062
+ else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
12063
+ else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
12064
+ if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
12065
+ return item;
12066
+ }
12067
+ function computeNoteIndexChain(prevChain, pageBytes) {
12068
+ if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
12069
+ if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12070
+ const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
12071
+ const input = new Uint8Array(32 + items.length);
12072
+ input.set(prevChain);
12073
+ input.set(items, 32);
12074
+ return sha2565(input);
12075
+ }
12076
+ var Writer = class {
12077
+ constructor() {
12078
+ this.chunks = [];
12079
+ this.length = 0;
12080
+ }
12081
+ push(bytes) {
12082
+ this.chunks.push(bytes);
12083
+ this.length += bytes.length;
12084
+ }
12085
+ u8(v) {
12086
+ if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
12087
+ this.push(Uint8Array.of(v));
12088
+ }
12089
+ u16(v) {
12090
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
12091
+ const b = new Uint8Array(2);
12092
+ new DataView(b.buffer).setUint16(0, v, true);
12093
+ this.push(b);
12094
+ }
12095
+ u32(v) {
12096
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
12097
+ const b = new Uint8Array(4);
12098
+ new DataView(b.buffer).setUint32(0, v, true);
12099
+ this.push(b);
12100
+ }
12101
+ u64(v) {
12102
+ if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
12103
+ const b = new Uint8Array(8);
12104
+ new DataView(b.buffer).setBigUint64(0, v, true);
12105
+ this.push(b);
12106
+ }
12107
+ i64(v) {
12108
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
12109
+ const b = new Uint8Array(8);
12110
+ new DataView(b.buffer).setBigInt64(0, v, true);
12111
+ this.push(b);
12112
+ }
12113
+ fixed(bytes, len, label) {
12114
+ if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
12115
+ this.push(bytes);
12116
+ }
12117
+ finish() {
12118
+ const out = new Uint8Array(this.length);
12119
+ let off = 0;
12120
+ for (const c of this.chunks) {
12121
+ out.set(c, off);
12122
+ off += c.length;
12123
+ }
12124
+ return out;
12125
+ }
12126
+ };
12127
+ function encodeItemBody(item) {
12128
+ const w = new Writer();
12129
+ switch (item.kind) {
12130
+ case NOTE_INDEX_KIND_TX: {
12131
+ w.fixed(item.mint, 32, "mint");
12132
+ w.u64(item.slot);
12133
+ w.u32(item.blockPos);
12134
+ w.u8(item.ixTag);
12135
+ w.i64(item.publicAmount);
12136
+ w.fixed(item.nullifier0, 32, "nullifier0");
12137
+ w.fixed(item.nullifier1, 32, "nullifier1");
12138
+ w.fixed(item.comm0, 32, "comm0");
12139
+ w.u64(item.leaf0);
12140
+ w.fixed(item.comm1, 32, "comm1");
12141
+ w.u64(item.leaf1);
12142
+ w.u8(item.noteSource);
12143
+ const noteLen = item.note.length;
12144
+ if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
12145
+ throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
12146
+ }
12147
+ w.u8(noteLen);
12148
+ w.push(item.note);
12149
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12150
+ break;
12151
+ }
12152
+ case NOTE_INDEX_KIND_DELIVERY:
12153
+ w.fixed(item.mint, 32, "mint");
12154
+ w.u64(item.slot);
12155
+ w.fixed(item.commitment, 32, "commitment");
12156
+ w.u64(item.leaf);
12157
+ w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
12158
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12159
+ break;
12160
+ case NOTE_INDEX_KIND_SWAP_REFUND:
12161
+ w.fixed(item.mint, 32, "mint");
12162
+ w.u64(item.slot);
12163
+ w.fixed(item.commitment, 32, "commitment");
12164
+ w.u64(item.leaf);
12165
+ w.u64(item.amountAfterFee);
12166
+ w.fixed(item.nullifier0, 32, "nullifier0");
12167
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12168
+ break;
12169
+ default:
12170
+ throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
12171
+ }
12172
+ return w.finish();
12173
+ }
12174
+ function encodeNoteIndexItem(item) {
12175
+ const body = encodeItemBody(item);
12176
+ const w = new Writer();
12177
+ w.u8(item.kind);
12178
+ w.u16(body.length);
12179
+ w.push(body);
12180
+ return w.finish();
12181
+ }
12182
+ function encodeNoteIndexPage(params) {
12183
+ const items = params.items ?? [];
12184
+ if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12185
+ const w = new Writer();
12186
+ w.push(NOTE_INDEX_MAGIC);
12187
+ w.u8(NOTE_INDEX_FORMAT_VERSION);
12188
+ w.u8(params.complete ? COMPLETE_FLAG : 0);
12189
+ w.u16(0);
12190
+ w.u64(BigInt(params.epoch));
12191
+ w.u64(BigInt(params.page));
12192
+ w.u64(BigInt(params.firstSeq));
12193
+ w.u32(items.length);
12194
+ w.fixed(params.prevChain, 32, "prevChain");
12195
+ for (const item of items) w.push(encodeNoteIndexItem(item));
12196
+ return w.finish();
12197
+ }
12198
+
12199
+ // src/relay/note-index-client.ts
12200
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
12201
+ var DEFAULT_MAX_RETRIES2 = 3;
12202
+ var RETRY_BASE_DELAY_MS = 500;
12203
+ var U64_MAX3 = (1n << 64n) - 1n;
12204
+ function joinPath(relayUrl, path) {
12205
+ const url = new URL(relayUrl);
12206
+ url.pathname = url.pathname.replace(/\/$/, "") + path;
12207
+ return url;
12208
+ }
12209
+ function abortError() {
12210
+ const error = new Error("Note index request aborted");
12211
+ error.name = "AbortError";
12212
+ return error;
12213
+ }
12214
+ function sleep4(ms, signal) {
12215
+ return new Promise((resolve, reject) => {
12216
+ if (signal?.aborted) return reject(abortError());
12217
+ const timer = setTimeout(() => {
12218
+ signal?.removeEventListener("abort", onAbort);
12219
+ resolve();
12220
+ }, ms);
12221
+ const onAbort = () => {
12222
+ clearTimeout(timer);
12223
+ reject(abortError());
12224
+ };
12225
+ signal?.addEventListener("abort", onAbort, { once: true });
12226
+ });
12227
+ }
12228
+ var RetryableStatusError = class extends Error {
12229
+ };
12230
+ var HttpStatusError = class extends Error {
12231
+ constructor(status, message) {
12232
+ super(message);
12233
+ this.status = status;
12234
+ this.name = "HttpStatusError";
12235
+ }
12236
+ };
12237
+ async function requestWithRetry(url, options, read) {
12238
+ assertAllowedRelayOrigin(url);
12239
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
12240
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
12241
+ let lastError;
12242
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
12243
+ if (options.signal?.aborted) throw abortError();
12244
+ const controller = new AbortController();
12245
+ const onAbort = () => controller.abort();
12246
+ options.signal?.addEventListener("abort", onAbort, { once: true });
12247
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
12248
+ try {
12249
+ const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
12250
+ if (response.status === 429 || response.status >= 500) {
12251
+ throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
12252
+ }
12253
+ return await read(response, controller.signal);
12254
+ } catch (error) {
12255
+ if (options.signal?.aborted) throw abortError();
12256
+ const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
12257
+ if (!retryable || attempt >= maxRetries) throw error;
12258
+ lastError = error;
12259
+ await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
12260
+ } finally {
12261
+ clearTimeout(timer);
12262
+ options.signal?.removeEventListener("abort", onAbort);
12263
+ }
12264
+ }
12265
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
12266
+ }
12267
+ async function readBoundedBody(response, maxBytes) {
12268
+ const declaredHeader = response.headers?.get?.("content-length") ?? null;
12269
+ const declared = declaredHeader === null ? NaN : Number(declaredHeader);
12270
+ if (Number.isFinite(declared) && declared > maxBytes) {
12271
+ throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
12272
+ }
12273
+ const reader = response.body?.getReader?.();
12274
+ if (!reader) {
12275
+ const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
12276
+ if (!Number.isSafeInteger(declared) || declared < 0) {
12277
+ throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
12278
+ }
12279
+ if (encoding !== "" && encoding !== "identity") {
12280
+ throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
12281
+ }
12282
+ const buffer = new Uint8Array(await response.arrayBuffer());
12283
+ if (buffer.length > maxBytes || buffer.length !== declared) {
12284
+ throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
12285
+ }
12286
+ return buffer;
12287
+ }
12288
+ const chunks = [];
12289
+ let total = 0;
12290
+ for (; ; ) {
12291
+ const { done, value } = await reader.read();
12292
+ if (done) break;
12293
+ total += value.length;
12294
+ if (total > maxBytes) {
12295
+ await reader.cancel().catch(() => void 0);
12296
+ throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
12297
+ }
12298
+ chunks.push(value);
12299
+ }
12300
+ const out = new Uint8Array(total);
12301
+ let off = 0;
12302
+ for (const c of chunks) {
12303
+ out.set(c, off);
12304
+ off += c.length;
12305
+ }
12306
+ return out;
12307
+ }
12308
+ function isNonNegativeSafeInteger(value) {
12309
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12310
+ }
12311
+ async function fetchNoteIndexHead(relayUrl, options = {}) {
12312
+ const url = joinPath(relayUrl, "/note-index/v1/head").toString();
12313
+ const raw = await requestWithRetry(url, options, async (response) => {
12314
+ if (!response.ok) {
12315
+ throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
12316
+ }
12317
+ const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
12318
+ try {
12319
+ return JSON.parse(text);
12320
+ } catch {
12321
+ throw new NoteIndexFormatError("head is not JSON");
12322
+ }
12323
+ });
12324
+ if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
12325
+ if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
12326
+ throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
12327
+ }
12328
+ if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
12329
+ throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
12330
+ }
12331
+ if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
12332
+ throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
12333
+ }
12334
+ if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
12335
+ throw new NoteIndexFormatError(
12336
+ `complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
12337
+ );
12338
+ }
12339
+ if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
12340
+ throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
12341
+ }
12342
+ if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
12343
+ throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
12344
+ }
12345
+ return {
12346
+ format: 1,
12347
+ epoch: BigInt(raw.epoch),
12348
+ pageSize: NOTE_INDEX_PAGE_SIZE,
12349
+ watermark: raw.watermark,
12350
+ completePages: raw.complete_pages,
12351
+ chainTip: raw.chain_tip.toLowerCase()
12352
+ };
12353
+ }
12354
+ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
12355
+ if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
12356
+ if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
12357
+ const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
12358
+ return requestWithRetry(url, options, async (response) => {
12359
+ if (!response.ok) {
12360
+ throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
12361
+ }
12362
+ return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
12363
+ });
12364
+ }
12365
+
12366
+ // src/scanning/note-index.ts
12367
+ import _bs584 from "bs58";
12368
+ import { sha256 as sha2566 } from "@noble/hashes/sha2";
12369
+ var bs584 = _bs584.default || _bs584;
12370
+ var CURSOR_VERSION = 2;
12371
+ var DEFAULT_CONCURRENCY = 6;
12372
+ var MAX_CONCURRENCY = 32;
12373
+ var ITEM_BATCH = 64;
12374
+ var CURSOR_PAGE_ALIGN = 8;
12375
+ var MAX_PERSISTED_PENDING_LEAVES = 4096;
12376
+ var MAX_CARRIED_PENDING = 256;
12377
+ var MAX_REJECTED_IDS = 1024;
12378
+ var LEAF_WINDOW = 512;
12379
+ var MAX_OVERRIDES = 256;
12380
+ var MAX_CURSOR_OWN_ITEMS = 65536;
12381
+ var MAX_CURSOR_KEYS = 131072;
12382
+ var MAX_CURSOR_POOLS = 256;
12383
+ var MAX_CURSOR_PAGE = 2 ** 32;
12384
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
12385
+ var ZERO_CHAIN = "00".repeat(32);
12386
+ var U64_MAX4 = (1n << 64n) - 1n;
12387
+ var NoteIndexHeadBehindError = class extends Error {
12388
+ constructor(cursorWatermark, headWatermark) {
12389
+ super(
12390
+ `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`
12391
+ );
12392
+ this.cursorWatermark = cursorWatermark;
12393
+ this.headWatermark = headWatermark;
12394
+ this.retryable = true;
12395
+ this.name = "NoteIndexHeadBehindError";
12396
+ }
12397
+ };
12398
+ var FullPassSignal = class {
12399
+ constructor(reason) {
12400
+ this.reason = reason;
12401
+ }
12402
+ };
12403
+ function abortError2() {
12404
+ const error = new Error("recoverNotesFromIndex aborted");
12405
+ error.name = "AbortError";
12406
+ return error;
12407
+ }
12408
+ function bytesToBigint2(bytes) {
12409
+ let v = 0n;
12410
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
12411
+ return v;
12412
+ }
12413
+ function toHex2(bytes) {
12414
+ let s = "";
12415
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
12416
+ return s;
12417
+ }
12418
+ function fromHex(hex) {
12419
+ return Uint8Array.from(Buffer.from(hex, "hex"));
12420
+ }
12421
+ function hex32(v) {
12422
+ return v.toString(16).padStart(64, "0");
12423
+ }
12424
+ function isAllZero3(bytes) {
12425
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12426
+ return true;
12427
+ }
12428
+ function floorAlign(page) {
12429
+ return page - page % CURSOR_PAGE_ALIGN;
12430
+ }
12431
+ function verifiedKey(mint, leaf, commitment) {
12432
+ return `${mint}:${leaf}:${hex32(commitment)}`;
12433
+ }
12434
+ function itemIdentity(raw) {
12435
+ return toHex2(sha2566(raw).subarray(0, 16));
12436
+ }
12437
+ var LeafBuffer = class {
12438
+ constructor() {
12439
+ this.bytes = new Uint8Array(32 * 1024);
12440
+ this.view = new DataView(this.bytes.buffer);
12441
+ this.count = 0;
12442
+ }
12443
+ get length() {
12444
+ return this.count;
12445
+ }
12446
+ push(values) {
12447
+ const need = (this.count + values.length) * 32;
12448
+ if (need > this.bytes.length) {
12449
+ let size = this.bytes.length;
12450
+ while (size < need) size *= 2;
12451
+ const next = new Uint8Array(size);
12452
+ next.set(this.bytes.subarray(0, this.count * 32));
12453
+ this.bytes = next;
12454
+ this.view = new DataView(next.buffer);
12455
+ }
12456
+ for (const v of values) {
12457
+ const o = this.count * 32;
12458
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
12459
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
12460
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
12461
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
12462
+ this.count++;
12463
+ }
12464
+ }
12465
+ get(i) {
12466
+ if (i < 0 || i >= this.count) return void 0;
12467
+ const o = i * 32;
12468
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
12469
+ }
12470
+ };
12471
+ async function trialItem(item, trial) {
12472
+ if (item.kind === 1) {
12473
+ if (item.note.length === 0) return null;
12474
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
12475
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
12476
+ return note ? { note } : null;
12477
+ }
12478
+ if (item.kind === 2) {
12479
+ const delivery = await trial.open(item.envelope);
12480
+ return delivery ? { delivery } : null;
12481
+ }
12482
+ if (item.amountAfterFee === 0n) return null;
12483
+ const refund = await matchSwapRefundLeaf({
12484
+ viewingKeyNk: trial.nk,
12485
+ inputNullifier: item.nullifier0,
12486
+ amountAfterFee: item.amountAfterFee,
12487
+ commitment: item.commitment,
12488
+ ownerUtxoKeypair: trial.owner
12489
+ });
12490
+ return refund ? { refund } : null;
12491
+ }
12492
+ function txOutputs(item) {
12493
+ const out = [toHex2(item.comm0)];
12494
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
12495
+ return out;
12496
+ }
12497
+ function leafOfTxOutput(item, commitment) {
12498
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint2(item.comm0)) return Number(item.leaf0);
12499
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
12500
+ return null;
12501
+ }
12502
+ async function matchOwnItems(own, trial, onReject) {
12503
+ const { nk, owner } = trial;
12504
+ const candidates = [];
12505
+ const claimed = /* @__PURE__ */ new Set();
12506
+ const byNullifier = /* @__PURE__ */ new Map();
12507
+ const legacyKeys = /* @__PURE__ */ new Map();
12508
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
12509
+ const spendsOf = /* @__PURE__ */ new Map();
12510
+ const byOutKey = /* @__PURE__ */ new Map();
12511
+ const index = (map, key, o) => {
12512
+ const list = map.get(key);
12513
+ if (list) list.push(o);
12514
+ else map.set(key, [o]);
12515
+ };
12516
+ for (const o of ownTxs) {
12517
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
12518
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
12519
+ }
12520
+ const queue = [];
12521
+ const queued = /* @__PURE__ */ new Set();
12522
+ const enqueue = (o) => {
12523
+ if (queued.has(o)) return;
12524
+ queued.add(o);
12525
+ queue.push(o);
12526
+ };
12527
+ const add = async (c) => {
12528
+ const nullifier = hex32(
12529
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
12530
+ );
12531
+ const full = { ...c, nullifier };
12532
+ candidates.push(full);
12533
+ if (!byNullifier.has(nullifier)) {
12534
+ byNullifier.set(nullifier, full);
12535
+ for (const o of spendsOf.get(nullifier) ?? []) enqueue(o);
12536
+ }
12537
+ if (full.atRisk && !legacyKeys.has(full.keypair.publicKey)) {
12538
+ legacyKeys.set(full.keypair.publicKey, full.keypair);
12539
+ for (const o of byOutKey.get(full.keypair.publicKey) ?? []) enqueue(o);
12540
+ }
12541
+ };
12542
+ const base = (o) => ({ signature: o.item.signature, page: o.page, seq: o.seq });
12543
+ const tryDeposit = async (o, item, amount) => {
12544
+ const note = o.note;
12545
+ const mint = addressFromBytes(item.mint);
12546
+ const deposit = await matchDepositNote({
12547
+ viewingKeyNk: nk,
12548
+ noteSalt: note.noteSalt,
12549
+ amount,
12550
+ mintAddress: mint,
12551
+ outputCommitments: txOutputs(item),
12552
+ ownerUtxoKeypair: owner
12553
+ });
12554
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
12555
+ if (!deposit || leaf === null) return false;
12556
+ await add({
12557
+ kind: "deposit",
12558
+ atRisk: deposit.legacyExposed,
12559
+ amount: deposit.amount,
12560
+ blinding: deposit.blinding,
12561
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
12562
+ mint,
12563
+ commitment: deposit.commitment,
12564
+ leaf,
12565
+ ...base(o)
12566
+ });
12567
+ return true;
12568
+ };
12569
+ const tryChange0 = async (o, item, keypair, atRisk) => {
12570
+ const note = o.note;
12571
+ const mint = addressFromBytes(item.mint);
12572
+ const change = await matchChangeNote({
12573
+ viewingKeyNk: nk,
12574
+ noteSalt: note.noteSalt,
12575
+ amount: note.outAmount0,
12576
+ keypair,
12577
+ mintAddress: mint,
12578
+ outputIndex: 0,
12579
+ outputCommitments: [toHex2(item.comm0)],
12580
+ ownerUtxoPublicKey: owner.publicKey
12581
+ });
12582
+ if (!change) return false;
12583
+ await add({
12584
+ kind: "change",
12585
+ atRisk,
12586
+ amount: change.amount,
12587
+ blinding: change.blinding,
12588
+ keypair,
12589
+ mint,
12590
+ commitment: change.commitment,
12591
+ leaf: Number(item.leaf0),
12592
+ ...base(o)
12593
+ });
12594
+ return true;
12595
+ };
12596
+ for (const o of own) {
12597
+ const item = o.item;
12598
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
12599
+ const note = o.note;
12600
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12601
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
12602
+ }
12603
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
12604
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
12605
+ }
12606
+ } else if (item.kind === 2 && o.delivery) {
12607
+ const mint = addressFromBytes(item.mint);
12608
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
12609
+ onReject(o);
12610
+ continue;
12611
+ }
12612
+ const commitment = await computeCommitment({
12613
+ amount: o.delivery.amount,
12614
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
12615
+ blinding: o.delivery.blinding,
12616
+ mintAddress: mint
12617
+ });
12618
+ if (commitment !== bytesToBigint2(item.commitment)) {
12619
+ onReject(o);
12620
+ continue;
12621
+ }
12622
+ await add({
12623
+ kind: "received",
12624
+ atRisk: false,
12625
+ amount: o.delivery.amount,
12626
+ blinding: o.delivery.blinding,
12627
+ keypair: owner,
12628
+ mint,
12629
+ commitment,
12630
+ leaf: Number(item.leaf),
12631
+ ...base(o)
12632
+ });
12633
+ } else if (item.kind === 3 && o.refund) {
12634
+ await add({
12635
+ kind: "swap_refund",
12636
+ atRisk: o.refund.legacyExposed,
12637
+ amount: o.refund.amount,
12638
+ blinding: o.refund.blinding,
12639
+ keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
12640
+ mint: NATIVE_SOL_MINT,
12641
+ commitment: o.refund.commitment,
12642
+ leaf: Number(item.leaf),
12643
+ ...base(o)
12644
+ });
12645
+ }
12646
+ }
12647
+ const processTx = async (o) => {
12648
+ const item = o.item;
12649
+ const note = o.note;
12650
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
12651
+ const legacy = legacyKeys.get(note.outPubkey0);
12652
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
12653
+ }
12654
+ const mint = addressFromBytes(item.mint);
12655
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
12656
+ if (inputs.length === 0) return;
12657
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
12658
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
12659
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
12660
+ if (out1 > 0n) {
12661
+ const blinding = deriveChangeNoteBlinding(nk, note.noteSalt, 1);
12662
+ const owners = [{ keypair: owner, atRisk: false }];
12663
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
12664
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
12665
+ for (const { keypair, atRisk } of owners) {
12666
+ const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
12667
+ if (commitment !== bytesToBigint2(item.comm1)) continue;
12668
+ claimed.add(`${o.seq}:1`);
12669
+ await add({ kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1), ...base(o) });
12670
+ break;
12671
+ }
12672
+ }
12673
+ }
12674
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12675
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
12676
+ }
12677
+ };
12678
+ for (const o of ownTxs) enqueue(o);
12679
+ for (let i = 0; i < queue.length; i++) {
12680
+ const o = queue[i];
12681
+ queued.delete(o);
12682
+ await processTx(o);
12683
+ }
12684
+ return candidates;
12685
+ }
12686
+ async function replayStream(start, pages, overrides, chain, targetPage) {
12687
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
12688
+ const startN = frontier.nextIndex;
12689
+ const pending = new Map(start.pending);
12690
+ const flushed = new LeafBuffer();
12691
+ const corrections = /* @__PURE__ */ new Map();
12692
+ let conflicts = 0;
12693
+ let verifiedPrefix = 0;
12694
+ let mismatch = false;
12695
+ const checks = [];
12696
+ const setBits = [];
12697
+ if (chain && chain.nextIndex > 0) {
12698
+ const last = chain.nextIndex - 1;
12699
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
12700
+ for (const l of setBits) {
12701
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
12702
+ if (at >= startN) checks.push({ at, level: l });
12703
+ }
12704
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
12705
+ checks.sort((a, b) => a.at - b.at);
12706
+ }
12707
+ let nextCheck = 0;
12708
+ const runChecks = () => {
12709
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
12710
+ const { at, level } = checks[nextCheck++];
12711
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
12712
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
12713
+ else mismatch = true;
12714
+ }
12715
+ };
12716
+ const append = (values) => {
12717
+ let i = 0;
12718
+ while (i < values.length) {
12719
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
12720
+ const take = Math.min(values.length - i, room);
12721
+ if (take > 0) {
12722
+ const part = values.slice(i, i + take);
12723
+ frontier.append(part);
12724
+ flushed.push(part);
12725
+ i += take;
12726
+ }
12727
+ runChecks();
12728
+ }
12729
+ };
12730
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
12731
+ const flush = () => {
12732
+ const batch = [];
12733
+ let next = frontier.nextIndex;
12734
+ while (pending.has(next)) {
12735
+ batch.push(pending.get(next));
12736
+ pending.delete(next);
12737
+ next++;
12738
+ }
12739
+ if (batch.length > 0) append(batch);
12740
+ };
12741
+ let snapshot = null;
12742
+ let taken = false;
12743
+ const takeSnapshot = () => {
12744
+ taken = true;
12745
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
12746
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
12747
+ };
12748
+ runChecks();
12749
+ flush();
12750
+ for (const { page, entries } of pages) {
12751
+ if (!taken && page >= targetPage) takeSnapshot();
12752
+ for (const e of entries) {
12753
+ if (e.leaf < startN) continue;
12754
+ const prior = valueAt(e.leaf);
12755
+ if (prior !== void 0) {
12756
+ if (prior !== e.commitment) {
12757
+ conflicts++;
12758
+ corrections.set(e.leaf, e.commitment);
12759
+ }
12760
+ continue;
12761
+ }
12762
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
12763
+ }
12764
+ flush();
12765
+ }
12766
+ if (!taken) takeSnapshot();
12767
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
12768
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
12769
+ }
12770
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
12771
+ }
12772
+ var HEX64 = /^[0-9a-f]{64}$/;
12773
+ var HEX32 = /^[0-9a-f]{32}$/;
12774
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
12775
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
12776
+ function isRecord(v) {
12777
+ return typeof v === "object" && v !== null && !Array.isArray(v);
12778
+ }
12779
+ function isIntIn(v, min, max) {
12780
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
12781
+ }
12782
+ function isBoundedArray(v, max) {
12783
+ return Array.isArray(v) && v.length <= max;
12784
+ }
12785
+ function emptyStartTree() {
12786
+ return {
12787
+ frontier: null,
12788
+ nextIndex: 0,
12789
+ pending: /* @__PURE__ */ new Map(),
12790
+ window: [],
12791
+ windowStart: 0,
12792
+ verified: 0,
12793
+ overrides: /* @__PURE__ */ new Map(),
12794
+ mismatch: false,
12795
+ hiBefore: -1
12796
+ };
12797
+ }
12798
+ async function parseCursor(cursor, poolMints) {
12799
+ try {
12800
+ if (!isRecord(cursor)) return "not an object";
12801
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
12802
+ const c = cursor;
12803
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
12804
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
12805
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
12806
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
12807
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
12808
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
12809
+ const trees = /* @__PURE__ */ new Map();
12810
+ for (const mint of poolMints) {
12811
+ const t = c.trees[mint];
12812
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
12813
+ const tree = t;
12814
+ if (!isRecord(tree.frontier)) return "bad frontier";
12815
+ let frontier;
12816
+ try {
12817
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
12818
+ } catch {
12819
+ return "bad frontier";
12820
+ }
12821
+ const nextIndex = frontier.nextIndex;
12822
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
12823
+ const pending = /* @__PURE__ */ new Map();
12824
+ let hiBefore = nextIndex - 1;
12825
+ for (const entry of tree.pending) {
12826
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
12827
+ const [leaf, value] = entry;
12828
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
12829
+ return "bad pending leaves";
12830
+ }
12831
+ pending.set(leaf, BigInt("0x" + value));
12832
+ hiBefore = Math.max(hiBefore, leaf);
12833
+ }
12834
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
12835
+ const windowLen = tree.window.length / 64;
12836
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
12837
+ const window2 = [];
12838
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
12839
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
12840
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
12841
+ const overrides = /* @__PURE__ */ new Map();
12842
+ for (const entry of tree.overrides) {
12843
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
12844
+ const [leaf, value] = entry;
12845
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
12846
+ overrides.set(leaf, BigInt("0x" + value));
12847
+ }
12848
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
12849
+ trees.set(mint, {
12850
+ frontier: frontier.toState(),
12851
+ nextIndex,
12852
+ pending,
12853
+ window: window2,
12854
+ windowStart: nextIndex - windowLen,
12855
+ verified: tree.verified,
12856
+ overrides,
12857
+ mismatch: tree.mismatch,
12858
+ hiBefore
12859
+ });
12860
+ }
12861
+ const own = c.own;
12862
+ if (!isRecord(own)) return "bad own state";
12863
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
12864
+ const items = [];
12865
+ const seqs = /* @__PURE__ */ new Set();
12866
+ for (const entry of own.items) {
12867
+ if (!isRecord(entry)) return "bad own items";
12868
+ const { seq, item } = entry;
12869
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
12870
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
12871
+ seqs.add(seq);
12872
+ const raw = fromHex(item);
12873
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
12874
+ }
12875
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
12876
+ return "bad verified notes";
12877
+ }
12878
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
12879
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
12880
+ const pendingLeaves = /* @__PURE__ */ new Map();
12881
+ for (const entry of own.pendingLeaves) {
12882
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
12883
+ const [mint, leaf, value] = entry;
12884
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
12885
+ return "bad pending notes";
12886
+ }
12887
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
12888
+ }
12889
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
12890
+ return "bad rejected set";
12891
+ }
12892
+ return {
12893
+ raw: c,
12894
+ trees,
12895
+ items,
12896
+ verified: new Set(own.verified),
12897
+ spent: new Set(own.spent),
12898
+ pendingLeaves,
12899
+ rejected: own.rejected
12900
+ };
12901
+ } catch {
12902
+ return "unreadable state";
12903
+ }
12904
+ }
12905
+ async function recoverNotesFromIndex(params) {
12906
+ const startedAt = Date.now();
12907
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
12908
+ assertAllowedRelayOrigin(relayUrl);
12909
+ assertAllowedRpcConnection(connection);
12910
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
12911
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
12912
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
12913
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
12914
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
12915
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
12916
+ }
12917
+ if (params.signal?.aborted) throw abortError2();
12918
+ const stats = {
12919
+ pages: 0,
12920
+ items: 0,
12921
+ bytes: 0,
12922
+ rpcCalls: 0,
12923
+ ms: 0,
12924
+ dropped: 0,
12925
+ decrypted: 0,
12926
+ candidates: 0,
12927
+ spent: 0,
12928
+ conflicts: 0,
12929
+ pendingDropped: 0
12930
+ };
12931
+ const rpc = new Proxy(connection, {
12932
+ get(target, prop, receiver) {
12933
+ const value = Reflect.get(target, prop, receiver);
12934
+ if (typeof value !== "function") return value;
12935
+ return (...args) => {
12936
+ const pending = value.apply(target, args);
12937
+ if (pending && typeof pending.send === "function") {
12938
+ const send = pending.send.bind(pending);
12939
+ return {
12940
+ ...pending,
12941
+ send: (...sendArgs) => {
12942
+ stats.rpcCalls++;
12943
+ return send(...sendArgs);
12944
+ }
12945
+ };
12946
+ }
12947
+ return pending;
12948
+ };
12949
+ }
12950
+ });
12951
+ const trial = {
12952
+ nk: viewingKeyNk,
12953
+ owner,
12954
+ decrypt: await createCompactChainNoteDecryptor(viewingKeyNk),
12955
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(viewingKeyNk).privateKey)
12956
+ };
12957
+ const poolMints = Array.from(new Set(params.poolMints));
12958
+ const warnings = [];
12959
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
12960
+ let cursor;
12961
+ if (params.cursor !== void 0) {
12962
+ const checked = await parseCursor(params.cursor, poolMints);
12963
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
12964
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
12965
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
12966
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
12967
+ } else cursor = checked;
12968
+ }
12969
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
12970
+ let treeRead;
12971
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
12972
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
12973
+ return poolMints.map((_, i) => {
12974
+ const account = accounts[i];
12975
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
12976
+ return account && parsed ? { ...parsed, data: account.data } : null;
12977
+ });
12978
+ })());
12979
+ const ctx = { params, head, trial, stats, poolMints, warnings, readTrees };
12980
+ let outcome = await runOnce(ctx, cursor);
12981
+ if (outcome instanceof FullPassSignal) {
12982
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
12983
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
12984
+ outcome = await runOnce(ctx, void 0);
12985
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
12986
+ }
12987
+ stats.ms = Date.now() - startedAt;
12988
+ return { ...outcome, stats, warnings };
12989
+ }
12990
+ async function runOnce(ctx, cursor) {
12991
+ const { params, head, trial, stats, poolMints } = ctx;
12992
+ const { relayUrl, onProgress } = params;
12993
+ const owner = trial.owner;
12994
+ const poolSet = new Set(poolMints);
12995
+ const startPage = cursor?.raw.page ?? 0;
12996
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
12997
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
12998
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
12999
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
13000
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
13001
+ const rejectedIds = new Set(cursor?.rejected ?? []);
13002
+ const controller = new AbortController();
13003
+ const onCallerAbort = () => controller.abort();
13004
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
13005
+ const signal = controller.signal;
13006
+ try {
13007
+ const pageData = /* @__PURE__ */ new Map();
13008
+ const ownItems = [];
13009
+ const nullifiers = /* @__PURE__ */ new Set();
13010
+ let fullPassReason = null;
13011
+ const lateReference = (mint, leaf, value, seq) => {
13012
+ if (!cursor || seq < fullPassSeq) return null;
13013
+ const t = startTrees.get(mint);
13014
+ if (leaf < t.nextIndex) {
13015
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
13016
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
13017
+ return null;
13018
+ }
13019
+ const held = t.pending.get(leaf);
13020
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
13021
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
13022
+ return null;
13023
+ };
13024
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
13025
+ const waiting = /* @__PURE__ */ new Map();
13026
+ let chainNext = startPage;
13027
+ let chainError = null;
13028
+ let wakers = [];
13029
+ const wakeAll = () => {
13030
+ const w = wakers;
13031
+ wakers = [];
13032
+ for (const f of w) f();
13033
+ };
13034
+ signal.addEventListener("abort", wakeAll);
13035
+ const advanceChain = () => {
13036
+ while (!chainError && waiting.has(chainNext)) {
13037
+ const w = waiting.get(chainNext);
13038
+ waiting.delete(chainNext);
13039
+ const expected = chainAt.get(chainNext);
13040
+ if (w.prevChain !== expected) {
13041
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
13042
+ controller.abort();
13043
+ return;
13044
+ }
13045
+ if (!w.complete) break;
13046
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
13047
+ chainNext++;
13048
+ }
13049
+ wakeAll();
13050
+ };
13051
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
13052
+ const lookahead = 2 * workerCount + 2;
13053
+ let nextToFetch = startPage;
13054
+ let pagesDone = 0;
13055
+ const worker = async () => {
13056
+ for (; ; ) {
13057
+ if (signal.aborted) throw abortError2();
13058
+ const pageNo = nextToFetch++;
13059
+ if (pageNo >= pagesTotal) return;
13060
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
13061
+ if (signal.aborted) throw abortError2();
13062
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13063
+ stats.bytes += bytes.length;
13064
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
13065
+ if (pageNo < head.completePages && !page2.complete) {
13066
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13067
+ }
13068
+ stats.pages++;
13069
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13070
+ advanceChain();
13071
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
13072
+ const late = (reason) => {
13073
+ if (reason && !fullPassReason) {
13074
+ fullPassReason = reason;
13075
+ controller.abort();
13076
+ }
13077
+ };
13078
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
13079
+ if (isAllZero3(commitment)) return;
13080
+ const mint = addressFromBytes(mintBytes);
13081
+ if (!poolSet.has(mint)) return;
13082
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint2(commitment) };
13083
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
13084
+ const list = data.leaves.get(mint);
13085
+ if (list) list.push(entry);
13086
+ else data.leaves.set(mint, [entry]);
13087
+ };
13088
+ page2.items.forEach((item, i) => {
13089
+ const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
13090
+ if (item.kind === 1) {
13091
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
13092
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
13093
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
13094
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
13095
+ } else if (item.kind === 3) {
13096
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
13097
+ } else {
13098
+ const mint = addressFromBytes(item.mint);
13099
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
13100
+ }
13101
+ });
13102
+ if (signal.aborted) throw abortError2();
13103
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
13104
+ if (signal.aborted) throw abortError2();
13105
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
13106
+ const opened = await Promise.all(batch.map((item) => trialItem(item, trial)));
13107
+ opened.forEach((o, k) => {
13108
+ if (!o) return;
13109
+ stats.decrypted++;
13110
+ const raw = page2.rawItems[i + k];
13111
+ const id = itemIdentity(raw);
13112
+ if (rejectedIds.has(id)) {
13113
+ stats.dropped++;
13114
+ return;
13115
+ }
13116
+ ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o });
13117
+ });
13118
+ stats.items += batch.length;
13119
+ }
13120
+ pageData.set(pageNo, data);
13121
+ pagesDone++;
13122
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
13123
+ }
13124
+ };
13125
+ const workers = Array.from(
13126
+ { length: workerCount },
13127
+ () => worker().catch((error) => {
13128
+ controller.abort();
13129
+ throw error;
13130
+ })
13131
+ );
13132
+ const settled = await Promise.allSettled(workers);
13133
+ signal.removeEventListener("abort", wakeAll);
13134
+ if (params.signal?.aborted) throw abortError2();
13135
+ const lateReason = fullPassReason;
13136
+ if (lateReason) return new FullPassSignal(lateReason);
13137
+ const chainFailure = chainError;
13138
+ if (chainFailure) {
13139
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
13140
+ throw chainFailure;
13141
+ }
13142
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
13143
+ if (failure) throw failure.reason;
13144
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
13145
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
13146
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
13147
+ }
13148
+ for (const entry of cursor?.items ?? []) {
13149
+ const o = await trialItem(entry.item, trial);
13150
+ if (!o) continue;
13151
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
13152
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o });
13153
+ if (entry.item.kind === 1) {
13154
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
13155
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
13156
+ }
13157
+ }
13158
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
13159
+ ownItems.sort((a, b) => a.seq - b.seq);
13160
+ const rejectedNow = /* @__PURE__ */ new Set();
13161
+ const allCandidates = await matchOwnItems(ownItems, trial, (o) => {
13162
+ stats.dropped++;
13163
+ rejectedNow.add(o.id);
13164
+ });
13165
+ stats.candidates = allCandidates.length;
13166
+ const cutoff = params.legacyCutoffLeaf ?? {};
13167
+ const candidates = allCandidates.filter((c) => {
13168
+ const limit = cutoff[c.mint];
13169
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
13170
+ stats.dropped++;
13171
+ return false;
13172
+ }
13173
+ return true;
13174
+ });
13175
+ const chainTrees = await ctx.readTrees();
13176
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
13177
+ const replays = /* @__PURE__ */ new Map();
13178
+ for (let i = 0; i < poolMints.length; i++) {
13179
+ const mint = poolMints[i];
13180
+ const start = startTrees.get(mint);
13181
+ const chainTree = chainTrees[i] ?? null;
13182
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
13183
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
13184
+ let overrides = start.overrides;
13185
+ stats.conflicts += r.conflicts;
13186
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
13187
+ const merged = new Map([...start.overrides, ...r.corrections]);
13188
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
13189
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
13190
+ r = alternative;
13191
+ overrides = merged;
13192
+ }
13193
+ }
13194
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
13195
+ replays.set(mint, { r, overrides });
13196
+ }
13197
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
13198
+ const streamValue = (mint, leaf) => {
13199
+ const v = replays.get(mint)?.r.valueAt(leaf);
13200
+ if (v !== void 0) return v;
13201
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
13202
+ if (carried !== void 0) return carried;
13203
+ const t = startTrees.get(mint);
13204
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
13205
+ return void 0;
13206
+ };
13207
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
13208
+ const verified = [];
13209
+ const pendingByKey = /* @__PURE__ */ new Map();
13210
+ const rejectedCandidates = /* @__PURE__ */ new Set();
13211
+ const outcomeOf = /* @__PURE__ */ new Map();
13212
+ const tally = (c, what) => {
13213
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
13214
+ t.total++;
13215
+ if (what === "kept") t.kept = true;
13216
+ if (what === "rejected") t.rejected++;
13217
+ outcomeOf.set(c.seq, t);
13218
+ };
13219
+ const pend = (c, rank) => {
13220
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
13221
+ const prior = pendingByKey.get(key);
13222
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
13223
+ };
13224
+ for (const c of candidates) {
13225
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
13226
+ verified.push(c);
13227
+ continue;
13228
+ }
13229
+ if (!poolSet.has(c.mint)) {
13230
+ pend(c, 3);
13231
+ continue;
13232
+ }
13233
+ const value = streamValue(c.mint, c.leaf);
13234
+ if (value === void 0) {
13235
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
13236
+ stats.dropped++;
13237
+ tally(c, "other");
13238
+ } else pend(c, 1);
13239
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
13240
+ pend(c, value === c.commitment ? 0 : 2);
13241
+ } else if (value === c.commitment) {
13242
+ verified.push(c);
13243
+ } else {
13244
+ stats.dropped++;
13245
+ rejectedCandidates.add(c);
13246
+ tally(c, "rejected");
13247
+ }
13248
+ }
13249
+ verified.sort((a, b) => a.seq - b.seq);
13250
+ const byLeaf = /* @__PURE__ */ new Map();
13251
+ for (const c of verified) {
13252
+ const key = `${c.mint}:${c.leaf}`;
13253
+ if (byLeaf.has(key)) {
13254
+ stats.dropped++;
13255
+ tally(c, "other");
13256
+ continue;
13257
+ }
13258
+ byLeaf.set(key, c);
13259
+ }
13260
+ const notes = [];
13261
+ const atRisk = [];
13262
+ const spentOut = new Set(knownSpent);
13263
+ const verifiedOut = new Set(knownVerified);
13264
+ const keyChecked = /* @__PURE__ */ new Map();
13265
+ for (const c of byLeaf.values()) {
13266
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
13267
+ keyChecked.set(c.keypair.privateKey, pubOk);
13268
+ if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
13269
+ stats.dropped++;
13270
+ tally(c, "rejected");
13271
+ continue;
13272
+ }
13273
+ tally(c, "kept");
13274
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
13275
+ const utxo = {
13276
+ amount: c.amount,
13277
+ keypair: c.atRisk ? { ...c.keypair } : owner,
13278
+ blinding: c.blinding,
13279
+ mintAddress: c.mint,
13280
+ index: c.leaf,
13281
+ commitment: c.commitment
13282
+ };
13283
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
13284
+ stats.spent++;
13285
+ spentOut.add(c.nullifier);
13286
+ continue;
13287
+ }
13288
+ const note = {
13289
+ kind: c.kind,
13290
+ utxo,
13291
+ signature: bs584.encode(c.signature),
13292
+ legacyExposed: c.atRisk
13293
+ };
13294
+ (c.atRisk ? atRisk : notes).push(note);
13295
+ }
13296
+ 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);
13297
+ sortNotes(notes);
13298
+ sortNotes(atRisk);
13299
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
13300
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
13301
+ const overflow = pendingList.length - carriedPending.length;
13302
+ if (overflow > 0) {
13303
+ stats.pendingDropped += overflow;
13304
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
13305
+ }
13306
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
13307
+ for (const c of carriedPending) tally(c, "kept");
13308
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
13309
+ let page = targetPage;
13310
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
13311
+ const trees = {};
13312
+ const treeEnd = /* @__PURE__ */ new Map();
13313
+ for (const mint of poolMints) {
13314
+ const start = startTrees.get(mint);
13315
+ const { r, overrides } = replays.get(mint);
13316
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
13317
+ const n = snap.nextIndex;
13318
+ const window2 = [];
13319
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
13320
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
13321
+ if (v === void 0) break;
13322
+ window2.push(hex32(v));
13323
+ }
13324
+ window2.reverse();
13325
+ trees[mint] = {
13326
+ frontier: snap.frontier,
13327
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
13328
+ window: window2.join(""),
13329
+ verified: Math.min(verifiedUpTo(mint), n),
13330
+ 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)]),
13331
+ mismatch: r.mismatch
13332
+ };
13333
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
13334
+ }
13335
+ const pendingLeaves = [];
13336
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
13337
+ for (const c of carriedPending) {
13338
+ const end = treeEnd.get(c.mint);
13339
+ if (!end || c.leaf >= end.nextIndex) continue;
13340
+ const value = streamValue(c.mint, c.leaf);
13341
+ const key = `${c.mint}:${c.leaf}`;
13342
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
13343
+ pendingLeafSeen.add(key);
13344
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
13345
+ }
13346
+ const keptItems = [];
13347
+ const keptIds = /* @__PURE__ */ new Set();
13348
+ for (const o of ownItems) {
13349
+ const t = outcomeOf.get(o.seq);
13350
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
13351
+ rejectedNow.add(o.id);
13352
+ continue;
13353
+ }
13354
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
13355
+ keptIds.add(o.id);
13356
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
13357
+ }
13358
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
13359
+ const nextCursor = {
13360
+ v: CURSOR_VERSION,
13361
+ epoch: head.epoch.toString(10),
13362
+ page,
13363
+ chain: chainAt.get(page) ?? startChain,
13364
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
13365
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
13366
+ trees,
13367
+ own: {
13368
+ items: keptItems,
13369
+ verified: Array.from(verifiedOut),
13370
+ spent: Array.from(spentOut),
13371
+ pendingLeaves,
13372
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
13373
+ }
13374
+ };
13375
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
13376
+ } finally {
13377
+ params.signal?.removeEventListener("abort", onCallerAbort);
13378
+ }
13379
+ }
13380
+
11382
13381
  // src/wallet/utxo-wallet.ts
11383
13382
  var UtxoWallet = class _UtxoWallet {
11384
13383
  constructor(viewingKey) {
@@ -11733,7 +13732,7 @@ async function loadWeb3() {
11733
13732
 
11734
13733
  // src/bridge/rail-verify.ts
11735
13734
  import nacl6 from "tweetnacl";
11736
- import { sha256 as sha2565 } from "@noble/hashes/sha256";
13735
+ import { sha256 as sha2567 } from "@noble/hashes/sha256";
11737
13736
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
11738
13737
  var b58 = /* @__PURE__ */ (() => {
11739
13738
  const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -11839,7 +13838,7 @@ function canonicalPayloadString(resp) {
11839
13838
  function verifyQuoteSignature(resp) {
11840
13839
  if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
11841
13840
  const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
11842
- const digest = sha2565(new TextEncoder().encode(stable(payload)));
13841
+ const digest = sha2567(new TextEncoder().encode(stable(payload)));
11843
13842
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
11844
13843
  const sig = resp.signature.replace(/^ed25519:/, "");
11845
13844
  try {
@@ -12034,7 +14033,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12034
14033
  })
12035
14034
  });
12036
14035
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12037
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
14036
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
12038
14037
  throw new Error(
12039
14038
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12040
14039
  );
@@ -12071,9 +14070,12 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12071
14070
  // src/bridge/derive.ts
12072
14071
  import { hmac } from "@noble/hashes/hmac";
12073
14072
  import { sha512 } from "@noble/hashes/sha512";
14073
+ import { blake3 as blake36 } from "@noble/hashes/blake3";
12074
14074
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
14075
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
14076
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
12075
14077
  var MAX_RECEIVER_INDEX = 1e4;
12076
- async function deriveBridgeReceiver(nk, index) {
14078
+ function assertReceiverIndex(index) {
12077
14079
  if (!Number.isInteger(index) || index < 0) {
12078
14080
  throw new Error(`index must be a non-negative integer, got ${index}`);
12079
14081
  }
@@ -12082,6 +14084,26 @@ async function deriveBridgeReceiver(nk, index) {
12082
14084
  `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
14085
  );
12084
14086
  }
14087
+ }
14088
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
14089
+ if (ownerUtxoKeypair instanceof Uint8Array) {
14090
+ throw new Error(
14091
+ "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."
14092
+ );
14093
+ }
14094
+ assertReceiverIndex(index);
14095
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
14096
+ const priv = bigintToBytes322(owner.privateKey);
14097
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
14098
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
14099
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
14100
+ const key = blake36(preimage);
14101
+ const h = hmac(sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
14102
+ return signerFromSecretKey(h.slice(0, 32));
14103
+ }
14104
+ async function deriveLegacyBridgeReceiver(nk, index) {
14105
+ assertReceiverIndex(index);
14106
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
12085
14107
  const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12086
14108
  return signerFromSecretKey(h.slice(0, 32));
12087
14109
  }
@@ -12092,13 +14114,44 @@ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS4, findAssociatedTokenPda
12092
14114
  function describeError(err) {
12093
14115
  return err instanceof Error ? err.message : String(err);
12094
14116
  }
12095
- async function listBridgeDeposits(rpc, nk, opts) {
14117
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
14118
+ if (ownerUtxoKeypair instanceof Uint8Array) {
14119
+ throw new Error(
14120
+ "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)."
14121
+ );
14122
+ }
14123
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
14124
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
14125
+ legacyExposed: false
14126
+ });
14127
+ if (opts.includeLegacy === false) return out;
14128
+ const nks = [];
14129
+ const seen = /* @__PURE__ */ new Set();
14130
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
14131
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
14132
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
14133
+ }
14134
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
14135
+ if (seen.has(key)) continue;
14136
+ seen.add(key);
14137
+ nks.push(nk);
14138
+ }
14139
+ for (const nk of nks) {
14140
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
14141
+ legacyExposed: true,
14142
+ legacyViewingKeyNk: nk
14143
+ });
14144
+ out.push(...legacy);
14145
+ }
14146
+ return out;
14147
+ }
14148
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12096
14149
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12097
14150
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12098
14151
  const out = [];
12099
14152
  let consecutiveUnused = 0;
12100
14153
  for (let index = 0; index < scanDepth; index++) {
12101
- const kp = await deriveBridgeReceiver(nk, index);
14154
+ const kp = await receiverAt(index);
12102
14155
  const receiver = kp.address;
12103
14156
  const [tokenAccount] = await findAssociatedTokenPda4({
12104
14157
  mint: opts.mint,
@@ -12150,7 +14203,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12150
14203
  tokenBalance,
12151
14204
  lamports,
12152
14205
  shieldSignature,
12153
- ...indexReused ? { indexReused, shieldSignatures } : {}
14206
+ ...indexReused ? { indexReused, shieldSignatures } : {},
14207
+ ...provenance
12154
14208
  });
12155
14209
  } catch (err) {
12156
14210
  out.push({
@@ -12160,7 +14214,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12160
14214
  state: "unknown",
12161
14215
  tokenBalance: 0n,
12162
14216
  lamports: 0n,
12163
- error: describeError(err)
14217
+ error: describeError(err),
14218
+ ...provenance
12164
14219
  });
12165
14220
  }
12166
14221
  }
@@ -12315,7 +14370,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12315
14370
  const signMessage = (m) => signMessageBytes(R, m);
12316
14371
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
12317
14372
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
12318
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
14373
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
14374
+ amount,
14375
+ viewingKeyNk: nk,
14376
+ ownerUtxoKeypair: utxoKeypair,
14377
+ mintAddress: mint
14378
+ });
12319
14379
  const zeroInput = await createZeroUtxo(mint);
12320
14380
  const rBefore = (await rpc.getBalance(R.address).send()).value;
12321
14381
  let result;
@@ -12334,6 +14394,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12334
14394
  signMessage,
12335
14395
  chainNoteViewingKeyNk: nk,
12336
14396
  chainNoteSalt: noteSalt,
14397
+ ownerUtxoKeypair: utxoKeypair,
12337
14398
  relaySupplementalAlt: true,
12338
14399
  onProgress: (s) => log(` \xB7 ${s}`)
12339
14400
  }
@@ -12527,13 +14588,13 @@ var DoNotRetry = class extends Error {
12527
14588
  };
12528
14589
  async function withShieldRetries(attempt, hooks = {}) {
12529
14590
  const attempts = hooks.attempts ?? 3;
12530
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
14591
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
12531
14592
  let last = "";
12532
14593
  for (let n = 1; n <= attempts; n++) {
12533
14594
  if (n > 1) {
12534
14595
  const delay = retryDelayMs(n);
12535
14596
  hooks.onRetry?.(n, delay, last);
12536
- await sleep4(delay);
14597
+ await sleep5(delay);
12537
14598
  }
12538
14599
  try {
12539
14600
  return await attempt(n);
@@ -12552,6 +14613,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12552
14613
  export {
12553
14614
  AccountRole,
12554
14615
  BRIDGE_ESCROW_LABEL,
14616
+ BRIDGE_ESCROW_LABEL_V2,
12555
14617
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
12556
14618
  CHAIN_NOTE_SALT_BITS,
12557
14619
  CLEANUP_FEE_BUDGET,
@@ -12580,6 +14642,10 @@ export {
12580
14642
  MemoryStorageAdapter,
12581
14643
  MerkleTree,
12582
14644
  NATIVE_SOL_MINT,
14645
+ NOTE_INDEX_NO_LEAF,
14646
+ NOTE_INDEX_PAGE_SIZE,
14647
+ NoteIndexFormatError,
14648
+ NoteIndexHeadBehindError,
12583
14649
  ONECLICK_PUBKEY_B58,
12584
14650
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
12585
14651
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -12656,6 +14722,7 @@ export {
12656
14722
  computeChainNoteHash,
12657
14723
  computeExtDataHash,
12658
14724
  computeMerkleRoot,
14725
+ computeNoteIndexChain,
12659
14726
  computeProofForLatestDeposit,
12660
14727
  computeProofFromChain,
12661
14728
  computeSignature,
@@ -12680,14 +14747,18 @@ export {
12680
14747
  depositFromDerivedKey,
12681
14748
  deriveBridgeReceiver,
12682
14749
  deriveChangeNoteBlinding,
12683
- deriveDepositNoteSecrets,
14750
+ deriveDepositNoteBlinding,
12684
14751
  deriveDiversifiedViewingKey,
12685
14752
  deriveDiversifier,
12686
14753
  deriveFundingTargets,
12687
14754
  deriveInputNullifierPdas,
14755
+ deriveLegacyBridgeReceiver,
14756
+ deriveLegacyDepositNoteSecrets,
14757
+ deriveLegacySwapRefundAuthorization,
12688
14758
  derivePublicKey,
12689
14759
  deriveSpendKey,
12690
14760
  deriveSwapRefundAuthorization,
14761
+ deriveSwapRefundBlinding,
12691
14762
  deriveUserCompliancePublicKey,
12692
14763
  deriveUserComplianceScalar,
12693
14764
  deriveUtxoKeypairFromSpendKey,
@@ -12700,6 +14771,8 @@ export {
12700
14771
  discoverSwapRefunds,
12701
14772
  downloadNote,
12702
14773
  encodeDeliveryCarrierMemo,
14774
+ encodeNoteIndexItem,
14775
+ encodeNoteIndexPage,
12703
14776
  encodeNoteSimple,
12704
14777
  encodeRecipientDeliveryNote,
12705
14778
  encryptCompactChainNote,
@@ -12715,6 +14788,8 @@ export {
12715
14788
  fetchCommitments,
12716
14789
  fetchLatestBlockhash,
12717
14790
  fetchLookupTables,
14791
+ fetchNoteIndexHead,
14792
+ fetchNoteIndexPage,
12718
14793
  fetchRiskQuoteInstruction,
12719
14794
  fetchRiskQuoteIx,
12720
14795
  fetchSignaturesForAddress,
@@ -12787,6 +14862,8 @@ export {
12787
14862
  parseDeliveryCarrierMemo,
12788
14863
  parseError,
12789
14864
  parseNote2 as parseNote,
14865
+ parseNoteIndexItem,
14866
+ parseNoteIndexPage,
12790
14867
  parseRelayErrorResponse,
12791
14868
  parseRelayErrorSignature,
12792
14869
  parseTransactionError,
@@ -12808,6 +14885,7 @@ export {
12808
14885
  readMerkleTreeState,
12809
14886
  readRent,
12810
14887
  recipientDeliveryNoteToBase64,
14888
+ recoverNotesFromIndex,
12811
14889
  registerViewingKey,
12812
14890
  relayRequestDigestHex,
12813
14891
  removePendingDeposit,