@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.js CHANGED
@@ -676,7 +676,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
676
676
 
677
677
  // src/config/relay.ts
678
678
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
679
- var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
679
+ var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
680
680
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
681
681
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
682
682
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -756,7 +756,7 @@ var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
756
756
  // src/relay/clock.ts
757
757
  var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
758
758
  var MAX_CLOCK_DIVERGENCE_MS = 2e3;
759
- var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
759
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
760
760
  var sample = null;
761
761
  function monotonicNowMs() {
762
762
  const perf = globalThis.performance;
@@ -4643,6 +4643,19 @@ async function preflightCheck(relayUrl, rootHex) {
4643
4643
  };
4644
4644
  }
4645
4645
 
4646
+ // src/relay/affiliate.ts
4647
+ var AFFILIATE_CODE_PATTERN = /^[a-z0-9_]{3,24}$/;
4648
+ var RELAY_CLIENT_HEADER_NAME = "X-Cloak-Client";
4649
+ var RELAY_CLIENT_HEADER_PATTERN = /^cloak-mobile\/(ios|android)\/\d+\.\d+\.\d+$/;
4650
+ function normalizeAffiliateCode(raw) {
4651
+ if (typeof raw !== "string") return null;
4652
+ const code = raw.trim().toLowerCase();
4653
+ return AFFILIATE_CODE_PATTERN.test(code) ? code : null;
4654
+ }
4655
+ function isValidRelayClientId(value) {
4656
+ return typeof value === "string" && RELAY_CLIENT_HEADER_PATTERN.test(value);
4657
+ }
4658
+
4646
4659
  // src/flows/transact.ts
4647
4660
  import { createNoopSigner as createNoopSigner2, isKeyPairSigner, isSignerRole } from "@solana/kit";
4648
4661
  import {
@@ -6301,7 +6314,41 @@ function assertInputMints(inputUtxos, expectedMint) {
6301
6314
  }
6302
6315
  }
6303
6316
  function affiliateCodeOrUndefined(code) {
6304
- return typeof code === "string" && code.length > 0 ? code : void 0;
6317
+ return normalizeAffiliateCode(code) ?? void 0;
6318
+ }
6319
+ function prepareAffiliateAndClient(options) {
6320
+ let next = options;
6321
+ const raw = options.affiliateCode;
6322
+ if (raw !== void 0 && raw !== null) {
6323
+ const normalized = normalizeAffiliateCode(raw);
6324
+ if (normalized === null) {
6325
+ if (typeof raw === "string" && raw.trim() !== "") {
6326
+ options.onWarning?.(
6327
+ `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.`
6328
+ );
6329
+ }
6330
+ next = { ...next, affiliateCode: void 0 };
6331
+ } else if (normalized !== raw) {
6332
+ next = { ...next, affiliateCode: normalized };
6333
+ }
6334
+ }
6335
+ const clientId = options.relayClientId;
6336
+ if (clientId !== void 0 && clientId !== null && !isValidRelayClientId(clientId)) {
6337
+ if (typeof clientId !== "string" || clientId.trim() !== "") {
6338
+ options.onWarning?.(
6339
+ `relayClientId ${JSON.stringify(clientId)} does not match cloak-mobile/(ios|android)/MAJOR.MINOR.PATCH; no X-Cloak-Client header was sent.`
6340
+ );
6341
+ }
6342
+ next = { ...next, relayClientId: void 0 };
6343
+ } else if (isValidRelayClientId(clientId)) {
6344
+ const headers = {};
6345
+ for (const [name, value] of Object.entries(options.relayHeaders ?? {})) {
6346
+ if (name.toLowerCase() !== RELAY_CLIENT_HEADER_NAME.toLowerCase()) headers[name] = value;
6347
+ }
6348
+ headers[RELAY_CLIENT_HEADER_NAME] = clientId;
6349
+ next = { ...next, relayHeaders: headers };
6350
+ }
6351
+ return next;
6305
6352
  }
6306
6353
  function parseNkInput(input) {
6307
6354
  if (typeof input !== "string") {
@@ -7956,7 +8003,8 @@ async function submitTransactToRelay(args) {
7956
8003
  new Error(`Relay submission exhausted ${maxNetworkRetries + 1} attempts without an outcome`)
7957
8004
  );
7958
8005
  }
7959
- async function transact(params, options) {
8006
+ async function transact(params, rawOptions) {
8007
+ const options = prepareAffiliateAndClient(rawOptions);
7960
8008
  const {
7961
8009
  connection,
7962
8010
  programId,
@@ -9077,7 +9125,8 @@ async function transact(params, options) {
9077
9125
  addressLookupTableAccounts: resultAddressLookupTableAccounts
9078
9126
  };
9079
9127
  }
9080
- async function transfer(inputUtxos, recipientPubkey, amount, options) {
9128
+ async function transfer(inputUtxos, recipientPubkey, amount, rawOptions) {
9129
+ const options = prepareAffiliateAndClient(rawOptions);
9081
9130
  const owner = await requireOwnerUtxoKeypair(options, "transfer");
9082
9131
  const transferNk = await requireWalletNk(options, "transfer");
9083
9132
  const inputSum = sumUtxoAmounts(inputUtxos);
@@ -9148,7 +9197,8 @@ async function transfer(inputUtxos, recipientPubkey, amount, options) {
9148
9197
  { ...spendOptions, chainNoteSalt: changeNoteSalt }
9149
9198
  );
9150
9199
  }
9151
- async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
9200
+ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, rawOptions) {
9201
+ const options = prepareAffiliateAndClient(rawOptions);
9152
9202
  const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
9153
9203
  const walletNk = await requireWalletNk(options, "partialWithdraw");
9154
9204
  const inputSum = sumUtxoAmounts(inputUtxos);
@@ -9290,7 +9340,8 @@ async function waitForSwapCompletion(relayUrl, requestId, onProgress, maxAttempt
9290
9340
  }
9291
9341
  return null;
9292
9342
  }
9293
- async function swapUtxo(params, options) {
9343
+ async function swapUtxo(params, rawOptions) {
9344
+ const options = prepareAffiliateAndClient(rawOptions);
9294
9345
  const {
9295
9346
  inputUtxos,
9296
9347
  changeUtxo,
@@ -10173,7 +10224,8 @@ async function swapUtxo(params, options) {
10173
10224
  }
10174
10225
  };
10175
10226
  }
10176
- async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
10227
+ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, rawOptions, recipientWallet) {
10228
+ const options = prepareAffiliateAndClient(rawOptions);
10177
10229
  const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
10178
10230
  const totalInput = sumUtxoAmounts(inputUtxos);
10179
10231
  const change = totalInput - swapAmount;
@@ -10578,7 +10630,8 @@ function createRelayBatchAuthCoordinator(options) {
10578
10630
  }
10579
10631
 
10580
10632
  // src/flows/transact-batch.ts
10581
- async function transactBatch(items, options) {
10633
+ async function transactBatch(items, rawOptions) {
10634
+ const options = prepareAffiliateAndClient(rawOptions);
10582
10635
  if (items.length === 0) {
10583
10636
  return { results: [], approvals: 0 };
10584
10637
  }
@@ -10650,6 +10703,7 @@ var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
10650
10703
  var SOL_MINT = "So11111111111111111111111111111111111111112";
10651
10704
  var USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
10652
10705
  var USDT_MINT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
10706
+ var BRS_MINT = "BRSxQRUaGswjLs7ewcH7uXj3r7SgmfKSSLLXyCKHZtUo";
10653
10707
  var PUBLIC_AMOUNT_OFFSET = 32;
10654
10708
  var EXT_DATA_HASH_OFFSET = 40;
10655
10709
  var OUTPUT_COMMITMENT_0_OFFSET = 168;
@@ -10706,6 +10760,7 @@ function symbolForMint(mint) {
10706
10760
  if (mint === SOL_MINT) return "SOL";
10707
10761
  if (mint === USDC_MINT) return "USDC";
10708
10762
  if (mint === USDT_MINT) return "USDT";
10763
+ if (mint === BRS_MINT) return "BRS";
10709
10764
  if (!mint || mint.length < 8) return "TOKEN";
10710
10765
  return `${mint.slice(0, 4)}...${mint.slice(-4)}`;
10711
10766
  }
@@ -11979,7 +12034,7 @@ function parseSwapRefund(r) {
11979
12034
  checkLeafPair(commitment, leaf, "SWAP_REFUND");
11980
12035
  return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
11981
12036
  }
11982
- function parseNoteIndexPage(bytes, expect) {
12037
+ function parseNoteIndexPage(bytes, expect, options = {}) {
11983
12038
  if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
11984
12039
  if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
11985
12040
  throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
@@ -12011,7 +12066,9 @@ function parseNoteIndexPage(bytes, expect) {
12011
12066
  }
12012
12067
  const items = [];
12013
12068
  const rawItems = [];
12069
+ const itemPositions = [];
12014
12070
  let skippedUnknown = 0;
12071
+ let skippedMalformed = 0;
12015
12072
  let offset = NOTE_INDEX_HEADER_LEN;
12016
12073
  for (let i = 0; i < count; i++) {
12017
12074
  if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
@@ -12020,34 +12077,45 @@ function parseNoteIndexPage(bytes, expect) {
12020
12077
  const bodyStart = offset + ITEM_HEADER_LEN;
12021
12078
  const bodyEnd = bodyStart + bodyLen;
12022
12079
  if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12023
- const r = new Reader(bytes, bodyStart, bodyEnd);
12080
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
12081
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12082
+ skippedUnknown++;
12083
+ offset = bodyEnd;
12084
+ continue;
12085
+ }
12024
12086
  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;
12087
+ try {
12088
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
12089
+ } catch (error) {
12090
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
12091
+ skippedMalformed++;
12092
+ offset = bodyEnd;
12093
+ continue;
12043
12094
  }
12044
- if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12045
12095
  items.push(item);
12046
12096
  rawItems.push(bytes.slice(offset, bodyEnd));
12097
+ itemPositions.push(i);
12047
12098
  offset = bodyEnd;
12048
12099
  }
12049
12100
  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 };
12101
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
12102
+ }
12103
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
12104
+ const bodyLen = bodyEnd - bodyStart;
12105
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12106
+ let item;
12107
+ if (kind === NOTE_INDEX_KIND_TX) {
12108
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12109
+ item = parseTx(r, bodyLen);
12110
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
12111
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12112
+ item = parseDelivery(r);
12113
+ } else {
12114
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12115
+ item = parseSwapRefund(r);
12116
+ }
12117
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12118
+ return item;
12051
12119
  }
12052
12120
  function parseNoteIndexItem(raw) {
12053
12121
  if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
@@ -12378,6 +12446,7 @@ var MAX_REJECTED_IDS = 1024;
12378
12446
  var LEAF_WINDOW = 512;
12379
12447
  var MAX_OVERRIDES = 256;
12380
12448
  var MAX_CURSOR_OWN_ITEMS = 65536;
12449
+ var MAX_LEGACY_VIEWING_KEYS = 8;
12381
12450
  var MAX_CURSOR_KEYS = 131072;
12382
12451
  var MAX_CURSOR_POOLS = 256;
12383
12452
  var MAX_CURSOR_PAGE = 2 ** 32;
@@ -12468,7 +12537,23 @@ var LeafBuffer = class {
12468
12537
  return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
12469
12538
  }
12470
12539
  };
12471
- async function trialItem(item, trial) {
12540
+ async function trialItem(item, trials) {
12541
+ for (const trial of trials) {
12542
+ if (trial.legacy && item.kind === 2) continue;
12543
+ const opened = await trialItemWith(item, trial);
12544
+ if (opened) return { ...opened, trial };
12545
+ }
12546
+ return null;
12547
+ }
12548
+ async function trialItemIsolated(item, trials, stats) {
12549
+ try {
12550
+ return await trialItem(item, trials);
12551
+ } catch {
12552
+ stats.skipped++;
12553
+ return null;
12554
+ }
12555
+ }
12556
+ async function trialItemWith(item, trial) {
12472
12557
  if (item.kind === 1) {
12473
12558
  if (item.note.length === 0) return null;
12474
12559
  let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
@@ -12499,8 +12584,14 @@ function leafOfTxOutput(item, commitment) {
12499
12584
  if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
12500
12585
  return null;
12501
12586
  }
12502
- async function matchOwnItems(own, trial, onReject) {
12503
- const { nk, owner } = trial;
12587
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
12588
+ try {
12589
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
12590
+ } catch {
12591
+ return null;
12592
+ }
12593
+ }
12594
+ async function matchOwnItems(own, owner, onReject, onSkip) {
12504
12595
  const candidates = [];
12505
12596
  const claimed = /* @__PURE__ */ new Set();
12506
12597
  const byNullifier = /* @__PURE__ */ new Map();
@@ -12524,27 +12615,26 @@ async function matchOwnItems(own, trial, onReject) {
12524
12615
  queued.add(o);
12525
12616
  queue.push(o);
12526
12617
  };
12527
- const add = async (c) => {
12618
+ const add = async (o, c) => {
12528
12619
  const nullifier = hex32(
12529
12620
  await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
12530
12621
  );
12531
- const full = { ...c, nullifier };
12622
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
12532
12623
  candidates.push(full);
12533
12624
  if (!byNullifier.has(nullifier)) {
12534
12625
  byNullifier.set(nullifier, full);
12535
- for (const o of spendsOf.get(nullifier) ?? []) enqueue(o);
12626
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
12536
12627
  }
12537
- if (full.atRisk && !legacyKeys.has(full.keypair.publicKey)) {
12538
- legacyKeys.set(full.keypair.publicKey, full.keypair);
12539
- for (const o of byOutKey.get(full.keypair.publicKey) ?? []) enqueue(o);
12628
+ if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
12629
+ legacyKeys.set(c.keypair.publicKey, c.keypair);
12630
+ for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
12540
12631
  }
12541
12632
  };
12542
- const base = (o) => ({ signature: o.item.signature, page: o.page, seq: o.seq });
12543
12633
  const tryDeposit = async (o, item, amount) => {
12544
12634
  const note = o.note;
12545
12635
  const mint = addressFromBytes(item.mint);
12546
12636
  const deposit = await matchDepositNote({
12547
- viewingKeyNk: nk,
12637
+ viewingKeyNk: o.trial.nk,
12548
12638
  noteSalt: note.noteSalt,
12549
12639
  amount,
12550
12640
  mintAddress: mint,
@@ -12553,7 +12643,7 @@ async function matchOwnItems(own, trial, onReject) {
12553
12643
  });
12554
12644
  const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
12555
12645
  if (!deposit || leaf === null) return false;
12556
- await add({
12646
+ await add(o, {
12557
12647
  kind: "deposit",
12558
12648
  atRisk: deposit.legacyExposed,
12559
12649
  amount: deposit.amount,
@@ -12561,8 +12651,7 @@ async function matchOwnItems(own, trial, onReject) {
12561
12651
  keypair: deposit.legacyExposed ? deposit.keypair : owner,
12562
12652
  mint,
12563
12653
  commitment: deposit.commitment,
12564
- leaf,
12565
- ...base(o)
12654
+ leaf
12566
12655
  });
12567
12656
  return true;
12568
12657
  };
@@ -12570,7 +12659,7 @@ async function matchOwnItems(own, trial, onReject) {
12570
12659
  const note = o.note;
12571
12660
  const mint = addressFromBytes(item.mint);
12572
12661
  const change = await matchChangeNote({
12573
- viewingKeyNk: nk,
12662
+ viewingKeyNk: o.trial.nk,
12574
12663
  noteSalt: note.noteSalt,
12575
12664
  amount: note.outAmount0,
12576
12665
  keypair,
@@ -12580,7 +12669,7 @@ async function matchOwnItems(own, trial, onReject) {
12580
12669
  ownerUtxoPublicKey: owner.publicKey
12581
12670
  });
12582
12671
  if (!change) return false;
12583
- await add({
12672
+ await add(o, {
12584
12673
  kind: "change",
12585
12674
  atRisk,
12586
12675
  amount: change.amount,
@@ -12588,12 +12677,11 @@ async function matchOwnItems(own, trial, onReject) {
12588
12677
  keypair,
12589
12678
  mint,
12590
12679
  commitment: change.commitment,
12591
- leaf: Number(item.leaf0),
12592
- ...base(o)
12680
+ leaf: Number(item.leaf0)
12593
12681
  });
12594
12682
  return true;
12595
12683
  };
12596
- for (const o of own) {
12684
+ const direct = async (o) => {
12597
12685
  const item = o.item;
12598
12686
  if (item.kind === 1 && o.note?.noteSalt !== void 0) {
12599
12687
  const note = o.note;
@@ -12607,7 +12695,7 @@ async function matchOwnItems(own, trial, onReject) {
12607
12695
  const mint = addressFromBytes(item.mint);
12608
12696
  if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
12609
12697
  onReject(o);
12610
- continue;
12698
+ return;
12611
12699
  }
12612
12700
  const commitment = await computeCommitment({
12613
12701
  amount: o.delivery.amount,
@@ -12617,9 +12705,9 @@ async function matchOwnItems(own, trial, onReject) {
12617
12705
  });
12618
12706
  if (commitment !== bytesToBigint2(item.commitment)) {
12619
12707
  onReject(o);
12620
- continue;
12708
+ return;
12621
12709
  }
12622
- await add({
12710
+ await add(o, {
12623
12711
  kind: "received",
12624
12712
  atRisk: false,
12625
12713
  amount: o.delivery.amount,
@@ -12627,11 +12715,10 @@ async function matchOwnItems(own, trial, onReject) {
12627
12715
  keypair: owner,
12628
12716
  mint,
12629
12717
  commitment,
12630
- leaf: Number(item.leaf),
12631
- ...base(o)
12718
+ leaf: Number(item.leaf)
12632
12719
  });
12633
12720
  } else if (item.kind === 3 && o.refund) {
12634
- await add({
12721
+ await add(o, {
12635
12722
  kind: "swap_refund",
12636
12723
  atRisk: o.refund.legacyExposed,
12637
12724
  amount: o.refund.amount,
@@ -12639,10 +12726,16 @@ async function matchOwnItems(own, trial, onReject) {
12639
12726
  keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
12640
12727
  mint: NATIVE_SOL_MINT,
12641
12728
  commitment: o.refund.commitment,
12642
- leaf: Number(item.leaf),
12643
- ...base(o)
12729
+ leaf: Number(item.leaf)
12644
12730
  });
12645
12731
  }
12732
+ };
12733
+ for (const o of own) {
12734
+ try {
12735
+ await direct(o);
12736
+ } catch {
12737
+ onSkip(o);
12738
+ }
12646
12739
  }
12647
12740
  const processTx = async (o) => {
12648
12741
  const item = o.item;
@@ -12657,8 +12750,9 @@ async function matchOwnItems(own, trial, onReject) {
12657
12750
  const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
12658
12751
  if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
12659
12752
  const out1 = sumIn + item.publicAmount - note.outAmount0;
12660
- if (out1 > 0n) {
12661
- const blinding = deriveChangeNoteBlinding(nk, note.noteSalt, 1);
12753
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
12754
+ if (out1 > 0n && blinding === null) onSkip(o);
12755
+ else if (blinding !== null) {
12662
12756
  const owners = [{ keypair: owner, atRisk: false }];
12663
12757
  const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
12664
12758
  if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
@@ -12666,7 +12760,7 @@ async function matchOwnItems(own, trial, onReject) {
12666
12760
  const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
12667
12761
  if (commitment !== bytesToBigint2(item.comm1)) continue;
12668
12762
  claimed.add(`${o.seq}:1`);
12669
- await add({ kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1), ...base(o) });
12763
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
12670
12764
  break;
12671
12765
  }
12672
12766
  }
@@ -12679,7 +12773,11 @@ async function matchOwnItems(own, trial, onReject) {
12679
12773
  for (let i = 0; i < queue.length; i++) {
12680
12774
  const o = queue[i];
12681
12775
  queued.delete(o);
12682
- await processTx(o);
12776
+ try {
12777
+ await processTx(o);
12778
+ } catch {
12779
+ onSkip(o);
12780
+ }
12683
12781
  }
12684
12782
  return candidates;
12685
12783
  }
@@ -12926,7 +13024,8 @@ async function recoverNotesFromIndex(params) {
12926
13024
  candidates: 0,
12927
13025
  spent: 0,
12928
13026
  conflicts: 0,
12929
- pendingDropped: 0
13027
+ pendingDropped: 0,
13028
+ skipped: 0
12930
13029
  };
12931
13030
  const rpc = new Proxy(connection, {
12932
13031
  get(target, prop, receiver) {
@@ -12948,12 +13047,25 @@ async function recoverNotesFromIndex(params) {
12948
13047
  };
12949
13048
  }
12950
13049
  });
12951
- const trial = {
12952
- nk: viewingKeyNk,
13050
+ const makeTrial = async (nk, legacy) => ({
13051
+ nk,
13052
+ legacy,
12953
13053
  owner,
12954
- decrypt: await createCompactChainNoteDecryptor(viewingKeyNk),
12955
- open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(viewingKeyNk).privateKey)
12956
- };
13054
+ decrypt: await createCompactChainNoteDecryptor(nk),
13055
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
13056
+ });
13057
+ const trials = [await makeTrial(viewingKeyNk, false)];
13058
+ const legacyNks = params.legacyViewingKeyNks ?? [];
13059
+ if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
13060
+ if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
13061
+ const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
13062
+ for (const nk of legacyNks) {
13063
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
13064
+ const key = toHex2(nk);
13065
+ if (seenNks.has(key)) continue;
13066
+ seenNks.add(key);
13067
+ trials.push(await makeTrial(Uint8Array.from(nk), true));
13068
+ }
12957
13069
  const poolMints = Array.from(new Set(params.poolMints));
12958
13070
  const warnings = [];
12959
13071
  const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
@@ -12976,21 +13088,21 @@ async function recoverNotesFromIndex(params) {
12976
13088
  return account && parsed ? { ...parsed, data: account.data } : null;
12977
13089
  });
12978
13090
  })());
12979
- const ctx = { params, head, trial, stats, poolMints, warnings, readTrees };
13091
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
12980
13092
  let outcome = await runOnce(ctx, cursor);
12981
13093
  if (outcome instanceof FullPassSignal) {
12982
13094
  warnings.push(`${outcome.reason}; re-syncing from page 0`);
12983
- Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
13095
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
12984
13096
  outcome = await runOnce(ctx, void 0);
12985
13097
  if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
12986
13098
  }
13099
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
12987
13100
  stats.ms = Date.now() - startedAt;
12988
13101
  return { ...outcome, stats, warnings };
12989
13102
  }
12990
13103
  async function runOnce(ctx, cursor) {
12991
- const { params, head, trial, stats, poolMints } = ctx;
13104
+ const { params, head, trials, owner, stats, poolMints } = ctx;
12992
13105
  const { relayUrl, onProgress } = params;
12993
- const owner = trial.owner;
12994
13106
  const poolSet = new Set(poolMints);
12995
13107
  const startPage = cursor?.raw.page ?? 0;
12996
13108
  const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
@@ -13061,11 +13173,13 @@ async function runOnce(ctx, cursor) {
13061
13173
  if (signal.aborted) throw abortError2();
13062
13174
  const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13063
13175
  stats.bytes += bytes.length;
13064
- const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
13176
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
13065
13177
  if (pageNo < head.completePages && !page2.complete) {
13066
13178
  throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13067
13179
  }
13068
13180
  stats.pages++;
13181
+ stats.skipped += page2.skippedMalformed;
13182
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
13069
13183
  waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13070
13184
  advanceChain();
13071
13185
  const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
@@ -13086,7 +13200,7 @@ async function runOnce(ctx, cursor) {
13086
13200
  else data.leaves.set(mint, [entry]);
13087
13201
  };
13088
13202
  page2.items.forEach((item, i) => {
13089
- const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
13203
+ const seq = seqOf(i);
13090
13204
  if (item.kind === 1) {
13091
13205
  addLeaf(item.mint, item.comm0, item.leaf0, seq);
13092
13206
  addLeaf(item.mint, item.comm1, item.leaf1, seq);
@@ -13103,7 +13217,7 @@ async function runOnce(ctx, cursor) {
13103
13217
  for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
13104
13218
  if (signal.aborted) throw abortError2();
13105
13219
  const batch = page2.items.slice(i, i + ITEM_BATCH);
13106
- const opened = await Promise.all(batch.map((item) => trialItem(item, trial)));
13220
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
13107
13221
  opened.forEach((o, k) => {
13108
13222
  if (!o) return;
13109
13223
  stats.decrypted++;
@@ -13113,7 +13227,7 @@ async function runOnce(ctx, cursor) {
13113
13227
  stats.dropped++;
13114
13228
  return;
13115
13229
  }
13116
- ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o });
13230
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
13117
13231
  });
13118
13232
  stats.items += batch.length;
13119
13233
  }
@@ -13146,10 +13260,10 @@ async function runOnce(ctx, cursor) {
13146
13260
  throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
13147
13261
  }
13148
13262
  for (const entry of cursor?.items ?? []) {
13149
- const o = await trialItem(entry.item, trial);
13263
+ const o = await trialItemIsolated(entry.item, trials, stats);
13150
13264
  if (!o) continue;
13151
13265
  const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
13152
- ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o });
13266
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
13153
13267
  if (entry.item.kind === 1) {
13154
13268
  if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
13155
13269
  if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
@@ -13158,10 +13272,20 @@ async function runOnce(ctx, cursor) {
13158
13272
  const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
13159
13273
  ownItems.sort((a, b) => a.seq - b.seq);
13160
13274
  const rejectedNow = /* @__PURE__ */ new Set();
13161
- const allCandidates = await matchOwnItems(ownItems, trial, (o) => {
13162
- stats.dropped++;
13163
- rejectedNow.add(o.id);
13164
- });
13275
+ const skippedNow = /* @__PURE__ */ new Set();
13276
+ const allCandidates = await matchOwnItems(
13277
+ ownItems,
13278
+ owner,
13279
+ (o) => {
13280
+ stats.dropped++;
13281
+ rejectedNow.add(o.id);
13282
+ },
13283
+ (o) => {
13284
+ if (skippedNow.has(o)) return;
13285
+ skippedNow.add(o);
13286
+ stats.skipped++;
13287
+ }
13288
+ );
13165
13289
  stats.candidates = allCandidates.length;
13166
13290
  const cutoff = params.legacyCutoffLeaf ?? {};
13167
13291
  const candidates = allCandidates.filter((c) => {
@@ -14608,7 +14732,7 @@ async function withShieldRetries(attempt, hooks = {}) {
14608
14732
  }
14609
14733
 
14610
14734
  // src/index.ts
14611
- var VERSION = "0.2.6";
14735
+ var VERSION = "0.2.7";
14612
14736
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
14613
14737
  export {
14614
14738
  AccountRole,
@@ -14844,6 +14968,7 @@ export {
14844
14968
  isTerminalFailure,
14845
14969
  isTransactionSigner,
14846
14970
  isValidHex,
14971
+ isValidRelayClientId,
14847
14972
  isValidRpcUrl,
14848
14973
  isValidSolanaAddress,
14849
14974
  isWithdrawAmountSufficient,
@@ -14857,6 +14982,7 @@ export {
14857
14982
  matchSwapRefundLeaf,
14858
14983
  mayRetry,
14859
14984
  messageSignerFromCallback,
14985
+ normalizeAffiliateCode,
14860
14986
  openRecipientDeliveryNote,
14861
14987
  parseAmount,
14862
14988
  parseDeliveryCarrierMemo,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cloak.dev/sdk",
3
3
  "description": "Shield, send, and swap on Solana privately — TypeScript SDK with UTXO-based zero-knowledge transactions",
4
- "version": "0.2.6-staging.f92dd96",
4
+ "version": "0.2.7",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",