@cloak.dev/sdk 0.2.7 → 0.2.8

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/CHANGELOG.md CHANGED
@@ -5,6 +5,30 @@ All notable changes to `@cloak.dev/sdk` are documented here. The format follows
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Releases before 0.2.6 are described in
6
6
  the README's "Version and compatibility" section and in the git history.
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [0.2.8]
11
+
12
+ ### Added
13
+
14
+ * Per-request receive keys, so two request links from one wallet share no key. `deriveRequestKeyRoot`,
15
+ `deriveRequestKeys` and `deriveRequestKeyRange` derive a fresh UTXO keypair and X25519 viewing
16
+ keypair per request counter from a root. The default root derives from `nk`, so compliance keeps
17
+ visibility of a wallet's requests while nothing public links two links to one requester;
18
+ `REQUEST_KEY_ROOT_SOURCE` can switch it to a spend-key ("seed") root the relay cannot recompute. `recoverNotesFromIndex` takes
19
+ `requestKeys` (at most `MAX_REQUEST_KEYS` = 64) and returns notes paid to them with
20
+ `requestIndex` set; a restore derives `REQUEST_KEY_GAP_LIMIT` (20) counters past the last known
21
+ one. `sweepToWalletKey` moves up to two such notes under the wallet key (one extra transaction);
22
+ `transfer` already did this implicitly, and withdrawals need no sweep.
23
+
24
+ ### Changed
25
+
26
+ * `engines.node` is now `>=22.0.0` (was `>=18.0.0`). Node 18 and 20 are end-of-life and received
27
+ no fix in the October 2026 Node security release (Brotli out-of-bounds write in `node:zlib`,
28
+ TLS identity bypasses); use Node 22.23.4 / 24.22.1 or later. npm only warns on an engines
29
+ mismatch unless `engine-strict` is set; no code changed.
30
+ * The publish pipeline builds and publishes on Node 24 (was 20).
31
+
8
32
  ## [0.2.7]
9
33
 
10
34
  Pairs with the same mainnet program (`zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`) and the same
package/README.md CHANGED
@@ -5,13 +5,13 @@ per-mint pool, send privately inside the pool, withdraw to any address, or swap
5
5
  USDC/USDT with the output landing in a public token account. Groth16 proofs are generated
6
6
  client-side (snarkjs) and verified on-chain by the Cloak program.
7
7
 
8
- Version 0.2.7 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
8
+ Version 0.2.8 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
9
9
  `cloak-transaction-0.2.0` circuit bundle. See [Version and compatibility](#version-and-compatibility).
10
10
 
11
11
  ## Installation
12
12
 
13
13
  ```bash
14
- npm install @cloak.dev/sdk@^0.2.7
14
+ npm install @cloak.dev/sdk@^0.2.8
15
15
  ```
16
16
 
17
17
  The SDK is built on [`@solana/kit`](https://github.com/anza-xyz/kit) and re-exports the pieces an
@@ -21,7 +21,7 @@ pools and swaps uses `@solana-program/token`, which the SDK depends on; import
21
21
  `findAssociatedTokenPda` from it directly. Coming from 0.2.4 or earlier (web3.js): see
22
22
  [Migrating from @solana/web3.js](#migrating-from-solanaweb3js).
23
23
 
24
- Node >= 18. Ships ESM and CJS builds with type declarations. Runs in Node and in the browser
24
+ Node >= 22. Ships ESM and CJS builds with type declarations. Runs in Node and in the browser
25
25
  (wallet signing); the on-chain Merkle-tree rebuild fallback is not available in browsers.
26
26
 
27
27
  ## Networks
@@ -790,7 +790,7 @@ relay endpoint and the localhost-RPC check.
790
790
 
791
791
  ## Version and compatibility
792
792
 
793
- - SDK 0.2.7 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
793
+ - SDK 0.2.8 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
794
794
  (deployed 2026-08-24) and the 0.2.0 circuit bundle — the program and circuit bundle are unchanged
795
795
  since 0.2.0; only the SDK package version has moved. The 0.2.5 flows were exercised on mainnet on
796
796
  2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to USDC and USDT;
@@ -813,6 +813,8 @@ relay endpoint and the localhost-RPC check.
813
813
  - 0.2.7 changes no wire format, hash or public signature. Scan results label BRS notes as `BRS`,
814
814
  and Cloak's own apps get stricter handling of the internal partner code (see
815
815
  [CHANGELOG.md](CHANGELOG.md)).
816
+ - 0.2.8 adds per-request receive keys for request links (`deriveRequestKeys`, `recoverNotesFromIndex({ requestKeys })`, `sweepToWalletKey`) and changes no wire format, hash or existing signature (see
817
+ [CHANGELOG.md](CHANGELOG.md)).
816
818
  - Proofs generated with the 0.1.x circuits are rejected by the mainnet program. SDK 0.1.x builds
817
819
  (which ship the 0.1.0 bundle) are not usable against it; upgrade to 0.2.x.
818
820
  - The note-based `CloakSDK` class is removed in 0.2.0. It targeted the pre-0.2.0 instruction layout
package/dist/index.cjs CHANGED
@@ -600,6 +600,7 @@ __export(index_exports, {
600
600
  MAINNET_RENT_0: () => MAINNET_RENT_0,
601
601
  MAINNET_RENT_1: () => MAINNET_RENT_1,
602
602
  MAX_RECEIVER_INDEX: () => MAX_RECEIVER_INDEX,
603
+ MAX_REQUEST_KEYS: () => MAX_REQUEST_KEYS,
603
604
  MERKLE_TREE_HEIGHT: () => MERKLE_TREE_HEIGHT2,
604
605
  MIN_DEPOSIT_LAMPORTS: () => MIN_DEPOSIT_LAMPORTS,
605
606
  MIN_DEPOSIT_SPL_BASE_UNITS: () => MIN_DEPOSIT_SPL_BASE_UNITS,
@@ -623,6 +624,8 @@ __export(index_exports, {
623
624
  REQUEST_AUTH_BATCH_MAX_AGE_SECONDS: () => REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
624
625
  REQUEST_AUTH_MAX_AGE_SECONDS: () => REQUEST_AUTH_MAX_AGE_SECONDS,
625
626
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS: () => REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
627
+ REQUEST_KEY_GAP_LIMIT: () => REQUEST_KEY_GAP_LIMIT,
628
+ REQUEST_KEY_ROOT_SOURCE: () => REQUEST_KEY_ROOT_SOURCE,
626
629
  RelayBatchAuthCoordinator: () => RelayBatchAuthCoordinator,
627
630
  RelayInternalError: () => RelayInternalError,
628
631
  RelayService: () => RelayService,
@@ -720,6 +723,9 @@ __export(index_exports, {
720
723
  deriveLegacyDepositNoteSecrets: () => deriveLegacyDepositNoteSecrets,
721
724
  deriveLegacySwapRefundAuthorization: () => deriveLegacySwapRefundAuthorization,
722
725
  derivePublicKey: () => derivePublicKey,
726
+ deriveRequestKeyRange: () => deriveRequestKeyRange,
727
+ deriveRequestKeyRoot: () => deriveRequestKeyRoot,
728
+ deriveRequestKeys: () => deriveRequestKeys,
723
729
  deriveSpendKey: () => deriveSpendKey,
724
730
  deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
725
731
  deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
@@ -886,6 +892,7 @@ __export(index_exports, {
886
892
  sumUtxoAmounts: () => sumUtxoAmounts,
887
893
  swapUtxo: () => swapUtxo,
888
894
  swapWithChange: () => swapWithChange,
895
+ sweepToWalletKey: () => sweepToWalletKey,
889
896
  toAddress: () => toAddress,
890
897
  toComplianceReport: () => toComplianceReport,
891
898
  transact: () => transact,
@@ -10042,20 +10049,10 @@ async function transfer(inputUtxos, recipientPubkey, amount, rawOptions) {
10042
10049
  );
10043
10050
  }
10044
10051
  options.onProgress?.("Moving notes under the wallet key before the transfer...");
10045
- const migrationSalt = randomChangeNoteSalt();
10046
- const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
10047
- const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
10048
- void _recipientViewingPublicKey;
10049
- const migration = await transact(
10050
- { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
10051
- { ...migrationOptions, chainNoteSalt: migrationSalt }
10052
- );
10053
- const migratedNote = migration.outputUtxos?.[0] ?? migrated;
10054
- if (migration.commitmentIndices?.[0] >= 0) {
10055
- migratedNote.index = migration.commitmentIndices[0];
10056
- }
10052
+ const migration = await sweepToWalletKey(spendInputs, options);
10053
+ const migratedNote = migration.note;
10057
10054
  spendInputs = [migratedNote];
10058
- spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
10055
+ spendOptions = { ...options, cachedMerkleTree: migration.result.merkleTree };
10059
10056
  }
10060
10057
  const changeNoteSalt = randomChangeNoteSalt();
10061
10058
  const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
@@ -10087,6 +10084,27 @@ async function transfer(inputUtxos, recipientPubkey, amount, rawOptions) {
10087
10084
  { ...spendOptions, chainNoteSalt: changeNoteSalt }
10088
10085
  );
10089
10086
  }
10087
+ async function sweepToWalletKey(inputUtxos, rawOptions) {
10088
+ if (inputUtxos.length === 0 || inputUtxos.length > 2) {
10089
+ throw new Error("sweepToWalletKey: one transaction moves 1 or 2 notes");
10090
+ }
10091
+ assertInputMints(inputUtxos, rawOptions.expectedMint);
10092
+ const options = prepareAffiliateAndClient(rawOptions);
10093
+ const owner = await requireOwnerUtxoKeypair(options, "sweepToWalletKey");
10094
+ const walletNk = await requireWalletNk(options, "sweepToWalletKey");
10095
+ const mint = inputUtxos[0].mintAddress;
10096
+ const salt = randomChangeNoteSalt();
10097
+ const migrated = (await createRecoverableChangeUtxo(sumUtxoAmounts(inputUtxos), owner, walletNk, mint, salt, 0)).utxo;
10098
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...sweepOptions } = options;
10099
+ void _recipientViewingPublicKey;
10100
+ const result = await transact(
10101
+ { inputUtxos, outputUtxos: [migrated], externalAmount: BigInt(0) },
10102
+ { ...sweepOptions, chainNoteSalt: salt }
10103
+ );
10104
+ const note = result.outputUtxos?.[0] ?? migrated;
10105
+ if (result.commitmentIndices?.[0] >= 0) note.index = result.commitmentIndices[0];
10106
+ return { note, result };
10107
+ }
10090
10108
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, rawOptions) {
10091
10109
  const options = prepareAffiliateAndClient(rawOptions);
10092
10110
  const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
@@ -13329,6 +13347,69 @@ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
13329
13347
  });
13330
13348
  }
13331
13349
 
13350
+ // src/notes/request-keys.ts
13351
+ var import_blake37 = require("@noble/hashes/blake3");
13352
+ var import_tweetnacl6 = __toESM(require("tweetnacl"), 1);
13353
+ init_utxo();
13354
+ var BN254_ORDER = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
13355
+ var ROOT_SEED_DOMAIN = new TextEncoder().encode("cloak_request_root_v1");
13356
+ var ROOT_NK_DOMAIN = new TextEncoder().encode("cloak_request_root_nk_v1");
13357
+ var UTXO_DOMAIN = new TextEncoder().encode("cloak_request_utxo_v1");
13358
+ var VIEWING_DOMAIN = new TextEncoder().encode("cloak_request_vk_v1");
13359
+ var REQUEST_KEY_ROOT_SOURCE = "nk";
13360
+ var REQUEST_KEY_GAP_LIMIT = 20;
13361
+ var MAX_REQUEST_KEYS = 64;
13362
+ function check32(value, label) {
13363
+ if (!(value instanceof Uint8Array) || value.length !== 32) throw new Error(`${label} must be 32 bytes`);
13364
+ return value;
13365
+ }
13366
+ function counterBytes(counter) {
13367
+ if (!Number.isInteger(counter) || counter < 0 || counter > 4294967295) throw new Error("request counter must be a u32");
13368
+ const out = new Uint8Array(4);
13369
+ new DataView(out.buffer).setUint32(0, counter, false);
13370
+ return out;
13371
+ }
13372
+ function hashWith(domain, root, counter) {
13373
+ const c = counterBytes(counter);
13374
+ const pre = new Uint8Array(domain.length + root.length + c.length);
13375
+ pre.set(domain, 0);
13376
+ pre.set(root, domain.length);
13377
+ pre.set(c, domain.length + root.length);
13378
+ return (0, import_blake37.blake3)(pre);
13379
+ }
13380
+ function deriveRequestKeyRoot(input, source = REQUEST_KEY_ROOT_SOURCE) {
13381
+ const secret = source === "seed" ? check32(input.skSpend, "skSpend") : check32(input.nk, "nk");
13382
+ const domain = source === "seed" ? ROOT_SEED_DOMAIN : ROOT_NK_DOMAIN;
13383
+ const pre = new Uint8Array(domain.length + 32);
13384
+ pre.set(domain, 0);
13385
+ pre.set(secret, domain.length);
13386
+ return (0, import_blake37.blake3)(pre);
13387
+ }
13388
+ async function deriveRequestKeys(root, counter) {
13389
+ check32(root, "request root");
13390
+ const h = hashWith(UTXO_DOMAIN, root, counter);
13391
+ let value = 0n;
13392
+ for (let i = 0; i < 32; i++) value = value << 8n | BigInt(h[i]);
13393
+ const privateKey = value % (BN254_ORDER >> 4n);
13394
+ if (privateKey === 0n) throw new Error("request key derivation produced a zero key");
13395
+ const publicKey = await derivePublicKey(privateKey);
13396
+ const vk = hashWith(VIEWING_DOMAIN, root, counter);
13397
+ vk[0] &= 248;
13398
+ vk[31] &= 127;
13399
+ vk[31] |= 64;
13400
+ return {
13401
+ counter,
13402
+ utxoKeypair: { privateKey, publicKey },
13403
+ viewingKeypair: { privateKey: vk, publicKey: import_tweetnacl6.default.scalarMult.base(vk) }
13404
+ };
13405
+ }
13406
+ async function deriveRequestKeyRange(root, from, count) {
13407
+ if (!Number.isInteger(count) || count < 0 || count > MAX_REQUEST_KEYS) throw new Error(`count must be in 0..${MAX_REQUEST_KEYS}`);
13408
+ const out = [];
13409
+ for (let i = 0; i < count; i++) out.push(await deriveRequestKeys(root, from + i));
13410
+ return out;
13411
+ }
13412
+
13332
13413
  // src/scanning/note-index.ts
13333
13414
  var import_bs584 = __toESM(require("bs58"), 1);
13334
13415
  var import_sha26 = require("@noble/hashes/sha2");
@@ -13440,6 +13521,7 @@ var LeafBuffer = class {
13440
13521
  async function trialItem(item, trials) {
13441
13522
  for (const trial of trials) {
13442
13523
  if (trial.legacy && item.kind === 2) continue;
13524
+ if (trial.requestIndex !== void 0 && item.kind !== 2) continue;
13443
13525
  const opened = await trialItemWith(item, trial);
13444
13526
  if (opened) return { ...opened, trial };
13445
13527
  }
@@ -13519,7 +13601,7 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
13519
13601
  const nullifier = hex32(
13520
13602
  await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
13521
13603
  );
13522
- const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
13604
+ const full = { ...c, requestIndex: o.trial.requestIndex, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
13523
13605
  candidates.push(full);
13524
13606
  if (!byNullifier.has(nullifier)) {
13525
13607
  byNullifier.set(nullifier, full);
@@ -13597,9 +13679,10 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
13597
13679
  onReject(o);
13598
13680
  return;
13599
13681
  }
13682
+ const deliveryOwner = o.trial.requestIndex !== void 0 ? o.trial.owner : owner;
13600
13683
  const commitment = await computeCommitment2({
13601
13684
  amount: o.delivery.amount,
13602
- keypair: { privateKey: 0n, publicKey: owner.publicKey },
13685
+ keypair: { privateKey: 0n, publicKey: deliveryOwner.publicKey },
13603
13686
  blinding: o.delivery.blinding,
13604
13687
  mintAddress: mint
13605
13688
  });
@@ -13612,7 +13695,7 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
13612
13695
  atRisk: false,
13613
13696
  amount: o.delivery.amount,
13614
13697
  blinding: o.delivery.blinding,
13615
- keypair: owner,
13698
+ keypair: deliveryOwner,
13616
13699
  mint,
13617
13700
  commitment,
13618
13701
  leaf: Number(item.leaf)
@@ -13966,6 +14049,24 @@ async function recoverNotesFromIndex(params) {
13966
14049
  seenNks.add(key);
13967
14050
  trials.push(await makeTrial(Uint8Array.from(nk), true));
13968
14051
  }
14052
+ const requestKeys = params.requestKeys ?? [];
14053
+ if (!Array.isArray(requestKeys)) throw new Error("requestKeys must be an array");
14054
+ if (requestKeys.length > MAX_REQUEST_KEYS) throw new Error(`requestKeys takes at most ${MAX_REQUEST_KEYS} keys`);
14055
+ const seenRequestIdx = /* @__PURE__ */ new Set();
14056
+ for (const rk of requestKeys) {
14057
+ if (!Number.isInteger(rk.index) || rk.index < 0 || seenRequestIdx.has(rk.index)) throw new Error("requestKeys entries need distinct non-negative integer indexes");
14058
+ seenRequestIdx.add(rk.index);
14059
+ if (!(rk.viewingSecretKey instanceof Uint8Array) || rk.viewingSecretKey.length !== 32) throw new Error("requestKeys viewingSecretKey must be 32 bytes");
14060
+ const ownerKp = await assertOwnerUtxoKeypair(rk.ownerKeypair, "requestKeys.ownerKeypair");
14061
+ trials.push({
14062
+ nk: new Uint8Array(32),
14063
+ legacy: false,
14064
+ owner: ownerKp,
14065
+ requestIndex: rk.index,
14066
+ decrypt: async () => null,
14067
+ open: await createRecipientDeliveryOpener(rk.viewingSecretKey)
14068
+ });
14069
+ }
13969
14070
  const poolMints = Array.from(new Set(params.poolMints));
13970
14071
  const warnings = [];
13971
14072
  const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
@@ -14002,6 +14103,7 @@ async function recoverNotesFromIndex(params) {
14002
14103
  }
14003
14104
  async function runOnce(ctx, cursor) {
14004
14105
  const { params, head, trials, owner, stats, poolMints } = ctx;
14106
+ const requestOwners = new Set(trials.filter((t) => t.requestIndex !== void 0).map((t) => t.owner.publicKey));
14005
14107
  const { relayUrl, onProgress } = params;
14006
14108
  const poolSet = new Set(poolMints);
14007
14109
  const startPage = cursor?.raw.page ?? 0;
@@ -14289,7 +14391,8 @@ async function runOnce(ctx, cursor) {
14289
14391
  for (const c of byLeaf.values()) {
14290
14392
  const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
14291
14393
  keyChecked.set(c.keypair.privateKey, pubOk);
14292
- if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
14394
+ const ownerOk = c.requestIndex !== void 0 ? requestOwners.has(c.keypair.publicKey) : c.keypair.publicKey === owner.publicKey;
14395
+ if (!pubOk || !c.atRisk && !ownerOk) {
14293
14396
  stats.dropped++;
14294
14397
  tally(c, "rejected");
14295
14398
  continue;
@@ -14298,7 +14401,7 @@ async function runOnce(ctx, cursor) {
14298
14401
  verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
14299
14402
  const utxo = {
14300
14403
  amount: c.amount,
14301
- keypair: c.atRisk ? { ...c.keypair } : owner,
14404
+ keypair: c.atRisk ? { ...c.keypair } : c.requestIndex !== void 0 ? c.keypair : owner,
14302
14405
  blinding: c.blinding,
14303
14406
  mintAddress: c.mint,
14304
14407
  index: c.leaf,
@@ -14313,7 +14416,8 @@ async function runOnce(ctx, cursor) {
14313
14416
  kind: c.kind,
14314
14417
  utxo,
14315
14418
  signature: bs584.encode(c.signature),
14316
- legacyExposed: c.atRisk
14419
+ legacyExposed: c.atRisk,
14420
+ ...c.requestIndex !== void 0 ? { requestIndex: c.requestIndex } : {}
14317
14421
  };
14318
14422
  (c.atRisk ? atRisk : notes).push(note);
14319
14423
  }
@@ -14758,7 +14862,7 @@ async function loadWeb3() {
14758
14862
  }
14759
14863
 
14760
14864
  // src/bridge/rail-verify.ts
14761
- var import_tweetnacl6 = __toESM(require("tweetnacl"), 1);
14865
+ var import_tweetnacl7 = __toESM(require("tweetnacl"), 1);
14762
14866
  var import_sha256 = require("@noble/hashes/sha256");
14763
14867
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
14764
14868
  var b58 = /* @__PURE__ */ (() => {
@@ -14869,7 +14973,7 @@ function verifyQuoteSignature(resp) {
14869
14973
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
14870
14974
  const sig = resp.signature.replace(/^ed25519:/, "");
14871
14975
  try {
14872
- return { valid: import_tweetnacl6.default.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
14976
+ return { valid: import_tweetnacl7.default.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
14873
14977
  } catch (e) {
14874
14978
  return { valid: false, reason: e instanceof Error ? e.message : String(e) };
14875
14979
  }
@@ -15098,7 +15202,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
15098
15202
  // src/bridge/derive.ts
15099
15203
  var import_hmac = require("@noble/hashes/hmac");
15100
15204
  var import_sha512 = require("@noble/hashes/sha512");
15101
- var import_blake37 = require("@noble/hashes/blake3");
15205
+ var import_blake38 = require("@noble/hashes/blake3");
15102
15206
  init_utxo();
15103
15207
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
15104
15208
  var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
@@ -15126,7 +15230,7 @@ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
15126
15230
  const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
15127
15231
  preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
15128
15232
  preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
15129
- const key = (0, import_blake37.blake3)(preimage);
15233
+ const key = (0, import_blake38.blake3)(preimage);
15130
15234
  const h = (0, import_hmac.hmac)(import_sha512.sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
15131
15235
  return signerFromSecretKey(h.slice(0, 32));
15132
15236
  }
@@ -15630,7 +15734,7 @@ async function withShieldRetries(attempt, hooks = {}) {
15630
15734
  }
15631
15735
 
15632
15736
  // src/index.ts
15633
- var VERSION = "0.2.7";
15737
+ var VERSION = "0.2.8";
15634
15738
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15635
15739
  // Annotate the CommonJS export names for ESM import in node:
15636
15740
  0 && (module.exports = {
@@ -15659,6 +15763,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15659
15763
  MAINNET_RENT_0,
15660
15764
  MAINNET_RENT_1,
15661
15765
  MAX_RECEIVER_INDEX,
15766
+ MAX_REQUEST_KEYS,
15662
15767
  MERKLE_TREE_HEIGHT,
15663
15768
  MIN_DEPOSIT_LAMPORTS,
15664
15769
  MIN_DEPOSIT_SPL_BASE_UNITS,
@@ -15682,6 +15787,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15682
15787
  REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
15683
15788
  REQUEST_AUTH_MAX_AGE_SECONDS,
15684
15789
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
15790
+ REQUEST_KEY_GAP_LIMIT,
15791
+ REQUEST_KEY_ROOT_SOURCE,
15685
15792
  RelayBatchAuthCoordinator,
15686
15793
  RelayInternalError,
15687
15794
  RelayService,
@@ -15779,6 +15886,9 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15779
15886
  deriveLegacyDepositNoteSecrets,
15780
15887
  deriveLegacySwapRefundAuthorization,
15781
15888
  derivePublicKey,
15889
+ deriveRequestKeyRange,
15890
+ deriveRequestKeyRoot,
15891
+ deriveRequestKeys,
15782
15892
  deriveSpendKey,
15783
15893
  deriveSwapRefundAuthorization,
15784
15894
  deriveSwapRefundBlinding,
@@ -15945,6 +16055,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
15945
16055
  sumUtxoAmounts,
15946
16056
  swapUtxo,
15947
16057
  swapWithChange,
16058
+ sweepToWalletKey,
15948
16059
  toAddress,
15949
16060
  toComplianceReport,
15950
16061
  transact,
package/dist/index.d.cts CHANGED
@@ -3834,6 +3834,20 @@ declare function transact(params: TransactParams, rawOptions: TransactOptions):
3834
3834
  * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3835
3835
  */
3836
3836
  declare function transfer(inputUtxos: Utxo[], recipientPubkey: bigint, amount: bigint, rawOptions: SpendOptions): Promise<TransactResult>;
3837
+ type SweepResult = {
3838
+ note: Utxo;
3839
+ result: TransactResult;
3840
+ };
3841
+ /**
3842
+ * Move up to two notes owned by other keys (a per-request receive key, or a pre-0.2.6 legacy key)
3843
+ * under the wallet's long-lived key with ONE self-spend: one extra transaction and one extra relay
3844
+ * request signature. `transfer` does this on its own when no input is wallet-owned; call it
3845
+ * directly to sweep received request notes in the background. `partialWithdraw`/`fullWithdraw` need
3846
+ * no sweep (their change is output 0, which the circuit leaves free).
3847
+ *
3848
+ * The sweep must not carry a recipient delivery, so `recipientViewingPublicKey` is dropped.
3849
+ */
3850
+ declare function sweepToWalletKey(inputUtxos: Utxo[], rawOptions: SpendOptions): Promise<SweepResult>;
3837
3851
  /**
3838
3852
  * Execute a partial withdrawal
3839
3853
  *
@@ -5342,6 +5356,59 @@ declare function encodeNoteIndexItem(item: NoteIndexItem): Uint8Array;
5342
5356
  */
5343
5357
  declare function encodeNoteIndexPage(params: EncodeNoteIndexPageParams): Uint8Array;
5344
5358
 
5359
+ /**
5360
+ * Per-request receive keys.
5361
+ *
5362
+ * A request link names who should be paid. If every link carried the wallet's long-lived UTXO key
5363
+ * and viewing key, two payers (or anyone who sees two links) could tell they came from one
5364
+ * requester. So each request gets its own UTXO keypair and its own X25519 viewing keypair:
5365
+ *
5366
+ * root = BLAKE3("cloak_request_root_nk_v1" || nk) (default, "nk")
5367
+ * | BLAKE3("cloak_request_root_v1" || skSpend) ("seed")
5368
+ * utxo priv = BLAKE3("cloak_request_utxo_v1" || root || counter_be32) mod (r >> 4)
5369
+ * view sk = clamp(BLAKE3("cloak_request_vk_v1" || root || counter_be32))
5370
+ *
5371
+ * Deterministic, so a restore from the seed re-derives counters 0..N and scans for them.
5372
+ *
5373
+ * ── Which root ─────────────────────────────────────────────────────────────────────────────────
5374
+ * The default root derives from `nk`, the viewing base the wallet registers with the relay for
5375
+ * compliance. So Cloak's compliance tooling can still see which requests belong to a wallet, while
5376
+ * nothing public links two request links to one requester: each link carries its own keys and the
5377
+ * public never sees nk. The "seed" root derives from the spend key instead and never reaches the
5378
+ * relay, so even the relay cannot link requests to a wallet. Both are implemented and tested;
5379
+ * {@link REQUEST_KEY_ROOT_SOURCE} is the one switch, and callers that pass no source get it.
5380
+ */
5381
+
5382
+ type RequestKeyRootSource = "seed" | "nk";
5383
+ /** The root the SDK derives request keys from when the caller does not choose. */
5384
+ declare const REQUEST_KEY_ROOT_SOURCE: RequestKeyRootSource;
5385
+ /** HD-style gap limit a restore derives and scans past the last counter it knows of. */
5386
+ declare const REQUEST_KEY_GAP_LIMIT = 20;
5387
+ /** Most request keys one scan trials (each costs one trial open per recipient-delivery item). */
5388
+ declare const MAX_REQUEST_KEYS = 64;
5389
+ interface RequestKeys {
5390
+ counter: number;
5391
+ /** Owner of notes paid to this request. Real private key. */
5392
+ utxoKeypair: UtxoKeypair;
5393
+ /** X25519 pair the delivery envelope is sealed to. */
5394
+ viewingKeypair: {
5395
+ privateKey: Uint8Array;
5396
+ publicKey: Uint8Array;
5397
+ };
5398
+ }
5399
+ /**
5400
+ * The 32-byte request root. `skSpend` is the wallet's spend key (seed root); `nk` is the registered
5401
+ * viewing base (nk root). Only the field the chosen source needs is read.
5402
+ */
5403
+ declare function deriveRequestKeyRoot(input: {
5404
+ skSpend?: Uint8Array;
5405
+ nk?: Uint8Array;
5406
+ }, source?: RequestKeyRootSource): Uint8Array;
5407
+ /** The keys for request `counter`. */
5408
+ declare function deriveRequestKeys(root: Uint8Array, counter: number): Promise<RequestKeys>;
5409
+ /** Keys for counters `[from, from + count)`, at most {@link MAX_REQUEST_KEYS}. */
5410
+ declare function deriveRequestKeyRange(root: Uint8Array, from: number, count: number): Promise<RequestKeys[]>;
5411
+
5345
5412
  /**
5346
5413
  * Restore a wallet's notes from the relay's Note Index v1 (contract revision 2.1), without walking
5347
5414
  * the chain and without telling anyone which notes, pools or nullifiers are its own.
@@ -5445,6 +5512,12 @@ interface IndexedRecoveredNote {
5445
5512
  * key), `false` for `notes`.
5446
5513
  */
5447
5514
  legacyExposed: boolean;
5515
+ /**
5516
+ * Set when the note was paid to a per-request key ({@link RecoverNotesFromIndexParams.requestKeys}):
5517
+ * that entry's `index`. `utxo.keypair` is then the request's keypair, not the wallet's, so the
5518
+ * note is spent by sweeping it into the wallet key first.
5519
+ */
5520
+ requestIndex?: number;
5448
5521
  }
5449
5522
  /**
5450
5523
  * The persisted resume point. JSON-serializable and holds NO key material, but `own` records which
@@ -5519,6 +5592,18 @@ interface RecoverNotesFromIndexParams {
5519
5592
  legacyViewingKeyNks?: Uint8Array[];
5520
5593
  /** The wallet's long-lived UTXO keypair, with its real private key. */
5521
5594
  ownerUtxoKeypair: UtxoKeypair;
5595
+ /**
5596
+ * Per-request receive keys (see `notes/request-keys.ts`), at most {@link MAX_REQUEST_KEYS}. Only
5597
+ * recipient-delivery items are trialed against them, so each costs one extra open per delivery
5598
+ * item and no extra request. Notes found through one come back in `notes` with `requestIndex`
5599
+ * set. A cursor from a run with fewer keys has already covered earlier pages without them: when
5600
+ * a restore adds keys, drop the cursor.
5601
+ */
5602
+ requestKeys?: Array<{
5603
+ index: number;
5604
+ viewingSecretKey: Uint8Array;
5605
+ ownerKeypair: UtxoKeypair;
5606
+ }>;
5522
5607
  /** The `cursor` of the previous run. Omit for a full sync. */
5523
5608
  cursor?: NoteIndexCursor;
5524
5609
  /** Per mint: ignore legacy-shaped (nk-owned) notes at or after this leaf (a release cutoff). */
@@ -6462,8 +6547,8 @@ declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>
6462
6547
  * @packageDocumentation
6463
6548
  */
6464
6549
 
6465
- declare const VERSION = "0.2.7";
6550
+ declare const VERSION = "0.2.8";
6466
6551
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
6467
6552
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
6468
6553
 
6469
- export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRelayClientId, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, normalizeAffiliateCode, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
6554
+ export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MAX_REQUEST_KEYS, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, REQUEST_KEY_GAP_LIMIT, REQUEST_KEY_ROOT_SOURCE, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RequestKeyRootSource, type RequestKeys, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, type SweepResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveRequestKeyRange, deriveRequestKeyRoot, deriveRequestKeys, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRelayClientId, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, normalizeAffiliateCode, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, sweepToWalletKey, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
package/dist/index.d.ts CHANGED
@@ -3834,6 +3834,20 @@ declare function transact(params: TransactParams, rawOptions: TransactOptions):
3834
3834
  * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3835
3835
  */
3836
3836
  declare function transfer(inputUtxos: Utxo[], recipientPubkey: bigint, amount: bigint, rawOptions: SpendOptions): Promise<TransactResult>;
3837
+ type SweepResult = {
3838
+ note: Utxo;
3839
+ result: TransactResult;
3840
+ };
3841
+ /**
3842
+ * Move up to two notes owned by other keys (a per-request receive key, or a pre-0.2.6 legacy key)
3843
+ * under the wallet's long-lived key with ONE self-spend: one extra transaction and one extra relay
3844
+ * request signature. `transfer` does this on its own when no input is wallet-owned; call it
3845
+ * directly to sweep received request notes in the background. `partialWithdraw`/`fullWithdraw` need
3846
+ * no sweep (their change is output 0, which the circuit leaves free).
3847
+ *
3848
+ * The sweep must not carry a recipient delivery, so `recipientViewingPublicKey` is dropped.
3849
+ */
3850
+ declare function sweepToWalletKey(inputUtxos: Utxo[], rawOptions: SpendOptions): Promise<SweepResult>;
3837
3851
  /**
3838
3852
  * Execute a partial withdrawal
3839
3853
  *
@@ -5342,6 +5356,59 @@ declare function encodeNoteIndexItem(item: NoteIndexItem): Uint8Array;
5342
5356
  */
5343
5357
  declare function encodeNoteIndexPage(params: EncodeNoteIndexPageParams): Uint8Array;
5344
5358
 
5359
+ /**
5360
+ * Per-request receive keys.
5361
+ *
5362
+ * A request link names who should be paid. If every link carried the wallet's long-lived UTXO key
5363
+ * and viewing key, two payers (or anyone who sees two links) could tell they came from one
5364
+ * requester. So each request gets its own UTXO keypair and its own X25519 viewing keypair:
5365
+ *
5366
+ * root = BLAKE3("cloak_request_root_nk_v1" || nk) (default, "nk")
5367
+ * | BLAKE3("cloak_request_root_v1" || skSpend) ("seed")
5368
+ * utxo priv = BLAKE3("cloak_request_utxo_v1" || root || counter_be32) mod (r >> 4)
5369
+ * view sk = clamp(BLAKE3("cloak_request_vk_v1" || root || counter_be32))
5370
+ *
5371
+ * Deterministic, so a restore from the seed re-derives counters 0..N and scans for them.
5372
+ *
5373
+ * ── Which root ─────────────────────────────────────────────────────────────────────────────────
5374
+ * The default root derives from `nk`, the viewing base the wallet registers with the relay for
5375
+ * compliance. So Cloak's compliance tooling can still see which requests belong to a wallet, while
5376
+ * nothing public links two request links to one requester: each link carries its own keys and the
5377
+ * public never sees nk. The "seed" root derives from the spend key instead and never reaches the
5378
+ * relay, so even the relay cannot link requests to a wallet. Both are implemented and tested;
5379
+ * {@link REQUEST_KEY_ROOT_SOURCE} is the one switch, and callers that pass no source get it.
5380
+ */
5381
+
5382
+ type RequestKeyRootSource = "seed" | "nk";
5383
+ /** The root the SDK derives request keys from when the caller does not choose. */
5384
+ declare const REQUEST_KEY_ROOT_SOURCE: RequestKeyRootSource;
5385
+ /** HD-style gap limit a restore derives and scans past the last counter it knows of. */
5386
+ declare const REQUEST_KEY_GAP_LIMIT = 20;
5387
+ /** Most request keys one scan trials (each costs one trial open per recipient-delivery item). */
5388
+ declare const MAX_REQUEST_KEYS = 64;
5389
+ interface RequestKeys {
5390
+ counter: number;
5391
+ /** Owner of notes paid to this request. Real private key. */
5392
+ utxoKeypair: UtxoKeypair;
5393
+ /** X25519 pair the delivery envelope is sealed to. */
5394
+ viewingKeypair: {
5395
+ privateKey: Uint8Array;
5396
+ publicKey: Uint8Array;
5397
+ };
5398
+ }
5399
+ /**
5400
+ * The 32-byte request root. `skSpend` is the wallet's spend key (seed root); `nk` is the registered
5401
+ * viewing base (nk root). Only the field the chosen source needs is read.
5402
+ */
5403
+ declare function deriveRequestKeyRoot(input: {
5404
+ skSpend?: Uint8Array;
5405
+ nk?: Uint8Array;
5406
+ }, source?: RequestKeyRootSource): Uint8Array;
5407
+ /** The keys for request `counter`. */
5408
+ declare function deriveRequestKeys(root: Uint8Array, counter: number): Promise<RequestKeys>;
5409
+ /** Keys for counters `[from, from + count)`, at most {@link MAX_REQUEST_KEYS}. */
5410
+ declare function deriveRequestKeyRange(root: Uint8Array, from: number, count: number): Promise<RequestKeys[]>;
5411
+
5345
5412
  /**
5346
5413
  * Restore a wallet's notes from the relay's Note Index v1 (contract revision 2.1), without walking
5347
5414
  * the chain and without telling anyone which notes, pools or nullifiers are its own.
@@ -5445,6 +5512,12 @@ interface IndexedRecoveredNote {
5445
5512
  * key), `false` for `notes`.
5446
5513
  */
5447
5514
  legacyExposed: boolean;
5515
+ /**
5516
+ * Set when the note was paid to a per-request key ({@link RecoverNotesFromIndexParams.requestKeys}):
5517
+ * that entry's `index`. `utxo.keypair` is then the request's keypair, not the wallet's, so the
5518
+ * note is spent by sweeping it into the wallet key first.
5519
+ */
5520
+ requestIndex?: number;
5448
5521
  }
5449
5522
  /**
5450
5523
  * The persisted resume point. JSON-serializable and holds NO key material, but `own` records which
@@ -5519,6 +5592,18 @@ interface RecoverNotesFromIndexParams {
5519
5592
  legacyViewingKeyNks?: Uint8Array[];
5520
5593
  /** The wallet's long-lived UTXO keypair, with its real private key. */
5521
5594
  ownerUtxoKeypair: UtxoKeypair;
5595
+ /**
5596
+ * Per-request receive keys (see `notes/request-keys.ts`), at most {@link MAX_REQUEST_KEYS}. Only
5597
+ * recipient-delivery items are trialed against them, so each costs one extra open per delivery
5598
+ * item and no extra request. Notes found through one come back in `notes` with `requestIndex`
5599
+ * set. A cursor from a run with fewer keys has already covered earlier pages without them: when
5600
+ * a restore adds keys, drop the cursor.
5601
+ */
5602
+ requestKeys?: Array<{
5603
+ index: number;
5604
+ viewingSecretKey: Uint8Array;
5605
+ ownerKeypair: UtxoKeypair;
5606
+ }>;
5522
5607
  /** The `cursor` of the previous run. Omit for a full sync. */
5523
5608
  cursor?: NoteIndexCursor;
5524
5609
  /** Per mint: ignore legacy-shaped (nk-owned) notes at or after this leaf (a release cutoff). */
@@ -6462,8 +6547,8 @@ declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>
6462
6547
  * @packageDocumentation
6463
6548
  */
6464
6549
 
6465
- declare const VERSION = "0.2.7";
6550
+ declare const VERSION = "0.2.8";
6466
6551
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
6467
6552
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
6468
6553
 
6469
- export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRelayClientId, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, normalizeAffiliateCode, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
6554
+ export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MAX_REQUEST_KEYS, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, REQUEST_KEY_GAP_LIMIT, REQUEST_KEY_ROOT_SOURCE, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RequestKeyRootSource, type RequestKeys, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, type SweepResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveRequestKeyRange, deriveRequestKeyRoot, deriveRequestKeys, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRelayClientId, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, normalizeAffiliateCode, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, sweepToWalletKey, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, withShieldRetries, withTiming, withdrawFeeFor };
package/dist/index.js CHANGED
@@ -9152,20 +9152,10 @@ async function transfer(inputUtxos, recipientPubkey, amount, rawOptions) {
9152
9152
  );
9153
9153
  }
9154
9154
  options.onProgress?.("Moving notes under the wallet key before the transfer...");
9155
- const migrationSalt = randomChangeNoteSalt();
9156
- const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
9157
- const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
9158
- void _recipientViewingPublicKey;
9159
- const migration = await transact(
9160
- { inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
9161
- { ...migrationOptions, chainNoteSalt: migrationSalt }
9162
- );
9163
- const migratedNote = migration.outputUtxos?.[0] ?? migrated;
9164
- if (migration.commitmentIndices?.[0] >= 0) {
9165
- migratedNote.index = migration.commitmentIndices[0];
9166
- }
9155
+ const migration = await sweepToWalletKey(spendInputs, options);
9156
+ const migratedNote = migration.note;
9167
9157
  spendInputs = [migratedNote];
9168
- spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
9158
+ spendOptions = { ...options, cachedMerkleTree: migration.result.merkleTree };
9169
9159
  }
9170
9160
  const changeNoteSalt = randomChangeNoteSalt();
9171
9161
  const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
@@ -9197,6 +9187,27 @@ async function transfer(inputUtxos, recipientPubkey, amount, rawOptions) {
9197
9187
  { ...spendOptions, chainNoteSalt: changeNoteSalt }
9198
9188
  );
9199
9189
  }
9190
+ async function sweepToWalletKey(inputUtxos, rawOptions) {
9191
+ if (inputUtxos.length === 0 || inputUtxos.length > 2) {
9192
+ throw new Error("sweepToWalletKey: one transaction moves 1 or 2 notes");
9193
+ }
9194
+ assertInputMints(inputUtxos, rawOptions.expectedMint);
9195
+ const options = prepareAffiliateAndClient(rawOptions);
9196
+ const owner = await requireOwnerUtxoKeypair(options, "sweepToWalletKey");
9197
+ const walletNk = await requireWalletNk(options, "sweepToWalletKey");
9198
+ const mint = inputUtxos[0].mintAddress;
9199
+ const salt = randomChangeNoteSalt();
9200
+ const migrated = (await createRecoverableChangeUtxo(sumUtxoAmounts(inputUtxos), owner, walletNk, mint, salt, 0)).utxo;
9201
+ const { recipientViewingPublicKey: _recipientViewingPublicKey, ...sweepOptions } = options;
9202
+ void _recipientViewingPublicKey;
9203
+ const result = await transact(
9204
+ { inputUtxos, outputUtxos: [migrated], externalAmount: BigInt(0) },
9205
+ { ...sweepOptions, chainNoteSalt: salt }
9206
+ );
9207
+ const note = result.outputUtxos?.[0] ?? migrated;
9208
+ if (result.commitmentIndices?.[0] >= 0) note.index = result.commitmentIndices[0];
9209
+ return { note, result };
9210
+ }
9200
9211
  async function partialWithdraw(inputUtxos, recipient, withdrawAmount, rawOptions) {
9201
9212
  const options = prepareAffiliateAndClient(rawOptions);
9202
9213
  const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
@@ -12431,6 +12442,68 @@ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
12431
12442
  });
12432
12443
  }
12433
12444
 
12445
+ // src/notes/request-keys.ts
12446
+ import { blake3 as blake36 } from "@noble/hashes/blake3";
12447
+ import nacl6 from "tweetnacl";
12448
+ var BN254_ORDER = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
12449
+ var ROOT_SEED_DOMAIN = new TextEncoder().encode("cloak_request_root_v1");
12450
+ var ROOT_NK_DOMAIN = new TextEncoder().encode("cloak_request_root_nk_v1");
12451
+ var UTXO_DOMAIN = new TextEncoder().encode("cloak_request_utxo_v1");
12452
+ var VIEWING_DOMAIN = new TextEncoder().encode("cloak_request_vk_v1");
12453
+ var REQUEST_KEY_ROOT_SOURCE = "nk";
12454
+ var REQUEST_KEY_GAP_LIMIT = 20;
12455
+ var MAX_REQUEST_KEYS = 64;
12456
+ function check32(value, label) {
12457
+ if (!(value instanceof Uint8Array) || value.length !== 32) throw new Error(`${label} must be 32 bytes`);
12458
+ return value;
12459
+ }
12460
+ function counterBytes(counter) {
12461
+ if (!Number.isInteger(counter) || counter < 0 || counter > 4294967295) throw new Error("request counter must be a u32");
12462
+ const out = new Uint8Array(4);
12463
+ new DataView(out.buffer).setUint32(0, counter, false);
12464
+ return out;
12465
+ }
12466
+ function hashWith(domain, root, counter) {
12467
+ const c = counterBytes(counter);
12468
+ const pre = new Uint8Array(domain.length + root.length + c.length);
12469
+ pre.set(domain, 0);
12470
+ pre.set(root, domain.length);
12471
+ pre.set(c, domain.length + root.length);
12472
+ return blake36(pre);
12473
+ }
12474
+ function deriveRequestKeyRoot(input, source = REQUEST_KEY_ROOT_SOURCE) {
12475
+ const secret = source === "seed" ? check32(input.skSpend, "skSpend") : check32(input.nk, "nk");
12476
+ const domain = source === "seed" ? ROOT_SEED_DOMAIN : ROOT_NK_DOMAIN;
12477
+ const pre = new Uint8Array(domain.length + 32);
12478
+ pre.set(domain, 0);
12479
+ pre.set(secret, domain.length);
12480
+ return blake36(pre);
12481
+ }
12482
+ async function deriveRequestKeys(root, counter) {
12483
+ check32(root, "request root");
12484
+ const h = hashWith(UTXO_DOMAIN, root, counter);
12485
+ let value = 0n;
12486
+ for (let i = 0; i < 32; i++) value = value << 8n | BigInt(h[i]);
12487
+ const privateKey = value % (BN254_ORDER >> 4n);
12488
+ if (privateKey === 0n) throw new Error("request key derivation produced a zero key");
12489
+ const publicKey = await derivePublicKey(privateKey);
12490
+ const vk = hashWith(VIEWING_DOMAIN, root, counter);
12491
+ vk[0] &= 248;
12492
+ vk[31] &= 127;
12493
+ vk[31] |= 64;
12494
+ return {
12495
+ counter,
12496
+ utxoKeypair: { privateKey, publicKey },
12497
+ viewingKeypair: { privateKey: vk, publicKey: nacl6.scalarMult.base(vk) }
12498
+ };
12499
+ }
12500
+ async function deriveRequestKeyRange(root, from, count) {
12501
+ if (!Number.isInteger(count) || count < 0 || count > MAX_REQUEST_KEYS) throw new Error(`count must be in 0..${MAX_REQUEST_KEYS}`);
12502
+ const out = [];
12503
+ for (let i = 0; i < count; i++) out.push(await deriveRequestKeys(root, from + i));
12504
+ return out;
12505
+ }
12506
+
12434
12507
  // src/scanning/note-index.ts
12435
12508
  import _bs584 from "bs58";
12436
12509
  import { sha256 as sha2566 } from "@noble/hashes/sha2";
@@ -12540,6 +12613,7 @@ var LeafBuffer = class {
12540
12613
  async function trialItem(item, trials) {
12541
12614
  for (const trial of trials) {
12542
12615
  if (trial.legacy && item.kind === 2) continue;
12616
+ if (trial.requestIndex !== void 0 && item.kind !== 2) continue;
12543
12617
  const opened = await trialItemWith(item, trial);
12544
12618
  if (opened) return { ...opened, trial };
12545
12619
  }
@@ -12619,7 +12693,7 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
12619
12693
  const nullifier = hex32(
12620
12694
  await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
12621
12695
  );
12622
- const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
12696
+ const full = { ...c, requestIndex: o.trial.requestIndex, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
12623
12697
  candidates.push(full);
12624
12698
  if (!byNullifier.has(nullifier)) {
12625
12699
  byNullifier.set(nullifier, full);
@@ -12697,9 +12771,10 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
12697
12771
  onReject(o);
12698
12772
  return;
12699
12773
  }
12774
+ const deliveryOwner = o.trial.requestIndex !== void 0 ? o.trial.owner : owner;
12700
12775
  const commitment = await computeCommitment({
12701
12776
  amount: o.delivery.amount,
12702
- keypair: { privateKey: 0n, publicKey: owner.publicKey },
12777
+ keypair: { privateKey: 0n, publicKey: deliveryOwner.publicKey },
12703
12778
  blinding: o.delivery.blinding,
12704
12779
  mintAddress: mint
12705
12780
  });
@@ -12712,7 +12787,7 @@ async function matchOwnItems(own, owner, onReject, onSkip) {
12712
12787
  atRisk: false,
12713
12788
  amount: o.delivery.amount,
12714
12789
  blinding: o.delivery.blinding,
12715
- keypair: owner,
12790
+ keypair: deliveryOwner,
12716
12791
  mint,
12717
12792
  commitment,
12718
12793
  leaf: Number(item.leaf)
@@ -13066,6 +13141,24 @@ async function recoverNotesFromIndex(params) {
13066
13141
  seenNks.add(key);
13067
13142
  trials.push(await makeTrial(Uint8Array.from(nk), true));
13068
13143
  }
13144
+ const requestKeys = params.requestKeys ?? [];
13145
+ if (!Array.isArray(requestKeys)) throw new Error("requestKeys must be an array");
13146
+ if (requestKeys.length > MAX_REQUEST_KEYS) throw new Error(`requestKeys takes at most ${MAX_REQUEST_KEYS} keys`);
13147
+ const seenRequestIdx = /* @__PURE__ */ new Set();
13148
+ for (const rk of requestKeys) {
13149
+ if (!Number.isInteger(rk.index) || rk.index < 0 || seenRequestIdx.has(rk.index)) throw new Error("requestKeys entries need distinct non-negative integer indexes");
13150
+ seenRequestIdx.add(rk.index);
13151
+ if (!(rk.viewingSecretKey instanceof Uint8Array) || rk.viewingSecretKey.length !== 32) throw new Error("requestKeys viewingSecretKey must be 32 bytes");
13152
+ const ownerKp = await assertOwnerUtxoKeypair(rk.ownerKeypair, "requestKeys.ownerKeypair");
13153
+ trials.push({
13154
+ nk: new Uint8Array(32),
13155
+ legacy: false,
13156
+ owner: ownerKp,
13157
+ requestIndex: rk.index,
13158
+ decrypt: async () => null,
13159
+ open: await createRecipientDeliveryOpener(rk.viewingSecretKey)
13160
+ });
13161
+ }
13069
13162
  const poolMints = Array.from(new Set(params.poolMints));
13070
13163
  const warnings = [];
13071
13164
  const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
@@ -13102,6 +13195,7 @@ async function recoverNotesFromIndex(params) {
13102
13195
  }
13103
13196
  async function runOnce(ctx, cursor) {
13104
13197
  const { params, head, trials, owner, stats, poolMints } = ctx;
13198
+ const requestOwners = new Set(trials.filter((t) => t.requestIndex !== void 0).map((t) => t.owner.publicKey));
13105
13199
  const { relayUrl, onProgress } = params;
13106
13200
  const poolSet = new Set(poolMints);
13107
13201
  const startPage = cursor?.raw.page ?? 0;
@@ -13389,7 +13483,8 @@ async function runOnce(ctx, cursor) {
13389
13483
  for (const c of byLeaf.values()) {
13390
13484
  const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
13391
13485
  keyChecked.set(c.keypair.privateKey, pubOk);
13392
- if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
13486
+ const ownerOk = c.requestIndex !== void 0 ? requestOwners.has(c.keypair.publicKey) : c.keypair.publicKey === owner.publicKey;
13487
+ if (!pubOk || !c.atRisk && !ownerOk) {
13393
13488
  stats.dropped++;
13394
13489
  tally(c, "rejected");
13395
13490
  continue;
@@ -13398,7 +13493,7 @@ async function runOnce(ctx, cursor) {
13398
13493
  verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
13399
13494
  const utxo = {
13400
13495
  amount: c.amount,
13401
- keypair: c.atRisk ? { ...c.keypair } : owner,
13496
+ keypair: c.atRisk ? { ...c.keypair } : c.requestIndex !== void 0 ? c.keypair : owner,
13402
13497
  blinding: c.blinding,
13403
13498
  mintAddress: c.mint,
13404
13499
  index: c.leaf,
@@ -13413,7 +13508,8 @@ async function runOnce(ctx, cursor) {
13413
13508
  kind: c.kind,
13414
13509
  utxo,
13415
13510
  signature: bs584.encode(c.signature),
13416
- legacyExposed: c.atRisk
13511
+ legacyExposed: c.atRisk,
13512
+ ...c.requestIndex !== void 0 ? { requestIndex: c.requestIndex } : {}
13417
13513
  };
13418
13514
  (c.atRisk ? atRisk : notes).push(note);
13419
13515
  }
@@ -13855,7 +13951,7 @@ async function loadWeb3() {
13855
13951
  }
13856
13952
 
13857
13953
  // src/bridge/rail-verify.ts
13858
- import nacl6 from "tweetnacl";
13954
+ import nacl7 from "tweetnacl";
13859
13955
  import { sha256 as sha2567 } from "@noble/hashes/sha256";
13860
13956
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
13861
13957
  var b58 = /* @__PURE__ */ (() => {
@@ -13966,7 +14062,7 @@ function verifyQuoteSignature(resp) {
13966
14062
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
13967
14063
  const sig = resp.signature.replace(/^ed25519:/, "");
13968
14064
  try {
13969
- return { valid: nacl6.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
14065
+ return { valid: nacl7.sign.detached.verify(message, b58.decode(sig), b58.decode(ONECLICK_PUBKEY_B58)) };
13970
14066
  } catch (e) {
13971
14067
  return { valid: false, reason: e instanceof Error ? e.message : String(e) };
13972
14068
  }
@@ -14194,7 +14290,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
14194
14290
  // src/bridge/derive.ts
14195
14291
  import { hmac } from "@noble/hashes/hmac";
14196
14292
  import { sha512 } from "@noble/hashes/sha512";
14197
- import { blake3 as blake36 } from "@noble/hashes/blake3";
14293
+ import { blake3 as blake37 } from "@noble/hashes/blake3";
14198
14294
  var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
14199
14295
  var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
14200
14296
  var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
@@ -14221,7 +14317,7 @@ async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
14221
14317
  const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
14222
14318
  preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
14223
14319
  preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
14224
- const key = blake36(preimage);
14320
+ const key = blake37(preimage);
14225
14321
  const h = hmac(sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
14226
14322
  return signerFromSecretKey(h.slice(0, 32));
14227
14323
  }
@@ -14732,7 +14828,7 @@ async function withShieldRetries(attempt, hooks = {}) {
14732
14828
  }
14733
14829
 
14734
14830
  // src/index.ts
14735
- var VERSION = "0.2.7";
14831
+ var VERSION = "0.2.8";
14736
14832
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
14737
14833
  export {
14738
14834
  AccountRole,
@@ -14760,6 +14856,7 @@ export {
14760
14856
  MAINNET_RENT_0,
14761
14857
  MAINNET_RENT_1,
14762
14858
  MAX_RECEIVER_INDEX,
14859
+ MAX_REQUEST_KEYS,
14763
14860
  MERKLE_TREE_HEIGHT2 as MERKLE_TREE_HEIGHT,
14764
14861
  MIN_DEPOSIT_LAMPORTS,
14765
14862
  MIN_DEPOSIT_SPL_BASE_UNITS,
@@ -14783,6 +14880,8 @@ export {
14783
14880
  REQUEST_AUTH_BATCH_MAX_AGE_SECONDS,
14784
14881
  REQUEST_AUTH_MAX_AGE_SECONDS,
14785
14882
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
14883
+ REQUEST_KEY_GAP_LIMIT,
14884
+ REQUEST_KEY_ROOT_SOURCE,
14786
14885
  RelayBatchAuthCoordinator,
14787
14886
  RelayInternalError,
14788
14887
  RelayService,
@@ -14880,6 +14979,9 @@ export {
14880
14979
  deriveLegacyDepositNoteSecrets,
14881
14980
  deriveLegacySwapRefundAuthorization,
14882
14981
  derivePublicKey,
14982
+ deriveRequestKeyRange,
14983
+ deriveRequestKeyRoot,
14984
+ deriveRequestKeys,
14883
14985
  deriveSpendKey,
14884
14986
  deriveSwapRefundAuthorization,
14885
14987
  deriveSwapRefundBlinding,
@@ -15046,6 +15148,7 @@ export {
15046
15148
  sumUtxoAmounts,
15047
15149
  swapUtxo,
15048
15150
  swapWithChange,
15151
+ sweepToWalletKey,
15049
15152
  toAddress,
15050
15153
  toComplianceReport,
15051
15154
  transact,
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.7",
4
+ "version": "0.2.8",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",
@@ -117,7 +117,7 @@
117
117
  "access": "public"
118
118
  },
119
119
  "engines": {
120
- "node": ">=18.0.0"
120
+ "node": ">=22.0.0"
121
121
  },
122
122
  "overrides": {
123
123
  "glob": "^10.5.0",