@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.cjs CHANGED
@@ -577,6 +577,7 @@ var index_exports = {};
577
577
  __export(index_exports, {
578
578
  AccountRole: () => import_kit7.AccountRole,
579
579
  BRIDGE_ESCROW_LABEL: () => BRIDGE_ESCROW_LABEL,
580
+ BRIDGE_ESCROW_LABEL_V2: () => BRIDGE_ESCROW_LABEL_V2,
580
581
  BUILD_ALLOWS_LOCAL_ENDPOINTS: () => BUILD_ALLOWS_LOCAL_ENDPOINTS,
581
582
  CHAIN_NOTE_SALT_BITS: () => CHAIN_NOTE_SALT_BITS,
582
583
  CLEANUP_FEE_BUDGET: () => CLEANUP_FEE_BUDGET,
@@ -705,14 +706,18 @@ __export(index_exports, {
705
706
  depositFromDerivedKey: () => depositFromDerivedKey,
706
707
  deriveBridgeReceiver: () => deriveBridgeReceiver,
707
708
  deriveChangeNoteBlinding: () => deriveChangeNoteBlinding,
708
- deriveDepositNoteSecrets: () => deriveDepositNoteSecrets,
709
+ deriveDepositNoteBlinding: () => deriveDepositNoteBlinding,
709
710
  deriveDiversifiedViewingKey: () => deriveDiversifiedViewingKey,
710
711
  deriveDiversifier: () => deriveDiversifier,
711
712
  deriveFundingTargets: () => deriveFundingTargets,
712
713
  deriveInputNullifierPdas: () => deriveInputNullifierPdas,
714
+ deriveLegacyBridgeReceiver: () => deriveLegacyBridgeReceiver,
715
+ deriveLegacyDepositNoteSecrets: () => deriveLegacyDepositNoteSecrets,
716
+ deriveLegacySwapRefundAuthorization: () => deriveLegacySwapRefundAuthorization,
713
717
  derivePublicKey: () => derivePublicKey,
714
718
  deriveSpendKey: () => deriveSpendKey,
715
719
  deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
720
+ deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
716
721
  deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
717
722
  deriveUserComplianceScalar: () => deriveUserComplianceScalar,
718
723
  deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
@@ -1545,7 +1550,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
1545
1550
 
1546
1551
  // src/config/relay.ts
1547
1552
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
1548
- var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
1553
+ var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
1549
1554
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
1550
1555
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1551
1556
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -1622,6 +1627,44 @@ function isLoopbackHost(value) {
1622
1627
  }
1623
1628
  var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
1624
1629
 
1630
+ // src/relay/clock.ts
1631
+ var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
1632
+ var MAX_CLOCK_DIVERGENCE_MS = 2e3;
1633
+ var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
1634
+ var sample = null;
1635
+ function monotonicNowMs() {
1636
+ const perf = globalThis.performance;
1637
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
1638
+ }
1639
+ function observeRelayClock(response) {
1640
+ const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
1641
+ if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
1642
+ const serverMs = Number(raw.trim());
1643
+ const wallMs = Date.now();
1644
+ const offsetMs = serverMs - wallMs;
1645
+ if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
1646
+ sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
1647
+ }
1648
+ function relayNowMs() {
1649
+ const wallMs = Date.now();
1650
+ if (!sample) return wallMs;
1651
+ const wallElapsed = wallMs - sample.wallAtSampleMs;
1652
+ const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
1653
+ if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
1654
+ sample = null;
1655
+ return wallMs;
1656
+ }
1657
+ return wallMs + sample.offsetMs;
1658
+ }
1659
+ function hasRelayClockSample() {
1660
+ if (!sample) return false;
1661
+ relayNowMs();
1662
+ return sample !== null;
1663
+ }
1664
+ function relayNowSeconds() {
1665
+ return Math.floor(relayNowMs() / 1e3);
1666
+ }
1667
+
1625
1668
  // src/relay/endpoint.ts
1626
1669
  var ALLOWED_ORIGINS = new Set(
1627
1670
  RELAY_ORIGIN_ALLOWLIST.map((entry) => {
@@ -1670,9 +1713,48 @@ function assertAllowedRelayOrigin(value) {
1670
1713
  }
1671
1714
  return trimmed.replace(/\/$/, "");
1672
1715
  }
1673
- async function relayFetch(url, init) {
1716
+ async function relayFetch(url, init, options) {
1674
1717
  assertAllowedRelayOrigin(url);
1675
- return fetch(url, init);
1718
+ const extra = sanitizeExtraHeaders(options?.extraHeaders);
1719
+ const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
1720
+ observeRelayClock(response);
1721
+ return response;
1722
+ }
1723
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1724
+ var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
1725
+ function sanitizeExtraHeaders(extra) {
1726
+ if (!extra || typeof extra !== "object") return void 0;
1727
+ const out = {};
1728
+ let any = false;
1729
+ for (const [name, value] of Object.entries(extra)) {
1730
+ if (typeof name !== "string" || !HEADER_NAME.test(name)) continue;
1731
+ if (typeof value !== "string" || FORBIDDEN_HEADER_VALUE_CHARS.test(value)) continue;
1732
+ out[name] = value;
1733
+ any = true;
1734
+ }
1735
+ return any ? out : void 0;
1736
+ }
1737
+ function mergeRelayHeaders(base, extraHeaders) {
1738
+ const extra = sanitizeExtraHeaders(extraHeaders);
1739
+ if (!extra) return base;
1740
+ const merged = {};
1741
+ const taken = /* @__PURE__ */ new Set();
1742
+ const put = (name, value) => {
1743
+ merged[name] = value;
1744
+ taken.add(name.toLowerCase());
1745
+ };
1746
+ if (typeof Headers !== "undefined" && base instanceof Headers) {
1747
+ base.forEach((value, name) => put(name, value));
1748
+ } else if (Array.isArray(base)) {
1749
+ for (const [name, value] of base) put(name, value);
1750
+ } else if (base) {
1751
+ for (const [name, value] of Object.entries(base)) put(name, value);
1752
+ }
1753
+ for (const [name, value] of Object.entries(extra)) {
1754
+ if (taken.has(name.toLowerCase())) continue;
1755
+ put(name, value);
1756
+ }
1757
+ return merged;
1676
1758
  }
1677
1759
  function assertAllowedRpcEndpoint(endpoint) {
1678
1760
  if (BUILD_ALLOWS_LOCAL_ENDPOINTS) return;
@@ -2022,6 +2104,7 @@ var TRANSACT_SWAP_AUTH_FIELDS = [
2022
2104
  "slippage_bps",
2023
2105
  "swap_max_retries"
2024
2106
  ];
2107
+ var RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT = ["affiliate_code"];
2025
2108
  var UTF8 = new TextEncoder();
2026
2109
  function compareKeysBytewise(a, b) {
2027
2110
  if (a === b) return 0;
@@ -2085,6 +2168,11 @@ function buildAuthRequest(body, sender, fields) {
2085
2168
  }
2086
2169
  out[k] = value;
2087
2170
  }
2171
+ for (const k of RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT) {
2172
+ const value = body[k];
2173
+ if (value === void 0 || value === null) continue;
2174
+ out[k] = value;
2175
+ }
2088
2176
  return out;
2089
2177
  }
2090
2178
  function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
@@ -2100,7 +2188,7 @@ ${digest}`
2100
2188
  }
2101
2189
  function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
2102
2190
  const senderB58 = sender;
2103
- const issuedAt = String(nowSeconds ?? Math.floor(Date.now() / 1e3));
2191
+ const issuedAt = String(nowSeconds ?? relayNowSeconds());
2104
2192
  const nonce = randomNonceUuid();
2105
2193
  const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
2106
2194
  const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
@@ -2179,7 +2267,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
2179
2267
  `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.`
2180
2268
  );
2181
2269
  }
2182
- function explainRelayAuthRejection(responseText) {
2270
+ function explainRelayAuthRejection(responseText, context) {
2183
2271
  const text = String(responseText);
2184
2272
  const has = (needle) => text.includes(needle);
2185
2273
  if (has("issued too far in the future")) {
@@ -2189,7 +2277,9 @@ function explainRelayAuthRejection(responseText) {
2189
2277
  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.`;
2190
2278
  }
2191
2279
  if (has("does not match the exact request")) {
2192
- 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\`.`;
2280
+ 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\`.`;
2281
+ if (!context?.carriedAffiliateCode) return base;
2282
+ 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\`.`;
2193
2283
  }
2194
2284
  if (has("has no registered viewing key")) {
2195
2285
  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.`;
@@ -5063,6 +5153,7 @@ async function fetchWithRetry(url, options = {}) {
5063
5153
  try {
5064
5154
  const response = await fetch(url, { signal: controller.signal });
5065
5155
  clearTimeout(timeoutId);
5156
+ observeRelayClock(response);
5066
5157
  return response;
5067
5158
  } finally {
5068
5159
  clearTimeout(timeoutId);
@@ -5698,10 +5789,43 @@ var import_blake34 = require("@noble/hashes/blake3");
5698
5789
  init_address();
5699
5790
  var import_bs582 = __toESM(require("bs58"), 1);
5700
5791
  init_utxo();
5792
+
5793
+ // src/notes/owner-key.ts
5794
+ init_utxo();
5795
+ var FIELD_MODULUS2 = BigInt(
5796
+ "21888242871839275222246405745257275088548364400416034343698204186575808495617"
5797
+ );
5798
+ async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
5799
+ if (!keypair || typeof keypair !== "object") {
5800
+ throw new Error(
5801
+ `${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.`
5802
+ );
5803
+ }
5804
+ const { privateKey, publicKey } = keypair;
5805
+ if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS2) {
5806
+ throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
5807
+ }
5808
+ if (typeof publicKey !== "bigint" || publicKey === 0n) {
5809
+ throw new Error(`${label}.publicKey must be a non-zero bigint`);
5810
+ }
5811
+ if (await derivePublicKey(privateKey) !== publicKey) {
5812
+ throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
5813
+ }
5814
+ return { privateKey, publicKey };
5815
+ }
5816
+ function normalizeOwnerPublicKey(publicKey, label) {
5817
+ if (publicKey === void 0 || publicKey === null) return void 0;
5818
+ if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS2) {
5819
+ throw new Error(`${label} must be a non-zero field element (bigint)`);
5820
+ }
5821
+ return publicKey;
5822
+ }
5823
+
5824
+ // src/notes/swap-refund.ts
5701
5825
  init_inputs();
5702
5826
  var bs582 = import_bs582.default.default || import_bs582.default;
5703
5827
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
5704
- var REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5828
+ var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5705
5829
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
5706
5830
  function normalizeNullifier(inputNullifier) {
5707
5831
  if (inputNullifier instanceof Uint8Array) {
@@ -5735,13 +5859,29 @@ function derive(nk, nullifier, info) {
5735
5859
  preimage.set(info, off);
5736
5860
  return (0, import_blake34.blake3)(preimage);
5737
5861
  }
5738
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5862
+ function assertNk(viewingKeyNk) {
5739
5863
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5740
5864
  throw new Error("viewingKeyNk must be 32 bytes");
5741
5865
  }
5866
+ return viewingKeyNk;
5867
+ }
5868
+ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
5869
+ const nk = assertNk(viewingKeyNk);
5870
+ return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
5871
+ }
5872
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
5873
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5874
+ const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5875
+ if (owner.publicKey === 0n || blinding === 0n) {
5876
+ throw new Error("refund authorization is degenerate");
5877
+ }
5878
+ return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
5879
+ }
5880
+ async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5881
+ const nk = assertNk(viewingKeyNk);
5742
5882
  const nullifier = normalizeNullifier(inputNullifier);
5743
- const privateKey = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_PRIVATE_KEY_INFO));
5744
- const blinding = toFieldSecret(derive(viewingKeyNk, nullifier, REFUND_BLINDING_INFO));
5883
+ const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
5884
+ const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
5745
5885
  const publicKey = await derivePublicKey(privateKey);
5746
5886
  if (publicKey === 0n || blinding === 0n) {
5747
5887
  throw new Error("derived refund authorization is degenerate");
@@ -5759,19 +5899,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
5759
5899
  async function matchSwapRefundLeaf(params) {
5760
5900
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
5761
5901
  const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
5762
- let auth;
5902
+ let blinding;
5903
+ try {
5904
+ blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5905
+ } catch {
5906
+ return null;
5907
+ }
5908
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5909
+ if (ownerPub !== void 0) {
5910
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
5911
+ if (candidate === expected) {
5912
+ return {
5913
+ keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
5914
+ blinding,
5915
+ amount: amountAfterFee,
5916
+ commitment: candidate,
5917
+ legacyExposed: false
5918
+ };
5919
+ }
5920
+ }
5921
+ let legacy;
5763
5922
  try {
5764
- auth = await deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier);
5923
+ legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
5765
5924
  } catch {
5766
5925
  return null;
5767
5926
  }
5768
- const candidate = await computeSwapRefundCommitment(amountAfterFee, auth.publicKey, auth.blinding);
5769
- if (candidate !== expected) return null;
5927
+ const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
5928
+ if (legacyCandidate !== expected) return null;
5770
5929
  return {
5771
- keypair: { privateKey: auth.privateKey, publicKey: auth.publicKey },
5772
- blinding: auth.blinding,
5930
+ keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
5931
+ blinding: legacy.blinding,
5773
5932
  amount: amountAfterFee,
5774
- commitment: candidate
5933
+ commitment: legacyCandidate,
5934
+ legacyExposed: true
5775
5935
  };
5776
5936
  }
5777
5937
  var TRANSACT_SWAP_TAG2 = 1;
@@ -5835,10 +5995,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
5835
5995
  if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
5836
5996
  return out;
5837
5997
  }
5838
- async function discoverSwapRefunds(connection, programId, viewingKeyNk, options = {}) {
5998
+ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
5839
5999
  if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5840
6000
  throw new Error("viewingKeyNk must be 32 bytes");
5841
6001
  }
6002
+ if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
6003
+ throw new Error(
6004
+ "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."
6005
+ );
6006
+ }
6007
+ const ownerUtxoKeypair = options.ownerUtxoKeypair;
5842
6008
  const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
5843
6009
  const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
5844
6010
  const programIdBase58 = programId;
@@ -5913,7 +6079,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
5913
6079
  viewingKeyNk,
5914
6080
  inputNullifier: candidate.nullifier,
5915
6081
  amountAfterFee: event.amountAfterFee,
5916
- commitment: event.commitmentField
6082
+ commitment: event.commitmentField,
6083
+ ownerUtxoKeypair
5917
6084
  });
5918
6085
  if (!recovered) continue;
5919
6086
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5939,7 +6106,7 @@ var import_blake35 = require("@noble/hashes/blake3");
5939
6106
  init_utxo();
5940
6107
  init_inputs();
5941
6108
  var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
5942
- var DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6109
+ var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5943
6110
  var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
5944
6111
  var CHAIN_NOTE_SALT_BITS = 96;
5945
6112
  var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
@@ -5975,30 +6142,47 @@ function derive2(nk, salt, info) {
5975
6142
  preimage.set(info, off);
5976
6143
  return (0, import_blake35.blake3)(preimage);
5977
6144
  }
6145
+ function assertNk2(viewingKeyNk) {
6146
+ if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
6147
+ throw new Error("viewingKeyNk must be 32 bytes");
6148
+ }
6149
+ return viewingKeyNk;
6150
+ }
5978
6151
  function randomDepositNoteSalt() {
5979
6152
  const bytes = randomBytes(12);
5980
6153
  let v = 0n;
5981
6154
  for (const b of bytes) v = v << 8n | BigInt(b);
5982
6155
  return v === 0n ? 1n : v;
5983
6156
  }
5984
- async function deriveDepositNoteSecrets(viewingKeyNk, noteSalt) {
5985
- if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
5986
- throw new Error("viewingKeyNk must be 32 bytes");
5987
- }
6157
+ function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
6158
+ const nk = assertNk2(viewingKeyNk);
6159
+ return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
6160
+ }
6161
+ async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
6162
+ const nk = assertNk2(viewingKeyNk);
5988
6163
  const salt = saltToBytes(noteSalt);
5989
- const privateKey = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_PRIVATE_KEY_INFO));
5990
- const blinding = toFieldSecret2(derive2(viewingKeyNk, salt, DEPOSIT_BLINDING_INFO));
6164
+ const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
6165
+ const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
5991
6166
  const publicKey = await derivePublicKey(privateKey);
5992
6167
  if (publicKey === 0n || blinding === 0n) {
5993
6168
  throw new Error("derived deposit note secrets are degenerate");
5994
6169
  }
5995
6170
  return { keypair: { privateKey, publicKey }, blinding };
5996
6171
  }
5997
- async function createRecoverableDepositUtxo(amount, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomDepositNoteSalt()) {
6172
+ async function createRecoverableDepositUtxo(params) {
6173
+ if (!params || typeof params !== "object" || params instanceof Uint8Array) {
6174
+ throw new Error(
6175
+ "createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
6176
+ );
6177
+ }
6178
+ const { amount, viewingKeyNk } = params;
5998
6179
  if (typeof amount !== "bigint" || amount <= 0n) {
5999
6180
  throw new Error("amount must be a positive bigint");
6000
6181
  }
6001
- const { keypair, blinding } = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
6182
+ const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
6183
+ const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
6184
+ const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
6185
+ const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
6002
6186
  const utxo = { amount, keypair, blinding, mintAddress };
6003
6187
  utxo.commitment = await computeCommitment2(utxo);
6004
6188
  return { utxo, noteSalt };
@@ -6013,21 +6197,46 @@ function normalizeCommitment(value) {
6013
6197
  async function matchDepositNote(params) {
6014
6198
  const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
6015
6199
  if (typeof amount !== "bigint" || amount <= 0n) return null;
6016
- let secrets;
6200
+ let blinding;
6201
+ try {
6202
+ blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
6203
+ } catch {
6204
+ return null;
6205
+ }
6206
+ const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
6207
+ if (published.length === 0) return null;
6208
+ const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
6209
+ if (ownerPub !== void 0) {
6210
+ const keypair = {
6211
+ privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
6212
+ publicKey: ownerPub
6213
+ };
6214
+ const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
6215
+ if (published.some((value) => value === candidate)) {
6216
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
6217
+ }
6218
+ }
6219
+ let legacy;
6017
6220
  try {
6018
- secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
6221
+ legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
6019
6222
  } catch {
6020
6223
  return null;
6021
6224
  }
6022
- const candidate = await computeCommitment2({
6225
+ const legacyCandidate = await computeCommitment2({
6023
6226
  amount,
6024
- keypair: secrets.keypair,
6025
- blinding: secrets.blinding,
6227
+ keypair: legacy.keypair,
6228
+ blinding: legacy.blinding,
6026
6229
  mintAddress
6027
6230
  });
6028
- const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
6029
- if (!published.some((value) => value === candidate)) return null;
6030
- return { ...secrets, amount, mintAddress, commitment: candidate, noteSalt };
6231
+ if (!published.some((value) => value === legacyCandidate)) return null;
6232
+ return {
6233
+ ...legacy,
6234
+ amount,
6235
+ mintAddress,
6236
+ commitment: legacyCandidate,
6237
+ noteSalt,
6238
+ legacyExposed: true
6239
+ };
6031
6240
  }
6032
6241
 
6033
6242
  // src/notes/change-note.ts
@@ -6085,10 +6294,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
6085
6294
  preimage.set(CHANGE_BLINDING_INFO, off);
6086
6295
  return toFieldSecret3((0, import_blake36.blake3)(preimage));
6087
6296
  }
6088
- async function createRecoverableChangeUtxo(amount, keypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
6297
+ async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
6089
6298
  if (typeof amount !== "bigint" || amount <= 0n) {
6090
6299
  throw new Error("amount must be a positive bigint");
6091
6300
  }
6301
+ const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
6092
6302
  const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
6093
6303
  const utxo = { amount, keypair, blinding, mintAddress };
6094
6304
  utxo.commitment = await computeCommitment2(utxo);
@@ -6114,12 +6324,28 @@ async function matchChangeNote(params) {
6114
6324
  const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
6115
6325
  const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
6116
6326
  if (!published.some((value) => value === candidate)) return null;
6117
- return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt };
6327
+ const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
6328
+ const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
6329
+ return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
6118
6330
  }
6119
6331
 
6120
6332
  // src/flows/transact.ts
6121
6333
  var import_circomlibjs4 = require("circomlibjs");
6122
6334
  var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
6335
+
6336
+ // src/relay/chain-note-time.ts
6337
+ async function relayChainNoteTimestampMs(relayUrl) {
6338
+ if (relayUrl && !hasRelayClockSample()) {
6339
+ try {
6340
+ const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
6341
+ await response.body?.cancel?.().catch(() => void 0);
6342
+ } catch {
6343
+ }
6344
+ }
6345
+ return BigInt(relayNowMs());
6346
+ }
6347
+
6348
+ // src/flows/transact.ts
6123
6349
  init_inputs();
6124
6350
 
6125
6351
  // src/proving/artifacts.ts
@@ -6742,6 +6968,9 @@ function assertInputMints(inputUtxos, expectedMint) {
6742
6968
  );
6743
6969
  }
6744
6970
  }
6971
+ function affiliateCodeOrUndefined(code) {
6972
+ return typeof code === "string" && code.length > 0 ? code : void 0;
6973
+ }
6745
6974
  function parseNkInput(input) {
6746
6975
  if (typeof input !== "string") {
6747
6976
  if (input.length !== 32) {
@@ -6755,6 +6984,33 @@ function parseNkInput(input) {
6755
6984
  }
6756
6985
  return Uint8Array.from(Buffer.from(clean, "hex"));
6757
6986
  }
6987
+ async function resolveWalletNk(options) {
6988
+ const explicit = await resolveChainNoteNk(options);
6989
+ if (explicit) return explicit;
6990
+ if (options.ownerUtxoKeypair) {
6991
+ const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
6992
+ return getNkFromUtxoPrivateKey(owner.privateKey);
6993
+ }
6994
+ return null;
6995
+ }
6996
+ function missingWalletNkError(flow) {
6997
+ return new Error(
6998
+ `${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.`
6999
+ );
7000
+ }
7001
+ async function requireWalletNk(options, flow) {
7002
+ const nk = await resolveWalletNk(options);
7003
+ if (nk) return nk;
7004
+ throw missingWalletNkError(flow);
7005
+ }
7006
+ async function requireOwnerUtxoKeypair(options, flow) {
7007
+ if (!options.ownerUtxoKeypair) {
7008
+ throw new Error(
7009
+ `${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].`
7010
+ );
7011
+ }
7012
+ return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
7013
+ }
6758
7014
  async function resolveChainNoteNk(options) {
6759
7015
  if (options.chainNoteViewingKeyNk) {
6760
7016
  return parseNkInput(options.chainNoteViewingKeyNk);
@@ -6772,7 +7028,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
6772
7028
  function toHex(bytes) {
6773
7029
  return Buffer.from(bytes).toString("hex");
6774
7030
  }
6775
- async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
7031
+ async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
6776
7032
  if (options.enforceViewingKeyRegistration === false) {
6777
7033
  return;
6778
7034
  }
@@ -6786,7 +7042,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
6786
7042
  "Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
6787
7043
  );
6788
7044
  }
6789
- const nk = await resolveChainNoteNk(options) ?? fallbackNk ?? null;
7045
+ const nk = walletNk;
6790
7046
  if (!nk || nk.length !== 32) {
6791
7047
  throw new Error(
6792
7048
  "Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
@@ -6928,10 +7184,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
6928
7184
  result.set(bigintToBytes323(BigInt(publicSignals[0])), offset);
6929
7185
  offset += 32;
6930
7186
  let amount = BigInt(publicSignals[1]);
6931
- const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
6932
- const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
7187
+ const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
7188
+ const HALF_FIELD = FIELD_MODULUS3 / BigInt(2);
6933
7189
  if (amount > HALF_FIELD) {
6934
- amount = amount - FIELD_MODULUS2;
7190
+ amount = amount - FIELD_MODULUS3;
6935
7191
  }
6936
7192
  const amountBytes = new Uint8Array(8);
6937
7193
  let amountValue = amount;
@@ -7878,8 +8134,9 @@ function chargeWalletApproval(used, budget, lastError) {
7878
8134
  }
7879
8135
  return used + 1;
7880
8136
  }
7881
- function relayFailureMessage(prefix, responseText) {
7882
- const explanation = explainRelayAuthRejection(responseText);
8137
+ function relayFailureMessage(prefix, responseText, requestBody) {
8138
+ const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
8139
+ const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
7883
8140
  return explanation ? `${prefix}: ${responseText}
7884
8141
 
7885
8142
  ${explanation}` : `${prefix}: ${responseText}`;
@@ -8085,6 +8342,39 @@ function buildTransactRequestBody(params) {
8085
8342
  if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
8086
8343
  body.recipient_delivery_notes = params.recipientDeliveryNotes;
8087
8344
  }
8345
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
8346
+ if (affiliateCode && params.externalAmount < BigInt(0) && params.recipient) {
8347
+ body.affiliate_code = affiliateCode;
8348
+ }
8349
+ return body;
8350
+ }
8351
+ function buildTransactSwapRequestBody(params) {
8352
+ const body = {
8353
+ proof_bytes: params.proofB64,
8354
+ public_inputs: params.publicInputsB64,
8355
+ output_mint: params.outputMint,
8356
+ recipient_ata: params.recipientAta,
8357
+ recipient: params.recipientWallet,
8358
+ // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
8359
+ // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
8360
+ min_output_amount: params.minOutputAmount.toString(),
8361
+ // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
8362
+ max_fee: params.maxFee.toString(),
8363
+ slippage_bps: params.slippageBps,
8364
+ dexes: params.dexes && params.dexes.length > 0 ? params.dexes : void 0,
8365
+ exclude_dexes: params.excludeDexes && params.excludeDexes.length > 0 ? params.excludeDexes : void 0,
8366
+ route_retry_attempts: params.routeRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(params.routeRetryAttempts))) : void 0,
8367
+ swap_max_retries: params.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(params.swapMaxRetries))) : void 0,
8368
+ encrypted_notes: params.encryptedNotes,
8369
+ risk_quote: params.riskQuote,
8370
+ // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
8371
+ // bound into the proof's ext_data_hash. The relay forwards both verbatim into the swap
8372
+ // params; the program builds the amount-bound R_fb from them at close.
8373
+ refund_pubkey: params.refundPubkeyB64,
8374
+ refund_blinding: params.refundBlindingB64
8375
+ };
8376
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
8377
+ if (affiliateCode) body.affiliate_code = affiliateCode;
8088
8378
  return body;
8089
8379
  }
8090
8380
  function resolveUserWallet(options) {
@@ -8220,10 +8510,11 @@ async function submitTransactToRelay(args) {
8220
8510
  try {
8221
8511
  response = await doFetch(`${relayUrl}/transact`, {
8222
8512
  method: "POST",
8223
- headers: { "Content-Type": "application/json" },
8513
+ headers: mergeRelayHeaders({ "Content-Type": "application/json" }, args.extraHeaders),
8224
8514
  body: requestPayload,
8225
8515
  signal: controller.signal
8226
8516
  });
8517
+ observeRelayClock(response);
8227
8518
  } finally {
8228
8519
  clearTimeout(timeoutId);
8229
8520
  }
@@ -8254,7 +8545,9 @@ async function submitTransactToRelay(args) {
8254
8545
  onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
8255
8546
  return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
8256
8547
  }
8257
- return await resolveFailure(new Error(relayFailureMessage("Relay error", responseText)));
8548
+ return await resolveFailure(
8549
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8550
+ );
8258
8551
  }
8259
8552
  const apiResponse = JSON.parse(responseText);
8260
8553
  if (!apiResponse.success || !apiResponse.data) {
@@ -8271,7 +8564,7 @@ async function submitTransactToRelay(args) {
8271
8564
  return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
8272
8565
  }
8273
8566
  return await resolveFailure(
8274
- new Error(relayFailureMessage("Relay returned error", errorStr))
8567
+ new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
8275
8568
  );
8276
8569
  }
8277
8570
  const result = apiResponse.data;
@@ -8379,34 +8672,37 @@ async function transact(params, options) {
8379
8672
  );
8380
8673
  }
8381
8674
  onProgress?.("Validating transaction parameters...");
8382
- const firstInputWithAmount = inputUtxos.find((u) => u.amount > BigInt(0));
8383
- const firstOutputWithAmount = outputUtxos.find((u) => u.amount > BigInt(0));
8384
- const fallbackNk = firstOutputWithAmount ? getNkFromUtxoPrivateKey(firstOutputWithAmount.keypair.privateKey) : firstInputWithAmount ? getNkFromUtxoPrivateKey(firstInputWithAmount.keypair.privateKey) : void 0;
8385
- const explicitChainNoteNk = await resolveChainNoteNk(options);
8386
- if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
8675
+ const walletNk = await resolveWalletNk(options);
8676
+ const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
8677
+ if (options.chainNoteSalt !== void 0 && !walletNk) {
8387
8678
  throw new Error(
8388
- "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."
8679
+ "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."
8389
8680
  );
8390
8681
  }
8391
8682
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
8392
8683
  const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
8393
- if (explicitChainNoteNk && chainNoteWillCarrySalt) {
8394
- const inputOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8684
+ if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
8685
+ throw missingWalletNkError("transact");
8686
+ }
8687
+ if (walletNk && chainNoteWillCarrySalt) {
8688
+ const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
8689
+ if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
8690
+ const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
8395
8691
  for (let i = 0; i < outputUtxos.length; i++) {
8396
8692
  const out = outputUtxos[i];
8397
8693
  if (!out || out.amount <= BigInt(0)) continue;
8398
- if (!inputOwners.has(out.keypair.publicKey)) continue;
8399
- if (out.blinding !== deriveChangeNoteBlinding(explicitChainNoteNk, chainNoteSalt, i)) {
8694
+ if (!selfOwners.has(out.keypair.publicKey)) continue;
8695
+ if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
8400
8696
  throw new Error(
8401
- `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.`
8697
+ `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.`
8402
8698
  );
8403
8699
  }
8404
8700
  }
8405
8701
  }
8406
8702
  assertAllowedRpcConnection(connection);
8407
8703
  assertInputMints(inputUtxos, options.expectedMint);
8408
- await ensureViewingKeyRegistered(options, onProgress, fallbackNk);
8409
- const resolvedChainNoteNk = explicitChainNoteNk ?? fallbackNk ?? null;
8704
+ await ensureViewingKeyRegistered(options, onProgress, walletNk);
8705
+ const resolvedChainNoteNk = walletNk;
8410
8706
  if (inputUtxos.length > 2) {
8411
8707
  throw new Error("Maximum 2 input UTXOs allowed");
8412
8708
  }
@@ -8780,7 +9076,7 @@ async function transact(params, options) {
8780
9076
  }
8781
9077
  const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
8782
9078
  const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
8783
- const chainNoteTimestamp = BigInt(Date.now());
9079
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
8784
9080
  const mintField = pubkeyToFieldElement(mint);
8785
9081
  let signature = "pending-" + Date.now().toString();
8786
9082
  let commitmentIndices = [-1, -1];
@@ -8876,9 +9172,9 @@ async function transact(params, options) {
8876
9172
  ]));
8877
9173
  const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
8878
9174
  const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
8879
- const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
8880
- if (chainNoteHash >= FIELD_MODULUS2) {
8881
- throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
9175
+ const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
9176
+ if (chainNoteHash >= FIELD_MODULUS3) {
9177
+ throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS3.toString()}`);
8882
9178
  }
8883
9179
  const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
8884
9180
  const totalInputs = 1 + // root
@@ -9243,7 +9539,10 @@ async function transact(params, options) {
9243
9539
  // For Send (shield-to-shield): always include sender so relay can enforce sanctions checks.
9244
9540
  sender: externalAmount === BigInt(0) && !recipient ? depositorPubkey : void 0,
9245
9541
  externalAmount,
9246
- recipientDeliveryNotes
9542
+ recipientDeliveryNotes,
9543
+ // SDK-002: attached only to a withdrawal / send to a public address; the builder ignores it
9544
+ // for deposits and shield-to-shield sends.
9545
+ affiliateCode: options.affiliateCode
9247
9546
  });
9248
9547
  void metadataBundle;
9249
9548
  const relaySubmission = await submitTransactToRelay({
@@ -9264,7 +9563,8 @@ async function transact(params, options) {
9264
9563
  inputNullifiers
9265
9564
  },
9266
9565
  canRetryStaleRoot: submissionAttempts < maxRootRetries,
9267
- onProgress
9566
+ onProgress,
9567
+ extraHeaders: options.relayHeaders
9268
9568
  });
9269
9569
  if (relaySubmission.kind === "stale-root") {
9270
9570
  lastError = relaySubmission.error;
@@ -9296,7 +9596,8 @@ async function transact(params, options) {
9296
9596
  throw lastError;
9297
9597
  }
9298
9598
  const classified = classifyRelayError(lastError.message);
9299
- const isMerkleClass = !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9599
+ const isDepositSubmission = externalAmount > BigInt(0);
9600
+ const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
9300
9601
  if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
9301
9602
  onProgress?.(
9302
9603
  "All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
@@ -9445,54 +9746,83 @@ async function transact(params, options) {
9445
9746
  };
9446
9747
  }
9447
9748
  async function transfer(inputUtxos, recipientPubkey, amount, options) {
9749
+ const owner = await requireOwnerUtxoKeypair(options, "transfer");
9750
+ const transferNk = await requireWalletNk(options, "transfer");
9448
9751
  const inputSum = sumUtxoAmounts(inputUtxos);
9449
9752
  if (inputSum < amount) {
9450
9753
  throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
9451
9754
  }
9452
9755
  const change = inputSum - amount;
9453
- const myKeypair = inputUtxos[0].keypair;
9454
9756
  const mint = inputUtxos[0].mintAddress;
9455
- const transferNk = await resolveChainNoteNk(options);
9456
- const changeNoteSalt = transferNk ? randomChangeNoteSalt() : void 0;
9457
- const isSendToSelf = inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
9757
+ let spendInputs = [
9758
+ ...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
9759
+ ...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
9760
+ ];
9761
+ let spendOptions = options;
9762
+ if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
9763
+ if (spendInputs.length > 2) {
9764
+ throw new Error(
9765
+ `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.`
9766
+ );
9767
+ }
9768
+ if (options.relayAuthBatch) {
9769
+ throw new Error(
9770
+ "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."
9771
+ );
9772
+ }
9773
+ options.onProgress?.("Moving notes under the wallet key before the transfer...");
9774
+ const migrationSalt = randomChangeNoteSalt();
9775
+ const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
9776
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
9777
+ void _recipientViewingPublicKey;
9778
+ const migration = await transact(
9779
+ { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
9780
+ { ...migrationOptions, chainNoteSalt: migrationSalt }
9781
+ );
9782
+ const migratedNote = migration.outputUtxos?.[0] ?? migrated;
9783
+ if (migration.commitmentIndices?.[0] >= 0) {
9784
+ migratedNote.index = migration.commitmentIndices[0];
9785
+ }
9786
+ spendInputs = [migratedNote];
9787
+ spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
9788
+ }
9789
+ const changeNoteSalt = randomChangeNoteSalt();
9790
+ const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
9458
9791
  const recipientKeypair = {
9459
9792
  privateKey: BigInt(0),
9460
9793
  // Recipient's private key unknown
9461
9794
  publicKey: recipientPubkey
9462
9795
  };
9463
- const recipientUtxo = transferNk && isSendToSelf ? (await createRecoverableChangeUtxo(amount, myKeypair, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
9796
+ const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
9464
9797
  const outputUtxos = [recipientUtxo];
9465
9798
  if (change > BigInt(0)) {
9466
- if (transferNk) {
9467
- const { utxo } = await createRecoverableChangeUtxo(
9468
- change,
9469
- myKeypair,
9470
- transferNk,
9471
- mint,
9472
- changeNoteSalt,
9473
- 1
9474
- );
9475
- outputUtxos.push(utxo);
9476
- } else {
9477
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
9478
- }
9799
+ const { utxo } = await createRecoverableChangeUtxo(
9800
+ change,
9801
+ owner,
9802
+ transferNk,
9803
+ mint,
9804
+ changeNoteSalt,
9805
+ 1
9806
+ );
9807
+ outputUtxos.push(utxo);
9479
9808
  }
9480
9809
  return transact(
9481
9810
  {
9482
- inputUtxos,
9811
+ inputUtxos: spendInputs,
9483
9812
  outputUtxos,
9484
9813
  externalAmount: BigInt(0)
9485
9814
  // Pure shield-to-shield
9486
9815
  },
9487
- changeNoteSalt !== void 0 ? { ...options, chainNoteSalt: changeNoteSalt } : options
9816
+ { ...spendOptions, chainNoteSalt: changeNoteSalt }
9488
9817
  );
9489
9818
  }
9490
9819
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9820
+ const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
9821
+ const walletNk = await requireWalletNk(options, "partialWithdraw");
9491
9822
  const inputSum = sumUtxoAmounts(inputUtxos);
9492
9823
  if (inputSum < withdrawAmount) {
9493
9824
  throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
9494
9825
  }
9495
- const myKeypair = inputUtxos[0].keypair;
9496
9826
  const mint = inputUtxos[0].mintAddress;
9497
9827
  let utxos = [...inputUtxos];
9498
9828
  let cachedTree = options.cachedMerkleTree;
@@ -9501,9 +9831,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9501
9831
  utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
9502
9832
  const [small1, small2, ...rest] = utxos;
9503
9833
  const mergedAmount = small1.amount + small2.amount;
9504
- const mergeNk = await resolveChainNoteNk(options);
9505
- const mergeSalt = mergeNk ? randomChangeNoteSalt() : void 0;
9506
- const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
9834
+ const mergeSalt = randomChangeNoteSalt();
9835
+ const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
9507
9836
  const mergeResult = await transact(
9508
9837
  {
9509
9838
  inputUtxos: [small1, small2],
@@ -9514,7 +9843,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9514
9843
  {
9515
9844
  ...options,
9516
9845
  cachedMerkleTree: cachedTree,
9517
- ...mergeSalt !== void 0 && { chainNoteSalt: mergeSalt }
9846
+ chainNoteSalt: mergeSalt
9518
9847
  }
9519
9848
  );
9520
9849
  cachedTree = mergeResult.merkleTree;
@@ -9529,23 +9858,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9529
9858
  const outputUtxos = [];
9530
9859
  let changeNoteSalt;
9531
9860
  if (change > BigInt(0)) {
9532
- const changeNk = await resolveChainNoteNk(options);
9533
- if (changeNk) {
9534
- const salt = randomChangeNoteSalt();
9535
- const { utxo } = await createRecoverableChangeUtxo(
9536
- change,
9537
- myKeypair,
9538
- changeNk,
9539
- mint,
9540
- salt,
9541
- 0
9542
- // partialWithdraw puts change at output 0
9543
- );
9544
- outputUtxos.push(utxo);
9545
- changeNoteSalt = salt;
9546
- } else {
9547
- outputUtxos.push(await createUtxo(change, myKeypair, mint));
9548
- }
9861
+ const salt = randomChangeNoteSalt();
9862
+ const { utxo } = await createRecoverableChangeUtxo(
9863
+ change,
9864
+ owner,
9865
+ walletNk,
9866
+ mint,
9867
+ salt,
9868
+ 0
9869
+ // partialWithdraw puts change at output 0
9870
+ );
9871
+ outputUtxos.push(utxo);
9872
+ changeNoteSalt = salt;
9549
9873
  }
9550
9874
  return transact(
9551
9875
  {
@@ -9668,6 +9992,8 @@ async function swapUtxo(params, options) {
9668
9992
  if (relayUrl) {
9669
9993
  assertRelayAuthAvailable(relayAuthPlan, "private swap");
9670
9994
  }
9995
+ const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
9996
+ const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
9671
9997
  if (inputUtxos.length === 0) {
9672
9998
  throw new Error("At least one input UTXO required");
9673
9999
  }
@@ -9693,15 +10019,12 @@ async function swapUtxo(params, options) {
9693
10019
  throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
9694
10020
  }
9695
10021
  onProgress?.("Validating transaction parameters...");
9696
- const swapFallbackNk = getNkFromUtxoPrivateKey(inputUtxos[0].keypair.privateKey);
9697
- await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
9698
- const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
9699
- const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
10022
+ await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
9700
10023
  const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
9701
- if (explicitSwapChainNoteNk && changeUtxo && changeUtxo.amount > BigInt(0) && inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey)) {
9702
- if (changeUtxo.blinding !== deriveChangeNoteBlinding(explicitSwapChainNoteNk, chainNoteSalt, 0)) {
10024
+ if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
10025
+ if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
9703
10026
  throw new Error(
9704
- `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.`
10027
+ `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.`
9705
10028
  );
9706
10029
  }
9707
10030
  }
@@ -9725,24 +10048,18 @@ async function swapUtxo(params, options) {
9725
10048
  );
9726
10049
  }
9727
10050
  const externalAmount = -swapAmount;
9728
- let refundKeypair;
9729
- let refundBlinding;
9730
- let refundDerivedFromNk = false;
9731
- if (resolvedSwapChainNoteNk) {
9732
- try {
9733
- const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
9734
- const derived = await deriveSwapRefundAuthorization(resolvedSwapChainNoteNk, refundNullifier);
9735
- refundKeypair = { privateKey: derived.privateKey, publicKey: derived.publicKey };
9736
- refundBlinding = derived.blinding;
9737
- refundDerivedFromNk = true;
9738
- } catch {
9739
- refundKeypair = await generateUtxoKeypair();
9740
- refundBlinding = randomFieldElement();
9741
- }
9742
- } else {
9743
- refundKeypair = await generateUtxoKeypair();
9744
- refundBlinding = randomFieldElement();
9745
- }
10051
+ const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
10052
+ const refundAuthorization = await deriveSwapRefundAuthorization(
10053
+ resolvedSwapChainNoteNk,
10054
+ refundNullifier,
10055
+ swapOwner
10056
+ );
10057
+ const refundKeypair = {
10058
+ privateKey: refundAuthorization.privateKey,
10059
+ publicKey: refundAuthorization.publicKey
10060
+ };
10061
+ const refundBlinding = refundAuthorization.blinding;
10062
+ const refundDerivedFromNk = true;
9746
10063
  if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
9747
10064
  throw new Error(
9748
10065
  "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."
@@ -10068,7 +10385,7 @@ async function swapUtxo(params, options) {
10068
10385
  for (const utxo of paddedOutputs) {
10069
10386
  outputCommitments.push(await computeCommitment2(utxo));
10070
10387
  }
10071
- const chainNoteTimestamp = BigInt(Date.now());
10388
+ const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
10072
10389
  onProgress?.("Computing external data hash...");
10073
10390
  const mint = swapPoolMint;
10074
10391
  const mintField = pubkeyToFieldElement(mint);
@@ -10311,30 +10628,27 @@ async function swapUtxo(params, options) {
10311
10628
  const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
10312
10629
  await options.onSwapStatePredicted(ssp);
10313
10630
  }
10314
- const requestBody = {
10315
- proof_bytes: proofB64,
10316
- public_inputs: publicInputsB64,
10317
- output_mint: outputMint,
10318
- recipient_ata: recipientAta,
10319
- recipient: recipientWallet,
10320
- // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
10321
- // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
10322
- min_output_amount: minOutputAmount.toString(),
10323
- // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
10324
- max_fee: swapMaxFee.toString(),
10325
- slippage_bps: swapSlippageBps,
10326
- dexes: swapDexes && swapDexes.length > 0 ? swapDexes : void 0,
10327
- exclude_dexes: swapExcludeDexes && swapExcludeDexes.length > 0 ? swapExcludeDexes : void 0,
10328
- route_retry_attempts: options.swapRouteRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(options.swapRouteRetryAttempts))) : void 0,
10329
- swap_max_retries: options.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(options.swapMaxRetries))) : void 0,
10330
- encrypted_notes: encryptedNotes,
10331
- risk_quote: riskQuoteData,
10332
- // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
10333
- // bound into the proof's ext_data_hash above. The relay forwards both verbatim into the swap
10334
- // params; the program builds the amount-bound R_fb from them at close.
10335
- refund_pubkey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("base64"),
10336
- refund_blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("base64")
10337
- };
10631
+ const requestBody = buildTransactSwapRequestBody({
10632
+ proofB64,
10633
+ publicInputsB64,
10634
+ outputMint,
10635
+ recipientAta,
10636
+ recipientWallet,
10637
+ minOutputAmount,
10638
+ maxFee: swapMaxFee,
10639
+ slippageBps: swapSlippageBps,
10640
+ dexes: swapDexes,
10641
+ excludeDexes: swapExcludeDexes,
10642
+ routeRetryAttempts: options.swapRouteRetryAttempts,
10643
+ swapMaxRetries: options.swapMaxRetries,
10644
+ encryptedNotes,
10645
+ riskQuote: riskQuoteData,
10646
+ refundPubkeyB64: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("base64"),
10647
+ refundBlindingB64: Buffer.from(bigintToBytes323(refundBlinding)).toString("base64"),
10648
+ // SDK-001/002: a swap intake is fee-bearing. Every attempt of this loop is a new intake with
10649
+ // a fresh proof, so each one carries the code; none of them is a `retry_request_id` retry.
10650
+ affiliateCode: options.affiliateCode
10651
+ });
10338
10652
  try {
10339
10653
  if (relayAuthPlan.kind === "wallet") {
10340
10654
  walletApprovals = chargeWalletApproval(walletApprovals, walletApprovalBudget, lastError);
@@ -10353,11 +10667,16 @@ async function swapUtxo(params, options) {
10353
10667
  TRANSACT_SWAP_AUTH_FIELDS
10354
10668
  );
10355
10669
  if (swapAuthFields) Object.assign(requestBody, swapAuthFields);
10356
- const response = await relayFetch(`${relayUrl}/transact_swap`, {
10357
- method: "POST",
10358
- headers: { "Content-Type": "application/json" },
10359
- body: JSON.stringify(requestBody)
10360
- });
10670
+ const response = await relayFetch(
10671
+ `${relayUrl}/transact_swap`,
10672
+ {
10673
+ method: "POST",
10674
+ headers: { "Content-Type": "application/json" },
10675
+ body: JSON.stringify(requestBody)
10676
+ },
10677
+ // SDK-004: e.g. the mobile app's `X-Cloak-Client`. Omitted, this is the old call exactly.
10678
+ { extraHeaders: options.relayHeaders }
10679
+ );
10361
10680
  const responseText = await response.text();
10362
10681
  if (!response.ok) {
10363
10682
  if (isRetryableRelayStatus(response.status) && attempt < maxRootRetries) {
@@ -10380,7 +10699,7 @@ async function swapUtxo(params, options) {
10380
10699
  forceChainIndexing = !relayUrl;
10381
10700
  continue;
10382
10701
  }
10383
- throw new Error(relayFailureMessage("Relay error", responseText));
10702
+ throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
10384
10703
  }
10385
10704
  const apiResponse = JSON.parse(responseText);
10386
10705
  if (!apiResponse.success || !apiResponse.data) {
@@ -10516,7 +10835,6 @@ async function swapUtxo(params, options) {
10516
10835
  // V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
10517
10836
  // swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
10518
10837
  refund: {
10519
- privateKey: Buffer.from(bigintToBytes323(refundKeypair.privateKey)).toString("hex"),
10520
10838
  publicKey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("hex"),
10521
10839
  blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("hex"),
10522
10840
  derivedFromNk: refundDerivedFromNk
@@ -10524,6 +10842,7 @@ async function swapUtxo(params, options) {
10524
10842
  };
10525
10843
  }
10526
10844
  async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
10845
+ const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
10527
10846
  const totalInput = sumUtxoAmounts(inputUtxos);
10528
10847
  const change = totalInput - swapAmount;
10529
10848
  if (change < BigInt(0)) {
@@ -10532,16 +10851,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
10532
10851
  let changeUtxo;
10533
10852
  let changeNoteSalt;
10534
10853
  if (change > BigInt(0)) {
10535
- const myKeypair = inputUtxos[0].keypair;
10536
10854
  const mint = inputUtxos[0].mintAddress;
10537
- const changeNk = await resolveChainNoteNk(options);
10538
- if (changeNk) {
10539
- const salt = randomChangeNoteSalt();
10540
- changeUtxo = (await createRecoverableChangeUtxo(change, myKeypair, changeNk, mint, salt, 0)).utxo;
10541
- changeNoteSalt = salt;
10542
- } else {
10543
- changeUtxo = await createUtxo(change, myKeypair, mint);
10544
- }
10855
+ const changeNk = await requireWalletNk(options, "swapWithChange");
10856
+ const salt = randomChangeNoteSalt();
10857
+ changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
10858
+ changeNoteSalt = salt;
10545
10859
  }
10546
10860
  return swapUtxo(
10547
10861
  {
@@ -10867,7 +11181,7 @@ var RelayBatchAuthCoordinator = class {
10867
11181
  throw new Error("Every item of a batch must target the same program id.");
10868
11182
  }
10869
11183
  }
10870
- const nowSeconds = Math.floor(Date.now() / 1e3);
11184
+ const nowSeconds = relayNowSeconds();
10871
11185
  const preimages = waiting.map(
10872
11186
  (w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
10873
11187
  );
@@ -11308,7 +11622,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
11308
11622
  const cached = depositSecretsCache.get(key);
11309
11623
  if (cached) return cached;
11310
11624
  try {
11311
- const secrets = await deriveDepositNoteSecrets(viewingKeyNk, noteSalt);
11625
+ const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
11312
11626
  if (depositSecretsCache.size >= 4096) {
11313
11627
  const oldest = depositSecretsCache.keys().next();
11314
11628
  if (!oldest.done) depositSecretsCache.delete(oldest.value);
@@ -11891,6 +12205,7 @@ async function scanTransactions(opts) {
11891
12205
  } else {
11892
12206
  const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
11893
12207
  const candidateKeys = [
12208
+ opts.ownerUtxoPublicKey,
11894
12209
  derived?.keypair.publicKey,
11895
12210
  opts.ownUtxoPublicKey,
11896
12211
  BigInt(0)
@@ -11944,6 +12259,7 @@ async function scanTransactions(opts) {
11944
12259
  try {
11945
12260
  const recoveredDeposit = await matchDepositNote({
11946
12261
  viewingKeyNk,
12262
+ ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
11947
12263
  noteSalt: compactNote.noteSalt,
11948
12264
  // Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
11949
12265
  // deposit — that is the public deposit amount. A deposit that also merged inputs
@@ -11978,7 +12294,8 @@ async function scanTransactions(opts) {
11978
12294
  mintAddress: (0, import_kit.address)(asset.mint),
11979
12295
  outputIndex: 0,
11980
12296
  // v4 describes output 0, which is where change lands
11981
- outputCommitments: ixCtx.outputCommitments ?? []
12297
+ outputCommitments: ixCtx.outputCommitments ?? [],
12298
+ ownerUtxoPublicKey: opts.ownerUtxoPublicKey
11982
12299
  });
11983
12300
  if (recoveredChange) {
11984
12301
  recoveredChangeNotes.push({
@@ -12088,6 +12405,17 @@ async function scanTransactions(opts) {
12088
12405
  runningByAsset.set(key, running);
12089
12406
  tx.runningBalance = running;
12090
12407
  }
12408
+ const legacyKeys = /* @__PURE__ */ new Map();
12409
+ for (const note of recoveredDepositNotes) {
12410
+ if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
12411
+ }
12412
+ for (const change of recoveredChangeNotes) {
12413
+ const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
12414
+ if (legacyPrivateKey !== void 0) {
12415
+ change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
12416
+ change.legacyExposed = true;
12417
+ }
12418
+ }
12091
12419
  return {
12092
12420
  transactions: txs,
12093
12421
  summary: {
@@ -12826,7 +13154,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12826
13154
  })
12827
13155
  });
12828
13156
  const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
12829
- if (Math.floor(Date.now() / 1e3) >= prepared.expires_at_unix) {
13157
+ if (relayNowSeconds() >= prepared.expires_at_unix) {
12830
13158
  throw new Error(
12831
13159
  "paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
12832
13160
  );
@@ -12863,9 +13191,13 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
12863
13191
  // src/bridge/derive.ts
12864
13192
  var import_hmac = require("@noble/hashes/hmac");
12865
13193
  var import_sha512 = require("@noble/hashes/sha512");
13194
+ var import_blake37 = require("@noble/hashes/blake3");
13195
+ init_utxo();
12866
13196
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
13197
+ var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
13198
+ var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
12867
13199
  var MAX_RECEIVER_INDEX = 1e4;
12868
- async function deriveBridgeReceiver(nk, index) {
13200
+ function assertReceiverIndex(index) {
12869
13201
  if (!Number.isInteger(index) || index < 0) {
12870
13202
  throw new Error(`index must be a non-negative integer, got ${index}`);
12871
13203
  }
@@ -12874,6 +13206,26 @@ async function deriveBridgeReceiver(nk, index) {
12874
13206
  `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.`
12875
13207
  );
12876
13208
  }
13209
+ }
13210
+ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
13211
+ if (ownerUtxoKeypair instanceof Uint8Array) {
13212
+ throw new Error(
13213
+ "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."
13214
+ );
13215
+ }
13216
+ assertReceiverIndex(index);
13217
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
13218
+ const priv = bigintToBytes323(owner.privateKey);
13219
+ const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
13220
+ preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
13221
+ preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
13222
+ const key = (0, import_blake37.blake3)(preimage);
13223
+ const h = (0, import_hmac.hmac)(import_sha512.sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
13224
+ return signerFromSecretKey(h.slice(0, 32));
13225
+ }
13226
+ async function deriveLegacyBridgeReceiver(nk, index) {
13227
+ assertReceiverIndex(index);
13228
+ if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
12877
13229
  const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
12878
13230
  return signerFromSecretKey(h.slice(0, 32));
12879
13231
  }
@@ -12884,13 +13236,44 @@ var import_token4 = require("@solana-program/token");
12884
13236
  function describeError(err) {
12885
13237
  return err instanceof Error ? err.message : String(err);
12886
13238
  }
12887
- async function listBridgeDeposits(rpc, nk, opts) {
13239
+ async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
13240
+ if (ownerUtxoKeypair instanceof Uint8Array) {
13241
+ throw new Error(
13242
+ "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)."
13243
+ );
13244
+ }
13245
+ const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
13246
+ const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
13247
+ legacyExposed: false
13248
+ });
13249
+ if (opts.includeLegacy === false) return out;
13250
+ const nks = [];
13251
+ const seen = /* @__PURE__ */ new Set();
13252
+ for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
13253
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) {
13254
+ throw new Error("legacyViewingKeyNks entries must be 32 bytes");
13255
+ }
13256
+ const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
13257
+ if (seen.has(key)) continue;
13258
+ seen.add(key);
13259
+ nks.push(nk);
13260
+ }
13261
+ for (const nk of nks) {
13262
+ const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
13263
+ legacyExposed: true,
13264
+ legacyViewingKeyNk: nk
13265
+ });
13266
+ out.push(...legacy);
13267
+ }
13268
+ return out;
13269
+ }
13270
+ async function scanReceivers(rpc, opts, receiverAt, provenance) {
12888
13271
  const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
12889
13272
  const stopAfterUnused = opts.stopAfterUnused ?? 5;
12890
13273
  const out = [];
12891
13274
  let consecutiveUnused = 0;
12892
13275
  for (let index = 0; index < scanDepth; index++) {
12893
- const kp = await deriveBridgeReceiver(nk, index);
13276
+ const kp = await receiverAt(index);
12894
13277
  const receiver = kp.address;
12895
13278
  const [tokenAccount] = await (0, import_token4.findAssociatedTokenPda)({
12896
13279
  mint: opts.mint,
@@ -12942,7 +13325,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12942
13325
  tokenBalance,
12943
13326
  lamports,
12944
13327
  shieldSignature,
12945
- ...indexReused ? { indexReused, shieldSignatures } : {}
13328
+ ...indexReused ? { indexReused, shieldSignatures } : {},
13329
+ ...provenance
12946
13330
  });
12947
13331
  } catch (err) {
12948
13332
  out.push({
@@ -12952,7 +13336,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
12952
13336
  state: "unknown",
12953
13337
  tokenBalance: 0n,
12954
13338
  lamports: 0n,
12955
- error: describeError(err)
13339
+ error: describeError(err),
13340
+ ...provenance
12956
13341
  });
12957
13342
  }
12958
13343
  }
@@ -13106,7 +13491,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13106
13491
  const signMessage = (m) => signMessageBytes(R, m);
13107
13492
  const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
13108
13493
  const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
13109
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
13494
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
13495
+ amount,
13496
+ viewingKeyNk: nk,
13497
+ ownerUtxoKeypair: utxoKeypair,
13498
+ mintAddress: mint
13499
+ });
13110
13500
  const zeroInput = await createZeroUtxo(mint);
13111
13501
  const rBefore = (await rpc.getBalance(R.address).send()).value;
13112
13502
  let result;
@@ -13125,6 +13515,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
13125
13515
  signMessage,
13126
13516
  chainNoteViewingKeyNk: nk,
13127
13517
  chainNoteSalt: noteSalt,
13518
+ ownerUtxoKeypair: utxoKeypair,
13128
13519
  relaySupplementalAlt: true,
13129
13520
  onProgress: (s) => log(` \xB7 ${s}`)
13130
13521
  }
@@ -13332,12 +13723,13 @@ async function withShieldRetries(attempt, hooks = {}) {
13332
13723
  }
13333
13724
 
13334
13725
  // src/index.ts
13335
- var VERSION = "0.2.5";
13726
+ var VERSION = "0.2.6";
13336
13727
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13337
13728
  // Annotate the CommonJS export names for ESM import in node:
13338
13729
  0 && (module.exports = {
13339
13730
  AccountRole,
13340
13731
  BRIDGE_ESCROW_LABEL,
13732
+ BRIDGE_ESCROW_LABEL_V2,
13341
13733
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
13342
13734
  CHAIN_NOTE_SALT_BITS,
13343
13735
  CLEANUP_FEE_BUDGET,
@@ -13466,14 +13858,18 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13466
13858
  depositFromDerivedKey,
13467
13859
  deriveBridgeReceiver,
13468
13860
  deriveChangeNoteBlinding,
13469
- deriveDepositNoteSecrets,
13861
+ deriveDepositNoteBlinding,
13470
13862
  deriveDiversifiedViewingKey,
13471
13863
  deriveDiversifier,
13472
13864
  deriveFundingTargets,
13473
13865
  deriveInputNullifierPdas,
13866
+ deriveLegacyBridgeReceiver,
13867
+ deriveLegacyDepositNoteSecrets,
13868
+ deriveLegacySwapRefundAuthorization,
13474
13869
  derivePublicKey,
13475
13870
  deriveSpendKey,
13476
13871
  deriveSwapRefundAuthorization,
13872
+ deriveSwapRefundBlinding,
13477
13873
  deriveUserCompliancePublicKey,
13478
13874
  deriveUserComplianceScalar,
13479
13875
  deriveUtxoKeypairFromSpendKey,