@cloak.dev/sdk 0.2.5-staging.4b3a899 → 0.2.6-staging.4f665f8

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 ADDED
@@ -0,0 +1,156 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@cloak.dev/sdk` are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Releases before 0.2.6 are described in
6
+ the README's "Version and compatibility" section and in the git history.
7
+
8
+ ## [0.2.6]
9
+
10
+ Pairs with the same mainnet program (`zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`) and the same
11
+ 0.2.0 circuit bundle as 0.2.5. Note format and hashing are unchanged.
12
+
13
+ ### nk view-only (for notes created from 0.2.6 on)
14
+
15
+ The viewing base `nk` is registered with the relay and may be shared with an auditor, so nothing
16
+ that spends or moves funds may be derivable from it. Every note the SDK creates for the wallet
17
+ (deposits, withdraw and swap change, `partialWithdraw` merges, the full-withdraw refund slot, swap
18
+ refunds, bridge receivers and sends to self) is now owned by the wallet's long-lived UTXO keypair,
19
+ passed explicitly as `ownerUtxoKeypair` (`deriveUtxoKeypairFromSpendKey(skSpend)`). `nk` only
20
+ derives blindings, so a scan still finds the notes, and encrypts chain notes.
21
+
22
+ **Older notes.** "nk view-only" holds for notes created from 0.2.6 on. A note created before 0.2.6
23
+ may have an owner key derived from `nk`; such a note moves under the wallet key only when it is
24
+ spent, and nothing in this release moves an idle balance. Until it is spent, `nk` can still spend
25
+ it. These notes are still found by `matchDepositNote`, `matchSwapRefundLeaf`, `matchChangeNote`,
26
+ `scanTransactions` and `discoverSwapRefunds`, come back spendable, and are flagged
27
+ `legacyExposed: true`.
28
+
29
+ #### Changed (BREAKING)
30
+
31
+ * **`SpendOptions.ownerUtxoKeypair` is required.** `transfer`, `partialWithdraw`, `fullWithdraw`,
32
+ `swapUtxo` and `swapWithChange` take `SpendOptions` (`TransactOptions & { ownerUtxoKeypair }`)
33
+ and refuse without it. Change, merges, send-to-self outputs and swap refund leaves are owned by
34
+ it, never by `inputUtxos[0]`'s key. When no input is owned by it, `transfer` first moves the
35
+ inputs into one wallet-owned note (the circuit pins a non-zero output 1 to input 0's key), which
36
+ a `relayAuthBatch` item cannot carry, and which takes at most 2 inputs: with more, `transfer`
37
+ throws and asks the caller to consolidate (send to self, 2 at a time) or withdraw the older
38
+ notes first.
39
+ * **`createRecoverableDepositUtxo` takes one options object**:
40
+ `createRecoverableDepositUtxo({ amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? })`
41
+ instead of `(amount, viewingKeyNk, mintAddress?, noteSalt?)`. The note is owned by
42
+ `ownerUtxoKeypair`; only its blinding comes from `(nk, noteSalt)`.
43
+ * **`deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair)`** gains the
44
+ third argument. The refund owner is the wallet keypair; the blinding stays
45
+ `PRF(nk, nullifier0)`. `UtxoSwapResult.refund` no longer carries a private key.
46
+ * **`discoverSwapRefunds` requires `options.ownerUtxoKeypair`**: refund leaves are owned by it, and
47
+ `nk` alone only finds legacy refunds.
48
+ * **`deriveBridgeReceiver(ownerUtxoKeypair, index)`** replaces `deriveBridgeReceiver(nk, index)`:
49
+ receivers are derived from the UTXO private key under the v2 label `cloak_bridge_escrow_v2`
50
+ (`BRIDGE_ESCROW_LABEL_V2`), no longer from `nk` under `cloak_bridge_escrow`.
51
+ `listBridgeDeposits(rpc, ownerUtxoKeypair, opts)` takes the keypair too, and also scans the
52
+ legacy `nk` receivers (`opts.includeLegacy`, default on; `opts.legacyViewingKeyNks` for other
53
+ viewing keys the wallet used), flagging them `legacyExposed`.
54
+ * **`transact` needs `chainNoteViewingKeyNk` / `getChainNoteViewingKeyNk` or `ownerUtxoKeypair`**
55
+ (whose canonical nk it then uses). It no longer infers `nk` from an input or output note's key,
56
+ and fails before touching the network when none is given.
57
+ * **`deriveDepositNoteSecrets` is removed.** Use `deriveDepositNoteBlinding` for current deposit
58
+ notes (blinding only; the owner is `ownerUtxoKeypair`) and the recovery-only
59
+ `deriveLegacyDepositNoteSecrets` for notes built by an earlier SDK.
60
+
61
+ #### Added
62
+
63
+ * `deriveDepositNoteBlinding`, `deriveLegacyDepositNoteSecrets`, `deriveSwapRefundBlinding`,
64
+ `deriveLegacySwapRefundAuthorization`, `deriveLegacyBridgeReceiver` and `BRIDGE_ESCROW_LABEL_V2`.
65
+ * `legacyExposed` on recovered deposit, change, swap refund and bridge records: `true` marks a note
66
+ or receiver from before 0.2.6 whose owner key is derivable from `nk`.
67
+ * `scanTransactions` takes `ownerUtxoPublicKey` to match the wallet's own deposits and to
68
+ authenticate delivered notes.
69
+
70
+ ### Affiliate code and extra relay headers
71
+
72
+ * `TransactOptions.affiliateCode` (internal, used by Cloak's own apps). `transact`, `swapUtxo` and
73
+ every flow built on them pass it to the request body builders: `/transact` carries
74
+ `affiliate_code` only for a withdrawal with a recipient, `/transact_swap` for any non-empty code;
75
+ deposits and shield-to-shield sends never carry it. It is signed only when present, so a request
76
+ without it is byte-identical to 0.2.5. A request that carries it needs a relay from the affiliate
77
+ release; an older relay answers 401, and the SDK's error then hints at upgrading the relay.
78
+ * `TransactOptions.relayHeaders` (internal) adds headers to `POST /transact` and
79
+ `POST /transact_swap`, for example the mobile client id `X-Cloak-Client`. A name that collides
80
+ with the call's own headers is ignored; names or values with CR, LF or NUL are dropped.
81
+
82
+ ### Relay clock
83
+
84
+ * Relay request signatures are stamped with the relay's clock, not the machine's. The relay stamps
85
+ every response with `x-cloak-server-time`; the SDK records the offset from every relay response
86
+ and `auth_issued_at` (single requests and batches) uses it. A machine clock more than 30 seconds
87
+ fast no longer fails with "signature was issued too far in the future".
88
+ * Chain-note timestamps use the relay clock too. Without a usable sample the SDK learns it with one
89
+ `GET /health` through the relay allowlist. A machine more than five minutes off no longer fails
90
+ withdraws, sends and swaps with "chain note is not decryptable".
91
+ * The paymaster client judges the relay-issued voucher expiry on the relay clock.
92
+ * With no sample (a relay that predates the header, or no relay reachable) every stamp falls back to
93
+ `Date.now()`, the 0.2.5 behaviour.
94
+ * A relay clock more than 24 hours from the machine's is ignored (the bound was a year). The clock
95
+ dates the proof-bound chain-note timestamp, which stays on chain and shows in history and
96
+ compliance reports, so a relay must not be able to move it by months. A machine more than 24
97
+ hours off falls back to its own clock, and the relay's auth window decides.
98
+
99
+ ### Note Index v1 (restore without walking the chain)
100
+
101
+ Restore and note discovery read the relay's Note Index: one bulk, unauthenticated, cacheable feed
102
+ of every confirmed Cloak transaction that the relay indexes once, server side. A restore costs one
103
+ `getMultipleAccounts` (the pool tree accounts) instead of a `getSignaturesForAddress` /
104
+ `getTransaction` walk per user. Needs a relay with migration `26_note_index.sql` and
105
+ `NOTE_INDEX_PUBLISH_ENABLED=true`.
106
+
107
+ #### Added
108
+
109
+ * `recoverNotesFromIndex({ relayUrl, connection, programId, poolMints, viewingKeyNk,
110
+ ownerUtxoKeypair, cursor?, legacyViewingKeyNks?, legacyCutoffLeaf?, concurrency?, onProgress?,
111
+ signal? })` returns `{ notes, atRisk, pending, cursor, stats, warnings }`. It downloads every page (the only request
112
+ parameters are the epoch and the page number, so the relay learns nothing about which notes are
113
+ the wallet's), opens each item locally, rebuilds the tree of every listed pool from the index's
114
+ own leaf stream and checks it against the chain, and computes spent status from the index's
115
+ nullifiers. No nullifier of the wallet is sent to the relay or the RPC.
116
+ * A note is returned only when it opens under the wallet's keys, its commitment recomputes with
117
+ `ownerUtxoKeypair.publicKey` (or a legacy key this recovery derived from `nk`), and it sits at its
118
+ leaf in a root-verified tree. Notes owned by the wallet keypair go to `notes`; legacy notes whose
119
+ owner key is derivable from `nk` go to `atRisk` with `legacyExposed: true`, never into `notes`.
120
+ Candidates that cannot be verified yet are counted in `pending` and carried in the cursor.
121
+ `pending` depends on what the wallet owns: gate polls on the public head (epoch, watermark), never
122
+ on `pending`, or the download pattern tells the relay which client owns an item it tampered with.
123
+ * `legacyViewingKeyNks` (at most 8): other viewing keys older clients of the wallet encrypted chain
124
+ notes under (older mobile builds used SHA-512 of the public wallet address, or the embedded
125
+ wallet's nsk). Each item is tried under the canonical `nk` first, then under each legacy key, in
126
+ the same download: no extra request, still one `getMultipleAccounts`. Everything found only
127
+ through a legacy key is returned in `atRisk` whatever its owner key, a legacy key never opens a
128
+ delivered note, and nothing it opens can enter `notes`. A migration (a canonical-`nk` spend of a
129
+ legacy note) marks the legacy note spent and returns its change, which is found by conservation
130
+ over the legacy input.
131
+ * The cursor (format v2) is JSON with no key material; persist it for incremental syncs. An epoch
132
+ change, a broken hash chain or an invalid cursor re-syncs from page 0; a head behind the cursor
133
+ throws the retryable `NoteIndexHeadBehindError`.
134
+ * `fetchNoteIndexHead`, `fetchNoteIndexPage`, the strict wire format (`parseNoteIndexPage`,
135
+ `parseNoteIndexItem`, `encodeNoteIndexPage`, `encodeNoteIndexItem`, `computeNoteIndexChain`,
136
+ `NoteIndexFormatError`, `NOTE_INDEX_PAGE_SIZE`, `NOTE_INDEX_NO_LEAF`) and their types. The golden
137
+ vector `note-index-golden-v1.hex` is shared with the relay.
138
+
139
+ #### Security notes
140
+
141
+ * The relay is untrusted. It can hide items but cannot inject, alter or forge a note. A hidden
142
+ nullifier can make a spent note look unspent, so restored notes must be spent through
143
+ `transact`, `partialWithdraw`, `fullWithdraw` or `swapUtxo`, which run `preflightNullifiers`
144
+ before proving. `submitTransactToRelay` documents that it does not (as does the internal
145
+ `buildTransactInstruction`, which is not exported).
146
+ * Note Index reads never set the relay clock. Complete pages are immutable and cacheable for a
147
+ year, so a cached response replays a stale `x-cloak-server-time`; learning from it would date
148
+ later signed requests in the past.
149
+
150
+ ### Fixed
151
+
152
+ * A failed deposit no longer rebuilds the Merkle tree from chain (98a818b). A deposit spends no
153
+ inputs, so the replay could not change its outcome; on React Native it cost one
154
+ `getTransaction` per pool transaction (about 2.5k, 7+ minutes) and turned any deposit failure
155
+ (wallet rejection, rent or balance shortfall) into an apparently endless "Generating proof". The
156
+ real error now surfaces at once.
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.5 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
8
+ Version 0.2.6 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.5
14
+ npm install @cloak.dev/sdk@^0.2.6
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
@@ -130,14 +130,21 @@ async function main() {
130
130
  const recipient = address(recipientArg);
131
131
  const amount = BigInt(lamportsArg);
132
132
 
133
- // The wallet's viewing base (nk). A real wallet derives it from its seed; a throwaway
134
- // keypair keeps this script self-contained.
133
+ // The wallet's long-lived UTXO keypair and its viewing base (nk). A real wallet derives the
134
+ // keypair from its seed (deriveUtxoKeypairFromSpendKey); a throwaway keypair keeps this script
135
+ // self-contained.
135
136
  const owner = await generateUtxoKeypair();
136
137
  const nk = getNkFromUtxoPrivateKey(owner.privateKey);
137
138
 
138
- // Shield. The note's keypair and blinding are derived from (nk, noteSalt) and the salt is
139
- // published inside the nk-encrypted chain note, so a scan holding only nk can rebuild it.
140
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, NATIVE_SOL_MINT);
139
+ // Shield. The note is owned by `owner`; only its blinding is derived from (nk, noteSalt), and the
140
+ // salt is published inside the nk-encrypted chain note, so a scan holding nk plus the owner's
141
+ // public key can find it again. nk is view-only: it can never spend the note.
142
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
143
+ amount,
144
+ viewingKeyNk: nk,
145
+ ownerUtxoKeypair: owner,
146
+ mintAddress: NATIVE_SOL_MINT,
147
+ });
141
148
  const deposited = await transact(
142
149
  {
143
150
  inputUtxos: [await createZeroUtxo(NATIVE_SOL_MINT)],
@@ -152,6 +159,7 @@ async function main() {
152
159
  depositorKeypair: signer,
153
160
  chainNoteViewingKeyNk: nk,
154
161
  chainNoteSalt: noteSalt,
162
+ ownerUtxoKeypair: owner,
155
163
  },
156
164
  );
157
165
 
@@ -164,6 +172,7 @@ async function main() {
164
172
  depositorKeypair: signer,
165
173
  walletPublicKey: signer.address,
166
174
  chainNoteViewingKeyNk: nk,
175
+ ownerUtxoKeypair: owner, // mandatory on every spend flow: it owns any change
167
176
  cachedMerkleTree: deposited.merkleTree,
168
177
  });
169
178
 
@@ -357,6 +366,7 @@ const result = await transfer(
357
366
  depositorKeypair: signer,
358
367
  walletPublicKey: signer.address,
359
368
  chainNoteViewingKeyNk: myNk,
369
+ ownerUtxoKeypair: myUtxoKeypair, // owns the change; never inherited from the inputs
360
370
  // The recipient's X25519 viewing public key. With it the recipient can discover the note
361
371
  // from chain with their own key (scanRecipientDeliveryNotes). Without it the note is still
362
372
  // valid but must be handed over out of band.
@@ -366,9 +376,13 @@ const result = await transfer(
366
376
  );
367
377
  ```
368
378
 
369
- `transfer` builds the recipient note as output 0 and returns the change (owned by the input's
370
- keypair) as output 1. Calling `transact` directly with `externalAmount: 0n` does the same; keep the
371
- recipient note at `outputUtxos[0]`, which is the one the delivery carrier is built for.
379
+ `transfer` builds the recipient note as output 0 and returns the change (owned by
380
+ `ownerUtxoKeypair`) as output 1. The circuit requires a private spend's output 1 to be owned by
381
+ input 0's key, so `transfer` puts a note owned by `ownerUtxoKeypair` first; when none of the inputs
382
+ is (notes built by an older SDK), it first moves them into one note owned by `ownerUtxoKeypair` with
383
+ a separate self-spend, then sends from that note. Calling `transact` directly with
384
+ `externalAmount: 0n` is the low-level form; keep the recipient note at `outputUtxos[0]`, which is
385
+ the one the delivery carrier is built for.
372
386
  The recipient shares two values with the sender: their UTXO public key (`UtxoKeypair.publicKey`)
373
387
  and their viewing public key (`deriveViewingKeyFromNk(nk).publicKey`).
374
388
 
@@ -377,6 +391,7 @@ and their viewing public key (`deriveViewingKeyFromNk(nk).publicKey`).
377
391
  ```ts
378
392
  await fullWithdraw([note], recipientWallet, options); // whole note
379
393
  await partialWithdraw([note], recipientWallet, amount, options); // amount out, change stays shielded
394
+ // options: SpendOptions, i.e. TransactOptions with the mandatory `ownerUtxoKeypair`
380
395
  ```
381
396
 
382
397
  For SPL pools the recipient receives tokens in their associated token account. The program charges
@@ -388,10 +403,15 @@ Same API with the pool mint on every note:
388
403
 
389
404
  ```ts
390
405
  const usdc = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
391
- const { utxo, noteSalt } = await createRecoverableDepositUtxo(2_000_000n, nk, usdc); // 2.00 USDC
406
+ const { utxo, noteSalt } = await createRecoverableDepositUtxo({
407
+ amount: 2_000_000n, // 2.00 USDC
408
+ viewingKeyNk: nk,
409
+ ownerUtxoKeypair: owner,
410
+ mintAddress: usdc,
411
+ });
392
412
  await transact(
393
413
  { inputUtxos: [await createZeroUtxo(usdc)], outputUtxos: [utxo], externalAmount: 2_000_000n, depositor: signer.address },
394
- { connection, programId: CLOAK_PROGRAM_ID, relayUrl, depositorKeypair: signer, chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt },
414
+ { connection, programId: CLOAK_PROGRAM_ID, relayUrl, depositorKeypair: signer, chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt, ownerUtxoKeypair: owner },
395
415
  );
396
416
  ```
397
417
 
@@ -426,13 +446,14 @@ const swap = await swapWithChange(
426
446
  depositorKeypair: signer,
427
447
  walletPublicKey: signer.address,
428
448
  chainNoteViewingKeyNk: nk,
449
+ ownerUtxoKeypair: owner, // owns the change and the timeout-refund note
429
450
  swapSlippageBps: 100,
430
451
  },
431
452
  recipientWallet, // required on mainnet: the wallet the swap's risk quote is issued for
432
453
  );
433
454
 
434
455
  swap.signature; // the executed swap; swapWithChange resolves only once execution has completed
435
- swap.refund; // persist: the refund-fallback secret (see below)
456
+ swap.refund; // the refund-fallback authorization: { publicKey, blinding, derivedFromNk } (see below)
436
457
  ```
437
458
 
438
459
  `swapUtxo` is the lower-level form taking `UtxoSwapParams` and an explicit change note. Quote the
@@ -445,18 +466,20 @@ the proof and cannot be changed after it is generated.
445
466
  `swapWithChange` polls the swap status and throws if the swap is refunded, cancelled or fails, or if
446
467
  polling runs out (`swapStatusMaxAttempts` x `swapStatusDelayMs`, default 60 x 2 s); the result above
447
468
  exists only for a completed swap. On a timeout the program returns the principal, net of the swap
448
- fee, to the SOL pool as a refund note, which is spent through the normal withdraw path. When the
449
- swap was submitted with `chainNoteViewingKeyNk` (`swap.refund.derivedFromNk === true`) that note is
450
- discoverable from the key alone:
469
+ fee, to the SOL pool as a refund note, which is spent through the normal withdraw path. The refund
470
+ note is owned by `ownerUtxoKeypair` and its blinding is derived from `nk` and the swap's first
471
+ input nullifier, so it is discoverable from the wallet's keys:
451
472
 
452
473
  ```ts
453
474
  import { discoverSwapRefunds, fullWithdraw, NATIVE_SOL_MINT, type Utxo } from "@cloak.dev/sdk";
454
475
 
455
- const refunds = await discoverSwapRefunds(connection, CLOAK_PROGRAM_ID, nk); // DiscoveredSwapRefund[]
476
+ const refunds = await discoverSwapRefunds(connection, CLOAK_PROGRAM_ID, nk, {
477
+ ownerUtxoKeypair: owner, // required; pass { privateKey: 0n, publicKey } for a view-only scan
478
+ }); // DiscoveredSwapRefund[]
456
479
  for (const refund of refunds) {
457
480
  const note: Utxo = {
458
481
  amount: refund.amount, // principal net of the swap fee
459
- keypair: refund.keypair,
482
+ keypair: refund.keypair, // `owner` (or, for a legacyExposed refund, its own key)
460
483
  blinding: refund.blinding,
461
484
  mintAddress: NATIVE_SOL_MINT,
462
485
  commitment: refund.commitment,
@@ -467,19 +490,31 @@ for (const refund of refunds) {
467
490
  ```
468
491
 
469
492
  Swaps that executed leave no refund note, and an empty result only says that none of the scanned
470
- leaves derive from this `nk`. A swap submitted without `chainNoteViewingKeyNk` has `swap.refund`
471
- (hex `privateKey`, `publicKey`, `blinding`) as the only copy of its secret; rebuild the note from it
472
- with the on-chain `SwapState.sol_amount` as the amount and
473
- `computeSwapRefundCommitment(amount, publicKey, blinding)` as the commitment, then look up the leaf
474
- index as in [Recovery and discovery](#recovery-and-discovery-viewing-key).
493
+ leaves derive from these keys. `swap.refund` (hex `publicKey` and `blinding`) is the fast path:
494
+ rebuild the note with the on-chain `SwapState.sol_amount` as the amount,
495
+ `computeSwapRefundCommitment(amount, publicKey, blinding)` as the commitment and `owner` as the
496
+ keypair, then look up the leaf index as in
497
+ [Recovery and discovery](#recovery-and-discovery-viewing-key). `swap.refund` no longer carries a
498
+ private key: the refund is spent with the wallet's own `ownerUtxoKeypair`.
475
499
 
476
500
  ## Recovery and discovery (viewing key)
477
501
 
478
- The viewing base `nk` is derived from the wallet's spend key (`getNkFromUtxoPrivateKey(privateKey)`
479
- or `expandSpendKey(skSpend).nsk`). It decrypts the chain notes the SDK attaches to transactions and
480
- opens notes delivered by other people's private sends. Recoverable deposit notes and swap refund
481
- notes also derive their secrets from it, which is what makes key-only recovery possible, so store
482
- it with the same care as the spend key.
502
+ The viewing base `nk` is derived from the wallet's long-lived UTXO private key
503
+ (`getNkFromUtxoPrivateKey(privateKey)`). It decrypts the chain notes the SDK attaches to
504
+ transactions, opens notes delivered by other people's private sends, and derives the blindings of
505
+ the wallet's own deposit, change and swap-refund notes so a scan can find them again.
506
+
507
+ **nk is view-only for notes created from 0.2.6 on.** For those it can find and read the wallet's
508
+ notes; it can never spend them or sign for funds. Every note the 0.2.6 SDK creates for the wallet
509
+ is owned by its long-lived UTXO keypair (`ownerUtxoKeypair` /
510
+ `createRecoverableDepositUtxo({ ownerUtxoKeypair })`), and the nullifier needs that keypair's
511
+ private key. Bridge receiving addresses are derived from the UTXO private key, not from nk. Keep the
512
+ spend key and the UTXO private key secret; nk may be shared with an auditor.
513
+
514
+ Notes created before 0.2.6 are different: some have an owner key derived from nk, so nk can spend
515
+ them (they are reported as `legacyExposed`). A pre-0.2.6 note moves under the wallet key only when
516
+ it is spent; nothing in 0.2.6 moves an idle balance. Until such a note is spent, sharing nk also
517
+ shares the ability to spend it.
483
518
 
484
519
  Before a wallet's first transaction the SDK registers `nk` with the relay for compliance scanning:
485
520
  it signs a one-time challenge with `signMessage` (wallet) or `depositorKeypair` and submits `nk`
@@ -494,39 +529,55 @@ const scan = await scanTransactions({
494
529
  connection,
495
530
  programId: CLOAK_PROGRAM_ID,
496
531
  viewingKeyNk: nk,
497
- ownerUtxoPublicKey: owner.publicKey, // authenticates delivered notes' commitments
532
+ ownerUtxoPublicKey: owner.publicKey, // matches your own deposits and authenticates delivered notes
498
533
  deliveryMints: [NATIVE_SOL_MINT],
499
534
  untilSignature: lastScan?.lastSignature, // incremental scans
500
535
  });
501
536
 
502
- scan.recoveredDepositNotes; // own deposits built with createRecoverableDepositUtxo, in spendable form
537
+ scan.recoveredDepositNotes; // own deposits built with createRecoverableDepositUtxo (keypair.privateKey 0n: use `owner`)
538
+ scan.recoveredChangeNotes; // own withdrawal/swap change (keypair.privateKey 0n: use `owner`)
503
539
  scan.deliveredNotes; // notes sent to this wallet (amount + blinding; the keypair is your own)
504
540
  scan.transactions; // history rows for compliance reporting
505
541
  ```
506
542
 
543
+ `scanTransactions` walks the chain with paid RPC calls per wallet. To restore a wallet or pick up
544
+ received notes, prefer [the Note Index](#restore-from-the-note-index-no-chain-walk), which costs one
545
+ RPC request; keep `scanTransactions` for compliance history.
546
+
507
547
  `scanRecipientDeliveryNotes` does the delivery sweep alone, returning `{ notes, rpcCalls }`
508
548
  instead of a full scan result. Deposit recovery applies to deposits built with
509
549
  `createRecoverableDepositUtxo` (the default in the examples); a deposit built with
510
- `createUtxo` has a random blinding that is written nowhere and appears as history only.
550
+ `createUtxo` has a random blinding that is written nowhere and appears as history only. Without
551
+ `ownerUtxoPublicKey` the scan can only match notes from an older SDK whose owner key came from nk.
552
+
553
+ Recovered records carry `legacyExposed`. `false` means the note is owned by the wallet's UTXO
554
+ keypair: substitute `owner` for the returned `keypair` (its `privateKey` is `0n`) before spending.
555
+ `true` marks a note built by an SDK before 0.2.6 whose owner key was derived from nk; it comes back
556
+ with a complete keypair and is spendable as is. Such a note moves under the wallet key only when it
557
+ is spent (to yourself, to someone else, or in a withdrawal): with 0.2.6 the change of any spend is
558
+ owned by `ownerUtxoKeypair`. Nothing in 0.2.6 moves an idle balance, so an unspent `legacyExposed`
559
+ note stays spendable by nk until the app spends it. `transfer` spends at most two such notes at a
560
+ time; with more, consolidate them first (send them to yourself two at a time) or withdraw them.
511
561
 
512
562
  A recovered or delivered note needs its leaf index before it can be spent. Look it up by commitment.
513
- The two record types differ: `RecoveredDepositNoteRecord` carries the note's own `keypair`, a
514
- `bigint` `commitment` and an `Address` `mintAddress`; `DeliveredNote` carries a hex `commitment`,
563
+ The two record types differ: `RecoveredDepositNoteRecord` carries a `keypair` (the owner public key
564
+ with `privateKey: 0n` for a current note, so substitute `owner`; complete for a `legacyExposed`
565
+ one), a `bigint` `commitment` and an `Address` `mintAddress`; `DeliveredNote` carries a hex `commitment`,
515
566
  a base58 `mint` (set only when the scan was given `ownerUtxoPublicKey`) and no keypair, because the
516
567
  keypair is yours.
517
568
 
518
569
  ```ts
519
- import { address } from "@cloak.dev/sdk";
570
+ import { address, fetchCommitments, NATIVE_SOL_MINT, type Utxo } from "@cloak.dev/sdk";
520
571
 
521
572
  const entries = await fetchCommitments(relayUrl, { mint: NATIVE_SOL_MINT });
522
573
  const indexOf = (commitment: bigint) =>
523
574
  entries.find((e) => BigInt("0x" + e.commitment.replace(/^0x/, "")) === commitment)?.index;
524
575
 
525
- // Own deposit recovered from nk
576
+ // Own deposit recovered by the scan
526
577
  const recovered = scan.recoveredDepositNotes[0];
527
578
  const ownNote: Utxo = {
528
579
  amount: recovered.amount,
529
- keypair: recovered.keypair,
580
+ keypair: recovered.legacyExposed ? recovered.keypair : owner,
530
581
  blinding: recovered.blinding,
531
582
  mintAddress: recovered.mintAddress,
532
583
  commitment: recovered.commitment,
@@ -549,12 +600,101 @@ const deliveredNote: Utxo = {
549
600
  };
550
601
  ```
551
602
 
552
- `discoverSwapRefunds(connection, programId, nk)` returns `DiscoveredSwapRefund` records (`keypair`,
553
- `blinding`, `amount`, `commitment`, `leafIndex: bigint`); build the `Utxo` from one as shown under
554
- [Timed-out swaps](#timed-out-swaps).
603
+ `discoverSwapRefunds(connection, programId, nk, { ownerUtxoKeypair })` returns `DiscoveredSwapRefund`
604
+ records (`keypair`, `blinding`, `amount`, `commitment`, `leafIndex: bigint`, `legacyExposed`); build
605
+ the `Utxo` from one as shown under [Timed-out swaps](#timed-out-swaps).
555
606
 
556
607
  `toComplianceReport(scan)` and `formatComplianceCsv(report)` turn a scan into a report.
557
608
 
609
+ ## Restore from the Note Index (no chain walk)
610
+
611
+ `scanTransactions` walks the program's signature history and fetches every transaction over RPC:
612
+ thousands of paid calls per wallet. From 0.2.6 the relay also serves a **Note Index**: one bulk,
613
+ unauthenticated, cacheable feed of every confirmed Cloak transaction (encrypted notes, leaves,
614
+ nullifiers), the same bytes for everyone. `recoverNotesFromIndex` downloads all of it, opens each
615
+ item locally under the wallet's keys, rebuilds every listed pool's tree from the index's own leaf
616
+ stream, and checks those trees with exactly **one** RPC request (`getMultipleAccounts` of the pool
617
+ tree accounts). Spent status comes from the nullifiers in the index, so no nullifier of the wallet
618
+ reaches the relay or the RPC, and the only request parameters are the epoch and a page number.
619
+
620
+ It needs a relay that serves `GET /note-index/v1/head` (the 0.2.6 relay with the index enabled); an
621
+ older relay answers 404. Use it for restore after a reinstall, for received private sends, and for
622
+ change made on another device.
623
+
624
+ ```ts
625
+ import {
626
+ address,
627
+ CLOAK_PROGRAM_ID,
628
+ fetchNoteIndexHead,
629
+ NATIVE_SOL_MINT,
630
+ recoverNotesFromIndex,
631
+ type NoteIndexCursor,
632
+ } from "@cloak.dev/sdk";
633
+
634
+ const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
635
+ const USDT = address("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
636
+ let savedCursor: NoteIndexCursor | undefined = loadCursor(); // your own private storage
637
+
638
+ const result = await recoverNotesFromIndex({
639
+ relayUrl, // must be on this build's relay allowlist
640
+ connection, // used for ONE getMultipleAccounts
641
+ programId: CLOAK_PROGRAM_ID,
642
+ poolMints: [NATIVE_SOL_MINT, USDC, USDT], // every pool the app uses, not only the ones with notes
643
+ viewingKeyNk: nk,
644
+ ownerUtxoKeypair: owner, // with its real private key
645
+ cursor: savedCursor, // omit for a full sync from page 0
646
+ onProgress: ({ pagesDone, pagesTotal }) => console.log(`${pagesDone}/${pagesTotal}`),
647
+ });
648
+
649
+ result.notes; // verified, unspent, owned by `owner`: ready to spend (leaf index included)
650
+ result.atRisk; // verified, unspent, but spendable or readable by nk holders (legacyExposed: true): migrate
651
+ result.pending; // candidates not verifiable yet; they travel inside the cursor
652
+ result.cursor; // persist it and pass it back next time
653
+ result.stats; // pages, items, bytes, rpcCalls (1), ms, ...
654
+ result.warnings; // non-fatal events, e.g. a re-sync from page 0
655
+ ```
656
+
657
+ **What you can trust.** A note is returned only when it opens under the wallet's keys, its
658
+ commitment recomputes from the opened values and the wallet's owner key, and it sits at its leaf in
659
+ a tree the chain authenticates. A dishonest relay can hide items; it cannot inject, alter or
660
+ re-point a note. A hidden nullifier can make a spent note look unspent, so spend restored notes
661
+ through `transact`, `transfer`, `partialWithdraw`, `fullWithdraw` or `swapUtxo`, which run
662
+ `preflightNullifiers` before proving.
663
+
664
+ **The cursor.** JSON, no key material, but it records which index items are the wallet's: store it
665
+ as privately as the notes, one per wallet and relay origin, and never hand one wallet's cursor to
666
+ another wallet or another owner key. Write it only after the notes it covers are stored. An epoch
667
+ change, a broken hash chain or an invalid cursor re-syncs from page 0 by itself.
668
+
669
+ **Polling.** Fetch the head (tiny and cacheable) and run a recovery only when it moved:
670
+
671
+ ```ts
672
+ const head = await fetchNoteIndexHead(relayUrl);
673
+ const moved = !savedCursor || savedCursor.epoch !== head.epoch.toString(10) || savedCursor.watermark !== head.watermark;
674
+ if (moved) {
675
+ /* recoverNotesFromIndex({ ..., cursor: savedCursor }) */
676
+ }
677
+ ```
678
+
679
+ Decide on the head alone. `pending` depends on what the wallet owns (a relay can make it non-zero
680
+ for the owner of one item), so a poll that re-downloads while `pending > 0` tells the relay which
681
+ client owns that item. Pending candidates are retried on the next run the head triggers.
682
+
683
+ **Errors.** `NoteIndexHeadBehindError` is retryable: a cached head from another CDN edge trails the
684
+ cursor; keep the cursor and try again later. `NoteIndexFormatError` means the relay served data that
685
+ did not verify; keep the cursor and report it. A 404 on the head means the relay does not serve the
686
+ index.
687
+
688
+ **Notes from older clients.** Notes whose owner key an SDK before 0.2.6 derived from nk come back in
689
+ `atRisk`. If an older version of your app encrypted chain notes under a different viewing key, pass
690
+ those keys as `legacyViewingKeyNks` (at most 8): they are tried in the same download at no extra
691
+ request, and everything found only through one of them is returned in `atRisk`, never in `notes`.
692
+ A legacy key never opens a delivered note. `legacyCutoffLeaf` (per mint) ignores legacy-shaped notes
693
+ at or after a leaf, for example the first leaf after your app stopped writing them.
694
+
695
+ From a browser the relay answers only the origins its CORS policy allows; servers and native apps
696
+ are not affected.
697
+
558
698
  ## Nullifiers and spent checks
559
699
 
560
700
  The nullifier export is `computeUtxoNullifier(utxo)`, the circuit's scheme:
@@ -647,17 +787,26 @@ relay endpoint and the localhost-RPC check.
647
787
 
648
788
  ## Version and compatibility
649
789
 
650
- - SDK 0.2.5 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
790
+ - SDK 0.2.6 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
651
791
  (deployed 2026-08-24) and the 0.2.0 circuit bundle — the program and circuit bundle are unchanged
652
- since 0.2.0; only the SDK package version has moved. All flows in this README were exercised on
653
- mainnet on 2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to
654
- USDC and USDT; viewing-key discovery followed by a spend; keypair-only deposit recovery.
792
+ since 0.2.0; only the SDK package version has moved. The 0.2.5 flows were exercised on mainnet on
793
+ 2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to USDC and USDT;
794
+ viewing-key discovery followed by a spend; keypair-only deposit recovery. The 0.2.6 API (the
795
+ required `ownerUtxoKeypair`, the relay clock and the Note Index restore) was exercised end to end
796
+ against a local mainnet fork with the 0.2.6 relay, not yet on mainnet.
655
797
  - 0.2.2 adds the opt-in `TransactOptions.relaySupplementalAlt` (see [SPL pools](#spl-pools-usdc-usdt)):
656
798
  off by default, and existing behavior is unchanged when it is left unset.
657
799
  - 0.2.5 moves the SDK from `@solana/web3.js` to `@solana/kit`. The program, the circuit bundle,
658
800
  the relay protocol and every hash the SDK computes are unchanged; what changes is the shape of
659
801
  the Solana values at the API boundary, listed under
660
802
  [Migrating from @solana/web3.js](#migrating-from-solanaweb3js).
803
+ - 0.2.6 adds one optional field, `affiliate_code`, to the relay request schema, used only by
804
+ Cloak's own apps. It is signed only when present, so a request without it is byte-identical to
805
+ 0.2.5 on the wire. Requests that carry it require a relay version that accepts `affiliate_code`
806
+ in the signed request view (the relay's affiliate-program release, REL-010/REL-011); an older
807
+ relay answers them with 401. 0.2.6 also makes nk view-only for notes created from 0.2.6 on, which
808
+ changes several public signatures (`ownerUtxoKeypair` is now required by every spend flow); the
809
+ full list is in [CHANGELOG.md](CHANGELOG.md).
661
810
  - Proofs generated with the 0.1.x circuits are rejected by the mainnet program. SDK 0.1.x builds
662
811
  (which ship the 0.1.0 bundle) are not usable against it; upgrade to 0.2.x.
663
812
  - The note-based `CloakSDK` class is removed in 0.2.0. It targeted the pre-0.2.0 instruction layout