@cloak.dev/sdk 0.2.6-staging.f92dd96 → 0.2.7

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
@@ -808,6 +808,7 @@ __export(index_exports, {
808
808
  isTerminalFailure: () => isTerminalFailure,
809
809
  isTransactionSigner: () => import_kit2.isTransactionSigner,
810
810
  isValidHex: () => isValidHex,
811
+ isValidRelayClientId: () => isValidRelayClientId,
811
812
  isValidRpcUrl: () => isValidRpcUrl,
812
813
  isValidSolanaAddress: () => isValidSolanaAddress,
813
814
  isWithdrawAmountSufficient: () => isWithdrawAmountSufficient,
@@ -821,6 +822,7 @@ __export(index_exports, {
821
822
  matchSwapRefundLeaf: () => matchSwapRefundLeaf,
822
823
  mayRetry: () => mayRetry,
823
824
  messageSignerFromCallback: () => messageSignerFromCallback,
825
+ normalizeAffiliateCode: () => normalizeAffiliateCode,
824
826
  openRecipientDeliveryNote: () => openRecipientDeliveryNote,
825
827
  parseAmount: () => parseAmount,
826
828
  parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
@@ -1562,7 +1564,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
1562
1564
 
1563
1565
  // src/config/relay.ts
1564
1566
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
1565
- var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
1567
+ var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
1566
1568
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
1567
1569
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1568
1570
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -1642,7 +1644,7 @@ var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
1642
1644
  // src/relay/clock.ts
1643
1645
  var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
1644
1646
  var MAX_CLOCK_DIVERGENCE_MS = 2e3;
1645
- var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
1647
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
1646
1648
  var sample = null;
1647
1649
  function monotonicNowMs() {
1648
1650
  const perf = globalThis.performance;
@@ -5531,6 +5533,19 @@ async function preflightCheck(relayUrl, rootHex) {
5531
5533
  };
5532
5534
  }
5533
5535
 
5536
+ // src/relay/affiliate.ts
5537
+ var AFFILIATE_CODE_PATTERN = /^[a-z0-9_]{3,24}$/;
5538
+ var RELAY_CLIENT_HEADER_NAME = "X-Cloak-Client";
5539
+ var RELAY_CLIENT_HEADER_PATTERN = /^cloak-mobile\/(ios|android)\/\d+\.\d+\.\d+$/;
5540
+ function normalizeAffiliateCode(raw) {
5541
+ if (typeof raw !== "string") return null;
5542
+ const code = raw.trim().toLowerCase();
5543
+ return AFFILIATE_CODE_PATTERN.test(code) ? code : null;
5544
+ }
5545
+ function isValidRelayClientId(value) {
5546
+ return typeof value === "string" && RELAY_CLIENT_HEADER_PATTERN.test(value);
5547
+ }
5548
+
5534
5549
  // src/flows/transact.ts
5535
5550
  var import_kit8 = require("@solana/kit");
5536
5551
  var import_compute_budget = require("@solana-program/compute-budget");
@@ -7189,7 +7204,41 @@ function assertInputMints(inputUtxos, expectedMint) {
7189
7204
  }
7190
7205
  }
7191
7206
  function affiliateCodeOrUndefined(code) {
7192
- return typeof code === "string" && code.length > 0 ? code : void 0;
7207
+ return normalizeAffiliateCode(code) ?? void 0;
7208
+ }
7209
+ function prepareAffiliateAndClient(options) {
7210
+ let next = options;
7211
+ const raw = options.affiliateCode;
7212
+ if (raw !== void 0 && raw !== null) {
7213
+ const normalized = normalizeAffiliateCode(raw);
7214
+ if (normalized === null) {
7215
+ if (typeof raw === "string" && raw.trim() !== "") {
7216
+ options.onWarning?.(
7217
+ `affiliateCode ${JSON.stringify(raw)} is not a valid partner code (3-24 characters of a-z, 0-9 or _, after trimming and lower-casing); it was left out of the request.`
7218
+ );
7219
+ }
7220
+ next = { ...next, affiliateCode: void 0 };
7221
+ } else if (normalized !== raw) {
7222
+ next = { ...next, affiliateCode: normalized };
7223
+ }
7224
+ }
7225
+ const clientId = options.relayClientId;
7226
+ if (clientId !== void 0 && clientId !== null && !isValidRelayClientId(clientId)) {
7227
+ if (typeof clientId !== "string" || clientId.trim() !== "") {
7228
+ options.onWarning?.(
7229
+ `relayClientId ${JSON.stringify(clientId)} does not match cloak-mobile/(ios|android)/MAJOR.MINOR.PATCH; no X-Cloak-Client header was sent.`
7230
+ );
7231
+ }
7232
+ next = { ...next, relayClientId: void 0 };
7233
+ } else if (isValidRelayClientId(clientId)) {
7234
+ const headers = {};
7235
+ for (const [name, value] of Object.entries(options.relayHeaders ?? {})) {
7236
+ if (name.toLowerCase() !== RELAY_CLIENT_HEADER_NAME.toLowerCase()) headers[name] = value;
7237
+ }
7238
+ headers[RELAY_CLIENT_HEADER_NAME] = clientId;
7239
+ next = { ...next, relayHeaders: headers };
7240
+ }
7241
+ return next;
7193
7242
  }
7194
7243
  function parseNkInput(input) {
7195
7244
  if (typeof input !== "string") {
@@ -8844,7 +8893,8 @@ async function submitTransactToRelay(args) {
8844
8893
  new Error(`Relay submission exhausted ${maxNetworkRetries + 1} attempts without an outcome`)
8845
8894
  );
8846
8895
  }
8847
- async function transact(params, options) {
8896
+ async function transact(params, rawOptions) {
8897
+ const options = prepareAffiliateAndClient(rawOptions);
8848
8898
  const {
8849
8899
  connection,
8850
8900
  programId,
@@ -9965,7 +10015,8 @@ async function transact(params, options) {
9965
10015
  addressLookupTableAccounts: resultAddressLookupTableAccounts
9966
10016
  };
9967
10017
  }
9968
- async function transfer(inputUtxos, recipientPubkey, amount, options) {
10018
+ async function transfer(inputUtxos, recipientPubkey, amount, rawOptions) {
10019
+ const options = prepareAffiliateAndClient(rawOptions);
9969
10020
  const owner = await requireOwnerUtxoKeypair(options, "transfer");
9970
10021
  const transferNk = await requireWalletNk(options, "transfer");
9971
10022
  const inputSum = sumUtxoAmounts(inputUtxos);
@@ -10036,7 +10087,8 @@ async function transfer(inputUtxos, recipientPubkey, amount, options) {
10036
10087
  { ...spendOptions, chainNoteSalt: changeNoteSalt }
10037
10088
  );
10038
10089
  }
10039
- async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
10090
+ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, rawOptions) {
10091
+ const options = prepareAffiliateAndClient(rawOptions);
10040
10092
  const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
10041
10093
  const walletNk = await requireWalletNk(options, "partialWithdraw");
10042
10094
  const inputSum = sumUtxoAmounts(inputUtxos);
@@ -10178,7 +10230,8 @@ async function waitForSwapCompletion(relayUrl, requestId, onProgress, maxAttempt
10178
10230
  }
10179
10231
  return null;
10180
10232
  }
10181
- async function swapUtxo(params, options) {
10233
+ async function swapUtxo(params, rawOptions) {
10234
+ const options = prepareAffiliateAndClient(rawOptions);
10182
10235
  const {
10183
10236
  inputUtxos,
10184
10237
  changeUtxo,
@@ -11061,7 +11114,8 @@ async function swapUtxo(params, options) {
11061
11114
  }
11062
11115
  };
11063
11116
  }
11064
- async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
11117
+ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, rawOptions, recipientWallet) {
11118
+ const options = prepareAffiliateAndClient(rawOptions);
11065
11119
  const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
11066
11120
  const totalInput = sumUtxoAmounts(inputUtxos);
11067
11121
  const change = totalInput - swapAmount;
@@ -11469,7 +11523,8 @@ function createRelayBatchAuthCoordinator(options) {
11469
11523
  }
11470
11524
 
11471
11525
  // src/flows/transact-batch.ts
11472
- async function transactBatch(items, options) {
11526
+ async function transactBatch(items, rawOptions) {
11527
+ const options = prepareAffiliateAndClient(rawOptions);
11473
11528
  if (items.length === 0) {
11474
11529
  return { results: [], approvals: 0 };
11475
11530
  }
@@ -11544,6 +11599,7 @@ var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
11544
11599
  var SOL_MINT = "So11111111111111111111111111111111111111112";
11545
11600
  var USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
11546
11601
  var USDT_MINT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
11602
+ var BRS_MINT = "BRSxQRUaGswjLs7ewcH7uXj3r7SgmfKSSLLXyCKHZtUo";
11547
11603
  var PUBLIC_AMOUNT_OFFSET = 32;
11548
11604
  var EXT_DATA_HASH_OFFSET = 40;
11549
11605
  var OUTPUT_COMMITMENT_0_OFFSET = 168;
@@ -11600,6 +11656,7 @@ function symbolForMint(mint) {
11600
11656
  if (mint === SOL_MINT) return "SOL";
11601
11657
  if (mint === USDC_MINT) return "USDC";
11602
11658
  if (mint === USDT_MINT) return "USDT";
11659
+ if (mint === BRS_MINT) return "BRS";
11603
11660
  if (!mint || mint.length < 8) return "TOKEN";
11604
11661
  return `${mint.slice(0, 4)}...${mint.slice(-4)}`;
11605
11662
  }
@@ -12875,7 +12932,7 @@ function parseSwapRefund(r) {
12875
12932
  checkLeafPair(commitment, leaf, "SWAP_REFUND");
12876
12933
  return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
12877
12934
  }
12878
- function parseNoteIndexPage(bytes, expect) {
12935
+ function parseNoteIndexPage(bytes, expect, options = {}) {
12879
12936
  if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
12880
12937
  if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
12881
12938
  throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
@@ -12907,7 +12964,9 @@ function parseNoteIndexPage(bytes, expect) {
12907
12964
  }
12908
12965
  const items = [];
12909
12966
  const rawItems = [];
12967
+ const itemPositions = [];
12910
12968
  let skippedUnknown = 0;
12969
+ let skippedMalformed = 0;
12911
12970
  let offset = NOTE_INDEX_HEADER_LEN;
12912
12971
  for (let i = 0; i < count; i++) {
12913
12972
  if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
@@ -12916,34 +12975,45 @@ function parseNoteIndexPage(bytes, expect) {
12916
12975
  const bodyStart = offset + ITEM_HEADER_LEN;
12917
12976
  const bodyEnd = bodyStart + bodyLen;
12918
12977
  if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12919
- const r = new Reader(bytes, bodyStart, bodyEnd);
12978
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
12979
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12980
+ skippedUnknown++;
12981
+ offset = bodyEnd;
12982
+ continue;
12983
+ }
12920
12984
  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;
12985
+ try {
12986
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
12987
+ } catch (error) {
12988
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
12989
+ skippedMalformed++;
12990
+ offset = bodyEnd;
12991
+ continue;
12939
12992
  }
12940
- if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12941
12993
  items.push(item);
12942
12994
  rawItems.push(bytes.slice(offset, bodyEnd));
12995
+ itemPositions.push(i);
12943
12996
  offset = bodyEnd;
12944
12997
  }
12945
12998
  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 };
12999
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
13000
+ }
13001
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
13002
+ const bodyLen = bodyEnd - bodyStart;
13003
+ const r = new Reader(bytes, bodyStart, bodyEnd);
13004
+ let item;
13005
+ if (kind === NOTE_INDEX_KIND_TX) {
13006
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
13007
+ item = parseTx(r, bodyLen);
13008
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
13009
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
13010
+ item = parseDelivery(r);
13011
+ } else {
13012
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
13013
+ item = parseSwapRefund(r);
13014
+ }
13015
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
13016
+ return item;
12947
13017
  }
12948
13018
  function parseNoteIndexItem(raw) {
12949
13019
  if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
@@ -13276,6 +13346,7 @@ var MAX_REJECTED_IDS = 1024;
13276
13346
  var LEAF_WINDOW = 512;
13277
13347
  var MAX_OVERRIDES = 256;
13278
13348
  var MAX_CURSOR_OWN_ITEMS = 65536;
13349
+ var MAX_LEGACY_VIEWING_KEYS = 8;
13279
13350
  var MAX_CURSOR_KEYS = 131072;
13280
13351
  var MAX_CURSOR_POOLS = 256;
13281
13352
  var MAX_CURSOR_PAGE = 2 ** 32;
@@ -13366,7 +13437,23 @@ var LeafBuffer = class {
13366
13437
  return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
13367
13438
  }
13368
13439
  };
13369
- async function trialItem(item, trial) {
13440
+ async function trialItem(item, trials) {
13441
+ for (const trial of trials) {
13442
+ if (trial.legacy && item.kind === 2) continue;
13443
+ const opened = await trialItemWith(item, trial);
13444
+ if (opened) return { ...opened, trial };
13445
+ }
13446
+ return null;
13447
+ }
13448
+ async function trialItemIsolated(item, trials, stats) {
13449
+ try {
13450
+ return await trialItem(item, trials);
13451
+ } catch {
13452
+ stats.skipped++;
13453
+ return null;
13454
+ }
13455
+ }
13456
+ async function trialItemWith(item, trial) {
13370
13457
  if (item.kind === 1) {
13371
13458
  if (item.note.length === 0) return null;
13372
13459
  let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
@@ -13397,8 +13484,14 @@ function leafOfTxOutput(item, commitment) {
13397
13484
  if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
13398
13485
  return null;
13399
13486
  }
13400
- async function matchOwnItems(own, trial, onReject) {
13401
- const { nk, owner } = trial;
13487
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
13488
+ try {
13489
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
13490
+ } catch {
13491
+ return null;
13492
+ }
13493
+ }
13494
+ async function matchOwnItems(own, owner, onReject, onSkip) {
13402
13495
  const candidates = [];
13403
13496
  const claimed = /* @__PURE__ */ new Set();
13404
13497
  const byNullifier = /* @__PURE__ */ new Map();
@@ -13422,27 +13515,26 @@ async function matchOwnItems(own, trial, onReject) {
13422
13515
  queued.add(o);
13423
13516
  queue.push(o);
13424
13517
  };
13425
- const add = async (c) => {
13518
+ const add = async (o, c) => {
13426
13519
  const nullifier = hex32(
13427
13520
  await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
13428
13521
  );
13429
- const full = { ...c, nullifier };
13522
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
13430
13523
  candidates.push(full);
13431
13524
  if (!byNullifier.has(nullifier)) {
13432
13525
  byNullifier.set(nullifier, full);
13433
- for (const o of spendsOf.get(nullifier) ?? []) enqueue(o);
13526
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
13434
13527
  }
13435
- if (full.atRisk && !legacyKeys.has(full.keypair.publicKey)) {
13436
- legacyKeys.set(full.keypair.publicKey, full.keypair);
13437
- for (const o of byOutKey.get(full.keypair.publicKey) ?? []) enqueue(o);
13528
+ if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
13529
+ legacyKeys.set(c.keypair.publicKey, c.keypair);
13530
+ for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
13438
13531
  }
13439
13532
  };
13440
- const base = (o) => ({ signature: o.item.signature, page: o.page, seq: o.seq });
13441
13533
  const tryDeposit = async (o, item, amount) => {
13442
13534
  const note = o.note;
13443
13535
  const mint = addressFromBytes(item.mint);
13444
13536
  const deposit = await matchDepositNote({
13445
- viewingKeyNk: nk,
13537
+ viewingKeyNk: o.trial.nk,
13446
13538
  noteSalt: note.noteSalt,
13447
13539
  amount,
13448
13540
  mintAddress: mint,
@@ -13451,7 +13543,7 @@ async function matchOwnItems(own, trial, onReject) {
13451
13543
  });
13452
13544
  const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
13453
13545
  if (!deposit || leaf === null) return false;
13454
- await add({
13546
+ await add(o, {
13455
13547
  kind: "deposit",
13456
13548
  atRisk: deposit.legacyExposed,
13457
13549
  amount: deposit.amount,
@@ -13459,8 +13551,7 @@ async function matchOwnItems(own, trial, onReject) {
13459
13551
  keypair: deposit.legacyExposed ? deposit.keypair : owner,
13460
13552
  mint,
13461
13553
  commitment: deposit.commitment,
13462
- leaf,
13463
- ...base(o)
13554
+ leaf
13464
13555
  });
13465
13556
  return true;
13466
13557
  };
@@ -13468,7 +13559,7 @@ async function matchOwnItems(own, trial, onReject) {
13468
13559
  const note = o.note;
13469
13560
  const mint = addressFromBytes(item.mint);
13470
13561
  const change = await matchChangeNote({
13471
- viewingKeyNk: nk,
13562
+ viewingKeyNk: o.trial.nk,
13472
13563
  noteSalt: note.noteSalt,
13473
13564
  amount: note.outAmount0,
13474
13565
  keypair,
@@ -13478,7 +13569,7 @@ async function matchOwnItems(own, trial, onReject) {
13478
13569
  ownerUtxoPublicKey: owner.publicKey
13479
13570
  });
13480
13571
  if (!change) return false;
13481
- await add({
13572
+ await add(o, {
13482
13573
  kind: "change",
13483
13574
  atRisk,
13484
13575
  amount: change.amount,
@@ -13486,12 +13577,11 @@ async function matchOwnItems(own, trial, onReject) {
13486
13577
  keypair,
13487
13578
  mint,
13488
13579
  commitment: change.commitment,
13489
- leaf: Number(item.leaf0),
13490
- ...base(o)
13580
+ leaf: Number(item.leaf0)
13491
13581
  });
13492
13582
  return true;
13493
13583
  };
13494
- for (const o of own) {
13584
+ const direct = async (o) => {
13495
13585
  const item = o.item;
13496
13586
  if (item.kind === 1 && o.note?.noteSalt !== void 0) {
13497
13587
  const note = o.note;
@@ -13505,7 +13595,7 @@ async function matchOwnItems(own, trial, onReject) {
13505
13595
  const mint = addressFromBytes(item.mint);
13506
13596
  if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
13507
13597
  onReject(o);
13508
- continue;
13598
+ return;
13509
13599
  }
13510
13600
  const commitment = await computeCommitment2({
13511
13601
  amount: o.delivery.amount,
@@ -13515,9 +13605,9 @@ async function matchOwnItems(own, trial, onReject) {
13515
13605
  });
13516
13606
  if (commitment !== bytesToBigint3(item.commitment)) {
13517
13607
  onReject(o);
13518
- continue;
13608
+ return;
13519
13609
  }
13520
- await add({
13610
+ await add(o, {
13521
13611
  kind: "received",
13522
13612
  atRisk: false,
13523
13613
  amount: o.delivery.amount,
@@ -13525,11 +13615,10 @@ async function matchOwnItems(own, trial, onReject) {
13525
13615
  keypair: owner,
13526
13616
  mint,
13527
13617
  commitment,
13528
- leaf: Number(item.leaf),
13529
- ...base(o)
13618
+ leaf: Number(item.leaf)
13530
13619
  });
13531
13620
  } else if (item.kind === 3 && o.refund) {
13532
- await add({
13621
+ await add(o, {
13533
13622
  kind: "swap_refund",
13534
13623
  atRisk: o.refund.legacyExposed,
13535
13624
  amount: o.refund.amount,
@@ -13537,10 +13626,16 @@ async function matchOwnItems(own, trial, onReject) {
13537
13626
  keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
13538
13627
  mint: NATIVE_SOL_MINT,
13539
13628
  commitment: o.refund.commitment,
13540
- leaf: Number(item.leaf),
13541
- ...base(o)
13629
+ leaf: Number(item.leaf)
13542
13630
  });
13543
13631
  }
13632
+ };
13633
+ for (const o of own) {
13634
+ try {
13635
+ await direct(o);
13636
+ } catch {
13637
+ onSkip(o);
13638
+ }
13544
13639
  }
13545
13640
  const processTx = async (o) => {
13546
13641
  const item = o.item;
@@ -13555,8 +13650,9 @@ async function matchOwnItems(own, trial, onReject) {
13555
13650
  const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
13556
13651
  if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
13557
13652
  const out1 = sumIn + item.publicAmount - note.outAmount0;
13558
- if (out1 > 0n) {
13559
- const blinding = deriveChangeNoteBlinding(nk, note.noteSalt, 1);
13653
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
13654
+ if (out1 > 0n && blinding === null) onSkip(o);
13655
+ else if (blinding !== null) {
13560
13656
  const owners = [{ keypair: owner, atRisk: false }];
13561
13657
  const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
13562
13658
  if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
@@ -13564,7 +13660,7 @@ async function matchOwnItems(own, trial, onReject) {
13564
13660
  const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
13565
13661
  if (commitment !== bytesToBigint3(item.comm1)) continue;
13566
13662
  claimed.add(`${o.seq}:1`);
13567
- await add({ kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1), ...base(o) });
13663
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
13568
13664
  break;
13569
13665
  }
13570
13666
  }
@@ -13577,7 +13673,11 @@ async function matchOwnItems(own, trial, onReject) {
13577
13673
  for (let i = 0; i < queue.length; i++) {
13578
13674
  const o = queue[i];
13579
13675
  queued.delete(o);
13580
- await processTx(o);
13676
+ try {
13677
+ await processTx(o);
13678
+ } catch {
13679
+ onSkip(o);
13680
+ }
13581
13681
  }
13582
13682
  return candidates;
13583
13683
  }
@@ -13824,7 +13924,8 @@ async function recoverNotesFromIndex(params) {
13824
13924
  candidates: 0,
13825
13925
  spent: 0,
13826
13926
  conflicts: 0,
13827
- pendingDropped: 0
13927
+ pendingDropped: 0,
13928
+ skipped: 0
13828
13929
  };
13829
13930
  const rpc = new Proxy(connection, {
13830
13931
  get(target, prop, receiver) {
@@ -13846,12 +13947,25 @@ async function recoverNotesFromIndex(params) {
13846
13947
  };
13847
13948
  }
13848
13949
  });
13849
- const trial = {
13850
- nk: viewingKeyNk,
13950
+ const makeTrial = async (nk, legacy) => ({
13951
+ nk,
13952
+ legacy,
13851
13953
  owner,
13852
- decrypt: await createCompactChainNoteDecryptor(viewingKeyNk),
13853
- open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(viewingKeyNk).privateKey)
13854
- };
13954
+ decrypt: await createCompactChainNoteDecryptor(nk),
13955
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
13956
+ });
13957
+ const trials = [await makeTrial(viewingKeyNk, false)];
13958
+ const legacyNks = params.legacyViewingKeyNks ?? [];
13959
+ if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
13960
+ if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
13961
+ const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
13962
+ for (const nk of legacyNks) {
13963
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
13964
+ const key = toHex2(nk);
13965
+ if (seenNks.has(key)) continue;
13966
+ seenNks.add(key);
13967
+ trials.push(await makeTrial(Uint8Array.from(nk), true));
13968
+ }
13855
13969
  const poolMints = Array.from(new Set(params.poolMints));
13856
13970
  const warnings = [];
13857
13971
  const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
@@ -13874,21 +13988,21 @@ async function recoverNotesFromIndex(params) {
13874
13988
  return account && parsed ? { ...parsed, data: account.data } : null;
13875
13989
  });
13876
13990
  })());
13877
- const ctx = { params, head, trial, stats, poolMints, warnings, readTrees };
13991
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
13878
13992
  let outcome = await runOnce(ctx, cursor);
13879
13993
  if (outcome instanceof FullPassSignal) {
13880
13994
  warnings.push(`${outcome.reason}; re-syncing from page 0`);
13881
- Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
13995
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
13882
13996
  outcome = await runOnce(ctx, void 0);
13883
13997
  if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13884
13998
  }
13999
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
13885
14000
  stats.ms = Date.now() - startedAt;
13886
14001
  return { ...outcome, stats, warnings };
13887
14002
  }
13888
14003
  async function runOnce(ctx, cursor) {
13889
- const { params, head, trial, stats, poolMints } = ctx;
14004
+ const { params, head, trials, owner, stats, poolMints } = ctx;
13890
14005
  const { relayUrl, onProgress } = params;
13891
- const owner = trial.owner;
13892
14006
  const poolSet = new Set(poolMints);
13893
14007
  const startPage = cursor?.raw.page ?? 0;
13894
14008
  const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
@@ -13959,11 +14073,13 @@ async function runOnce(ctx, cursor) {
13959
14073
  if (signal.aborted) throw abortError2();
13960
14074
  const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13961
14075
  stats.bytes += bytes.length;
13962
- const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
14076
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
13963
14077
  if (pageNo < head.completePages && !page2.complete) {
13964
14078
  throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13965
14079
  }
13966
14080
  stats.pages++;
14081
+ stats.skipped += page2.skippedMalformed;
14082
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
13967
14083
  waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13968
14084
  advanceChain();
13969
14085
  const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
@@ -13984,7 +14100,7 @@ async function runOnce(ctx, cursor) {
13984
14100
  else data.leaves.set(mint, [entry]);
13985
14101
  };
13986
14102
  page2.items.forEach((item, i) => {
13987
- const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
14103
+ const seq = seqOf(i);
13988
14104
  if (item.kind === 1) {
13989
14105
  addLeaf(item.mint, item.comm0, item.leaf0, seq);
13990
14106
  addLeaf(item.mint, item.comm1, item.leaf1, seq);
@@ -14001,7 +14117,7 @@ async function runOnce(ctx, cursor) {
14001
14117
  for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
14002
14118
  if (signal.aborted) throw abortError2();
14003
14119
  const batch = page2.items.slice(i, i + ITEM_BATCH);
14004
- const opened = await Promise.all(batch.map((item) => trialItem(item, trial)));
14120
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
14005
14121
  opened.forEach((o, k) => {
14006
14122
  if (!o) return;
14007
14123
  stats.decrypted++;
@@ -14011,7 +14127,7 @@ async function runOnce(ctx, cursor) {
14011
14127
  stats.dropped++;
14012
14128
  return;
14013
14129
  }
14014
- ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o });
14130
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
14015
14131
  });
14016
14132
  stats.items += batch.length;
14017
14133
  }
@@ -14044,10 +14160,10 @@ async function runOnce(ctx, cursor) {
14044
14160
  throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
14045
14161
  }
14046
14162
  for (const entry of cursor?.items ?? []) {
14047
- const o = await trialItem(entry.item, trial);
14163
+ const o = await trialItemIsolated(entry.item, trials, stats);
14048
14164
  if (!o) continue;
14049
14165
  const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
14050
- ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o });
14166
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
14051
14167
  if (entry.item.kind === 1) {
14052
14168
  if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
14053
14169
  if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
@@ -14056,10 +14172,20 @@ async function runOnce(ctx, cursor) {
14056
14172
  const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
14057
14173
  ownItems.sort((a, b) => a.seq - b.seq);
14058
14174
  const rejectedNow = /* @__PURE__ */ new Set();
14059
- const allCandidates = await matchOwnItems(ownItems, trial, (o) => {
14060
- stats.dropped++;
14061
- rejectedNow.add(o.id);
14062
- });
14175
+ const skippedNow = /* @__PURE__ */ new Set();
14176
+ const allCandidates = await matchOwnItems(
14177
+ ownItems,
14178
+ owner,
14179
+ (o) => {
14180
+ stats.dropped++;
14181
+ rejectedNow.add(o.id);
14182
+ },
14183
+ (o) => {
14184
+ if (skippedNow.has(o)) return;
14185
+ skippedNow.add(o);
14186
+ stats.skipped++;
14187
+ }
14188
+ );
14063
14189
  stats.candidates = allCandidates.length;
14064
14190
  const cutoff = params.legacyCutoffLeaf ?? {};
14065
14191
  const candidates = allCandidates.filter((c) => {
@@ -15504,7 +15630,7 @@ async function withShieldRetries(attempt, hooks = {}) {
15504
15630
  }
15505
15631
 
15506
15632
  // src/index.ts
15507
- var VERSION = "0.2.6";
15633
+ var VERSION = "0.2.7";
15508
15634
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15509
15635
  // Annotate the CommonJS export names for ESM import in node:
15510
15636
  0 && (module.exports = {
@@ -15741,6 +15867,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15741
15867
  isTerminalFailure,
15742
15868
  isTransactionSigner,
15743
15869
  isValidHex,
15870
+ isValidRelayClientId,
15744
15871
  isValidRpcUrl,
15745
15872
  isValidSolanaAddress,
15746
15873
  isWithdrawAmountSufficient,
@@ -15754,6 +15881,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15754
15881
  matchSwapRefundLeaf,
15755
15882
  mayRetry,
15756
15883
  messageSignerFromCallback,
15884
+ normalizeAffiliateCode,
15757
15885
  openRecipientDeliveryNote,
15758
15886
  parseAmount,
15759
15887
  parseDeliveryCarrierMemo,