@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.js CHANGED
@@ -638,13 +638,16 @@ import { sha256 as sha2562 } from "@noble/hashes/sha2";
638
638
 
639
639
  // src/relay/viewing-key.ts
640
640
  var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
641
+ var VIEWING_KEY_CHALLENGE_READABLE_HEADER = "Cloak: Enable private transactions\n\nShares your viewing key with Cloak so you can transact privately. Signing this does not move any funds.\n\n";
642
+ var VIEWING_KEY_CHALLENGE_REQUEST_FORMAT = "readable";
641
643
  var UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
642
644
  var MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS = 300;
643
645
  function normalizeViewingKeyHex(viewingKeyHex) {
644
646
  return viewingKeyHex.replace(/^0x/i, "").toLowerCase();
645
647
  }
646
- function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex) {
647
- return [
648
+ function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format = "legacy") {
649
+ const header = format === "readable" ? VIEWING_KEY_CHALLENGE_READABLE_HEADER : "";
650
+ return header + [
648
651
  VIEWING_KEY_CHALLENGE_PREFIX,
649
652
  userPubkey,
650
653
  nonce,
@@ -659,17 +662,16 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
659
662
  const challenge = data;
660
663
  const nonce = typeof challenge.nonce === "string" ? challenge.nonce : "";
661
664
  const expiresInSeconds = challenge.expires_in_seconds;
662
- const expectedMessage = buildViewingKeyChallengeMessage(
663
- userPubkey,
664
- nonce,
665
- viewingKeyHex
665
+ const messageFormat = ["readable", "legacy"].find(
666
+ (format) => challenge.message === buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format)
666
667
  );
667
- if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || challenge.message !== expectedMessage) {
668
+ if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || messageFormat === void 0) {
668
669
  throw new Error("Relay returned an unsafe viewing-key challenge");
669
670
  }
670
671
  return {
671
672
  nonce,
672
- message: expectedMessage,
673
+ message: buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, messageFormat),
674
+ messageFormat,
673
675
  expiresInSeconds
674
676
  };
675
677
  }
@@ -1634,7 +1636,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1634
1636
  headers: { "Content-Type": "application/json" },
1635
1637
  body: JSON.stringify({
1636
1638
  user_pubkey: userPubkey,
1637
- viewing_key: nkHex
1639
+ viewing_key: nkHex,
1640
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
1638
1641
  })
1639
1642
  });
1640
1643
  if (!challengeResponse.ok) {
@@ -1662,7 +1665,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
1662
1665
  nonce: challenge.nonce,
1663
1666
  identifier: keyId,
1664
1667
  signature,
1665
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
1668
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
1669
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
1666
1670
  })
1667
1671
  });
1668
1672
  if (!response.ok) {
@@ -1945,6 +1949,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
1945
1949
  return false;
1946
1950
  }
1947
1951
  }
1952
+ function isRelayRequestInFlightResponse(responseText) {
1953
+ try {
1954
+ const parsed = JSON.parse(responseText);
1955
+ return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
1956
+ } catch {
1957
+ return false;
1958
+ }
1959
+ }
1948
1960
  function classifyRelayError(responseText, httpStatus) {
1949
1961
  let inner = "";
1950
1962
  try {
@@ -3483,7 +3495,11 @@ var RelayService = class {
3483
3495
  const challengeRes = await relayFetch(`${this.baseUrl}/viewing-key/challenge`, {
3484
3496
  method: "POST",
3485
3497
  headers: { "Content-Type": "application/json" },
3486
- body: JSON.stringify({ user_pubkey: userPubkey, viewing_key: viewingKey })
3498
+ body: JSON.stringify({
3499
+ user_pubkey: userPubkey,
3500
+ viewing_key: viewingKey,
3501
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
3502
+ })
3487
3503
  });
3488
3504
  if (!challengeRes.ok) {
3489
3505
  const error = await challengeRes.text();
@@ -3508,7 +3524,8 @@ var RelayService = class {
3508
3524
  nonce: challenge.nonce,
3509
3525
  identifier,
3510
3526
  signature,
3511
- ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
3527
+ ...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
3528
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
3512
3529
  })
3513
3530
  });
3514
3531
  if (!response.ok) {
@@ -5164,6 +5181,8 @@ function normalizeOwnerPublicKey(publicKey, label) {
5164
5181
  // src/notes/swap-refund.ts
5165
5182
  var bs582 = _bs582.default || _bs582;
5166
5183
  var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
5184
+ var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
5185
+ var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
5167
5186
  var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
5168
5187
  var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
5169
5188
  function normalizeNullifier(inputNullifier) {
@@ -5208,13 +5227,35 @@ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
5208
5227
  const nk = assertNk(viewingKeyNk);
5209
5228
  return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
5210
5229
  }
5211
- async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
5230
+ function privateKeyBytes(privateKey) {
5231
+ return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
5232
+ }
5233
+ async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
5212
5234
  const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
5235
+ const nullifier = normalizeNullifier(inputNullifier);
5236
+ const preimage = new Uint8Array(
5237
+ REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
5238
+ );
5239
+ let off = 0;
5240
+ preimage.set(REFUND_KEY_DOMAIN_V2, off);
5241
+ off += REFUND_KEY_DOMAIN_V2.length;
5242
+ preimage.set(privateKeyBytes(owner.privateKey), off);
5243
+ off += 32;
5244
+ preimage.set(nullifier, off);
5245
+ off += nullifier.length;
5246
+ preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
5247
+ const privateKey = toFieldSecret(blake33(preimage));
5248
+ const publicKey = await derivePublicKey(privateKey);
5249
+ if (publicKey === 0n) throw new Error("refund authorization is degenerate");
5250
+ return { privateKey, publicKey };
5251
+ }
5252
+ async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
5213
5253
  const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
5214
- if (owner.publicKey === 0n || blinding === 0n) {
5254
+ const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
5255
+ if (keypair.publicKey === 0n || blinding === 0n) {
5215
5256
  throw new Error("refund authorization is degenerate");
5216
5257
  }
5217
- return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
5258
+ return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
5218
5259
  }
5219
5260
  async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
5220
5261
  const nk = assertNk(viewingKeyNk);
@@ -5235,9 +5276,12 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
5235
5276
  mintAddress: NATIVE_SOL_MINT
5236
5277
  });
5237
5278
  }
5279
+ function toField(value) {
5280
+ return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
5281
+ }
5238
5282
  async function matchSwapRefundLeaf(params) {
5239
5283
  const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
5240
- const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
5284
+ const expected = toField(params.commitment);
5241
5285
  let blinding;
5242
5286
  try {
5243
5287
  blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
@@ -5245,11 +5289,55 @@ async function matchSwapRefundLeaf(params) {
5245
5289
  return null;
5246
5290
  }
5247
5291
  const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
5292
+ const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
5293
+ let perSwapPub;
5294
+ let perSwapPriv = 0n;
5295
+ if (ownerPriv > 0n && ownerPub !== void 0) {
5296
+ try {
5297
+ const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
5298
+ perSwapPub = kp.publicKey;
5299
+ perSwapPriv = kp.privateKey;
5300
+ } catch {
5301
+ return null;
5302
+ }
5303
+ }
5304
+ if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
5305
+ const published = toField(params.publishedRefundPubkey);
5306
+ const publishedBlinding = toField(params.publishedRefundBlinding);
5307
+ if (published !== 0n && publishedBlinding === blinding) {
5308
+ if (perSwapPub === void 0 || perSwapPub === published) {
5309
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
5310
+ if (candidate === expected && published !== ownerPub) {
5311
+ return {
5312
+ keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
5313
+ shape: "per-swap",
5314
+ blinding,
5315
+ amount: amountAfterFee,
5316
+ commitment: candidate,
5317
+ legacyExposed: false
5318
+ };
5319
+ }
5320
+ }
5321
+ }
5322
+ } else if (perSwapPub !== void 0) {
5323
+ const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
5324
+ if (candidate === expected) {
5325
+ return {
5326
+ keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
5327
+ shape: "per-swap",
5328
+ blinding,
5329
+ amount: amountAfterFee,
5330
+ commitment: candidate,
5331
+ legacyExposed: false
5332
+ };
5333
+ }
5334
+ }
5248
5335
  if (ownerPub !== void 0) {
5249
5336
  const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
5250
5337
  if (candidate === expected) {
5251
5338
  return {
5252
- keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
5339
+ keypair: { privateKey: ownerPriv, publicKey: ownerPub },
5340
+ shape: "owner",
5253
5341
  blinding,
5254
5342
  amount: amountAfterFee,
5255
5343
  commitment: candidate,
@@ -5267,6 +5355,7 @@ async function matchSwapRefundLeaf(params) {
5267
5355
  if (legacyCandidate !== expected) return null;
5268
5356
  return {
5269
5357
  keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
5358
+ shape: "legacy-nk",
5270
5359
  blinding: legacy.blinding,
5271
5360
  amount: amountAfterFee,
5272
5361
  commitment: legacyCandidate,
@@ -5278,6 +5367,9 @@ var PROOF_LEN2 = 256;
5278
5367
  var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
5279
5368
  var PUBLIC_INPUTS_LEN2 = 264;
5280
5369
  var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
5370
+ var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
5371
+ var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
5372
+ var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
5281
5373
  function toBase58(key) {
5282
5374
  if (!key) return void 0;
5283
5375
  if (typeof key === "string") return key;
@@ -5340,7 +5432,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
5340
5432
  }
5341
5433
  if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
5342
5434
  throw new Error(
5343
- "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are owned by it, and nk alone can only find legacy refunds."
5435
+ "discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): per-swap and owner-key refund leaves are matched against it, and nk alone can only find legacy refunds."
5344
5436
  );
5345
5437
  }
5346
5438
  const ownerUtxoKeypair = options.ownerUtxoKeypair;
@@ -5400,7 +5492,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
5400
5492
  programId
5401
5493
  );
5402
5494
  const key = swapState;
5403
- if (!nullifierBySwapState.has(key)) nullifierBySwapState.set(key, { nullifier, signature });
5495
+ const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
5496
+ if (!nullifierBySwapState.has(key)) {
5497
+ nullifierBySwapState.set(key, {
5498
+ nullifier,
5499
+ signature,
5500
+ refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
5501
+ refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
5502
+ });
5503
+ }
5404
5504
  }
5405
5505
  const logs = tx.meta?.logMessages;
5406
5506
  const scan = scanRefundLeafEvents(logs, programIdBase58);
@@ -5419,7 +5519,9 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
5419
5519
  inputNullifier: candidate.nullifier,
5420
5520
  amountAfterFee: event.amountAfterFee,
5421
5521
  commitment: event.commitmentField,
5422
- ownerUtxoKeypair
5522
+ ownerUtxoKeypair,
5523
+ publishedRefundPubkey: candidate.refundPubkey,
5524
+ publishedRefundBlinding: candidate.refundBlinding
5423
5525
  });
5424
5526
  if (!recovered) continue;
5425
5527
  const dedupe = `${close.signature}:${event.leafIndex}`;
@@ -5966,6 +6068,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
5966
6068
  var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
5967
6069
  var DEFAULT_RELAY_NETWORK_RETRIES = 6;
5968
6070
  var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
6071
+ var RELAY_SOURCE_LEASE_MS = 18e4;
6072
+ var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
6073
+ var MAX_LEASE_EXPIRY_REPLAYS = 2;
6074
+ var RELAY_IN_FLIGHT_POLL_MS = 5e3;
6075
+ var RELAY_LANDED_POLL_MS = 1e3;
6076
+ var MAX_LANDED_POLLS = 5;
5969
6077
  function parseMissingRelayIndexError(message) {
5970
6078
  const match = message.match(
5971
6079
  /Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
@@ -6410,7 +6518,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6410
6518
  headers: { "Content-Type": "application/json" },
6411
6519
  body: JSON.stringify({
6412
6520
  user_pubkey: userPubkey,
6413
- viewing_key: viewingKeyHex
6521
+ viewing_key: viewingKeyHex,
6522
+ message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
6414
6523
  })
6415
6524
  });
6416
6525
  if (!challengeResponse.ok) {
@@ -6457,7 +6566,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
6457
6566
  viewing_key: viewingKeyHex,
6458
6567
  nonce: challenge.nonce,
6459
6568
  signature: signatureBase64,
6460
- ...authMode === "transaction" ? { auth_mode: authMode } : {}
6569
+ ...authMode === "transaction" ? { auth_mode: authMode } : {},
6570
+ ...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
6461
6571
  })
6462
6572
  });
6463
6573
  if (!response.ok) {
@@ -7550,6 +7660,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
7550
7660
  function sleep2(ms) {
7551
7661
  return new Promise((resolve) => setTimeout(resolve, ms));
7552
7662
  }
7663
+ function sleepUnlessAborted(ms, signal) {
7664
+ if (signal?.aborted) return Promise.resolve(false);
7665
+ return new Promise((resolve) => {
7666
+ const onAbort = () => {
7667
+ clearTimeout(timer);
7668
+ resolve(false);
7669
+ };
7670
+ const timer = setTimeout(() => {
7671
+ signal?.removeEventListener("abort", onAbort);
7672
+ resolve(true);
7673
+ }, ms);
7674
+ signal?.addEventListener("abort", onAbort, { once: true });
7675
+ });
7676
+ }
7553
7677
  function hexToBytes2(hex) {
7554
7678
  const bytes = new Uint8Array(hex.length / 2);
7555
7679
  for (let i = 0; i < hex.length; i += 2) {
@@ -7784,6 +7908,9 @@ async function submitTransactToRelay(args) {
7784
7908
  let unknownOutcomeSignature = null;
7785
7909
  let possiblySubmitted = false;
7786
7910
  let networkRetry = 0;
7911
+ let leaseReplays = 0;
7912
+ let landedPolls = 0;
7913
+ let leaseBaseMs = null;
7787
7914
  const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
7788
7915
  connection: settlement.connection,
7789
7916
  programId: settlement.programId,
@@ -7839,6 +7966,7 @@ async function submitTransactToRelay(args) {
7839
7966
  const controller = new AbortController();
7840
7967
  const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
7841
7968
  let response;
7969
+ leaseBaseMs ?? (leaseBaseMs = Date.now());
7842
7970
  try {
7843
7971
  response = await doFetch(`${relayUrl}/transact`, {
7844
7972
  method: "POST",
@@ -7857,6 +7985,49 @@ async function submitTransactToRelay(args) {
7857
7985
  if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
7858
7986
  possiblySubmitted = true;
7859
7987
  }
7988
+ if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
7989
+ networkRetry = 0;
7990
+ const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
7991
+ const polling = Date.now() < leaseEndsMs;
7992
+ const probe = await verifySettlement(
7993
+ unknownOutcomeSignature,
7994
+ polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
7995
+ );
7996
+ if (probe.status === "landed") {
7997
+ landedPolls++;
7998
+ if (!polling || landedPolls > MAX_LANDED_POLLS) {
7999
+ return await resolveFailure(
8000
+ new Error(relayFailureMessage("Relay error", responseText, requestBody))
8001
+ );
8002
+ }
8003
+ if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
8004
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8005
+ }
8006
+ continue;
8007
+ }
8008
+ if (polling) {
8009
+ onProgress?.("Relay is still processing this request; checking again shortly...");
8010
+ const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
8011
+ if (!await sleepUnlessAborted(pollMs, args.signal)) {
8012
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8013
+ }
8014
+ continue;
8015
+ }
8016
+ leaseReplays++;
8017
+ const waitMs = Math.max(
8018
+ 0,
8019
+ (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
8020
+ );
8021
+ onProgress?.(
8022
+ `Relay has not confirmed the outcome. Waiting ${Math.ceil(waitMs / 1e3)}s for its request lease to expire, then replaying the identical signed request (${leaseReplays}/${MAX_LEASE_EXPIRY_REPLAYS})...`
8023
+ );
8024
+ if (!await sleepUnlessAborted(waitMs, args.signal)) {
8025
+ return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
8026
+ }
8027
+ networkRetry = 0;
8028
+ leaseBaseMs = null;
8029
+ continue;
8030
+ }
7860
8031
  if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
7861
8032
  networkRetry++;
7862
8033
  const delay = relayBackoffMs(networkRetry);
@@ -11979,7 +12150,7 @@ function parseSwapRefund(r) {
11979
12150
  checkLeafPair(commitment, leaf, "SWAP_REFUND");
11980
12151
  return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
11981
12152
  }
11982
- function parseNoteIndexPage(bytes, expect) {
12153
+ function parseNoteIndexPage(bytes, expect, options = {}) {
11983
12154
  if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
11984
12155
  if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
11985
12156
  throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
@@ -12011,7 +12182,9 @@ function parseNoteIndexPage(bytes, expect) {
12011
12182
  }
12012
12183
  const items = [];
12013
12184
  const rawItems = [];
12185
+ const itemPositions = [];
12014
12186
  let skippedUnknown = 0;
12187
+ let skippedMalformed = 0;
12015
12188
  let offset = NOTE_INDEX_HEADER_LEN;
12016
12189
  for (let i = 0; i < count; i++) {
12017
12190
  if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
@@ -12020,34 +12193,45 @@ function parseNoteIndexPage(bytes, expect) {
12020
12193
  const bodyStart = offset + ITEM_HEADER_LEN;
12021
12194
  const bodyEnd = bodyStart + bodyLen;
12022
12195
  if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12023
- const r = new Reader(bytes, bodyStart, bodyEnd);
12196
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
12197
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12198
+ skippedUnknown++;
12199
+ offset = bodyEnd;
12200
+ continue;
12201
+ }
12024
12202
  let item;
12025
- switch (kind) {
12026
- case NOTE_INDEX_KIND_TX:
12027
- if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12028
- item = parseTx(r, bodyLen);
12029
- break;
12030
- case NOTE_INDEX_KIND_DELIVERY:
12031
- if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12032
- item = parseDelivery(r);
12033
- break;
12034
- case NOTE_INDEX_KIND_SWAP_REFUND:
12035
- if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12036
- item = parseSwapRefund(r);
12037
- break;
12038
- default:
12039
- if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12040
- skippedUnknown++;
12041
- offset = bodyEnd;
12042
- continue;
12203
+ try {
12204
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
12205
+ } catch (error) {
12206
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
12207
+ skippedMalformed++;
12208
+ offset = bodyEnd;
12209
+ continue;
12043
12210
  }
12044
- if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12045
12211
  items.push(item);
12046
12212
  rawItems.push(bytes.slice(offset, bodyEnd));
12213
+ itemPositions.push(i);
12047
12214
  offset = bodyEnd;
12048
12215
  }
12049
12216
  if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12050
- return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown };
12217
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
12218
+ }
12219
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
12220
+ const bodyLen = bodyEnd - bodyStart;
12221
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12222
+ let item;
12223
+ if (kind === NOTE_INDEX_KIND_TX) {
12224
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12225
+ item = parseTx(r, bodyLen);
12226
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
12227
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12228
+ item = parseDelivery(r);
12229
+ } else {
12230
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12231
+ item = parseSwapRefund(r);
12232
+ }
12233
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12234
+ return item;
12051
12235
  }
12052
12236
  function parseNoteIndexItem(raw) {
12053
12237
  if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
@@ -12477,6 +12661,14 @@ async function trialItem(item, trials) {
12477
12661
  }
12478
12662
  return null;
12479
12663
  }
12664
+ async function trialItemIsolated(item, trials, stats) {
12665
+ try {
12666
+ return await trialItem(item, trials);
12667
+ } catch {
12668
+ stats.skipped++;
12669
+ return null;
12670
+ }
12671
+ }
12480
12672
  async function trialItemWith(item, trial) {
12481
12673
  if (item.kind === 1) {
12482
12674
  if (item.note.length === 0) return null;
@@ -12508,7 +12700,14 @@ function leafOfTxOutput(item, commitment) {
12508
12700
  if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
12509
12701
  return null;
12510
12702
  }
12511
- async function matchOwnItems(own, owner, onReject) {
12703
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
12704
+ try {
12705
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
12706
+ } catch {
12707
+ return null;
12708
+ }
12709
+ }
12710
+ async function matchOwnItems(own, owner, onReject, onSkip) {
12512
12711
  const candidates = [];
12513
12712
  const claimed = /* @__PURE__ */ new Set();
12514
12713
  const byNullifier = /* @__PURE__ */ new Map();
@@ -12598,7 +12797,7 @@ async function matchOwnItems(own, owner, onReject) {
12598
12797
  });
12599
12798
  return true;
12600
12799
  };
12601
- for (const o of own) {
12800
+ const direct = async (o) => {
12602
12801
  const item = o.item;
12603
12802
  if (item.kind === 1 && o.note?.noteSalt !== void 0) {
12604
12803
  const note = o.note;
@@ -12612,7 +12811,7 @@ async function matchOwnItems(own, owner, onReject) {
12612
12811
  const mint = addressFromBytes(item.mint);
12613
12812
  if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
12614
12813
  onReject(o);
12615
- continue;
12814
+ return;
12616
12815
  }
12617
12816
  const commitment = await computeCommitment({
12618
12817
  amount: o.delivery.amount,
@@ -12622,7 +12821,7 @@ async function matchOwnItems(own, owner, onReject) {
12622
12821
  });
12623
12822
  if (commitment !== bytesToBigint2(item.commitment)) {
12624
12823
  onReject(o);
12625
- continue;
12824
+ return;
12626
12825
  }
12627
12826
  await add(o, {
12628
12827
  kind: "received",
@@ -12640,12 +12839,20 @@ async function matchOwnItems(own, owner, onReject) {
12640
12839
  atRisk: o.refund.legacyExposed,
12641
12840
  amount: o.refund.amount,
12642
12841
  blinding: o.refund.blinding,
12643
- keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
12842
+ // per-swap refunds carry their derived keypair; owner-shape ones carry the owner
12843
+ keypair: o.refund.keypair,
12644
12844
  mint: NATIVE_SOL_MINT,
12645
12845
  commitment: o.refund.commitment,
12646
12846
  leaf: Number(item.leaf)
12647
12847
  });
12648
12848
  }
12849
+ };
12850
+ for (const o of own) {
12851
+ try {
12852
+ await direct(o);
12853
+ } catch {
12854
+ onSkip(o);
12855
+ }
12649
12856
  }
12650
12857
  const processTx = async (o) => {
12651
12858
  const item = o.item;
@@ -12660,8 +12867,9 @@ async function matchOwnItems(own, owner, onReject) {
12660
12867
  const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
12661
12868
  if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
12662
12869
  const out1 = sumIn + item.publicAmount - note.outAmount0;
12663
- if (out1 > 0n) {
12664
- const blinding = deriveChangeNoteBlinding(o.trial.nk, note.noteSalt, 1);
12870
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
12871
+ if (out1 > 0n && blinding === null) onSkip(o);
12872
+ else if (blinding !== null) {
12665
12873
  const owners = [{ keypair: owner, atRisk: false }];
12666
12874
  const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
12667
12875
  if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
@@ -12682,7 +12890,11 @@ async function matchOwnItems(own, owner, onReject) {
12682
12890
  for (let i = 0; i < queue.length; i++) {
12683
12891
  const o = queue[i];
12684
12892
  queued.delete(o);
12685
- await processTx(o);
12893
+ try {
12894
+ await processTx(o);
12895
+ } catch {
12896
+ onSkip(o);
12897
+ }
12686
12898
  }
12687
12899
  return candidates;
12688
12900
  }
@@ -12929,7 +13141,8 @@ async function recoverNotesFromIndex(params) {
12929
13141
  candidates: 0,
12930
13142
  spent: 0,
12931
13143
  conflicts: 0,
12932
- pendingDropped: 0
13144
+ pendingDropped: 0,
13145
+ skipped: 0
12933
13146
  };
12934
13147
  const rpc = new Proxy(connection, {
12935
13148
  get(target, prop, receiver) {
@@ -12996,10 +13209,11 @@ async function recoverNotesFromIndex(params) {
12996
13209
  let outcome = await runOnce(ctx, cursor);
12997
13210
  if (outcome instanceof FullPassSignal) {
12998
13211
  warnings.push(`${outcome.reason}; re-syncing from page 0`);
12999
- Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
13212
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
13000
13213
  outcome = await runOnce(ctx, void 0);
13001
13214
  if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13002
13215
  }
13216
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
13003
13217
  stats.ms = Date.now() - startedAt;
13004
13218
  return { ...outcome, stats, warnings };
13005
13219
  }
@@ -13076,11 +13290,13 @@ async function runOnce(ctx, cursor) {
13076
13290
  if (signal.aborted) throw abortError2();
13077
13291
  const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13078
13292
  stats.bytes += bytes.length;
13079
- const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
13293
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
13080
13294
  if (pageNo < head.completePages && !page2.complete) {
13081
13295
  throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13082
13296
  }
13083
13297
  stats.pages++;
13298
+ stats.skipped += page2.skippedMalformed;
13299
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
13084
13300
  waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13085
13301
  advanceChain();
13086
13302
  const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
@@ -13101,7 +13317,7 @@ async function runOnce(ctx, cursor) {
13101
13317
  else data.leaves.set(mint, [entry]);
13102
13318
  };
13103
13319
  page2.items.forEach((item, i) => {
13104
- const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
13320
+ const seq = seqOf(i);
13105
13321
  if (item.kind === 1) {
13106
13322
  addLeaf(item.mint, item.comm0, item.leaf0, seq);
13107
13323
  addLeaf(item.mint, item.comm1, item.leaf1, seq);
@@ -13118,7 +13334,7 @@ async function runOnce(ctx, cursor) {
13118
13334
  for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
13119
13335
  if (signal.aborted) throw abortError2();
13120
13336
  const batch = page2.items.slice(i, i + ITEM_BATCH);
13121
- const opened = await Promise.all(batch.map((item) => trialItem(item, trials)));
13337
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
13122
13338
  opened.forEach((o, k) => {
13123
13339
  if (!o) return;
13124
13340
  stats.decrypted++;
@@ -13128,7 +13344,7 @@ async function runOnce(ctx, cursor) {
13128
13344
  stats.dropped++;
13129
13345
  return;
13130
13346
  }
13131
- ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
13347
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
13132
13348
  });
13133
13349
  stats.items += batch.length;
13134
13350
  }
@@ -13161,7 +13377,7 @@ async function runOnce(ctx, cursor) {
13161
13377
  throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
13162
13378
  }
13163
13379
  for (const entry of cursor?.items ?? []) {
13164
- const o = await trialItem(entry.item, trials);
13380
+ const o = await trialItemIsolated(entry.item, trials, stats);
13165
13381
  if (!o) continue;
13166
13382
  const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
13167
13383
  ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
@@ -13173,10 +13389,20 @@ async function runOnce(ctx, cursor) {
13173
13389
  const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
13174
13390
  ownItems.sort((a, b) => a.seq - b.seq);
13175
13391
  const rejectedNow = /* @__PURE__ */ new Set();
13176
- const allCandidates = await matchOwnItems(ownItems, owner, (o) => {
13177
- stats.dropped++;
13178
- rejectedNow.add(o.id);
13179
- });
13392
+ const skippedNow = /* @__PURE__ */ new Set();
13393
+ const allCandidates = await matchOwnItems(
13394
+ ownItems,
13395
+ owner,
13396
+ (o) => {
13397
+ stats.dropped++;
13398
+ rejectedNow.add(o.id);
13399
+ },
13400
+ (o) => {
13401
+ if (skippedNow.has(o)) return;
13402
+ skippedNow.add(o);
13403
+ stats.skipped++;
13404
+ }
13405
+ );
13180
13406
  stats.candidates = allCandidates.length;
13181
13407
  const cutoff = params.legacyCutoffLeaf ?? {};
13182
13408
  const candidates = allCandidates.filter((c) => {
@@ -13280,7 +13506,8 @@ async function runOnce(ctx, cursor) {
13280
13506
  for (const c of byLeaf.values()) {
13281
13507
  const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
13282
13508
  keyChecked.set(c.keypair.privateKey, pubOk);
13283
- if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
13509
+ const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
13510
+ if (!pubOk || !c.atRisk && !ownerOk) {
13284
13511
  stats.dropped++;
13285
13512
  tally(c, "rejected");
13286
13513
  continue;
@@ -13289,7 +13516,7 @@ async function runOnce(ctx, cursor) {
13289
13516
  verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
13290
13517
  const utxo = {
13291
13518
  amount: c.amount,
13292
- keypair: c.atRisk ? { ...c.keypair } : owner,
13519
+ keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
13293
13520
  blinding: c.blinding,
13294
13521
  mintAddress: c.mint,
13295
13522
  index: c.leaf,
@@ -14774,6 +15001,7 @@ export {
14774
15001
  deriveSpendKey,
14775
15002
  deriveSwapRefundAuthorization,
14776
15003
  deriveSwapRefundBlinding,
15004
+ deriveSwapRefundKeypair,
14777
15005
  deriveUserCompliancePublicKey,
14778
15006
  deriveUserComplianceScalar,
14779
15007
  deriveUtxoKeypairFromSpendKey,