@cloak.dev/sdk 0.2.6-staging.4f665f8 → 0.2.6-staging.81e481e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -723,6 +723,7 @@ __export(index_exports, {
723
723
  deriveSpendKey: () => deriveSpendKey,
724
724
  deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
725
725
  deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
726
+ deriveSwapRefundKeypair: () => deriveSwapRefundKeypair,
726
727
  deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
727
728
  deriveUserComplianceScalar: () => deriveUserComplianceScalar,
728
729
  deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
@@ -1524,13 +1525,16 @@ init_inputs();
1524
1525
 
1525
1526
  // src/relay/viewing-key.ts
1526
1527
  var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
1528
+ var VIEWING_KEY_CHALLENGE_READABLE_HEADER = "Cloak: Enable private transactions\n\nShares your viewing key with Cloak so you can transact privately. Signing this does not move any funds.\n\n";
1529
+ var VIEWING_KEY_CHALLENGE_REQUEST_FORMAT = "readable";
1527
1530
  var UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1528
1531
  var MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS = 300;
1529
1532
  function normalizeViewingKeyHex(viewingKeyHex) {
1530
1533
  return viewingKeyHex.replace(/^0x/i, "").toLowerCase();
1531
1534
  }
1532
- function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex) {
1533
- return [
1535
+ function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format = "legacy") {
1536
+ const header = format === "readable" ? VIEWING_KEY_CHALLENGE_READABLE_HEADER : "";
1537
+ return header + [
1534
1538
  VIEWING_KEY_CHALLENGE_PREFIX,
1535
1539
  userPubkey,
1536
1540
  nonce,
@@ -1545,17 +1549,16 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
1545
1549
  const challenge = data;
1546
1550
  const nonce = typeof challenge.nonce === "string" ? challenge.nonce : "";
1547
1551
  const expiresInSeconds = challenge.expires_in_seconds;
1548
- const expectedMessage = buildViewingKeyChallengeMessage(
1549
- userPubkey,
1550
- nonce,
1551
- viewingKeyHex
1552
+ const messageFormat = ["readable", "legacy"].find(
1553
+ (format) => challenge.message === buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format)
1552
1554
  );
1553
- if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || challenge.message !== expectedMessage) {
1555
+ if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || messageFormat === void 0) {
1554
1556
  throw new Error("Relay returned an unsafe viewing-key challenge");
1555
1557
  }
1556
1558
  return {
1557
1559
  nonce,
1558
- message: expectedMessage,
1560
+ message: buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, messageFormat),
1561
+ messageFormat,
1559
1562
  expiresInSeconds
1560
1563
  };
1561
1564
  }
@@ -2497,7 +2500,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
2497
2500
  headers: { "Content-Type": "application/json" },
2498
2501
  body: JSON.stringify({
2499
2502
  user_pubkey: userPubkey,
2500
- viewing_key: nkHex
2503
+ viewing_key: nkHex,
2504
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
2501
2505
  })
2502
2506
  });
2503
2507
  if (!challengeResponse.ok) {
@@ -2525,7 +2529,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
2525
2529
  nonce: challenge.nonce,
2526
2530
  identifier: keyId,
2527
2531
  signature,
2528
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
2532
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
2533
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
2529
2534
  })
2530
2535
  });
2531
2536
  if (!response.ok) {
@@ -2813,6 +2818,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
2813
2818
  return false;
2814
2819
  }
2815
2820
  }
2821
+ function isRelayRequestInFlightResponse(responseText) {
2822
+ try {
2823
+ const parsed = JSON.parse(responseText);
2824
+ return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
2825
+ } catch {
2826
+ return false;
2827
+ }
2828
+ }
2816
2829
  function classifyRelayError(responseText, httpStatus) {
2817
2830
  let inner = "";
2818
2831
  try {
@@ -4360,7 +4373,11 @@ var RelayService = class {
4360
4373
  const challengeRes = await relayFetch(`${this.baseUrl}/viewing-key/challenge`, {
4361
4374
  method: "POST",
4362
4375
  headers: { "Content-Type": "application/json" },
4363
- body: JSON.stringify({ user_pubkey: userPubkey, viewing_key: viewingKey })
4376
+ body: JSON.stringify({
4377
+ user_pubkey: userPubkey,
4378
+ viewing_key: viewingKey,
4379
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
4380
+ })
4364
4381
  });
4365
4382
  if (!challengeRes.ok) {
4366
4383
  const error = await challengeRes.text();
@@ -4385,7 +4402,8 @@ var RelayService = class {
4385
4402
  nonce: challenge.nonce,
4386
4403
  identifier,
4387
4404
  signature,
4388
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
4405
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
4406
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
4389
4407
  })
4390
4408
  });
4391
4409
  if (!response.ok) {
@@ -6045,6 +6063,8 @@ function normalizeOwnerPublicKey(publicKey, label) {
6045
6063
  init_inputs();
6046
6064
  var bs582 = import_bs582.default.default || import_bs582.default;
6047
6065
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
6066
+ var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
6067
+ var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
6048
6068
  var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
6049
6069
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
6050
6070
  function normalizeNullifier(inputNullifier) {
@@ -6089,13 +6109,35 @@ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
6089
6109
  const nk = assertNk(viewingKeyNk);
6090
6110
  return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
6091
6111
  }
6092
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
6112
+ function privateKeyBytes(privateKey) {
6113
+ return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
6114
+ }
6115
+ async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
6093
6116
  const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
6117
+ const nullifier = normalizeNullifier(inputNullifier);
6118
+ const preimage = new Uint8Array(
6119
+ REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
6120
+ );
6121
+ let off = 0;
6122
+ preimage.set(REFUND_KEY_DOMAIN_V2, off);
6123
+ off += REFUND_KEY_DOMAIN_V2.length;
6124
+ preimage.set(privateKeyBytes(owner.privateKey), off);
6125
+ off += 32;
6126
+ preimage.set(nullifier, off);
6127
+ off += nullifier.length;
6128
+ preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
6129
+ const privateKey = toFieldSecret((0, import_blake34.blake3)(preimage));
6130
+ const publicKey = await derivePublicKey(privateKey);
6131
+ if (publicKey === 0n) throw new Error("refund authorization is degenerate");
6132
+ return { privateKey, publicKey };
6133
+ }
6134
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
6094
6135
  const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
6095
- if (owner.publicKey === 0n || blinding === 0n) {
6136
+ const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
6137
+ if (keypair.publicKey === 0n || blinding === 0n) {
6096
6138
  throw new Error("refund authorization is degenerate");
6097
6139
  }
6098
- return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
6140
+ return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
6099
6141
  }
6100
6142
  async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
6101
6143
  const nk = assertNk(viewingKeyNk);
@@ -6116,9 +6158,12 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
6116
6158
  mintAddress: NATIVE_SOL_MINT
6117
6159
  });
6118
6160
  }
6161
+ function toField(value) {
6162
+ return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
6163
+ }
6119
6164
  async function matchSwapRefundLeaf(params) {
6120
6165
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
6121
- const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
6166
+ const expected = toField(params.commitment);
6122
6167
  let blinding;
6123
6168
  try {
6124
6169
  blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
@@ -6126,11 +6171,55 @@ async function matchSwapRefundLeaf(params) {
6126
6171
  return null;
6127
6172
  }
6128
6173
  const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
6174
+ const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
6175
+ let perSwapPub;
6176
+ let perSwapPriv = 0n;
6177
+ if (ownerPriv > 0n && ownerPub !== void 0) {
6178
+ try {
6179
+ const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
6180
+ perSwapPub = kp.publicKey;
6181
+ perSwapPriv = kp.privateKey;
6182
+ } catch {
6183
+ return null;
6184
+ }
6185
+ }
6186
+ if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
6187
+ const published = toField(params.publishedRefundPubkey);
6188
+ const publishedBlinding = toField(params.publishedRefundBlinding);
6189
+ if (published !== 0n && publishedBlinding === blinding) {
6190
+ if (perSwapPub === void 0 || perSwapPub === published) {
6191
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
6192
+ if (candidate === expected && published !== ownerPub) {
6193
+ return {
6194
+ keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
6195
+ shape: "per-swap",
6196
+ blinding,
6197
+ amount: amountAfterFee,
6198
+ commitment: candidate,
6199
+ legacyExposed: false
6200
+ };
6201
+ }
6202
+ }
6203
+ }
6204
+ } else if (perSwapPub !== void 0) {
6205
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
6206
+ if (candidate === expected) {
6207
+ return {
6208
+ keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
6209
+ shape: "per-swap",
6210
+ blinding,
6211
+ amount: amountAfterFee,
6212
+ commitment: candidate,
6213
+ legacyExposed: false
6214
+ };
6215
+ }
6216
+ }
6129
6217
  if (ownerPub !== void 0) {
6130
6218
  const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
6131
6219
  if (candidate === expected) {
6132
6220
  return {
6133
- keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
6221
+ keypair: { privateKey: ownerPriv, publicKey: ownerPub },
6222
+ shape: "owner",
6134
6223
  blinding,
6135
6224
  amount: amountAfterFee,
6136
6225
  commitment: candidate,
@@ -6148,6 +6237,7 @@ async function matchSwapRefundLeaf(params) {
6148
6237
  if (legacyCandidate !== expected) return null;
6149
6238
  return {
6150
6239
  keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
6240
+ shape: "legacy-nk",
6151
6241
  blinding: legacy.blinding,
6152
6242
  amount: amountAfterFee,
6153
6243
  commitment: legacyCandidate,
@@ -6159,6 +6249,9 @@ var PROOF_LEN2 = 256;
6159
6249
  var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
6160
6250
  var PUBLIC_INPUTS_LEN2 = 264;
6161
6251
  var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
6252
+ var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
6253
+ var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
6254
+ var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
6162
6255
  function toBase58(key) {
6163
6256
  if (!key) return void 0;
6164
6257
  if (typeof key === "string") return key;
@@ -6221,7 +6314,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
6221
6314
  }
6222
6315
  if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
6223
6316
  throw new Error(
6224
- "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."
6317
+ "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): per-swap and owner-key refund leaves are matched against it, and nk alone can only find legacy refunds."
6225
6318
  );
6226
6319
  }
6227
6320
  const ownerUtxoKeypair = options.ownerUtxoKeypair;
@@ -6281,7 +6374,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
6281
6374
  programId
6282
6375
  );
6283
6376
  const key = swapState;
6284
- if (!nullifierBySwapState.has(key)) nullifierBySwapState.set(key, { nullifier, signature });
6377
+ const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
6378
+ if (!nullifierBySwapState.has(key)) {
6379
+ nullifierBySwapState.set(key, {
6380
+ nullifier,
6381
+ signature,
6382
+ refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
6383
+ refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
6384
+ });
6385
+ }
6285
6386
  }
6286
6387
  const logs = tx.meta?.logMessages;
6287
6388
  const scan = scanRefundLeafEvents(logs, programIdBase58);
@@ -6300,7 +6401,9 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
6300
6401
  inputNullifier: candidate.nullifier,
6301
6402
  amountAfterFee: event.amountAfterFee,
6302
6403
  commitment: event.commitmentField,
6303
- ownerUtxoKeypair
6404
+ ownerUtxoKeypair,
6405
+ publishedRefundPubkey: candidate.refundPubkey,
6406
+ publishedRefundBlinding: candidate.refundBlinding
6304
6407
  });
6305
6408
  if (!recovered) continue;
6306
6409
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -6854,6 +6957,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
6854
6957
  var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
6855
6958
  var DEFAULT_RELAY_NETWORK_RETRIES = 6;
6856
6959
  var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
6960
+ var RELAY_SOURCE_LEASE_MS = 18e4;
6961
+ var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
6962
+ var MAX_LEASE_EXPIRY_REPLAYS = 2;
6963
+ var RELAY_IN_FLIGHT_POLL_MS = 5e3;
6964
+ var RELAY_LANDED_POLL_MS = 1e3;
6965
+ var MAX_LANDED_POLLS = 5;
6857
6966
  function parseMissingRelayIndexError(message) {
6858
6967
  const match = message.match(
6859
6968
  /Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
@@ -7298,7 +7407,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
7298
7407
  headers: { "Content-Type": "application/json" },
7299
7408
  body: JSON.stringify({
7300
7409
  user_pubkey: userPubkey,
7301
- viewing_key: viewingKeyHex
7410
+ viewing_key: viewingKeyHex,
7411
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
7302
7412
  })
7303
7413
  });
7304
7414
  if (!challengeResponse.ok) {
@@ -7345,7 +7455,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
7345
7455
  viewing_key: viewingKeyHex,
7346
7456
  nonce: challenge.nonce,
7347
7457
  signature: signatureBase64,
7348
- ...authMode === "transaction" ? { auth_mode: authMode } : {}
7458
+ ...authMode === "transaction" ? { auth_mode: authMode } : {},
7459
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
7349
7460
  })
7350
7461
  });
7351
7462
  if (!response.ok) {
@@ -8438,6 +8549,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
8438
8549
  function sleep2(ms) {
8439
8550
  return new Promise((resolve) => setTimeout(resolve, ms));
8440
8551
  }
8552
+ function sleepUnlessAborted(ms, signal) {
8553
+ if (signal?.aborted) return Promise.resolve(false);
8554
+ return new Promise((resolve) => {
8555
+ const onAbort = () => {
8556
+ clearTimeout(timer);
8557
+ resolve(false);
8558
+ };
8559
+ const timer = setTimeout(() => {
8560
+ signal?.removeEventListener("abort", onAbort);
8561
+ resolve(true);
8562
+ }, ms);
8563
+ signal?.addEventListener("abort", onAbort, { once: true });
8564
+ });
8565
+ }
8441
8566
  function hexToBytes2(hex) {
8442
8567
  const bytes = new Uint8Array(hex.length / 2);
8443
8568
  for (let i = 0; i < hex.length; i += 2) {
@@ -8672,6 +8797,9 @@ async function submitTransactToRelay(args) {
8672
8797
  let unknownOutcomeSignature = null;
8673
8798
  let possiblySubmitted = false;
8674
8799
  let networkRetry = 0;
8800
+ let leaseReplays = 0;
8801
+ let landedPolls = 0;
8802
+ let leaseBaseMs = null;
8675
8803
  const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
8676
8804
  connection: settlement.connection,
8677
8805
  programId: settlement.programId,
@@ -8727,6 +8855,7 @@ async function submitTransactToRelay(args) {
8727
8855
  const controller = new AbortController();
8728
8856
  const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
8729
8857
  let response;
8858
+ leaseBaseMs ?? (leaseBaseMs = Date.now());
8730
8859
  try {
8731
8860
  response = await doFetch(`${relayUrl}/transact`, {
8732
8861
  method: "POST",
@@ -8745,6 +8874,49 @@ async function submitTransactToRelay(args) {
8745
8874
  if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
8746
8875
  possiblySubmitted = true;
8747
8876
  }
8877
+ if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
8878
+ networkRetry = 0;
8879
+ const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
8880
+ const polling = Date.now() < leaseEndsMs;
8881
+ const probe = await verifySettlement(
8882
+ unknownOutcomeSignature,
8883
+ polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
8884
+ );
8885
+ if (probe.status === "landed") {
8886
+ landedPolls++;
8887
+ if (!polling || landedPolls > MAX_LANDED_POLLS) {
8888
+ return await resolveFailure(
8889
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8890
+ );
8891
+ }
8892
+ if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
8893
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8894
+ }
8895
+ continue;
8896
+ }
8897
+ if (polling) {
8898
+ onProgress?.("Relay is still processing this request; checking again shortly...");
8899
+ const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
8900
+ if (!await sleepUnlessAborted(pollMs, args.signal)) {
8901
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8902
+ }
8903
+ continue;
8904
+ }
8905
+ leaseReplays++;
8906
+ const waitMs = Math.max(
8907
+ 0,
8908
+ (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
8909
+ );
8910
+ onProgress?.(
8911
+ `Relay has not confirmed the outcome. Waiting ${Math.ceil(waitMs / 1e3)}s for its request lease to expire, then replaying the identical signed request (${leaseReplays}/${MAX_LEASE_EXPIRY_REPLAYS})...`
8912
+ );
8913
+ if (!await sleepUnlessAborted(waitMs, args.signal)) {
8914
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8915
+ }
8916
+ networkRetry = 0;
8917
+ leaseBaseMs = null;
8918
+ continue;
8919
+ }
8748
8920
  if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
8749
8921
  networkRetry++;
8750
8922
  const delay = relayBackoffMs(networkRetry);
@@ -12875,7 +13047,7 @@ function parseSwapRefund(r) {
12875
13047
  checkLeafPair(commitment, leaf, "SWAP_REFUND");
12876
13048
  return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
12877
13049
  }
12878
- function parseNoteIndexPage(bytes, expect) {
13050
+ function parseNoteIndexPage(bytes, expect, options = {}) {
12879
13051
  if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
12880
13052
  if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
12881
13053
  throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
@@ -12907,7 +13079,9 @@ function parseNoteIndexPage(bytes, expect) {
12907
13079
  }
12908
13080
  const items = [];
12909
13081
  const rawItems = [];
13082
+ const itemPositions = [];
12910
13083
  let skippedUnknown = 0;
13084
+ let skippedMalformed = 0;
12911
13085
  let offset = NOTE_INDEX_HEADER_LEN;
12912
13086
  for (let i = 0; i < count; i++) {
12913
13087
  if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
@@ -12916,34 +13090,45 @@ function parseNoteIndexPage(bytes, expect) {
12916
13090
  const bodyStart = offset + ITEM_HEADER_LEN;
12917
13091
  const bodyEnd = bodyStart + bodyLen;
12918
13092
  if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12919
- const r = new Reader(bytes, bodyStart, bodyEnd);
13093
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
13094
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
13095
+ skippedUnknown++;
13096
+ offset = bodyEnd;
13097
+ continue;
13098
+ }
12920
13099
  let item;
12921
- switch (kind) {
12922
- case NOTE_INDEX_KIND_TX:
12923
- if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12924
- item = parseTx(r, bodyLen);
12925
- break;
12926
- case NOTE_INDEX_KIND_DELIVERY:
12927
- if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12928
- item = parseDelivery(r);
12929
- break;
12930
- case NOTE_INDEX_KIND_SWAP_REFUND:
12931
- if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12932
- item = parseSwapRefund(r);
12933
- break;
12934
- default:
12935
- if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12936
- skippedUnknown++;
12937
- offset = bodyEnd;
12938
- continue;
13100
+ try {
13101
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
13102
+ } catch (error) {
13103
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
13104
+ skippedMalformed++;
13105
+ offset = bodyEnd;
13106
+ continue;
12939
13107
  }
12940
- if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12941
13108
  items.push(item);
12942
13109
  rawItems.push(bytes.slice(offset, bodyEnd));
13110
+ itemPositions.push(i);
12943
13111
  offset = bodyEnd;
12944
13112
  }
12945
13113
  if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12946
- return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown };
13114
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
13115
+ }
13116
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
13117
+ const bodyLen = bodyEnd - bodyStart;
13118
+ const r = new Reader(bytes, bodyStart, bodyEnd);
13119
+ let item;
13120
+ if (kind === NOTE_INDEX_KIND_TX) {
13121
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
13122
+ item = parseTx(r, bodyLen);
13123
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
13124
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
13125
+ item = parseDelivery(r);
13126
+ } else {
13127
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
13128
+ item = parseSwapRefund(r);
13129
+ }
13130
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
13131
+ return item;
12947
13132
  }
12948
13133
  function parseNoteIndexItem(raw) {
12949
13134
  if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
@@ -13375,6 +13560,14 @@ async function trialItem(item, trials) {
13375
13560
  }
13376
13561
  return null;
13377
13562
  }
13563
+ async function trialItemIsolated(item, trials, stats) {
13564
+ try {
13565
+ return await trialItem(item, trials);
13566
+ } catch {
13567
+ stats.skipped++;
13568
+ return null;
13569
+ }
13570
+ }
13378
13571
  async function trialItemWith(item, trial) {
13379
13572
  if (item.kind === 1) {
13380
13573
  if (item.note.length === 0) return null;
@@ -13406,7 +13599,14 @@ function leafOfTxOutput(item, commitment) {
13406
13599
  if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
13407
13600
  return null;
13408
13601
  }
13409
- async function matchOwnItems(own, owner, onReject) {
13602
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
13603
+ try {
13604
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
13605
+ } catch {
13606
+ return null;
13607
+ }
13608
+ }
13609
+ async function matchOwnItems(own, owner, onReject, onSkip) {
13410
13610
  const candidates = [];
13411
13611
  const claimed = /* @__PURE__ */ new Set();
13412
13612
  const byNullifier = /* @__PURE__ */ new Map();
@@ -13496,7 +13696,7 @@ async function matchOwnItems(own, owner, onReject) {
13496
13696
  });
13497
13697
  return true;
13498
13698
  };
13499
- for (const o of own) {
13699
+ const direct = async (o) => {
13500
13700
  const item = o.item;
13501
13701
  if (item.kind === 1 && o.note?.noteSalt !== void 0) {
13502
13702
  const note = o.note;
@@ -13510,7 +13710,7 @@ async function matchOwnItems(own, owner, onReject) {
13510
13710
  const mint = addressFromBytes(item.mint);
13511
13711
  if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
13512
13712
  onReject(o);
13513
- continue;
13713
+ return;
13514
13714
  }
13515
13715
  const commitment = await computeCommitment2({
13516
13716
  amount: o.delivery.amount,
@@ -13520,7 +13720,7 @@ async function matchOwnItems(own, owner, onReject) {
13520
13720
  });
13521
13721
  if (commitment !== bytesToBigint3(item.commitment)) {
13522
13722
  onReject(o);
13523
- continue;
13723
+ return;
13524
13724
  }
13525
13725
  await add(o, {
13526
13726
  kind: "received",
@@ -13538,12 +13738,20 @@ async function matchOwnItems(own, owner, onReject) {
13538
13738
  atRisk: o.refund.legacyExposed,
13539
13739
  amount: o.refund.amount,
13540
13740
  blinding: o.refund.blinding,
13541
- keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
13741
+ // per-swap refunds carry their derived keypair; owner-shape ones carry the owner
13742
+ keypair: o.refund.keypair,
13542
13743
  mint: NATIVE_SOL_MINT,
13543
13744
  commitment: o.refund.commitment,
13544
13745
  leaf: Number(item.leaf)
13545
13746
  });
13546
13747
  }
13748
+ };
13749
+ for (const o of own) {
13750
+ try {
13751
+ await direct(o);
13752
+ } catch {
13753
+ onSkip(o);
13754
+ }
13547
13755
  }
13548
13756
  const processTx = async (o) => {
13549
13757
  const item = o.item;
@@ -13558,8 +13766,9 @@ async function matchOwnItems(own, owner, onReject) {
13558
13766
  const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
13559
13767
  if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
13560
13768
  const out1 = sumIn + item.publicAmount - note.outAmount0;
13561
- if (out1 > 0n) {
13562
- const blinding = deriveChangeNoteBlinding(o.trial.nk, note.noteSalt, 1);
13769
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
13770
+ if (out1 > 0n && blinding === null) onSkip(o);
13771
+ else if (blinding !== null) {
13563
13772
  const owners = [{ keypair: owner, atRisk: false }];
13564
13773
  const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
13565
13774
  if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
@@ -13580,7 +13789,11 @@ async function matchOwnItems(own, owner, onReject) {
13580
13789
  for (let i = 0; i < queue.length; i++) {
13581
13790
  const o = queue[i];
13582
13791
  queued.delete(o);
13583
- await processTx(o);
13792
+ try {
13793
+ await processTx(o);
13794
+ } catch {
13795
+ onSkip(o);
13796
+ }
13584
13797
  }
13585
13798
  return candidates;
13586
13799
  }
@@ -13827,7 +14040,8 @@ async function recoverNotesFromIndex(params) {
13827
14040
  candidates: 0,
13828
14041
  spent: 0,
13829
14042
  conflicts: 0,
13830
- pendingDropped: 0
14043
+ pendingDropped: 0,
14044
+ skipped: 0
13831
14045
  };
13832
14046
  const rpc = new Proxy(connection, {
13833
14047
  get(target, prop, receiver) {
@@ -13894,10 +14108,11 @@ async function recoverNotesFromIndex(params) {
13894
14108
  let outcome = await runOnce(ctx, cursor);
13895
14109
  if (outcome instanceof FullPassSignal) {
13896
14110
  warnings.push(`${outcome.reason}; re-syncing from page 0`);
13897
- Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
14111
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
13898
14112
  outcome = await runOnce(ctx, void 0);
13899
14113
  if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13900
14114
  }
14115
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
13901
14116
  stats.ms = Date.now() - startedAt;
13902
14117
  return { ...outcome, stats, warnings };
13903
14118
  }
@@ -13974,11 +14189,13 @@ async function runOnce(ctx, cursor) {
13974
14189
  if (signal.aborted) throw abortError2();
13975
14190
  const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13976
14191
  stats.bytes += bytes.length;
13977
- const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
14192
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
13978
14193
  if (pageNo < head.completePages && !page2.complete) {
13979
14194
  throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13980
14195
  }
13981
14196
  stats.pages++;
14197
+ stats.skipped += page2.skippedMalformed;
14198
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
13982
14199
  waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13983
14200
  advanceChain();
13984
14201
  const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
@@ -13999,7 +14216,7 @@ async function runOnce(ctx, cursor) {
13999
14216
  else data.leaves.set(mint, [entry]);
14000
14217
  };
14001
14218
  page2.items.forEach((item, i) => {
14002
- const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
14219
+ const seq = seqOf(i);
14003
14220
  if (item.kind === 1) {
14004
14221
  addLeaf(item.mint, item.comm0, item.leaf0, seq);
14005
14222
  addLeaf(item.mint, item.comm1, item.leaf1, seq);
@@ -14016,7 +14233,7 @@ async function runOnce(ctx, cursor) {
14016
14233
  for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
14017
14234
  if (signal.aborted) throw abortError2();
14018
14235
  const batch = page2.items.slice(i, i + ITEM_BATCH);
14019
- const opened = await Promise.all(batch.map((item) => trialItem(item, trials)));
14236
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
14020
14237
  opened.forEach((o, k) => {
14021
14238
  if (!o) return;
14022
14239
  stats.decrypted++;
@@ -14026,7 +14243,7 @@ async function runOnce(ctx, cursor) {
14026
14243
  stats.dropped++;
14027
14244
  return;
14028
14245
  }
14029
- ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
14246
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
14030
14247
  });
14031
14248
  stats.items += batch.length;
14032
14249
  }
@@ -14059,7 +14276,7 @@ async function runOnce(ctx, cursor) {
14059
14276
  throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
14060
14277
  }
14061
14278
  for (const entry of cursor?.items ?? []) {
14062
- const o = await trialItem(entry.item, trials);
14279
+ const o = await trialItemIsolated(entry.item, trials, stats);
14063
14280
  if (!o) continue;
14064
14281
  const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
14065
14282
  ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
@@ -14071,10 +14288,20 @@ async function runOnce(ctx, cursor) {
14071
14288
  const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
14072
14289
  ownItems.sort((a, b) => a.seq - b.seq);
14073
14290
  const rejectedNow = /* @__PURE__ */ new Set();
14074
- const allCandidates = await matchOwnItems(ownItems, owner, (o) => {
14075
- stats.dropped++;
14076
- rejectedNow.add(o.id);
14077
- });
14291
+ const skippedNow = /* @__PURE__ */ new Set();
14292
+ const allCandidates = await matchOwnItems(
14293
+ ownItems,
14294
+ owner,
14295
+ (o) => {
14296
+ stats.dropped++;
14297
+ rejectedNow.add(o.id);
14298
+ },
14299
+ (o) => {
14300
+ if (skippedNow.has(o)) return;
14301
+ skippedNow.add(o);
14302
+ stats.skipped++;
14303
+ }
14304
+ );
14078
14305
  stats.candidates = allCandidates.length;
14079
14306
  const cutoff = params.legacyCutoffLeaf ?? {};
14080
14307
  const candidates = allCandidates.filter((c) => {
@@ -14178,7 +14405,8 @@ async function runOnce(ctx, cursor) {
14178
14405
  for (const c of byLeaf.values()) {
14179
14406
  const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
14180
14407
  keyChecked.set(c.keypair.privateKey, pubOk);
14181
- if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
14408
+ const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
14409
+ if (!pubOk || !c.atRisk && !ownerOk) {
14182
14410
  stats.dropped++;
14183
14411
  tally(c, "rejected");
14184
14412
  continue;
@@ -14187,7 +14415,7 @@ async function runOnce(ctx, cursor) {
14187
14415
  verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
14188
14416
  const utxo = {
14189
14417
  amount: c.amount,
14190
- keypair: c.atRisk ? { ...c.keypair } : owner,
14418
+ keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
14191
14419
  blinding: c.blinding,
14192
14420
  mintAddress: c.mint,
14193
14421
  index: c.leaf,
@@ -15671,6 +15899,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15671
15899
  deriveSpendKey,
15672
15900
  deriveSwapRefundAuthorization,
15673
15901
  deriveSwapRefundBlinding,
15902
+ deriveSwapRefundKeypair,
15674
15903
  deriveUserCompliancePublicKey,
15675
15904
  deriveUserComplianceScalar,
15676
15905
  deriveUtxoKeypairFromSpendKey,