@cloak.dev/sdk 0.2.5 → 0.2.6-staging.af2dfc0

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
@@ -676,7 +676,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
676
676
 
677
677
  // src/config/relay.ts
678
678
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
679
- var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
679
+ var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
680
680
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
681
681
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
682
682
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -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) => {
@@ -801,9 +839,48 @@ function assertAllowedRelayOrigin(value) {
801
839
  }
802
840
  return trimmed.replace(/\/$/, "");
803
841
  }
804
- async function relayFetch(url, init) {
842
+ async function relayFetch(url, init, options) {
805
843
  assertAllowedRelayOrigin(url);
806
- return fetch(url, init);
844
+ const extra = sanitizeExtraHeaders(options?.extraHeaders);
845
+ const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
846
+ observeRelayClock(response);
847
+ return response;
848
+ }
849
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
850
+ var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
851
+ function sanitizeExtraHeaders(extra) {
852
+ if (!extra || typeof extra !== "object") return void 0;
853
+ const out = {};
854
+ let any = false;
855
+ for (const [name, value] of Object.entries(extra)) {
856
+ if (typeof name !== "string" || !HEADER_NAME.test(name)) continue;
857
+ if (typeof value !== "string" || FORBIDDEN_HEADER_VALUE_CHARS.test(value)) continue;
858
+ out[name] = value;
859
+ any = true;
860
+ }
861
+ return any ? out : void 0;
862
+ }
863
+ function mergeRelayHeaders(base, extraHeaders) {
864
+ const extra = sanitizeExtraHeaders(extraHeaders);
865
+ if (!extra) return base;
866
+ const merged = {};
867
+ const taken = /* @__PURE__ */ new Set();
868
+ const put = (name, value) => {
869
+ merged[name] = value;
870
+ taken.add(name.toLowerCase());
871
+ };
872
+ if (typeof Headers !== "undefined" && base instanceof Headers) {
873
+ base.forEach((value, name) => put(name, value));
874
+ } else if (Array.isArray(base)) {
875
+ for (const [name, value] of base) put(name, value);
876
+ } else if (base) {
877
+ for (const [name, value] of Object.entries(base)) put(name, value);
878
+ }
879
+ for (const [name, value] of Object.entries(extra)) {
880
+ if (taken.has(name.toLowerCase())) continue;
881
+ put(name, value);
882
+ }
883
+ return merged;
807
884
  }
808
885
  function assertAllowedRpcEndpoint(endpoint) {
809
886
  if (BUILD_ALLOWS_LOCAL_ENDPOINTS) return;
@@ -1176,6 +1253,7 @@ var TRANSACT_SWAP_AUTH_FIELDS = [
1176
1253
  "slippage_bps",
1177
1254
  "swap_max_retries"
1178
1255
  ];
1256
+ var RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT = ["affiliate_code"];
1179
1257
  var UTF8 = new TextEncoder();
1180
1258
  function compareKeysBytewise(a, b) {
1181
1259
  if (a === b) return 0;
@@ -1239,6 +1317,11 @@ function buildAuthRequest(body, sender, fields) {
1239
1317
  }
1240
1318
  out[k] = value;
1241
1319
  }
1320
+ for (const k of RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT) {
1321
+ const value = body[k];
1322
+ if (value === void 0 || value === null) continue;
1323
+ out[k] = value;
1324
+ }
1242
1325
  return out;
1243
1326
  }
1244
1327
  function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
@@ -1254,7 +1337,7 @@ ${digest}`
1254
1337
  }
1255
1338
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
1256
1339
  const senderB58 = sender;
1257
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
1340
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
1258
1341
  const nonce = randomNonceUuid();
1259
1342
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
1260
1343
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -1333,7 +1416,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
1333
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.`
1334
1417
  );
1335
1418
  }
1336
- function explainRelayAuthRejection(responseText) {
1419
+ function explainRelayAuthRejection(responseText, context) {
1337
1420
  const text = String(responseText);
1338
1421
  const has = (needle) => text.includes(needle);
1339
1422
  if (has("issued too far in the future")) {
@@ -1343,7 +1426,9 @@ function explainRelayAuthRejection(responseText) {
1343
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.`;
1344
1427
  }
1345
1428
  if (has("does not match the exact request")) {
1346
- 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\`.`;
1347
1432
  }
1348
1433
  if (has("has no registered viewing key")) {
1349
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.`;
@@ -4192,6 +4277,7 @@ async function fetchWithRetry(url, options = {}) {
4192
4277
  try {
4193
4278
  const response = await fetch(url, { signal: controller.signal });
4194
4279
  clearTimeout(timeoutId);
4280
+ observeRelayClock(response);
4195
4281
  return response;
4196
4282
  } finally {
4197
4283
  clearTimeout(timeoutId);
@@ -4836,9 +4922,41 @@ function parseDeliveryCarrierMemo(data) {
4836
4922
  // src/notes/swap-refund.ts
4837
4923
  import { blake3 as blake33 } from "@noble/hashes/blake3";
4838
4924
  import _bs582 from "bs58";
4925
+
4926
+ // src/notes/owner-key.ts
4927
+ var FIELD_MODULUS = BigInt(
4928
+ "21888242871839275222246405745257275088548364400416034343698204186575808495617"
4929
+ );
4930
+ async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
4931
+ if (!keypair || typeof keypair !== "object") {
4932
+ throw new Error(
4933
+ `${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.`
4934
+ );
4935
+ }
4936
+ const { privateKey, publicKey } = keypair;
4937
+ if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS) {
4938
+ throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
4939
+ }
4940
+ if (typeof publicKey !== "bigint" || publicKey === 0n) {
4941
+ throw new Error(`${label}.publicKey must be a non-zero bigint`);
4942
+ }
4943
+ if (await derivePublicKey(privateKey) !== publicKey) {
4944
+ throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
4945
+ }
4946
+ return { privateKey, publicKey };
4947
+ }
4948
+ function normalizeOwnerPublicKey(publicKey, label) {
4949
+ if (publicKey === void 0 || publicKey === null) return void 0;
4950
+ if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS) {
4951
+ throw new Error(`${label} must be a non-zero field element (bigint)`);
4952
+ }
4953
+ return publicKey;
4954
+ }
4955
+
4956
+ // src/notes/swap-refund.ts
4839
4957
  var bs582 = _bs582.default || _bs582;
4840
4958
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
4841
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
4959
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
4842
4960
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
4843
4961
  function normalizeNullifier(inputNullifier) {
4844
4962
  if (inputNullifier instanceof Uint8Array) {
@@ -4872,13 +4990,29 @@ function derive(nk, nullifier, info) {
4872
4990
  preimage.set(info, off);
4873
4991
  return blake33(preimage);
4874
4992
  }
4875
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
4993
+ function assertNk(viewingKeyNk) {
4876
4994
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
4877
4995
  throw new Error("viewingKeyNk must be 32 bytes");
4878
4996
  }
4997
+ return viewingKeyNk;
4998
+ }
4999
+ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
5000
+ const nk = assertNk(viewingKeyNk);
5001
+ return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
5002
+ }
5003
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
5004
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5005
+ const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5006
+ if (owner.publicKey === 0n || blinding === 0n) {
5007
+ throw new Error("refund authorization is degenerate");
5008
+ }
5009
+ return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
5010
+ }
5011
+ async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5012
+ const nk = assertNk(viewingKeyNk);
4879
5013
  const nullifier = normalizeNullifier(inputNullifier);
4880
- const privateKey = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_PRIVATE_KEY_INFO));
4881
- const blinding = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_BLINDING_INFO));
5014
+ const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
5015
+ const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
4882
5016
  const publicKey = await derivePublicKey(privateKey);
4883
5017
  if (publicKey === 0n || blinding === 0n) {
4884
5018
  throw new Error("derived refund authorization is degenerate");
@@ -4896,19 +5030,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
4896
5030
  async function matchSwapRefundLeaf(params) {
4897
5031
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
4898
5032
  const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
4899
- let auth;
5033
+ let blinding;
4900
5034
  try {
4901
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
5035
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
4902
5036
  } catch {
4903
5037
  return null;
4904
5038
  }
4905
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
4906
- if (candidate !== expected) return null;
5039
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5040
+ if (ownerPub !== void 0) {
5041
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
5042
+ if (candidate === expected) {
5043
+ return {
5044
+ keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
5045
+ blinding,
5046
+ amount: amountAfterFee,
5047
+ commitment: candidate,
5048
+ legacyExposed: false
5049
+ };
5050
+ }
5051
+ }
5052
+ let legacy;
5053
+ try {
5054
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
5055
+ } catch {
5056
+ return null;
5057
+ }
5058
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
5059
+ if (legacyCandidate !== expected) return null;
4907
5060
  return {
4908
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
4909
- blinding: auth.blinding,
5061
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
5062
+ blinding: legacy.blinding,
4910
5063
  amount: amountAfterFee,
4911
- commitment: candidate
5064
+ commitment: legacyCandidate,
5065
+ legacyExposed: true
4912
5066
  };
4913
5067
  }
4914
5068
  var TRANSACT_SWAP_TAG2 = 1;
@@ -4972,10 +5126,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
4972
5126
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
4973
5127
  return out;
4974
5128
  }
4975
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
5129
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
4976
5130
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
4977
5131
  throw new Error("viewingKeyNk must be 32 bytes");
4978
5132
  }
5133
+ if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
5134
+ throw new Error(
5135
+ "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."
5136
+ );
5137
+ }
5138
+ const ownerUtxoKeypair = options.ownerUtxoKeypair;
4979
5139
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
4980
5140
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
4981
5141
  const programIdBase58 = programId;
@@ -5050,7 +5210,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5050
5210
  viewingKeyNk,
5051
5211
  inputNullifier: candidate.nullifier,
5052
5212
  amountAfterFee: event.amountAfterFee,
5053
- commitment: event.commitmentField
5213
+ commitment: event.commitmentField,
5214
+ ownerUtxoKeypair
5054
5215
  });
5055
5216
  if (!recovered) continue;
5056
5217
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5074,7 +5235,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5074
5235
  // src/notes/deposit-note.ts
5075
5236
  import { blake3 as blake34 } from "@noble/hashes/blake3";
5076
5237
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5077
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5238
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5078
5239
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5079
5240
  var CHAIN_NOTE_SALT_BITS = 96;
5080
5241
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -5110,30 +5271,47 @@ function derive2(nk, salt, info) {
5110
5271
  preimage.set(info, off);
5111
5272
  return blake34(preimage);
5112
5273
  }
5274
+ function assertNk2(viewingKeyNk) {
5275
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5276
+ throw new Error("viewingKeyNk must be 32 bytes");
5277
+ }
5278
+ return viewingKeyNk;
5279
+ }
5113
5280
  function randomDepositNoteSalt() {
5114
5281
  const bytes = randomBytes(12);
5115
5282
  let v = 0n;
5116
5283
  for (const b of bytes) v = v << 8n | BigInt(b);
5117
5284
  return v === 0n ? 1n : v;
5118
5285
  }
5119
- async function deriveDepositNoteSecrets(viewingKeyNk, noteSalt) {
5120
- if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5121
- throw new Error("viewingKeyNk must be 32 bytes");
5122
- }
5286
+ function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
5287
+ const nk = assertNk2(viewingKeyNk);
5288
+ return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
5289
+ }
5290
+ async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
5291
+ const nk = assertNk2(viewingKeyNk);
5123
5292
  const salt = saltToBytes(noteSalt);
5124
- const privateKey = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_PRIVATE_KEY_INFO));
5125
- const blinding = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_BLINDING_INFO));
5293
+ const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
5294
+ const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
5126
5295
  const publicKey = await derivePublicKey(privateKey);
5127
5296
  if (publicKey === 0n || blinding === 0n) {
5128
5297
  throw new Error("derived deposit note secrets are degenerate");
5129
5298
  }
5130
5299
  return { keypair: { privateKey, publicKey }, blinding };
5131
5300
  }
5132
- async function createRecoverableDepositUtxo(amount, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomDepositNoteSalt()) {
5301
+ async function createRecoverableDepositUtxo(params) {
5302
+ if (!params || typeof params !== "object" || params instanceof Uint8Array) {
5303
+ throw new Error(
5304
+ "createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
5305
+ );
5306
+ }
5307
+ const { amount, viewingKeyNk } = params;
5133
5308
  if (typeof amount !== "bigint" || amount <= 0n) {
5134
5309
  throw new Error("amount must be a positive bigint");
5135
5310
  }
5136
- const { keypair, blinding } = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5311
+ const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
5312
+ const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
5313
+ const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
5314
+ const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5137
5315
  const utxo = { amount, keypair, blinding, mintAddress };
5138
5316
  utxo.commitment = await computeCommitment(utxo);
5139
5317
  return { utxo, noteSalt };
@@ -5148,21 +5326,46 @@ function normalizeCommitment(value) {
5148
5326
  async function matchDepositNote(params) {
5149
5327
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
5150
5328
  if (typeof amount !== "bigint" || amount <= 0n) return null;
5151
- let secrets;
5329
+ let blinding;
5330
+ try {
5331
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
5332
+ } catch {
5333
+ return null;
5334
+ }
5335
+ const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
5336
+ if (published.length === 0) return null;
5337
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5338
+ if (ownerPub !== void 0) {
5339
+ const keypair = {
5340
+ privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
5341
+ publicKey: ownerPub
5342
+ };
5343
+ const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5344
+ if (published.some((value) => value === candidate)) {
5345
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
5346
+ }
5347
+ }
5348
+ let legacy;
5152
5349
  try {
5153
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
5350
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
5154
5351
  } catch {
5155
5352
  return null;
5156
5353
  }
5157
- const candidate = await computeCommitment({
5354
+ const legacyCandidate = await computeCommitment({
5158
5355
  amount,
5159
- keypair: secrets.keypair,
5160
- blinding: secrets.blinding,
5356
+ keypair: legacy.keypair,
5357
+ blinding: legacy.blinding,
5161
5358
  mintAddress
5162
5359
  });
5163
- const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
5164
- if (!published.some((value) => value === candidate)) return null;
5165
- return { ...secrets, amount, mintAddress, commitment: candidate, noteSalt };
5360
+ if (!published.some((value) => value === legacyCandidate)) return null;
5361
+ return {
5362
+ ...legacy,
5363
+ amount,
5364
+ mintAddress,
5365
+ commitment: legacyCandidate,
5366
+ noteSalt,
5367
+ legacyExposed: true
5368
+ };
5166
5369
  }
5167
5370
 
5168
5371
  // src/notes/change-note.ts
@@ -5218,10 +5421,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
5218
5421
  preimage.set(CHANGE_BLINDING_INFO, off);
5219
5422
  return toFieldSecret3(blake35(preimage));
5220
5423
  }
5221
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5424
+ async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
5222
5425
  if (typeof amount !== "bigint" || amount <= 0n) {
5223
5426
  throw new Error("amount must be a positive bigint");
5224
5427
  }
5428
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5225
5429
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
5226
5430
  const utxo = { amount, keypair, blinding, mintAddress };
5227
5431
  utxo.commitment = await computeCommitment(utxo);
@@ -5247,13 +5451,27 @@ async function matchChangeNote(params) {
5247
5451
  const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
5248
5452
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
5249
5453
  if (!published.some((value) => value === candidate)) return null;
5250
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
5454
+ const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
5455
+ const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
5456
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
5251
5457
  }
5252
5458
 
5253
5459
  // src/flows/transact.ts
5254
5460
  import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
5255
5461
  import nacl5 from "tweetnacl";
5256
5462
 
5463
+ // src/relay/chain-note-time.ts
5464
+ async function relayChainNoteTimestampMs(relayUrl) {
5465
+ if (relayUrl && !hasRelayClockSample()) {
5466
+ try {
5467
+ const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
5468
+ await response.body?.cancel?.().catch(() => void 0);
5469
+ } catch {
5470
+ }
5471
+ }
5472
+ return BigInt(relayNowMs());
5473
+ }
5474
+
5257
5475
  // src/proving/artifacts.ts
5258
5476
  import { sha256 as sha2564 } from "@noble/hashes/sha2";
5259
5477
 
@@ -5874,6 +6092,9 @@ function assertInputMints(inputUtxos, expectedMint) {
5874
6092
  );
5875
6093
  }
5876
6094
  }
6095
+ function affiliateCodeOrUndefined(code) {
6096
+ return typeof code === "string" && code.length > 0 ? code : void 0;
6097
+ }
5877
6098
  function parseNkInput(input) {
5878
6099
  if (typeof input !== "string") {
5879
6100
  if (input.length !== 32) {
@@ -5887,6 +6108,33 @@ function parseNkInput(input) {
5887
6108
  }
5888
6109
  return Uint8Array.from(Buffer.from(clean, "hex"));
5889
6110
  }
6111
+ async function resolveWalletNk(options) {
6112
+ const explicit = await resolveChainNoteNk(options);
6113
+ if (explicit) return explicit;
6114
+ if (options.ownerUtxoKeypair) {
6115
+ const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
6116
+ return getNkFromUtxoPrivateKey(owner.privateKey);
6117
+ }
6118
+ return null;
6119
+ }
6120
+ function missingWalletNkError(flow) {
6121
+ return new Error(
6122
+ `${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.`
6123
+ );
6124
+ }
6125
+ async function requireWalletNk(options, flow) {
6126
+ const nk = await resolveWalletNk(options);
6127
+ if (nk) return nk;
6128
+ throw missingWalletNkError(flow);
6129
+ }
6130
+ async function requireOwnerUtxoKeypair(options, flow) {
6131
+ if (!options.ownerUtxoKeypair) {
6132
+ throw new Error(
6133
+ `${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].`
6134
+ );
6135
+ }
6136
+ return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
6137
+ }
5890
6138
  async function resolveChainNoteNk(options) {
5891
6139
  if (options.chainNoteViewingKeyNk) {
5892
6140
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -5904,7 +6152,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
5904
6152
  function toHex(bytes) {
5905
6153
  return Buffer.from(bytes).toString("hex");
5906
6154
  }
5907
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6155
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
5908
6156
  if (options.enforceViewingKeyRegistration === false) {
5909
6157
  return;
5910
6158
  }
@@ -5918,7 +6166,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
5918
6166
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
5919
6167
  );
5920
6168
  }
5921
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
6169
+ const nk = walletNk;
5922
6170
  if (!nk || nk.length !== 32) {
5923
6171
  throw new Error(
5924
6172
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6060,10 +6308,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6060
6308
  result.set(bigintToBytes322(BigInt(publicSignals[0])), offset);
6061
6309
  offset += 32;
6062
6310
  let amount = BigInt(publicSignals[1]);
6063
- const FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6064
- const HALF_FIELD = FIELD_MODULUS / BigInt(2);
6311
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6312
+ const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
6065
6313
  if (amount > HALF_FIELD) {
6066
- amount = amount - FIELD_MODULUS;
6314
+ amount = amount - FIELD_MODULUS2;
6067
6315
  }
6068
6316
  const amountBytes = new Uint8Array(8);
6069
6317
  let amountValue = amount;
@@ -7010,8 +7258,9 @@ function chargeWalletApproval(used, budget, lastError) {
7010
7258
  }
7011
7259
  return used + 1;
7012
7260
  }
7013
- function relayFailureMessage(prefix, responseText) {
7014
- const explanation = explainRelayAuthRejection(responseText);
7261
+ function relayFailureMessage(prefix, responseText, requestBody) {
7262
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
7263
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7015
7264
  return explanation ? `${prefix}: ${responseText}
7016
7265
 
7017
7266
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -7217,6 +7466,39 @@ function buildTransactRequestBody(params) {
7217
7466
  if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
7218
7467
  body.recipient_delivery_notes = params.recipientDeliveryNotes;
7219
7468
  }
7469
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
7470
+ if (affiliateCode && params.externalAmount < BigInt(0) && params.recipient) {
7471
+ body.affiliate_code = affiliateCode;
7472
+ }
7473
+ return body;
7474
+ }
7475
+ function buildTransactSwapRequestBody(params) {
7476
+ const body = {
7477
+ proof_bytes: params.proofB64,
7478
+ public_inputs: params.publicInputsB64,
7479
+ output_mint: params.outputMint,
7480
+ recipient_ata: params.recipientAta,
7481
+ recipient: params.recipientWallet,
7482
+ // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
7483
+ // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
7484
+ min_output_amount: params.minOutputAmount.toString(),
7485
+ // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
7486
+ max_fee: params.maxFee.toString(),
7487
+ slippage_bps: params.slippageBps,
7488
+ dexes: params.dexes && params.dexes.length > 0 ? params.dexes : void 0,
7489
+ exclude_dexes: params.excludeDexes && params.excludeDexes.length > 0 ? params.excludeDexes : void 0,
7490
+ route_retry_attempts: params.routeRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(params.routeRetryAttempts))) : void 0,
7491
+ swap_max_retries: params.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(params.swapMaxRetries))) : void 0,
7492
+ encrypted_notes: params.encryptedNotes,
7493
+ risk_quote: params.riskQuote,
7494
+ // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
7495
+ // bound into the proof's ext_data_hash. The relay forwards both verbatim into the swap
7496
+ // params; the program builds the amount-bound R_fb from them at close.
7497
+ refund_pubkey: params.refundPubkeyB64,
7498
+ refund_blinding: params.refundBlindingB64
7499
+ };
7500
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
7501
+ if (affiliateCode) body.affiliate_code = affiliateCode;
7220
7502
  return body;
7221
7503
  }
7222
7504
  function resolveUserWallet(options) {
@@ -7352,10 +7634,11 @@ async function submitTransactToRelay(args) {
7352
7634
  try {
7353
7635
  response = await doFetch(`${relayUrl}/transact`, {
7354
7636
  method: "POST",
7355
- headers: { "Content-Type": "application/json" },
7637
+ headers: mergeRelayHeaders({ "Content-Type": "application/json" }, args.extraHeaders),
7356
7638
  body: requestPayload,
7357
7639
  signal: controller.signal
7358
7640
  });
7641
+ observeRelayClock(response);
7359
7642
  } finally {
7360
7643
  clearTimeout(timeoutId);
7361
7644
  }
@@ -7386,7 +7669,9 @@ async function submitTransactToRelay(args) {
7386
7669
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
7387
7670
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
7388
7671
  }
7389
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
7672
+ return await resolveFailure(
7673
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
7674
+ );
7390
7675
  }
7391
7676
  const apiResponse = JSON.parse(responseText);
7392
7677
  if (!apiResponse.success || !apiResponse.data) {
@@ -7403,7 +7688,7 @@ async function submitTransactToRelay(args) {
7403
7688
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
7404
7689
  }
7405
7690
  return await resolveFailure(
7406
- new Error(relayFailureMessage("Relay returned error", errorStr))
7691
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
7407
7692
  );
7408
7693
  }
7409
7694
  const result = apiResponse.data;
@@ -7511,34 +7796,37 @@ async function transact(params, options) {
7511
7796
  );
7512
7797
  }
7513
7798
  onProgress?.("Validating transaction parameters...");
7514
- const firstInputWithAmount = inputUtxos.find((u) => u.amount > BigInt(0));
7515
- const firstOutputWithAmount = outputUtxos.find((u) => u.amount > BigInt(0));
7516
- const fallbackNk = firstOutputWithAmount ? getNkFromUtxoPrivateKey(firstOutputWithAmount.keypair.privateKey) : firstInputWithAmount ? getNkFromUtxoPrivateKey(firstInputWithAmount.keypair.privateKey) : void 0;
7517
- const explicitChainNoteNk = await resolveChainNoteNk(options);
7518
- if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
7799
+ const walletNk = await resolveWalletNk(options);
7800
+ const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
7801
+ if (options.chainNoteSalt !== void 0 && !walletNk) {
7519
7802
  throw new Error(
7520
- "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."
7803
+ "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."
7521
7804
  );
7522
7805
  }
7523
7806
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
7524
7807
  const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
7525
- if (explicitChainNoteNk && chainNoteWillCarrySalt) {
7526
- const inputOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
7808
+ if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
7809
+ throw missingWalletNkError("transact");
7810
+ }
7811
+ if (walletNk && chainNoteWillCarrySalt) {
7812
+ const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
7813
+ if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
7814
+ const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
7527
7815
  for (let i = 0; i < outputUtxos.length; i++) {
7528
7816
  const out = outputUtxos[i];
7529
7817
  if (!out || out.amount <= BigInt(0)) continue;
7530
- if (!inputOwners.has(out.keypair.publicKey)) continue;
7531
- if (out.blinding !== deriveChangeNoteBlinding(explicitChainNoteNk, chainNoteSalt, i)) {
7818
+ if (!selfOwners.has(out.keypair.publicKey)) continue;
7819
+ if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
7532
7820
  throw new Error(
7533
- `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.`
7821
+ `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.`
7534
7822
  );
7535
7823
  }
7536
7824
  }
7537
7825
  }
7538
7826
  assertAllowedRpcConnection(connection);
7539
7827
  assertInputMints(inputUtxos, options.expectedMint);
7540
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
7541
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
7828
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
7829
+ const resolvedChainNoteNk = walletNk;
7542
7830
  if (inputUtxos.length > 2) {
7543
7831
  throw new Error("Maximum 2 input UTXOs allowed");
7544
7832
  }
@@ -7912,7 +8200,7 @@ async function transact(params, options) {
7912
8200
  }
7913
8201
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
7914
8202
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
7915
- const chainNoteTimestamp = BigInt(Date.now());
8203
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
7916
8204
  const mintField = pubkeyToFieldElement(mint);
7917
8205
  let signature = "pending-" + Date.now().toString();
7918
8206
  let commitmentIndices = [-1, -1];
@@ -8008,9 +8296,9 @@ async function transact(params, options) {
8008
8296
  ]));
8009
8297
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8010
8298
  const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
8011
- const FIELD_MODULUS = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8012
- if (chainNoteHash >= FIELD_MODULUS) {
8013
- throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS.toString()}`);
8299
+ const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8300
+ if (chainNoteHash >= FIELD_MODULUS2) {
8301
+ throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
8014
8302
  }
8015
8303
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8016
8304
  const totalInputs = 1 + // root
@@ -8375,7 +8663,10 @@ async function transact(params, options) {
8375
8663
  // For Send (shield-to-shield): always include sender so relay can enforce sanctions checks.
8376
8664
  sender: externalAmount === BigInt(0) && !recipient ? depositorPubkey : void 0,
8377
8665
  externalAmount,
8378
- recipientDeliveryNotes
8666
+ recipientDeliveryNotes,
8667
+ // SDK-002: attached only to a withdrawal / send to a public address; the builder ignores it
8668
+ // for deposits and shield-to-shield sends.
8669
+ affiliateCode: options.affiliateCode
8379
8670
  });
8380
8671
  void metadataBundle;
8381
8672
  const relaySubmission = await submitTransactToRelay({
@@ -8396,7 +8687,8 @@ async function transact(params, options) {
8396
8687
  inputNullifiers
8397
8688
  },
8398
8689
  canRetryStaleRoot: submissionAttempts < maxRootRetries,
8399
- onProgress
8690
+ onProgress,
8691
+ extraHeaders: options.relayHeaders
8400
8692
  });
8401
8693
  if (relaySubmission.kind === "stale-root") {
8402
8694
  lastError = relaySubmission.error;
@@ -8428,7 +8720,8 @@ async function transact(params, options) {
8428
8720
  throw lastError;
8429
8721
  }
8430
8722
  const classified = classifyRelayError(lastError.message);
8431
- const isMerkleClass = !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
8723
+ const isDepositSubmission = externalAmount > BigInt(0);
8724
+ const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
8432
8725
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
8433
8726
  onProgress?.(
8434
8727
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -8577,54 +8870,83 @@ async function transact(params, options) {
8577
8870
  };
8578
8871
  }
8579
8872
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
8873
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
8874
+ const transferNk = await requireWalletNk(options, "transfer");
8580
8875
  const inputSum = sumUtxoAmounts(inputUtxos);
8581
8876
  if (inputSum < amount) {
8582
8877
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
8583
8878
  }
8584
8879
  const change = inputSum - amount;
8585
- const myKeypair = inputUtxos[0].keypair;
8586
8880
  const mint = inputUtxos[0].mintAddress;
8587
- const transferNk = await resolveChainNoteNk(options);
8588
- const changeNoteSalt = transferNk ? randomChangeNoteSalt() : void 0;
8589
- const isSendToSelf = inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
8881
+ let spendInputs = [
8882
+ ...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
8883
+ ...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
8884
+ ];
8885
+ let spendOptions = options;
8886
+ if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
8887
+ if (spendInputs.length > 2) {
8888
+ throw new Error(
8889
+ `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.`
8890
+ );
8891
+ }
8892
+ if (options.relayAuthBatch) {
8893
+ throw new Error(
8894
+ "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."
8895
+ );
8896
+ }
8897
+ options.onProgress?.("Moving notes under the wallet key before the transfer...");
8898
+ const migrationSalt = randomChangeNoteSalt();
8899
+ const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
8900
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
8901
+ void _recipientViewingPublicKey;
8902
+ const migration = await transact(
8903
+ { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
8904
+ { ...migrationOptions, chainNoteSalt: migrationSalt }
8905
+ );
8906
+ const migratedNote = migration.outputUtxos?.[0] ?? migrated;
8907
+ if (migration.commitmentIndices?.[0] >= 0) {
8908
+ migratedNote.index = migration.commitmentIndices[0];
8909
+ }
8910
+ spendInputs = [migratedNote];
8911
+ spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
8912
+ }
8913
+ const changeNoteSalt = randomChangeNoteSalt();
8914
+ const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
8590
8915
  const recipientKeypair = {
8591
8916
  privateKey: BigInt(0),
8592
8917
  // Recipient's private key unknown
8593
8918
  publicKey: recipientPubkey
8594
8919
  };
8595
- const recipientUtxo = transferNk && isSendToSelf ? (await createRecoverableChangeUtxo(amount, myKeypair, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
8920
+ const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
8596
8921
  const outputUtxos = [recipientUtxo];
8597
8922
  if (change > BigInt(0)) {
8598
- if (transferNk) {
8599
- const { utxo } = await createRecoverableChangeUtxo(
8600
- change,
8601
- myKeypair,
8602
- transferNk,
8603
- mint,
8604
- changeNoteSalt,
8605
- 1
8606
- );
8607
- outputUtxos.push(utxo);
8608
- } else {
8609
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
8610
- }
8923
+ const { utxo } = await createRecoverableChangeUtxo(
8924
+ change,
8925
+ owner,
8926
+ transferNk,
8927
+ mint,
8928
+ changeNoteSalt,
8929
+ 1
8930
+ );
8931
+ outputUtxos.push(utxo);
8611
8932
  }
8612
8933
  return transact(
8613
8934
  {
8614
- inputUtxos,
8935
+ inputUtxos: spendInputs,
8615
8936
  outputUtxos,
8616
8937
  externalAmount: BigInt(0)
8617
8938
  // Pure shield-to-shield
8618
8939
  },
8619
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
8940
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
8620
8941
  );
8621
8942
  }
8622
8943
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8944
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
8945
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
8623
8946
  const inputSum = sumUtxoAmounts(inputUtxos);
8624
8947
  if (inputSum < withdrawAmount) {
8625
8948
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
8626
8949
  }
8627
- const myKeypair = inputUtxos[0].keypair;
8628
8950
  const mint = inputUtxos[0].mintAddress;
8629
8951
  let utxos = [...inputUtxos];
8630
8952
  let cachedTree = options.cachedMerkleTree;
@@ -8633,9 +8955,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8633
8955
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
8634
8956
  const [small1, small2, ...rest] = utxos;
8635
8957
  const mergedAmount = small1.amount + small2.amount;
8636
- const mergeNk = await resolveChainNoteNk(options);
8637
- const mergeSalt = mergeNk ? randomChangeNoteSalt() : void 0;
8638
- const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
8958
+ const mergeSalt = randomChangeNoteSalt();
8959
+ const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
8639
8960
  const mergeResult = await transact(
8640
8961
  {
8641
8962
  inputUtxos: [small1, small2],
@@ -8646,7 +8967,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8646
8967
  {
8647
8968
  ...options,
8648
8969
  cachedMerkleTree: cachedTree,
8649
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
8970
+ chainNoteSalt: mergeSalt
8650
8971
  }
8651
8972
  );
8652
8973
  cachedTree = mergeResult.merkleTree;
@@ -8661,23 +8982,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
8661
8982
  const outputUtxos = [];
8662
8983
  let changeNoteSalt;
8663
8984
  if (change > BigInt(0)) {
8664
- const changeNk = await resolveChainNoteNk(options);
8665
- if (changeNk) {
8666
- const salt = randomChangeNoteSalt();
8667
- const { utxo } = await createRecoverableChangeUtxo(
8668
- change,
8669
- myKeypair,
8670
- changeNk,
8671
- mint,
8672
- salt,
8673
- 0
8674
- // partialWithdraw puts change at output 0
8675
- );
8676
- outputUtxos.push(utxo);
8677
- changeNoteSalt = salt;
8678
- } else {
8679
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
8680
- }
8985
+ const salt = randomChangeNoteSalt();
8986
+ const { utxo } = await createRecoverableChangeUtxo(
8987
+ change,
8988
+ owner,
8989
+ walletNk,
8990
+ mint,
8991
+ salt,
8992
+ 0
8993
+ // partialWithdraw puts change at output 0
8994
+ );
8995
+ outputUtxos.push(utxo);
8996
+ changeNoteSalt = salt;
8681
8997
  }
8682
8998
  return transact(
8683
8999
  {
@@ -8800,6 +9116,8 @@ async function swapUtxo(params, options) {
8800
9116
  if (relayUrl) {
8801
9117
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
8802
9118
  }
9119
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
9120
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
8803
9121
  if (inputUtxos.length === 0) {
8804
9122
  throw new Error("At least one input UTXO required");
8805
9123
  }
@@ -8825,15 +9143,12 @@ async function swapUtxo(params, options) {
8825
9143
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
8826
9144
  }
8827
9145
  onProgress?.("Validating transaction parameters...");
8828
- const swapFallbackNk = getNkFromUtxoPrivateKey(inputUtxos[0].keypair.privateKey);
8829
- await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
8830
- const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
8831
- const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
9146
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
8832
9147
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
8833
- if (explicitSwapChainNoteNk && changeUtxo && changeUtxo.amount > BigInt(0) && inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey)) {
8834
- if (changeUtxo.blinding !== deriveChangeNoteBlinding(explicitSwapChainNoteNk, chainNoteSalt, 0)) {
9148
+ if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
9149
+ if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
8835
9150
  throw new Error(
8836
- `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.`
9151
+ `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.`
8837
9152
  );
8838
9153
  }
8839
9154
  }
@@ -8857,24 +9172,18 @@ async function swapUtxo(params, options) {
8857
9172
  );
8858
9173
  }
8859
9174
  const externalAmount = -swapAmount;
8860
- let refundKeypair;
8861
- let refundBlinding;
8862
- let refundDerivedFromNk = false;
8863
- if (resolvedSwapChainNoteNk) {
8864
- try {
8865
- const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
8866
- const derived = await deriveSwapRefundAuthorization(resolvedSwapChainNoteNk, refundNullifier);
8867
- refundKeypair = { privateKey: derived.privateKey, publicKey: derived.publicKey };
8868
- refundBlinding = derived.blinding;
8869
- refundDerivedFromNk = true;
8870
- } catch {
8871
- refundKeypair = await generateUtxoKeypair();
8872
- refundBlinding = randomFieldElement();
8873
- }
8874
- } else {
8875
- refundKeypair = await generateUtxoKeypair();
8876
- refundBlinding = randomFieldElement();
8877
- }
9175
+ const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
9176
+ const refundAuthorization = await deriveSwapRefundAuthorization(
9177
+ resolvedSwapChainNoteNk,
9178
+ refundNullifier,
9179
+ swapOwner
9180
+ );
9181
+ const refundKeypair = {
9182
+ privateKey: refundAuthorization.privateKey,
9183
+ publicKey: refundAuthorization.publicKey
9184
+ };
9185
+ const refundBlinding = refundAuthorization.blinding;
9186
+ const refundDerivedFromNk = true;
8878
9187
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
8879
9188
  throw new Error(
8880
9189
  "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."
@@ -9200,7 +9509,7 @@ async function swapUtxo(params, options) {
9200
9509
  for (const utxo of paddedOutputs) {
9201
9510
  outputCommitments.push(await computeCommitment(utxo));
9202
9511
  }
9203
- const chainNoteTimestamp = BigInt(Date.now());
9512
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
9204
9513
  onProgress?.("Computing external data hash...");
9205
9514
  const mint = swapPoolMint;
9206
9515
  const mintField = pubkeyToFieldElement(mint);
@@ -9443,30 +9752,27 @@ async function swapUtxo(params, options) {
9443
9752
  const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
9444
9753
  await options.onSwapStatePredicted(ssp);
9445
9754
  }
9446
- const requestBody = {
9447
- proof_bytes: proofB64,
9448
- public_inputs: publicInputsB64,
9449
- output_mint: outputMint,
9450
- recipient_ata: recipientAta,
9451
- recipient: recipientWallet,
9452
- // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
9453
- // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
9454
- min_output_amount: minOutputAmount.toString(),
9455
- // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
9456
- max_fee: swapMaxFee.toString(),
9457
- slippage_bps: swapSlippageBps,
9458
- dexes: swapDexes && swapDexes.length > 0 ? swapDexes : void 0,
9459
- exclude_dexes: swapExcludeDexes && swapExcludeDexes.length > 0 ? swapExcludeDexes : void 0,
9460
- route_retry_attempts: options.swapRouteRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(options.swapRouteRetryAttempts))) : void 0,
9461
- swap_max_retries: options.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(options.swapMaxRetries))) : void 0,
9462
- encrypted_notes: encryptedNotes,
9463
- risk_quote: riskQuoteData,
9464
- // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
9465
- // bound into the proof's ext_data_hash above. The relay forwards both verbatim into the swap
9466
- // params; the program builds the amount-bound R_fb from them at close.
9467
- refund_pubkey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("base64"),
9468
- refund_blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("base64")
9469
- };
9755
+ const requestBody = buildTransactSwapRequestBody({
9756
+ proofB64,
9757
+ publicInputsB64,
9758
+ outputMint,
9759
+ recipientAta,
9760
+ recipientWallet,
9761
+ minOutputAmount,
9762
+ maxFee: swapMaxFee,
9763
+ slippageBps: swapSlippageBps,
9764
+ dexes: swapDexes,
9765
+ excludeDexes: swapExcludeDexes,
9766
+ routeRetryAttempts: options.swapRouteRetryAttempts,
9767
+ swapMaxRetries: options.swapMaxRetries,
9768
+ encryptedNotes,
9769
+ riskQuote: riskQuoteData,
9770
+ refundPubkeyB64: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("base64"),
9771
+ refundBlindingB64: Buffer.from(bigintToBytes322(refundBlinding)).toString("base64"),
9772
+ // SDK-001/002: a swap intake is fee-bearing. Every attempt of this loop is a new intake with
9773
+ // a fresh proof, so each one carries the code; none of them is a `retry_request_id` retry.
9774
+ affiliateCode: options.affiliateCode
9775
+ });
9470
9776
  try {
9471
9777
  if (relayAuthPlan.kind === "wallet") {
9472
9778
  walletApprovals = chargeWalletApproval(walletApprovals, walletApprovalBudget, lastError);
@@ -9485,11 +9791,16 @@ async function swapUtxo(params, options) {
9485
9791
  TRANSACT_SWAP_AUTH_FIELDS
9486
9792
  );
9487
9793
  if (swapAuthFields) Object.assign(requestBody, swapAuthFields);
9488
- const response = await relayFetch(`${relayUrl}/transact_swap`, {
9489
- method: "POST",
9490
- headers: { "Content-Type": "application/json" },
9491
- body: JSON.stringify(requestBody)
9492
- });
9794
+ const response = await relayFetch(
9795
+ `${relayUrl}/transact_swap`,
9796
+ {
9797
+ method: "POST",
9798
+ headers: { "Content-Type": "application/json" },
9799
+ body: JSON.stringify(requestBody)
9800
+ },
9801
+ // SDK-004: e.g. the mobile app's `X-Cloak-Client`. Omitted, this is the old call exactly.
9802
+ { extraHeaders: options.relayHeaders }
9803
+ );
9493
9804
  const responseText = await response.text();
9494
9805
  if (!response.ok) {
9495
9806
  if (isRetryableRelayStatus(response.status) && attempt < maxRootRetries) {
@@ -9512,7 +9823,7 @@ async function swapUtxo(params, options) {
9512
9823
  forceChainIndexing = !relayUrl;
9513
9824
  continue;
9514
9825
  }
9515
- throw new Error(relayFailureMessage("Relay error", responseText));
9826
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
9516
9827
  }
9517
9828
  const apiResponse = JSON.parse(responseText);
9518
9829
  if (!apiResponse.success || !apiResponse.data) {
@@ -9648,7 +9959,6 @@ async function swapUtxo(params, options) {
9648
9959
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
9649
9960
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
9650
9961
  refund: {
9651
- privateKey: Buffer.from(bigintToBytes322(refundKeypair.privateKey)).toString("hex"),
9652
9962
  publicKey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("hex"),
9653
9963
  blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("hex"),
9654
9964
  derivedFromNk: refundDerivedFromNk
@@ -9656,6 +9966,7 @@ async function swapUtxo(params, options) {
9656
9966
  };
9657
9967
  }
9658
9968
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
9969
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
9659
9970
  const totalInput = sumUtxoAmounts(inputUtxos);
9660
9971
  const change = totalInput - swapAmount;
9661
9972
  if (change < BigInt(0)) {
@@ -9664,16 +9975,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
9664
9975
  let changeUtxo;
9665
9976
  let changeNoteSalt;
9666
9977
  if (change > BigInt(0)) {
9667
- const myKeypair = inputUtxos[0].keypair;
9668
9978
  const mint = inputUtxos[0].mintAddress;
9669
- const changeNk = await resolveChainNoteNk(options);
9670
- if (changeNk) {
9671
- const salt = randomChangeNoteSalt();
9672
- changeUtxo = (await createRecoverableChangeUtxo(change, myKeypair, changeNk, mint, salt, 0)).utxo;
9673
- changeNoteSalt = salt;
9674
- } else {
9675
- changeUtxo = await createUtxo(change, myKeypair, mint);
9676
- }
9979
+ const changeNk = await requireWalletNk(options, "swapWithChange");
9980
+ const salt = randomChangeNoteSalt();
9981
+ changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
9982
+ changeNoteSalt = salt;
9677
9983
  }
9678
9984
  return swapUtxo(
9679
9985
  {
@@ -9996,7 +10302,7 @@ var RelayBatchAuthCoordinator = class {
9996
10302
  throw new Error("Every item of a batch must target the same program id.");
9997
10303
  }
9998
10304
  }
9999
- const nowSeconds = Math.floor(Date.now() / 1e3);
10305
+ const nowSeconds = relayNowSeconds();
10000
10306
  const preimages = waiting.map(
10001
10307
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10002
10308
  );
@@ -10434,7 +10740,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
10434
10740
  const cached = depositSecretsCache.get(key);
10435
10741
  if (cached) return cached;
10436
10742
  try {
10437
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
10743
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
10438
10744
  if (depositSecretsCache.size >= 4096) {
10439
10745
  const oldest = depositSecretsCache.keys().next();
10440
10746
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11017,6 +11323,7 @@ async function scanTransactions(opts) {
11017
11323
  } else {
11018
11324
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11019
11325
  const candidateKeys = [
11326
+ opts.ownerUtxoPublicKey,
11020
11327
  derived?.keypair.publicKey,
11021
11328
  opts.ownUtxoPublicKey,
11022
11329
  BigInt(0)
@@ -11070,6 +11377,7 @@ async function scanTransactions(opts) {
11070
11377
  try {
11071
11378
  const recoveredDeposit = await matchDepositNote({
11072
11379
  viewingKeyNk,
11380
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
11073
11381
  noteSalt: compactNote.noteSalt,
11074
11382
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
11075
11383
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -11104,7 +11412,8 @@ async function scanTransactions(opts) {
11104
11412
  mintAddress: address(asset.mint),
11105
11413
  outputIndex: 0,
11106
11414
  // v4 describes output 0, which is where change lands
11107
- outputCommitments: ixCtx.outputCommitments ?? []
11415
+ outputCommitments: ixCtx.outputCommitments ?? [],
11416
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
11108
11417
  });
11109
11418
  if (recoveredChange) {
11110
11419
  recoveredChangeNotes.push({
@@ -11214,6 +11523,17 @@ async function scanTransactions(opts) {
11214
11523
  runningByAsset.set(key, running);
11215
11524
  tx.runningBalance = running;
11216
11525
  }
11526
+ const legacyKeys = /* @__PURE__ */ new Map();
11527
+ for (const note of recoveredDepositNotes) {
11528
+ if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
11529
+ }
11530
+ for (const change of recoveredChangeNotes) {
11531
+ const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
11532
+ if (legacyPrivateKey !== void 0) {
11533
+ change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
11534
+ change.legacyExposed = true;
11535
+ }
11536
+ }
11217
11537
  return {
11218
11538
  transactions: txs,
11219
11539
  summary: {
@@ -11948,7 +12268,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
11948
12268
  })
11949
12269
  });
11950
12270
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
11951
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
12271
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
11952
12272
  throw new Error(
11953
12273
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
11954
12274
  );
@@ -11985,9 +12305,12 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
11985
12305
  // src/bridge/derive.ts
11986
12306
  import { hmac } from "@noble/hashes/hmac";
11987
12307
  import { sha512 } from "@noble/hashes/sha512";
12308
+ import { blake3 as blake36 } from "@noble/hashes/blake3";
11988
12309
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
12310
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
12311
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
11989
12312
  var MAX_RECEIVER_INDEX = 1e4;
11990
- async function deriveBridgeReceiver(nk, index) {
12313
+ function assertReceiverIndex(index) {
11991
12314
  if (!Number.isInteger(index) || index < 0) {
11992
12315
  throw new Error(`index must be a non-negative integer, got ${index}`);
11993
12316
  }
@@ -11996,6 +12319,26 @@ async function deriveBridgeReceiver(nk, index) {
11996
12319
  `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.`
11997
12320
  );
11998
12321
  }
12322
+ }
12323
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
12324
+ if (ownerUtxoKeypair instanceof Uint8Array) {
12325
+ throw new Error(
12326
+ "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."
12327
+ );
12328
+ }
12329
+ assertReceiverIndex(index);
12330
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
12331
+ const priv = bigintToBytes322(owner.privateKey);
12332
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
12333
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
12334
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
12335
+ const key = blake36(preimage);
12336
+ const h = hmac(sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
12337
+ return signerFromSecretKey(h.slice(0, 32));
12338
+ }
12339
+ async function deriveLegacyBridgeReceiver(nk, index) {
12340
+ assertReceiverIndex(index);
12341
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
11999
12342
  const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12000
12343
  return signerFromSecretKey(h.slice(0, 32));
12001
12344
  }
@@ -12006,13 +12349,44 @@ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS4, findAssociatedTokenPda
12006
12349
  function describeError(err) {
12007
12350
  return err instanceof Error ? err.message : String(err);
12008
12351
  }
12009
- async function listBridgeDeposits(rpc, nk, opts) {
12352
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
12353
+ if (ownerUtxoKeypair instanceof Uint8Array) {
12354
+ throw new Error(
12355
+ "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)."
12356
+ );
12357
+ }
12358
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
12359
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
12360
+ legacyExposed: false
12361
+ });
12362
+ if (opts.includeLegacy === false) return out;
12363
+ const nks = [];
12364
+ const seen = /* @__PURE__ */ new Set();
12365
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
12366
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
12367
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
12368
+ }
12369
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
12370
+ if (seen.has(key)) continue;
12371
+ seen.add(key);
12372
+ nks.push(nk);
12373
+ }
12374
+ for (const nk of nks) {
12375
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
12376
+ legacyExposed: true,
12377
+ legacyViewingKeyNk: nk
12378
+ });
12379
+ out.push(...legacy);
12380
+ }
12381
+ return out;
12382
+ }
12383
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12010
12384
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12011
12385
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12012
12386
  const out = [];
12013
12387
  let consecutiveUnused = 0;
12014
12388
  for (let index = 0; index < scanDepth; index++) {
12015
- const kp = await deriveBridgeReceiver(nk, index);
12389
+ const kp = await receiverAt(index);
12016
12390
  const receiver = kp.address;
12017
12391
  const [tokenAccount] = await findAssociatedTokenPda4({
12018
12392
  mint: opts.mint,
@@ -12064,7 +12438,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12064
12438
  tokenBalance,
12065
12439
  lamports,
12066
12440
  shieldSignature,
12067
- ...indexReused ? { indexReused, shieldSignatures } : {}
12441
+ ...indexReused ? { indexReused, shieldSignatures } : {},
12442
+ ...provenance
12068
12443
  });
12069
12444
  } catch (err) {
12070
12445
  out.push({
@@ -12074,7 +12449,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12074
12449
  state: "unknown",
12075
12450
  tokenBalance: 0n,
12076
12451
  lamports: 0n,
12077
- error: describeError(err)
12452
+ error: describeError(err),
12453
+ ...provenance
12078
12454
  });
12079
12455
  }
12080
12456
  }
@@ -12229,7 +12605,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12229
12605
  const signMessage = (m) => signMessageBytes(R, m);
12230
12606
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
12231
12607
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
12232
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
12608
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
12609
+ amount,
12610
+ viewingKeyNk: nk,
12611
+ ownerUtxoKeypair: utxoKeypair,
12612
+ mintAddress: mint
12613
+ });
12233
12614
  const zeroInput = await createZeroUtxo(mint);
12234
12615
  const rBefore = (await rpc.getBalance(R.address).send()).value;
12235
12616
  let result;
@@ -12248,6 +12629,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
12248
12629
  signMessage,
12249
12630
  chainNoteViewingKeyNk: nk,
12250
12631
  chainNoteSalt: noteSalt,
12632
+ ownerUtxoKeypair: utxoKeypair,
12251
12633
  relaySupplementalAlt: true,
12252
12634
  onProgress: (s) => log(` \xB7 ${s}`)
12253
12635
  }
@@ -12461,11 +12843,12 @@ async function withShieldRetries(attempt, hooks = {}) {
12461
12843
  }
12462
12844
 
12463
12845
  // src/index.ts
12464
- var VERSION = "0.2.5";
12846
+ var VERSION = "0.2.6";
12465
12847
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12466
12848
  export {
12467
12849
  AccountRole,
12468
12850
  BRIDGE_ESCROW_LABEL,
12851
+ BRIDGE_ESCROW_LABEL_V2,
12469
12852
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
12470
12853
  CHAIN_NOTE_SALT_BITS,
12471
12854
  CLEANUP_FEE_BUDGET,
@@ -12594,14 +12977,18 @@ export {
12594
12977
  depositFromDerivedKey,
12595
12978
  deriveBridgeReceiver,
12596
12979
  deriveChangeNoteBlinding,
12597
- deriveDepositNoteSecrets,
12980
+ deriveDepositNoteBlinding,
12598
12981
  deriveDiversifiedViewingKey,
12599
12982
  deriveDiversifier,
12600
12983
  deriveFundingTargets,
12601
12984
  deriveInputNullifierPdas,
12985
+ deriveLegacyBridgeReceiver,
12986
+ deriveLegacyDepositNoteSecrets,
12987
+ deriveLegacySwapRefundAuthorization,
12602
12988
  derivePublicKey,
12603
12989
  deriveSpendKey,
12604
12990
  deriveSwapRefundAuthorization,
12991
+ deriveSwapRefundBlinding,
12605
12992
  deriveUserCompliancePublicKey,
12606
12993
  deriveUserComplianceScalar,
12607
12994
  deriveUtxoKeypairFromSpendKey,