@cloak.dev/sdk 0.2.6-staging.6c85601 → 0.2.6-staging.81e481e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -985,9 +985,10 @@ declare const REQUEST_AUTH_MAX_AGE_SECONDS = 300;
985
985
  * How far ahead of the relay's clock a request may be stamped
986
986
  * (`REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS`, `api/request_auth.rs`).
987
987
  *
988
- * `auth_issued_at` comes from `Date.now()`. On a server that is NTP-disciplined; in a browser it
989
- * is the user's own machine clock, and a laptop more than 30 seconds fast cannot authenticate at
990
- * all until its clock is corrected.
988
+ * `auth_issued_at` is read from the relay's own clock (`relayNowSeconds`, `relay/clock.ts`), learned
989
+ * from the `x-cloak-server-time` header on every relay response, so a machine clock that is off
990
+ * does not matter. Before the first relay response, or against a relay without the header, it
991
+ * falls back to `Date.now()`, where a machine more than 30 seconds fast is refused.
991
992
  */
992
993
  declare const REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30;
993
994
  /**
@@ -1123,8 +1124,15 @@ declare function signRelayAuthPayload(signer: RelayAuthSigner, payload: Uint8Arr
1123
1124
  * arrive as the same bare 401. Two of them are not the caller's mistake at all: an approval that
1124
1125
  * sat too long, and a machine clock that is simply wrong. Returns `null` for anything that is not
1125
1126
  * an authentication rejection, so callers can append it only when there is something to add.
1127
+ *
1128
+ * `context.carriedAffiliateCode` says the rejected body carried `affiliate_code`. A relay older
1129
+ * than the affiliate release (REL-010/REL-011) ignores that field and leaves it out of the digest
1130
+ * it recomputes, so the request fails as a body mismatch even though nothing was tampered with.
1131
+ * Only that case gets the extra hint; without the flag the output is unchanged.
1126
1132
  */
1127
- declare function explainRelayAuthRejection(responseText: string): string | null;
1133
+ declare function explainRelayAuthRejection(responseText: string, context?: {
1134
+ carriedAffiliateCode?: boolean;
1135
+ }): string | null;
1128
1136
  declare const REQUEST_AUTH_BATCH_DOMAIN = "CLOAK_RELAY_BATCH_AUTH_V1";
1129
1137
  /**
1130
1138
  * How long the relay accepts an item that arrives under a batch signature
@@ -1539,6 +1547,14 @@ declare class MerkleTree {
1539
1547
  * @param height Tree height (default: 32)
1540
1548
  */
1541
1549
  declare function buildMerkleTree(commitments: bigint[], height?: number): Promise<MerkleTree>;
1550
+ /**
1551
+ * Serializable state of a {@link MerkleFrontier}: the leaf count and, per level, the hash of the
1552
+ * last complete LEFT node still waiting for its right sibling (hex, `""` when that level has none).
1553
+ */
1554
+ interface MerkleFrontierState {
1555
+ nextIndex: number;
1556
+ left: string[];
1557
+ }
1542
1558
 
1543
1559
  /**
1544
1560
  * Error Utilities
@@ -3431,6 +3447,20 @@ interface TransactOptions {
3431
3447
  * passing nk at every call site — e.g. pass a getter from your key manager.
3432
3448
  */
3433
3449
  getChainNoteViewingKeyNk?: () => Promise<string | Uint8Array | null>;
3450
+ /**
3451
+ * The wallet's long-lived UTXO keypair (`deriveUtxoKeypairFromSpendKey(skSpend)`).
3452
+ *
3453
+ * It OWNS every self-owned note a flow creates: change, merges, send-to-self outputs and swap
3454
+ * refund leaves. The SDK never takes that owner from an input or output note, because a note's
3455
+ * own key may be a legacy key derived from the viewing key `nk`, and `nk` must only ever VIEW.
3456
+ *
3457
+ * When no explicit `chainNoteViewingKeyNk` / `getChainNoteViewingKeyNk` is given, the canonical
3458
+ * `nk` is derived from it (`getNkFromUtxoPrivateKey(privateKey)`).
3459
+ *
3460
+ * Required by `transfer`, `partialWithdraw`, `fullWithdraw`, `swapUtxo` and `swapWithChange`
3461
+ * (see {@link SpendOptions}). Optional for `transact`, which then requires an explicit `nk`.
3462
+ */
3463
+ ownerUtxoKeypair?: UtxoKeypair;
3434
3464
  /**
3435
3465
  * Pin the chain note's 96-bit `noteSalt` instead of drawing a fresh one (VK-01).
3436
3466
  *
@@ -3582,6 +3612,14 @@ interface TransactOptions {
3582
3612
  */
3583
3613
  relayHeaders?: Record<string, string>;
3584
3614
  }
3615
+ /**
3616
+ * Options for the spend flows that create self-owned notes (`transfer`, `partialWithdraw`,
3617
+ * `fullWithdraw`, `swapUtxo`, `swapWithChange`): {@link TransactOptions} with the wallet's
3618
+ * long-lived UTXO keypair made mandatory.
3619
+ */
3620
+ type SpendOptions = TransactOptions & {
3621
+ ownerUtxoKeypair: UtxoKeypair;
3622
+ };
3585
3623
  /**
3586
3624
  * Switchboard-style response: a pre-built instruction.
3587
3625
  *
@@ -3718,6 +3756,8 @@ interface SubmitTransactToRelayArgs {
3718
3756
  settlementTimeoutMs?: number;
3719
3757
  /** Shorter window used to ask "did it land anyway?" after a terminal relay failure. */
3720
3758
  failureProbeTimeoutMs?: number;
3759
+ /** Stops the wait for the relay's source lease to expire; the chain is still checked after. */
3760
+ signal?: AbortSignal;
3721
3761
  }
3722
3762
  /**
3723
3763
  * POST one logical `/transact` request and REPORT ONLY WHAT THE CHAIN CONFIRMS.
@@ -3746,6 +3786,12 @@ interface SubmitTransactToRelayArgs {
3746
3786
  * captured across attempts, and every terminal failure that could plausibly have been submitted
3747
3787
  * is resolved against chain into a `SettlementVerificationError` that states the outcome and
3748
3788
  * carries the signature.
3789
+ *
3790
+ * WARNING [preflight 0x1020]: this posts an already-built request and does NOT run
3791
+ * `preflightNullifiers`. Notes restored from an untrusted source (the relay's note index can hide a
3792
+ * nullifier, so a spent note can look unspent) must go through `transact` / `partialWithdraw` /
3793
+ * `fullWithdraw` / `swapUtxo`, which run the preflight before proof generation; a caller that
3794
+ * builds its own request must `await preflightNullifiers(inputUtxos, connection, programId)` first.
3749
3795
  */
3750
3796
  declare function submitTransactToRelay(args: SubmitTransactToRelayArgs): Promise<RelaySubmissionResult>;
3751
3797
  declare function transact(params: TransactParams, options: TransactOptions): Promise<TransactResult>;
@@ -3755,24 +3801,31 @@ declare function transact(params: TransactParams, options: TransactOptions): Pro
3755
3801
  * Transfers funds from your UTXOs to another recipient's public key,
3756
3802
  * keeping everything within the shielded pool.
3757
3803
  *
3804
+ * Change (and a send to yourself) is owned by `options.ownerUtxoKeypair`, the wallet's long-lived
3805
+ * UTXO keypair, never by `inputUtxos[0]`'s key. The chain note is encrypted under the wallet's nk
3806
+ * (explicit, or the canonical nk of `ownerUtxoKeypair`).
3807
+ *
3758
3808
  * @param inputUtxos Your UTXOs to spend
3759
3809
  * @param recipientPubkey Recipient's UTXO public key
3760
3810
  * @param amount Amount to transfer
3761
- * @param options Transaction options
3811
+ * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3762
3812
  */
3763
- declare function transfer(inputUtxos: Utxo[], recipientPubkey: bigint, amount: bigint, options: TransactOptions): Promise<TransactResult>;
3813
+ declare function transfer(inputUtxos: Utxo[], recipientPubkey: bigint, amount: bigint, options: SpendOptions): Promise<TransactResult>;
3764
3814
  /**
3765
3815
  * Execute a partial withdrawal
3766
3816
  *
3767
3817
  * Withdraws a portion of funds to an external Solana address,
3768
3818
  * keeping the remainder shielded.
3769
3819
  *
3820
+ * The change note (and any consolidation merge) is owned by `options.ownerUtxoKeypair`, the
3821
+ * wallet's long-lived UTXO keypair, never by `inputUtxos[0]`'s key.
3822
+ *
3770
3823
  * @param inputUtxos Your UTXOs to spend
3771
3824
  * @param recipient External Solana address
3772
3825
  * @param withdrawAmount Amount to withdraw
3773
- * @param options Transaction options
3826
+ * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3774
3827
  */
3775
- declare function partialWithdraw(inputUtxos: Utxo[], recipient: Address, withdrawAmount: bigint, options: TransactOptions): Promise<TransactResult>;
3828
+ declare function partialWithdraw(inputUtxos: Utxo[], recipient: Address, withdrawAmount: bigint, options: SpendOptions): Promise<TransactResult>;
3776
3829
  /**
3777
3830
  * Execute a full withdrawal
3778
3831
  *
@@ -3780,9 +3833,9 @@ declare function partialWithdraw(inputUtxos: Utxo[], recipient: Address, withdra
3780
3833
  *
3781
3834
  * @param inputUtxos Your UTXOs to spend
3782
3835
  * @param recipient External Solana address
3783
- * @param options Transaction options
3836
+ * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3784
3837
  */
3785
- declare function fullWithdraw(inputUtxos: Utxo[], recipient: Address, options: TransactOptions): Promise<TransactResult>;
3838
+ declare function fullWithdraw(inputUtxos: Utxo[], recipient: Address, options: SpendOptions): Promise<TransactResult>;
3786
3839
  /**
3787
3840
  * Parameters for UTXO swap operation
3788
3841
  */
@@ -3813,20 +3866,21 @@ interface UtxoSwapResult extends TransactResult {
3813
3866
  /** Relay request ID for swap execution status */
3814
3867
  requestId?: string;
3815
3868
  /**
3816
- * V3-04 refund-fallback secret. **Persist this** to recover the swap principal if the swap times
3817
- * out before TX2. On a timeout close the program builds the amount-bound note
3869
+ * V3-04 refund-fallback authorization. On a timeout close the program builds the amount-bound note
3818
3870
  * R_fb = Poseidon(amountAfterFee, publicKey, blinding, WSOL)
3819
3871
  * where `amountAfterFee` is the principal it locked (read authoritatively from the on-chain
3820
- * `SwapState.sol_amount`, = gross swap amount minus the on-chain swap fee). `ClaimRefund` then spends
3821
- * `R_fb` with `privateKey` (a plain ZK membership proof of the refund tree). All values are hex.
3872
+ * `SwapState.sol_amount`, = gross swap amount minus the on-chain swap fee). R_fb is an ordinary
3873
+ * leaf of the main pool tree, spent with the ordinary `transact()` path. All values are hex.
3822
3874
  *
3823
- * VK-02: when `derivedFromNk` is true this secret is ALSO recoverable from the wallet's `nk` plus
3824
- * the swap's public first input nullifier — see `matchSwapRefundLeaf`. Persisting it is still the
3825
- * fast path; losing it is no longer terminal. When false (no `nk` was supplied to the swap) this
3826
- * object is the only copy that will ever exist.
3875
+ * `publicKey` is a PER-SWAP public key, derived from `options.ownerUtxoKeypair`'s private key and
3876
+ * the swap's first input nullifier, so no two swaps from one wallet share it and it is not the
3877
+ * wallet's UTXO public key. Spend R_fb with `deriveSwapRefundKeypair(owner, nullifier)`; the
3878
+ * private key is deliberately not repeated here and `nk` cannot produce it. The
3879
+ * blinding is derived from the wallet's `nk` and the swap's public first input nullifier
3880
+ * (`derivedFromNk` is always true), so `discoverSwapRefunds` finds the leaf again from key
3881
+ * material if this object is lost.
3827
3882
  */
3828
3883
  refund: {
3829
- privateKey: string;
3830
3884
  publicKey: string;
3831
3885
  blinding: string;
3832
3886
  derivedFromNk: boolean;
@@ -3844,7 +3898,7 @@ interface UtxoSwapResult extends TransactResult {
3844
3898
  * @param options Transaction options
3845
3899
  * @returns UtxoSwapResult with SwapState PDA for executing the swap
3846
3900
  */
3847
- declare function swapUtxo(params: UtxoSwapParams, options: TransactOptions): Promise<UtxoSwapResult>;
3901
+ declare function swapUtxo(params: UtxoSwapParams, options: SpendOptions): Promise<UtxoSwapResult>;
3848
3902
  /**
3849
3903
  * Execute a swap with change
3850
3904
  *
@@ -3857,7 +3911,7 @@ declare function swapUtxo(params: UtxoSwapParams, options: TransactOptions): Pro
3857
3911
  * @param minOutputAmount Minimum output (slippage protection)
3858
3912
  * @param options Transaction options
3859
3913
  */
3860
- declare function swapWithChange(inputUtxos: Utxo[], swapAmount: bigint, outputMint: Address, recipientAta: Address, minOutputAmount: bigint, options: TransactOptions, recipientWallet?: Address): Promise<UtxoSwapResult>;
3914
+ declare function swapWithChange(inputUtxos: Utxo[], swapAmount: bigint, outputMint: Address, recipientAta: Address, minOutputAmount: bigint, options: SpendOptions, recipientWallet?: Address): Promise<UtxoSwapResult>;
3861
3915
 
3862
3916
  /**
3863
3917
  * Circuit artifact loading and integrity verification.
@@ -4305,77 +4359,45 @@ declare function parseDeliveryCarrierMemo(data: Uint8Array): ParsedDeliveryCarri
4305
4359
  /**
4306
4360
  * Recoverable deposit notes (VK-01, deposit shape).
4307
4361
  *
4308
- * ── The defect this closes ────────────────────────────────────────────────────────────────────
4309
- * A cold scan holding exactly `(rpc, programId, nk)` — the contract the SDK advertises for viewing
4310
- * keys — found the WITHDRAWAL change note and did NOT find the DEPOSIT. The control that makes the
4311
- * miss attributable is the withdrawal: the same scanner, the same 300-signature window, the same
4312
- * key, one shape found and one not.
4313
- *
4314
- * Two things were missing, and only one of them was visible from the failing arm:
4315
- *
4316
- * 1. `outPubkey0`. The deposit's chain note is v3 (timestamp + noteSalt), and `chainNoteHash` binds
4317
- * `noteSemantics = Poseidon(outAmount0, outPubkey0, isSendToSelfKey0)`. `outPubkey0` is the
4318
- * output note's OWNER key, which is not derivable from `nk` — the key hierarchy runs
4319
- * `skSpend → nk` through BLAKE3 and does not run backwards. So the scanner could decrypt the
4320
- * note and then had to drop it, because the hash it recomputed could never match. That is why
4321
- * the widened arm needed an undocumented `ownUtxoPublicKey`: it was feeding the scanner the one
4322
- * value the advertised contract does not carry.
4323
- * 2. The BLINDING. Even with `ownUtxoPublicKey` the deposit is only VISIBLE, not RECOVERABLE — the
4324
- * blinding came from `randomFieldElement()` inside `createUtxo` and is written nowhere. A note
4325
- * you can see and cannot spend is not a recovered note.
4326
- *
4327
- * ── Why derivation, and not another envelope ──────────────────────────────────────────────────
4328
- * The shielded-send shape was fixed with a CLKD1 delivery envelope because a send's output is owned
4329
- * by SOMEONE ELSE: the only way to reach them is to encrypt to their key. A deposit's output is
4330
- * SELF-owned. There is nobody to deliver to, and an envelope would cost 112 bytes on the one
4331
- * transaction in the protocol that is wallet-signed and already tight against the 1232-byte packet
4332
- * limit (a v4 chain note's extra 41 bytes is measured at 1282 and is exactly why deposits stay v3).
4333
- *
4334
- * So make the existing chain-note path recoverable instead. Both missing values become a PRF of the
4335
- * wallet's own `nk` and the note salt the chain note ALREADY carries:
4336
- *
4337
- * seed = BLAKE3("cloak_deposit_note_v1" || nk || noteSalt(32B BE) || info)
4338
- * privateKey = seed("sk") reduced into the field
4339
- * blinding = seed("blinding") reduced into the field
4340
- * publicKey = PoseidonEx(privateKey, KEYPAIR_) [L-02, matches keypair.circom]
4341
- *
4342
- * A cold scanner decrypts the chain note with `nk` (AES-GCM, HKDF-salted by the output commitment),
4343
- * reads `noteSalt` out of the plaintext, replays those three lines, recomputes
4344
- * `Poseidon(amount, publicKey, blinding, mint)` and requires it to equal a commitment the
4345
- * transaction actually published. That equality is the authentication: it is not a heuristic, and a
4346
- * wrong `nk` cannot produce it. Zero extra bytes on chain, no new envelope, no relay change.
4347
- *
4348
- * This is the same shape already blessed for swap timeout refunds in `notes/swap-refund.ts`
4349
- * (PRF(nk, nullifier0)), for the same reason: unrecoverable randomness becomes recoverable
4350
- * randomness without changing anything an observer can see.
4351
- *
4352
- * ── The consequence to be explicit about ──────────────────────────────────────────────────────
4353
- * The deposit note is owned by a PER-DEPOSIT key rather than by the wallet's single long-lived UTXO
4354
- * keypair. It is still fully spendable — the wallet re-derives `privateKey` from `nk` whenever it
4355
- * needs it — and it is strictly better for privacy, because `outPubkey0` no longer links a wallet's
4356
- * deposits to each other. But it means the caller MUST persist (or be able to re-derive) `nk`, which
4357
- * a Cloak wallet already does, and it means `transact` must be given an explicit `nk` rather than
4358
- * inferring one from the output note's own key. `transact` enforces that rather than trusting it.
4362
+ * ── What a deposit note is ────────────────────────────────────────────────────────────────────
4363
+ * A deposit's output note is owned by the wallet's long-lived UTXO keypair (passed explicitly by
4364
+ * the caller) and carries a blinding derived from the wallet's viewing key:
4365
+ *
4366
+ * blinding = BLAKE3("cloak_deposit_note_v1" || nk || noteSalt(32B BE) || "blinding") -> field
4367
+ * owner = ownerUtxoKeypair (deriveUtxoKeypairFromSpendKey(skSpend)), never derived from nk
4368
+ *
4369
+ * The chain note (encrypted under `nk`) publishes `noteSalt`, so a scan holding `nk` and the
4370
+ * wallet's UTXO PUBLIC key can replay the blinding, recompute `Poseidon(amount, ownerPub, blinding,
4371
+ * mint)` and require it to equal a commitment the transaction actually published. That equality is
4372
+ * the authentication. Spending still needs the owner's PRIVATE key, which `nk` cannot produce: the
4373
+ * nullifier is `Poseidon(commitment, index, Poseidon(privateKey, commitment, index))`.
4374
+ *
4375
+ * ── nk is view-only ───────────────────────────────────────────────────────────────────────────
4376
+ * `nk` is registered with the relay for compliance and may be shared with an auditor, so it must
4377
+ * only ever VIEW. The first version of this module derived the owner private key as well, as
4378
+ * PRF(nk, noteSalt). Notes built that way still exist on chain; they are recovered by
4379
+ * {@link matchDepositNote} through {@link deriveLegacyDepositNoteSecrets} and come back flagged
4380
+ * `legacyExposed: true`, so an app can offer to move them under the wallet's own key. No API here
4381
+ * creates a note in that shape any more.
4359
4382
  *
4360
4383
  * ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
4361
- * [L-02] the public key comes from the capacity-tagged `derivePublicKey`. [H-04-shaped] a zero
4362
- * public key or blinding would be an unspendable note, so the reduction forces non-zero and the
4363
- * derivation refuses to return a degenerate pair. [M-04] `noteSalt` stays a private input to
4364
- * `chainNoteHash`; it is only ever published inside the note's own authenticated ciphertext.
4384
+ * [L-02] public keys come from the capacity-tagged `derivePublicKey`. [H-04-shaped] the reduction
4385
+ * forces a non-zero blinding. [M-04] `noteSalt` stays a private input to `chainNoteHash`; it is
4386
+ * only ever published inside the note's own authenticated ciphertext.
4365
4387
  */
4366
4388
 
4367
4389
  /**
4368
- * The chain note salt is 96 bits — the circuit constrains it with `Num2Bits(96)` and `transact`
4390
+ * The chain note salt is 96 bits: the circuit constrains it with `Num2Bits(96)` and `transact`
4369
4391
  * generates exactly 12 bytes. A salt outside that range would produce a proof the circuit rejects,
4370
4392
  * so it is refused here rather than at proof time.
4371
4393
  */
4372
4394
  declare const CHAIN_NOTE_SALT_BITS = 96;
4373
- /** The secrets a deposit note is built from — and the ones a cold scan re-derives. */
4395
+ /** The secrets a deposit note is built from. */
4374
4396
  interface DepositNoteSecrets {
4375
4397
  keypair: UtxoKeypair;
4376
4398
  blinding: bigint;
4377
4399
  }
4378
- /** A deposit note recovered from `nk` alone, in spendable form. */
4400
+ /** A deposit note recovered by a scan. */
4379
4401
  interface RecoveredDepositNote extends DepositNoteSecrets {
4380
4402
  amount: bigint;
4381
4403
  mintAddress: Address;
@@ -4383,30 +4405,67 @@ interface RecoveredDepositNote extends DepositNoteSecrets {
4383
4405
  commitment: bigint;
4384
4406
  /** The salt the chain note carried, which anchored the derivation. */
4385
4407
  noteSalt: bigint;
4408
+ /**
4409
+ * `false`: the note is owned by the wallet's long-lived UTXO keypair. `keypair` is the owner
4410
+ * keypair the matcher was given, so `keypair.privateKey` is `0n` when only the public key was
4411
+ * supplied (a view-only scan); substitute the wallet's own keypair before spending.
4412
+ *
4413
+ * `true`: a legacy deposit whose owner key was derived from `nk` (the pre-fix shape). `keypair`
4414
+ * is complete and spendable, and the same is true for anyone holding `nk`, so an app should offer
4415
+ * to move these funds into a note owned by the wallet's long-lived keypair.
4416
+ */
4417
+ legacyExposed: boolean;
4386
4418
  }
4387
4419
  /** A fresh 96-bit chain-note salt, from the same fail-closed source `transact` uses. */
4388
4420
  declare function randomDepositNoteSalt(): bigint;
4389
4421
  /**
4390
- * Derive a deposit note's keypair and blinding from `(nk, noteSalt)`.
4422
+ * Derive a deposit note's BLINDING from `(nk, noteSalt)`.
4391
4423
  *
4392
- * Deterministic by design: this is the whole reason a cold scan can rebuild the note. Both the
4393
- * builder and the scanner call it, so there is exactly one definition of what a deposit note is.
4424
+ * Deterministic by design: this is what lets a scan rebuild the commitment. The blinding is a view
4425
+ * secret (it hides the amount and owner inside the commitment); it cannot spend anything, because
4426
+ * spending needs the owner's private key. Both current and legacy deposit notes use this blinding.
4427
+ */
4428
+ declare function deriveDepositNoteBlinding(viewingKeyNk: Uint8Array, noteSalt: bigint): bigint;
4429
+ /**
4430
+ * LEGACY. The secrets of a deposit note built by the first recoverable-deposit release, whose owner
4431
+ * private key was PRF(nk, noteSalt).
4432
+ *
4433
+ * Exists only so scans can still find and spend those notes. Never build a new note from this: the
4434
+ * owner key is derivable by anyone who holds `nk`.
4394
4435
  */
4395
- declare function deriveDepositNoteSecrets(viewingKeyNk: Uint8Array, noteSalt: bigint): Promise<DepositNoteSecrets>;
4436
+ declare function deriveLegacyDepositNoteSecrets(viewingKeyNk: Uint8Array, noteSalt: bigint): Promise<DepositNoteSecrets>;
4437
+ /** Parameters for {@link createRecoverableDepositUtxo}. */
4438
+ interface CreateRecoverableDepositUtxoParams {
4439
+ /** Deposit amount in base units. */
4440
+ amount: bigint;
4441
+ /** The wallet's 32-byte viewing base `nk`. Derives the blinding and encrypts the chain note. */
4442
+ viewingKeyNk: Uint8Array;
4443
+ /**
4444
+ * The wallet's long-lived UTXO keypair, which OWNS the note. Required: a deposit note is never
4445
+ * owned by a key derived from `nk`.
4446
+ */
4447
+ ownerUtxoKeypair: UtxoKeypair;
4448
+ /** Pool mint. Defaults to native SOL. */
4449
+ mintAddress?: Address;
4450
+ /** Pin the 96-bit chain-note salt. Defaults to a fresh random salt. */
4451
+ noteSalt?: bigint;
4452
+ }
4396
4453
  /**
4397
- * Build a deposit output note that a cold `(rpc, programId, nk)` scan can recover.
4454
+ * Build a deposit output note that a scan holding `nk` plus the wallet's UTXO public key can
4455
+ * recover, and that only the holder of the owner's private key can spend.
4398
4456
  *
4399
4457
  * Returns the UTXO to pass as `outputUtxos[0]` AND the salt that anchored it. The SAME salt must be
4400
- * handed to `transact` as `options.chainNoteSalt`, because the chain note is what publishes it — a
4401
- * salt that does not reach the note leaves the deposit exactly as undiscoverable as before.
4458
+ * handed to `transact` as `options.chainNoteSalt`, because the chain note is what publishes it.
4402
4459
  *
4403
4460
  * ```ts
4404
- * const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
4461
+ * const { utxo, noteSalt } = await createRecoverableDepositUtxo({
4462
+ * amount, viewingKeyNk: nk, ownerUtxoKeypair, mintAddress: mint,
4463
+ * });
4405
4464
  * await transact({ ..., outputUtxos: [utxo], externalAmount: amount },
4406
- * { chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt, ... });
4465
+ * { chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt, ownerUtxoKeypair, ... });
4407
4466
  * ```
4408
4467
  */
4409
- declare function createRecoverableDepositUtxo(amount: bigint, viewingKeyNk: Uint8Array, mintAddress?: Address, noteSalt?: bigint): Promise<{
4468
+ declare function createRecoverableDepositUtxo(params: CreateRecoverableDepositUtxoParams): Promise<{
4410
4469
  utxo: Utxo;
4411
4470
  noteSalt: bigint;
4412
4471
  }>;
@@ -4415,20 +4474,26 @@ interface MatchDepositNoteParams {
4415
4474
  viewingKeyNk: Uint8Array;
4416
4475
  /** `noteSalt`, read out of the decrypted chain note. */
4417
4476
  noteSalt: bigint;
4418
- /** Candidate note amount — for a shield with no inputs this is the public deposit amount. */
4477
+ /** Candidate note amount. For a shield with no inputs this is the public deposit amount. */
4419
4478
  amount: bigint;
4420
4479
  /** Pool mint the commitment was computed under. */
4421
4480
  mintAddress: Address;
4422
4481
  /** Output commitments the transaction actually published, hex or field elements. */
4423
4482
  outputCommitments: Array<string | bigint>;
4483
+ /**
4484
+ * The wallet's long-lived UTXO keypair. Only `publicKey` is needed for a match; pass
4485
+ * `privateKey: 0n` for a view-only scan, or the real keypair to get a spendable result. Without
4486
+ * it only legacy (nk-owned) deposits can be matched.
4487
+ */
4488
+ ownerUtxoKeypair?: UtxoKeypair;
4424
4489
  }
4425
4490
  /**
4426
- * Decide whether a deposit's published commitment is one this `nk` can rebuild, and if so return
4427
- * the note in spendable form. Returns `null` for everything that is not ours.
4491
+ * Decide whether a deposit's published commitment is one of this wallet's notes, and if so return
4492
+ * it. Returns `null` for everything that is not ours.
4428
4493
  *
4429
- * The commitment equality is the authentication. Nothing here trusts the chain note's own claim
4430
- * about what it describes; the note only supplies `noteSalt`, and the derived secrets have to
4431
- * reproduce a value the transaction published or the candidate is discarded.
4494
+ * Tries the current shape first (owner = `ownerUtxoKeypair`), then the legacy shape (owner derived
4495
+ * from `nk`, flagged `legacyExposed`). The commitment equality is the authentication; nothing here
4496
+ * trusts the chain note's own claim about what it describes.
4432
4497
  */
4433
4498
  declare function matchDepositNote(params: MatchDepositNoteParams): Promise<RecoveredDepositNote | null>;
4434
4499
 
@@ -4470,16 +4535,19 @@ declare function matchDepositNote(params: MatchDepositNoteParams): Promise<Recov
4470
4535
  * derive one blinding, and `transact`'s fail-closed check could not tell which slot it was looking
4471
4536
  * at. With it, every slot has its own answer.
4472
4537
  *
4473
- * ── Why only the blinding, when deposits derive the keypair too ───────────────────────────────
4474
- * A deposit's output note has no prior owner, so `deposit-note.ts` is free to give it a per-deposit
4475
- * key and gains unlinkability by doing so. A change note is different: its owner is already fixed —
4476
- * it is the keypair of the note being spent (`inputUtxos[0].keypair`), which the spender by
4477
- * definition holds, and which callers rely on to keep spending their own change. Re-owning it under
4478
- * a derived key would change `outPubkey0`, break that expectation, and buy nothing, because the
4479
- * spender's key is the one value in a change note that was never at risk. Only the randomness was.
4538
+ * ── Who owns change ───────────────────────────────────────────────────────────────────────────
4539
+ * Change is owned by the wallet's long-lived UTXO keypair, passed explicitly by the caller
4540
+ * (`ownerUtxoKeypair` on the spend flows). It is never inherited from `inputUtxos[0]`: an input may
4541
+ * be a legacy note whose key was derived from `nk`, and inheriting that key would keep the change
4542
+ * spendable by anyone holding the viewing key. Owning change under the wallet key also means that
4543
+ * spending a legacy note produces safe change, which is how legacy funds migrate.
4544
+ *
4545
+ * Only the blinding comes from `nk`. The blinding is a view secret; spending needs the owner's
4546
+ * private key, which `nk` cannot produce.
4480
4547
  *
4481
4548
  * ── What a cold scan can rebuild, and what it cannot ──────────────────────────────────────────
4482
- * For the shape that lost the money — a partial withdrawal — recovery is COMPLETE from `nk` alone.
4549
+ * For the shape that lost the money (a partial withdrawal) a scan holding `nk` finds the note and
4550
+ * rebuilds its commitment; spending it needs the owner's private key, which the wallet holds.
4483
4551
  * `partialWithdraw` emits the change as `outputUtxos[0]`, and a v4 chain note binds
4484
4552
  * `noteSemantics = Poseidon(outAmount0, outPubkey0, isSendToSelfKey0)` and carries all three in its
4485
4553
  * (encrypted, authenticated) plaintext. So a scanner holding `nk` decrypts the note, reads
@@ -4498,8 +4566,7 @@ declare function matchDepositNote(params: MatchDepositNoteParams): Promise<Recov
4498
4566
  * ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
4499
4567
  * [M-04] `noteSalt` stays a private input to `chainNoteHash`; it is only ever published inside the
4500
4568
  * note's own authenticated ciphertext, so nothing an observer can see changes. [H-04-shaped] the
4501
- * reduction forces non-zero, because a zero blinding is an unspendable note. Callers that pass no
4502
- * `nk` keep the previous random-blinding behaviour unchanged, so this is additive.
4569
+ * reduction forces non-zero, because a zero blinding is an unspendable note.
4503
4570
  */
4504
4571
 
4505
4572
  /** A change note recovered from `nk` (plus the owner key the spender already holds). */
@@ -4512,6 +4579,13 @@ interface RecoveredChangeNote {
4512
4579
  commitment: bigint;
4513
4580
  /** The salt the chain note carried, which anchored the derivation. */
4514
4581
  noteSalt: bigint;
4582
+ /**
4583
+ * `true` when the note is NOT owned by the wallet's long-lived UTXO keypair: legacy change that
4584
+ * inherited the key of the note it spent (for example an nk-derived deposit or refund key). Such
4585
+ * a note may be spendable by anyone holding `nk`; an app should offer to migrate it. Only
4586
+ * decidable when the wallet's public key is known, so it is `false` when it was not supplied.
4587
+ */
4588
+ legacyExposed: boolean;
4515
4589
  }
4516
4590
  /** A fresh 96-bit chain-note salt, from the same fail-closed source `transact` uses. */
4517
4591
  declare function randomChangeNoteSalt(): bigint;
@@ -4523,14 +4597,17 @@ declare function randomChangeNoteSalt(): bigint;
4523
4597
  */
4524
4598
  declare function deriveChangeNoteBlinding(viewingKeyNk: Uint8Array, noteSalt: bigint, outputIndex: number): bigint;
4525
4599
  /**
4526
- * Build a change output note whose blinding a cold `(rpc, programId, nk)` scan can re-derive.
4600
+ * Build a change output note whose blinding a scan holding `nk` can re-derive.
4601
+ *
4602
+ * `ownerUtxoKeypair` is the wallet's long-lived UTXO keypair. It is validated (non-zero private key,
4603
+ * public key derived from it), because change must be owned by a key only the wallet holds.
4527
4604
  *
4528
4605
  * Returns the UTXO AND the salt that anchored it. The SAME salt must reach `transact` as
4529
4606
  * `options.chainNoteSalt`, because the chain note is what publishes it — a salt that does not reach
4530
4607
  * the note leaves the change exactly as unrecoverable as before. `partialWithdraw` and `transfer`
4531
4608
  * do this for you; the pairing is only your concern if you call `transact` directly.
4532
4609
  */
4533
- declare function createRecoverableChangeUtxo(amount: bigint, keypair: UtxoKeypair, viewingKeyNk: Uint8Array, mintAddress?: Address, noteSalt?: bigint, outputIndex?: number): Promise<{
4610
+ declare function createRecoverableChangeUtxo(amount: bigint, ownerUtxoKeypair: UtxoKeypair, viewingKeyNk: Uint8Array, mintAddress?: Address, noteSalt?: bigint, outputIndex?: number): Promise<{
4534
4611
  utxo: Utxo;
4535
4612
  noteSalt: bigint;
4536
4613
  }>;
@@ -4552,6 +4629,11 @@ interface MatchChangeNoteParams {
4552
4629
  outputIndex: number;
4553
4630
  /** Output commitments the transaction actually published, hex or field elements. */
4554
4631
  outputCommitments: Array<string | bigint>;
4632
+ /**
4633
+ * The wallet's long-lived UTXO public key. When supplied, a match whose owner differs from it is
4634
+ * flagged `legacyExposed`.
4635
+ */
4636
+ ownerUtxoPublicKey?: bigint;
4555
4637
  }
4556
4638
  /**
4557
4639
  * Decide whether a published commitment is a change note this `nk` can rebuild, and if so return it
@@ -4578,25 +4660,38 @@ declare function matchChangeNote(params: MatchChangeNoteParams): Promise<Recover
4578
4660
  * viewing key and the swap creator's, and found nothing under either.
4579
4661
  *
4580
4662
  * ── The fix, and why it is SDK-only ───────────────────────────────────────────────────────────
4581
- * Derive the refund authorization as a PRF of the owner's `nk` and the swap's own first input
4582
- * nullifier:
4663
+ * The refund leaf's BLINDING is derived as a PRF of the owner's `nk` and the swap's own first input
4664
+ * nullifier, and its OWNER KEY is derived per swap from the wallet's UTXO private key:
4583
4665
  *
4584
- * seed = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0)
4666
+ * blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding") -> field
4667
+ * priv = BLAKE3("cloak_swap_refund_v2" || ownerPrivateKey || nullifier0 || "sk_v2") -> field
4668
+ * pub = derivePublicKey(priv)
4585
4669
  *
4586
- * `nullifier0` is published in the TransactSwap public inputs, so a cold scanner enumerating
4587
- * program transactions can replay this derivation for every swap it sees, recompute R_fb, and
4588
- * match it against the commitment `CloseSwapState` declared. `nk` is secret, so no third party can
4589
- * predict, front-run or link the refund key — the on-chain artefacts are unchanged in shape and
4590
- * every existing binding still holds.
4670
+ * `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk` can replay
4671
+ * the blinding for every swap it sees. `refund_pubkey` and `refund_blinding` are ALSO published, in
4672
+ * plain text, in the TransactSwap instruction data (and in SwapState), so a view-only scanner (nk
4673
+ * plus the owner PUBLIC key) reads the per-swap pubkey from there, checks that the published
4674
+ * blinding equals the nk-derived one, and checks that the commitment matches. Spending R_fb needs
4675
+ * `priv`, which needs the owner's private key: `nk` cannot produce it, so the viewing key stays
4676
+ * view-only, and the owner re-derives the spend key from its own private key plus the nullifier.
4677
+ *
4678
+ * Why not the owner key itself (0.2.6 - 0.2.8)? That shape published the wallet's permanent UTXO
4679
+ * public key as `refund_pubkey` on every swap, so anyone holding a user's receiving key could list
4680
+ * all of that wallet's swaps. A different public key per swap removes the link.
4591
4681
  *
4592
4682
  * This changes NOTHING on chain or in the relay. `refund_pubkey` / `refund_blinding` remain
4593
- * caller-supplied values bound into `computeSwapExtDataHash`; only their provenance changes, from
4594
- * "unrecoverable randomness" to "recoverable randomness".
4683
+ * caller-supplied values bound into `computeSwapExtDataHash`; only their provenance changes.
4684
+ *
4685
+ * ── Three refund shapes, all still recognised ─────────────────────────────────────────────────
4686
+ * "per-swap" (0.2.9+) owner = per-swap key from the owner private key (above)
4687
+ * "owner" (0.2.6 - 0.2.8) owner = the wallet's permanent UTXO keypair; linkable across swaps
4688
+ * "legacy-nk" (< 0.2.6) owner key AND blinding from nk; `legacyExposed: true`, because anyone
4689
+ * holding `nk` can spend it. An app should migrate those refunds.
4690
+ * No API builds a refund in the last two shapes any more.
4595
4691
  *
4596
4692
  * ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
4597
- * [H-04 / DD-01] the derivation is rejected unless publicKey and blinding are both non-zero, and
4598
- * it is unique per swap because `nullifier0` is unique per spend. [L-02] the public key comes from
4599
- * the capacity-tagged `derivePublicKey`, matching `keypair.circom`.
4693
+ * [H-04 / DD-01] the authorization is rejected unless publicKey and blinding are both non-zero.
4694
+ * [L-02] public keys come from the capacity-tagged `derivePublicKey`, matching `keypair.circom`.
4600
4695
  *
4601
4696
  * ── FORWARD-LOOKING ONLY ──────────────────────────────────────────────────────────────────────
4602
4697
  * Everything here — including `discoverSwapRefunds`, the RPC walker at the bottom of this file —
@@ -4613,20 +4708,57 @@ interface SwapRefundAuthorization {
4613
4708
  publicKey: bigint;
4614
4709
  blinding: bigint;
4615
4710
  }
4616
- /** A refund leaf matched back to its owner, ready to spend. */
4711
+ /** Which key shape owns a refund leaf; see the file header. */
4712
+ type SwapRefundShape = "per-swap" | "owner" | "legacy-nk";
4713
+ /** A refund leaf matched back to its owner. */
4617
4714
  interface RecoveredSwapRefund {
4715
+ /**
4716
+ * The key that owns the leaf. `per-swap`: the key derived from the owner private key and the
4717
+ * swap nullifier (`privateKey` is `0n` for a view-only match: the public key is real, but the
4718
+ * spend key needs the owner private key, see {@link deriveSwapRefundKeypair}). `owner`: the
4719
+ * `ownerUtxoKeypair` the matcher was given (`privateKey` `0n` if only the public key was
4720
+ * supplied). `legacy-nk`: the nk-derived keypair, complete and spendable.
4721
+ */
4618
4722
  keypair: UtxoKeypair;
4723
+ /** Which of the three shapes matched. */
4724
+ shape: SwapRefundShape;
4619
4725
  blinding: bigint;
4620
4726
  amount: bigint;
4621
4727
  /** R_fb as a field element, identical to the commitment `CloseSwapState` appended. */
4622
4728
  commitment: bigint;
4729
+ /**
4730
+ * `true` for a legacy refund whose key was derived from `nk`: spendable by anyone holding `nk`,
4731
+ * so an app should offer to move it under the wallet's own key.
4732
+ */
4733
+ legacyExposed: boolean;
4623
4734
  }
4624
4735
  /**
4625
- * Derive a swap's refund authorization from the owner's `nk` and the swap's first input nullifier.
4736
+ * Derive a swap refund leaf's BLINDING from the owner's `nk` and the swap's first input nullifier.
4626
4737
  *
4627
- * Deterministic by design: this is what makes the refund leaf recoverable from key material alone.
4738
+ * Deterministic by design: this is what makes the refund leaf findable from key material. The
4739
+ * blinding is a view secret and cannot spend the leaf.
4740
+ */
4741
+ declare function deriveSwapRefundBlinding(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): bigint;
4742
+ /**
4743
+ * The per-swap refund KEYPAIR: a different key for every swap, derived from the owner's private key
4744
+ * and the swap's first input nullifier. `nk` cannot reproduce it. Use this to spend a refund the
4745
+ * swap result reported, or any `per-swap` refund a view-only scan found.
4746
+ */
4747
+ declare function deriveSwapRefundKeypair(ownerUtxoKeypair: UtxoKeypair, inputNullifier: Uint8Array | bigint): Promise<UtxoKeypair>;
4748
+ /**
4749
+ * The refund authorization `swapUtxo` binds into the swap ext-data hash: a per-swap keypair derived
4750
+ * from the wallet's UTXO private key and the swap's first input nullifier, plus the nk-derived
4751
+ * blinding. The public key differs for every swap and differs from the wallet's UTXO public key.
4752
+ *
4753
+ * `ownerUtxoKeypair` is required and validated. The refund key is never derived from `nk`.
4754
+ */
4755
+ declare function deriveSwapRefundAuthorization(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint, ownerUtxoKeypair: UtxoKeypair): Promise<SwapRefundAuthorization>;
4756
+ /**
4757
+ * LEGACY. The refund authorization of the first derived-refund release, whose private key was
4758
+ * PRF(nk, nullifier0). Exists only so scans can still find and spend those refunds; never bind a new
4759
+ * swap to it, because anyone holding `nk` can spend the leaf.
4628
4760
  */
4629
- declare function deriveSwapRefundAuthorization(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): Promise<SwapRefundAuthorization>;
4761
+ declare function deriveLegacySwapRefundAuthorization(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): Promise<SwapRefundAuthorization>;
4630
4762
  /**
4631
4763
  * R_fb, exactly as `CloseSwapState` computes it. The swap principal is always WSOL-locked, so the
4632
4764
  * mint term is the native-SOL sentinel.
@@ -4641,11 +4773,30 @@ interface MatchSwapRefundLeafParams {
4641
4773
  amountAfterFee: bigint;
4642
4774
  /** R_fb as appended on chain. */
4643
4775
  commitment: bigint | Uint8Array;
4776
+ /**
4777
+ * The wallet's long-lived UTXO keypair (`privateKey: 0n` is fine for a view-only match). Without
4778
+ * it only legacy-nk refunds can be matched.
4779
+ */
4780
+ ownerUtxoKeypair?: UtxoKeypair;
4781
+ /**
4782
+ * `refund_pubkey` as published in the swap's TransactSwap instruction data (bytes 593-624) or its
4783
+ * SwapState. A view-only scanner needs it to match a `per-swap` refund, because it cannot derive
4784
+ * the key. Pass it together with {@link publishedRefundBlinding}.
4785
+ */
4786
+ publishedRefundPubkey?: bigint | Uint8Array;
4787
+ /** `refund_blinding` as published in the same place (bytes 625-656). */
4788
+ publishedRefundBlinding?: bigint | Uint8Array;
4644
4789
  }
4645
4790
  /**
4646
- * Decide whether a public refund leaf belongs to the holder of `viewingKeyNk`, and if so return it
4647
- * in spendable form. Returns `null` for every leaf that is not ours — a scanner runs this against
4648
- * every close it can see.
4791
+ * Decide whether a public refund leaf belongs to this wallet, and if so return it. Returns `null`
4792
+ * for every leaf that is not ours; a scanner runs this against every close it can see.
4793
+ *
4794
+ * Tries, in order: the per-swap shape (published pubkey, or re-derived when the owner private key
4795
+ * is present), the 0.2.6 - 0.2.8 owner-key shape, then the legacy nk shape (`legacyExposed`).
4796
+ * `shape` on the result says which one matched.
4797
+ *
4798
+ * A per-swap match from a view-only scan returns `keypair.privateKey === 0n`; the caller spends it
4799
+ * with {@link deriveSwapRefundKeypair} once it holds the owner private key.
4649
4800
  */
4650
4801
  declare function matchSwapRefundLeaf(params: MatchSwapRefundLeafParams): Promise<RecoveredSwapRefund | null>;
4651
4802
  /** One recovered refund leaf, with the chain coordinates that produced it. */
@@ -4660,6 +4811,15 @@ interface DiscoveredSwapRefund extends RecoveredSwapRefund {
4660
4811
  swapSignature?: string;
4661
4812
  }
4662
4813
  interface DiscoverSwapRefundsOptions {
4814
+ /**
4815
+ * The wallet's long-lived UTXO keypair. Required. Pass the real keypair to get spendable
4816
+ * results (per-swap refunds come back with their derived keypair), or `{ privateKey: 0n,
4817
+ * publicKey }` for a view-only scan: per-swap refunds are then matched from the `refund_pubkey`
4818
+ * published in the swap instruction and come back with `privateKey: 0n` (re-derive it with
4819
+ * `deriveSwapRefundKeypair`). Legacy (nk-owned) refunds are found either way and flagged
4820
+ * `legacyExposed`.
4821
+ */
4822
+ ownerUtxoKeypair: UtxoKeypair;
4663
4823
  /** Maximum program signatures to walk. Omit or 0 to walk the whole history. */
4664
4824
  limit?: number;
4665
4825
  /** Stop when this signature is reached (exclusive) — the cursor from a previous run. */
@@ -4675,16 +4835,18 @@ interface DiscoverSwapRefundsOptions {
4675
4835
  poolMint?: Address;
4676
4836
  }
4677
4837
  /**
4678
- * Find every swap timeout-refund leaf on chain that belongs to the holder of `viewingKeyNk`, and
4679
- * return each in spendable form (`keypair`, `blinding`, `amount`, `commitment`).
4838
+ * Find every swap timeout-refund leaf on chain that belongs to this wallet (`viewingKeyNk` plus
4839
+ * `options.ownerUtxoKeypair`), and return each with `keypair`, `blinding`, `amount`, `commitment`
4840
+ * and `legacyExposed`.
4680
4841
  *
4681
4842
  * Key material only — no relay, no local note store, no prior knowledge of the swap. This is the
4682
4843
  * recovery path for the exact situation VK-02 described: `CloseSwapState` appended a funded leaf and
4683
4844
  * its owner could not see it under any key they held.
4684
4845
  *
4685
- * FORWARD-LOOKING ONLY. This finds refunds whose authorization was DERIVED as PRF(nk, nullifier0).
4686
- * A swap whose refund keypair and blinding were drawn from raw randomness — every swap submitted
4687
- * before that derivation shipped, and any swap built without an `nk` — has no derivation to replay,
4846
+ * FORWARD-LOOKING ONLY. This finds refunds whose blinding was DERIVED from (nk, nullifier0), owned
4847
+ * by a per-swap key (0.2.9+), the wallet UTXO key (0.2.6-0.2.8) or an nk-derived key (legacy, flagged).
4848
+ * A swap whose refund keypair and blinding were drawn from raw randomness (every swap submitted
4849
+ * before that derivation shipped) has no derivation to replay,
4688
4850
  * and no key-only scan can ever recover it. Those secrets existed solely in the caller's in-memory
4689
4851
  * `UtxoSwapResult.refund`. An empty result is therefore NOT proof that a wallet has no stranded
4690
4852
  * refund; it means none of the leaves in the scanned window were derivable from this `nk`.
@@ -4693,7 +4855,7 @@ interface DiscoverSwapRefundsOptions {
4693
4855
  * @param programId Shield-pool program id.
4694
4856
  * @param viewingKeyNk 32-byte `nk` — the same value chain notes are decrypted with.
4695
4857
  */
4696
- declare function discoverSwapRefunds(connection: CloakRpc, programId: Address, viewingKeyNk: Uint8Array, options?: DiscoverSwapRefundsOptions): Promise<DiscoveredSwapRefund[]>;
4858
+ declare function discoverSwapRefunds(connection: CloakRpc, programId: Address, viewingKeyNk: Uint8Array, options: DiscoverSwapRefundsOptions): Promise<DiscoveredSwapRefund[]>;
4697
4859
 
4698
4860
  /**
4699
4861
  * Compact deterministic chain note format.
@@ -4804,12 +4966,17 @@ interface ScanResult {
4804
4966
  */
4805
4967
  deliveredNotes: DeliveredNote[];
4806
4968
  /**
4807
- * This wallet's OWN deposits, rebuilt in SPENDABLE form from `nk` alone (VK-01).
4969
+ * This wallet's OWN deposits, rebuilt from `nk` plus `ownerUtxoPublicKey` (VK-01).
4808
4970
  *
4809
- * `transactions` records that a deposit happened and for how much. These carry the keypair and
4810
- * blinding as well, which is the difference between seeing a note and being able to spend it.
4811
- * Only deposits built with {@link createRecoverableDepositUtxo} appear here; a deposit whose
4812
- * blinding came from raw randomness has nothing to rebuild and shows up as a history row only.
4971
+ * `transactions` records that a deposit happened and for how much. These carry the owner key and
4972
+ * blinding as well. Only deposits built with {@link createRecoverableDepositUtxo} appear here; a
4973
+ * deposit whose blinding came from raw randomness has nothing to rebuild and shows up as a history
4974
+ * row only.
4975
+ *
4976
+ * Current deposits are owned by the wallet's long-lived UTXO keypair and need `ownerUtxoPublicKey`
4977
+ * to be matched; they come back with `keypair.privateKey === 0n` (nk cannot produce it) and
4978
+ * `legacyExposed: false`, so substitute the wallet's own keypair before spending. Legacy deposits
4979
+ * (owner key derived from nk) come back complete and flagged `legacyExposed: true`.
4813
4980
  *
4814
4981
  * Additive, for the same reason as `deliveredNotes`: note secrets are not compliance rows.
4815
4982
  */
@@ -4820,10 +4987,12 @@ interface ScanResult {
4820
4987
  * `partialWithdraw` and `swapWithChange` emit change as output 0, and a v4 chain note carries
4821
4988
  * `outAmount0`/`outPubkey0`, so `nk` plus the derived blinding is everything the note needs.
4822
4989
  *
4823
- * One difference from `recoveredDepositNotes`: a change note's owner key is NOT derived — it is
4824
- * the keypair of the note that was spent, deliberately, so that holding a viewing key never
4825
- * confers spend authority. So `keypair.privateKey` comes back as `0n` and the caller must supply
4826
- * their own before spending. Everything else is complete.
4990
+ * A change note's owner key is never derived from nk: it is the wallet's long-lived UTXO keypair
4991
+ * (or, for legacy change, the key of the note that was spent). So `keypair.privateKey` comes back
4992
+ * as `0n` and the caller supplies its own before spending. Two exceptions, both flagged
4993
+ * `legacyExposed: true`: change owned by a legacy nk-derived deposit key found in the same scan
4994
+ * comes back with that key's private half filled in, and change whose owner is not
4995
+ * `ownerUtxoPublicKey` (when supplied) is flagged so an app can migrate it.
4827
4996
  */
4828
4997
  recoveredChangeNotes: RecoveredChangeNoteRecord[];
4829
4998
  }
@@ -4881,9 +5050,14 @@ interface ScanOptions {
4881
5050
  */
4882
5051
  includeRecipientDeliveries?: boolean;
4883
5052
  /**
4884
- * This wallet's UTXO public key. Supply it to authenticate each delivery carrier's declared
4885
- * commitment (see `ScanRecipientDeliveryOptions.ownerUtxoPublicKey`). Without it the commitment
4886
- * is reported unverified.
5053
+ * This wallet's long-lived UTXO public key. Supply it to:
5054
+ * - match this wallet's own deposits, which are owned by it (without it only legacy, nk-owned
5055
+ * deposits can be recovered into `recoveredDepositNotes`);
5056
+ * - flag legacy change (`legacyExposed`) whose owner is not this key;
5057
+ * - authenticate each delivery carrier's declared commitment (see
5058
+ * `ScanRecipientDeliveryOptions.ownerUtxoPublicKey`); without it the commitment is reported
5059
+ * unverified.
5060
+ * A public key cannot spend anything, so passing it keeps the scan view-only.
4887
5061
  */
4888
5062
  ownerUtxoPublicKey?: bigint;
4889
5063
  /** Candidate pool mints for delivery-carrier commitment verification. Defaults to native SOL. */
@@ -4978,6 +5152,459 @@ declare function toComplianceReport(result: ScanResult): ComplianceReport;
4978
5152
  /** Format compliance report as CSV for export. */
4979
5153
  declare function formatComplianceCsv(report: ComplianceReport): string;
4980
5154
 
5155
+ /**
5156
+ * Note Index v1 transport (contract revision 2): the head and the pages.
5157
+ *
5158
+ * Every request goes through `relayFetch`, the origin-allowlisted egress chokepoint
5159
+ * (`relay/endpoint.ts`), so nothing here can reach a host the build is not pinned to.
5160
+ *
5161
+ * ── Privacy rule ──────────────────────────────────────────────────────────────────────────────
5162
+ * No request here carries anything that points at a specific note, commitment, nullifier, wallet,
5163
+ * pool or time window. Pages are addressed by epoch and page number only, and every page is
5164
+ * downloaded. Trees are rebuilt from the pages themselves, so nothing else is ever requested.
5165
+ *
5166
+ * Caching: complete pages are served `immutable` with a strong ETag and the tail with
5167
+ * `max-age=5`, so a browser's HTTP cache makes a refresh cheap without any client-side store.
5168
+ * Nothing here persists an ETag (the contract forbids persisting a tail ETag). Compression is
5169
+ * negotiated by the fetch implementation; the decoded size is capped while streaming.
5170
+ */
5171
+ /** `GET /note-index/v1/head`. */
5172
+ interface NoteIndexHead {
5173
+ format: 1;
5174
+ /** Random id of this index instance; a rebuild or restore gets a new one. */
5175
+ epoch: bigint;
5176
+ pageSize: number;
5177
+ /** Number of published items. */
5178
+ watermark: number;
5179
+ /** Pages with exactly `pageSize` items; they never change. */
5180
+ completePages: number;
5181
+ /** chain_{completePages}, 64 lowercase hex. */
5182
+ chainTip: string;
5183
+ }
5184
+ /** Transport options shared by every note-index request. */
5185
+ interface NoteIndexFetchOptions {
5186
+ signal?: AbortSignal;
5187
+ /** Per-attempt timeout. Default 30 s. */
5188
+ timeoutMs?: number;
5189
+ /** Retries after the first attempt, for network errors, 429 and 5xx. Default 3. */
5190
+ maxRetries?: number;
5191
+ }
5192
+ /** Fetch and validate `GET /note-index/v1/head`. */
5193
+ declare function fetchNoteIndexHead(relayUrl: string, options?: NoteIndexFetchOptions): Promise<NoteIndexHead>;
5194
+ /**
5195
+ * Fetch the raw bytes of `GET /note-index/v1/e/{epoch}/pages/{n}`, with the decoded size bounded
5196
+ * to {@link NOTE_INDEX_MAX_PAGE_BYTES} while streaming. Parse with
5197
+ * `parseNoteIndexPage(bytes, { epoch, page })`.
5198
+ */
5199
+ declare function fetchNoteIndexPage(relayUrl: string, epoch: bigint, page: number, options?: NoteIndexFetchOptions): Promise<Uint8Array>;
5200
+
5201
+ /** Items per page. A page is complete iff it holds exactly this many items. */
5202
+ declare const NOTE_INDEX_PAGE_SIZE = 1024;
5203
+ /** Leaf index of an all-zero (never appended) commitment. */
5204
+ declare const NOTE_INDEX_NO_LEAF = 18446744073709551615n;
5205
+ /** Thrown for every byte sequence that is not a well-formed Note Index v1 page or head. */
5206
+ declare class NoteIndexFormatError extends Error {
5207
+ constructor(message: string);
5208
+ }
5209
+ /** kind 1: one confirmed Cloak Transact / TransactSwap instruction, with its note if any. */
5210
+ interface NoteIndexTxItem {
5211
+ kind: 1;
5212
+ mint: Uint8Array;
5213
+ slot: bigint;
5214
+ blockPos: number;
5215
+ /** 0 Transact, 1 TransactSwap. */
5216
+ ixTag: number;
5217
+ /** Signed public amount from the public inputs (positive for a deposit). */
5218
+ publicAmount: bigint;
5219
+ nullifier0: Uint8Array;
5220
+ nullifier1: Uint8Array;
5221
+ comm0: Uint8Array;
5222
+ /** {@link NOTE_INDEX_NO_LEAF} iff comm0 is all zero. */
5223
+ leaf0: bigint;
5224
+ comm1: Uint8Array;
5225
+ leaf1: bigint;
5226
+ /** 0 none, 1 inline in the instruction data, 2 CLK1 carrier. */
5227
+ noteSource: number;
5228
+ /** The bare chain-note envelope `[version][AES-GCM ct || tag]`; empty when noteSource is 0. */
5229
+ note: Uint8Array;
5230
+ /** The Cloak program transaction. Relay-supplied metadata, not proof of anything. */
5231
+ signature: Uint8Array;
5232
+ }
5233
+ /** kind 2: a CLKD1 recipient-delivery envelope. */
5234
+ interface NoteIndexDeliveryItem {
5235
+ kind: 2;
5236
+ mint: Uint8Array;
5237
+ slot: bigint;
5238
+ /** output_commitment[0] of the source transaction. */
5239
+ commitment: Uint8Array;
5240
+ leaf: bigint;
5241
+ envelope: Uint8Array;
5242
+ signature: Uint8Array;
5243
+ }
5244
+ /** kind 3: an R_fb swap refund leaf appended by CloseSwapState. */
5245
+ interface NoteIndexSwapRefundItem {
5246
+ kind: 3;
5247
+ /** Always WSOL. */
5248
+ mint: Uint8Array;
5249
+ slot: bigint;
5250
+ commitment: Uint8Array;
5251
+ leaf: bigint;
5252
+ amountAfterFee: bigint;
5253
+ /** The swap's first input nullifier (TransactSwap public inputs +104). */
5254
+ nullifier0: Uint8Array;
5255
+ /** The close transaction. */
5256
+ signature: Uint8Array;
5257
+ }
5258
+ type NoteIndexItem = NoteIndexTxItem | NoteIndexDeliveryItem | NoteIndexSwapRefundItem;
5259
+ interface NoteIndexPage {
5260
+ epoch: bigint;
5261
+ page: bigint;
5262
+ firstSeq: bigint;
5263
+ complete: boolean;
5264
+ /** The item count the header declared, unknown kinds included. */
5265
+ count: number;
5266
+ /** chain_page: the hash chain value BEFORE this page. */
5267
+ prevChain: Uint8Array;
5268
+ /** Items of known kinds, in page order. */
5269
+ items: NoteIndexItem[];
5270
+ /** Raw `kind | body_len | body` bytes of each entry of `items`, same order. */
5271
+ rawItems: Uint8Array[];
5272
+ /** Items of unknown kinds, skipped by `body_len`. */
5273
+ skippedUnknown: number;
5274
+ /**
5275
+ * Position in the page (0-based, unknown and malformed kinds counted) of each entry of `items`,
5276
+ * so `page * NOTE_INDEX_PAGE_SIZE + itemPositions[i]` is the item's real sequence number.
5277
+ */
5278
+ itemPositions: number[];
5279
+ /**
5280
+ * Known-kind items whose body failed that kind's checks and were skipped by `body_len`. Always 0
5281
+ * unless {@link ParseNoteIndexPageOptions.skipMalformedItems} is set (otherwise they throw).
5282
+ */
5283
+ skippedMalformed: number;
5284
+ }
5285
+ /** Options of {@link parseNoteIndexPage}. */
5286
+ interface ParseNoteIndexPageOptions {
5287
+ /**
5288
+ * Skip (and count in `skippedMalformed`) a known-kind item whose body fails that kind's checks,
5289
+ * instead of refusing the whole page. Only the BODY is forgiven: the page header, the item
5290
+ * framing (`kind | body_len` inside the page, no truncation, no trailing bytes) and the hash
5291
+ * chain stay strict, so a skipped item is exactly a hidden item, which an untrusted relay can
5292
+ * already do. `recoverNotesFromIndex` sets it, so that one bad entry cannot abort every
5293
+ * wallet's restore.
5294
+ */
5295
+ skipMalformedItems?: boolean;
5296
+ }
5297
+ /** Input to {@link encodeNoteIndexPage}. */
5298
+ interface EncodeNoteIndexPageParams {
5299
+ epoch: bigint | number;
5300
+ page: bigint | number;
5301
+ firstSeq: bigint | number;
5302
+ complete: boolean;
5303
+ prevChain: Uint8Array;
5304
+ items: NoteIndexItem[];
5305
+ }
5306
+ /**
5307
+ * Parse one page, strictly. Throws {@link NoteIndexFormatError} on anything that is not exactly a
5308
+ * Note Index v1 page: wrong magic/version, unknown flag bits, non-zero reserved bytes, a count over
5309
+ * 1024, a complete page whose count is not 1024, first_seq that is not page * 1024, an epoch or page
5310
+ * other than `expect`, an item whose body_len differs from the exact length of its kind, a note
5311
+ * whose version disagrees with its length, an out-of-range ix_tag / note_source, a refund whose mint
5312
+ * is not WSOL, an unknown kind longer than 1024 bytes, a truncated item, or trailing bytes.
5313
+ *
5314
+ * With `options.skipMalformedItems`, an item whose body alone is at fault (its framing inside the
5315
+ * page is intact) is skipped and counted in `skippedMalformed` instead; everything else above
5316
+ * still throws.
5317
+ */
5318
+ declare function parseNoteIndexPage(bytes: Uint8Array, expect?: {
5319
+ epoch: bigint;
5320
+ page: number;
5321
+ }, options?: ParseNoteIndexPageOptions): NoteIndexPage;
5322
+ /**
5323
+ * Parse ONE raw item (`kind | body_len | body`), as kept in `NoteIndexPage.rawItems` and in a
5324
+ * persisted cursor. Same strictness as the page parser; unknown kinds are an error here.
5325
+ */
5326
+ declare function parseNoteIndexItem(raw: Uint8Array): NoteIndexItem;
5327
+ /** chain_{n+1} = sha256(chain_n || items bytes of page n), for a COMPLETE page's raw bytes. */
5328
+ declare function computeNoteIndexChain(prevChain: Uint8Array, pageBytes: Uint8Array): Uint8Array;
5329
+ /** Encode one item as `kind | body_len | body`. */
5330
+ declare function encodeNoteIndexItem(item: NoteIndexItem): Uint8Array;
5331
+ /**
5332
+ * Encode a page exactly as the relay serves it. The relay is the producer; this exists so both
5333
+ * sides pin the same golden vector and so tests can serve real pages from a stub.
5334
+ */
5335
+ declare function encodeNoteIndexPage(params: EncodeNoteIndexPageParams): Uint8Array;
5336
+
5337
+ /**
5338
+ * Restore a wallet's notes from the relay's Note Index v1 (contract revision 2.1), without walking
5339
+ * the chain and without telling anyone which notes, pools or nullifiers are its own.
5340
+ *
5341
+ * ── What this replaces ────────────────────────────────────────────────────────────────────────
5342
+ * `scanTransactions` enumerates the program's whole signature history and fetches every
5343
+ * transaction over RPC (thousands of paid calls, minutes). The relay indexes every confirmed Cloak
5344
+ * transaction once and serves all of it in bulk; this downloads every page, decrypts and matches
5345
+ * locally, rebuilds every listed pool's commitment tree from the index's own leaf stream, and spends
5346
+ * exactly ONE RPC request: a `getMultipleAccounts` of every listed pool's tree account, to check the
5347
+ * rebuilt trees. Spent status comes from the nullifiers in the index, so no nullifier of the user
5348
+ * reaches the relay or the RPC.
5349
+ *
5350
+ * ── Trust model (every byte from the relay is untrusted) ──────────────────────────────────────
5351
+ * A note is returned only when all of these hold:
5352
+ * (a) it decrypts / opens under the caller's own keys;
5353
+ * (b) the commitment recomputed from the decrypted values and an owner public key equals the
5354
+ * item's commitment, that owner key is the caller's `ownerUtxoKeypair.publicKey` (or a legacy
5355
+ * key this same recovery derived from nk), and derivePublicKey(privateKey) === publicKey for
5356
+ * the keypair returned. A relay cannot plant a note under somebody else's key and have it
5357
+ * counted as balance (the R2 fake-balance fix: `matchChangeNote` accepts any `outPubkey0`,
5358
+ * so the index path refuses every owner that is not the caller's);
5359
+ * (c) the commitment sits at the item's leaf in the tree rebuilt from the index's leaf stream,
5360
+ * and that leaf lies in a prefix of the stream the chain's tree account authenticates: the
5361
+ * whole stream when its root is the account's current root or one in its root history, or
5362
+ * the leaves under a COMPLETE node the account still stores in its frontier (`subtrees`,
5363
+ * see `readTreeAccountFrontier`), which keeps old notes verifiable when a busy pool has
5364
+ * moved more than the 100-root history past the index. Unverifiable candidates are counted
5365
+ * in `pending`, never returned, and carried in the cursor until they verify.
5366
+ * A lying relay can hide items. It cannot inject a note, alter one, or point one at a wrong leaf.
5367
+ * A HIDDEN nullifier makes a spent note look unspent; the spend-time `preflightNullifiers` in every
5368
+ * spend entry point is what catches that, and it stays mandatory.
5369
+ *
5370
+ * What is NOT checked: the proof-bound `chainNoteHash`. An index item does not carry it (nor the
5371
+ * `extDataHash` its preimage needs), and fetching either per transaction would break the one-RPC
5372
+ * budget. It is not needed for (a) to (c): the chain note is AES-GCM under a key HKDF'd from nk
5373
+ * with the item's own `comm0` as salt (`comm1` for a v2 note), so a note written for one
5374
+ * transaction never opens when the relay attaches it to another (a mispaired CLK1 carrier), for its
5375
+ * real owner or anyone else, and whatever does open (a note crafted for the transaction it sits
5376
+ * on, say under a public legacy key) is still held to (b) and (c). The item's other public fields (`publicAmount`,
5377
+ * the nullifiers) feed only derivations whose result must reproduce a published commitment, so a
5378
+ * wrong value there can only make a note fail to match. The cost of a mispairing is therefore
5379
+ * hidden notes (the memo's real owner's, and the paired source's own), never a wrong note, and no
5380
+ * client-side check can recover them: only the relay can pair correctly.
5381
+ *
5382
+ * ── One bad entry never aborts a run ──────────────────────────────────────────────────────────
5383
+ * The index carries what anyone can put on chain, and a legacy viewing key may be public, so a
5384
+ * stranger can write a note that opens for a wallet. An item whose body is malformed (framing
5385
+ * intact), or whose opened contents make a matcher throw, is skipped and counted in
5386
+ * `stats.skipped`, exactly as if it were not this wallet's. Only page-level faults (header,
5387
+ * framing, hash chain, head) still fail the run, since they are not one entry's.
5388
+ *
5389
+ * ── The cursor never depends on what the wallet owns (contract property 1) ────────────────────
5390
+ * Every run downloads from the persisted cursor page, so that page must be a function of public
5391
+ * data only. It is always `floor(complete_pages / 8) * 8` of the head this run saw (or the previous
5392
+ * page when a public condition holds it: more out-of-order leaves than the cursor may carry). It is
5393
+ * NEVER held back by this wallet's candidates: a candidate that cannot be verified yet travels
5394
+ * INSIDE the cursor instead (its raw item bytes, plus the stream's own value at its leaf, which is
5395
+ * exactly the value the client hashed into its frontier), bounded by `MAX_CARRIED_PENDING`, so a
5396
+ * later run can verify it without re-reading the pages it came from. A full re-sync from page 0 is
5397
+ * likewise only ever triggered by public conditions (an epoch change, a broken hash chain, a later
5398
+ * item that rewrites or fills the tree before the cursor, a rebuilt tree the chain disproves), never
5399
+ * by anything about this wallet's own items, so the request pattern of two wallets with the same
5400
+ * cursor is identical.
5401
+ *
5402
+ * ── Legacy (nk-derived owner keys) ────────────────────────────────────────────────────────────
5403
+ * Notes whose owner key older releases derived from nk are spendable by anyone holding nk. They are
5404
+ * returned in `atRisk`, never in `notes`, so an app can migrate them without counting them as
5405
+ * balance.
5406
+ *
5407
+ * Some older clients also encrypted their chain notes under a viewing key that is not the wallet's
5408
+ * canonical nk (mobile used SHA-512 of the public wallet address, or the embedded wallet's nsk).
5409
+ * Pass those as `legacyViewingKeyNks` to find such notes in the same download, at no extra request:
5410
+ * every item is trial-opened under the canonical nk first, then under each legacy key. A legacy key
5411
+ * only ever FINDS notes. Everything that opened only under one is returned in `atRisk`, whatever
5412
+ * its owner key (a legacy key may be public, so the relay and anyone else can read those notes), it
5413
+ * never opens a recipient delivery (the delivery rail never used one), and nothing a legacy key opens
5414
+ * can enter `notes`. A note of this wallet's that spends a legacy note and is encrypted under the
5415
+ * canonical nk (a migration) is matched normally and lands in `notes`.
5416
+ *
5417
+ * ── Refund leaves ─────────────────────────────────────────────────────────────────────────────
5418
+ * CloseSwapState appends R_fb to the WSOL MAIN tree (`["merkle_tree", WSOL]`; the separate refund
5419
+ * tree belonged to the retired ClaimRefund design and the program rejects it). So SWAP_REFUND
5420
+ * leaves are part of the WSOL leaf stream here, interleaved with TX leaves. Treating them as a
5421
+ * separate tree would leave a gap at every refund leaf and the WSOL root could never verify.
5422
+ */
5423
+
5424
+ type IndexedRecoveredNoteKind = "deposit" | "change" | "received" | "swap_refund";
5425
+ /** A verified note restored from the index. */
5426
+ interface IndexedRecoveredNote {
5427
+ kind: IndexedRecoveredNoteKind;
5428
+ /**
5429
+ * Ready to spend: `keypair` has the real private key, plus `blinding`, `amount`, `mintAddress`,
5430
+ * `index` (leaf, verified against the on-chain tree) and `commitment`.
5431
+ */
5432
+ utxo: Utxo;
5433
+ /** Base58 signature the relay attached. Metadata only, NOT proof of payment. */
5434
+ signature: string;
5435
+ /**
5436
+ * `true` for every `atRisk` note (owner key derivable from nk, or found through a legacy viewing
5437
+ * key), `false` for `notes`.
5438
+ */
5439
+ legacyExposed: boolean;
5440
+ }
5441
+ /**
5442
+ * The persisted resume point. JSON-serializable and holds NO key material, but `own` records which
5443
+ * index items are this wallet's, so store it as privately as the notes themselves, and never hand
5444
+ * one wallet's cursor to another wallet.
5445
+ *
5446
+ * Version 2. Any other version (including the v1 cursor of the first release), or anything that
5447
+ * fails validation, is ignored with a warning and the run re-syncs from page 0.
5448
+ */
5449
+ interface NoteIndexCursor {
5450
+ v: 2;
5451
+ /** Index epoch (u64, decimal). A different epoch at the relay means a full re-sync. */
5452
+ epoch: string;
5453
+ /**
5454
+ * First page the next run downloads: `floor(complete_pages / 8) * 8` of a head this wallet saw.
5455
+ * Public data only; it never depends on which items are this wallet's.
5456
+ */
5457
+ page: number;
5458
+ /** chain_page, 64 hex. */
5459
+ chain: string;
5460
+ /** Highest watermark seen in this epoch; a lower one is refused (`NoteIndexHeadBehindError`). */
5461
+ watermark: number;
5462
+ /** Items below this seq were covered by a pass from page 0; only later items can trigger one. */
5463
+ fullPassSeq: number;
5464
+ /** Per listed pool mint: its leaf stream as rebuilt from every page before `page`. Public data. */
5465
+ trees: Record<string, {
5466
+ frontier: MerkleFrontierState;
5467
+ /** Leaves past a gap, `[leaf, 64 hex]`, waiting for the gap to fill. */
5468
+ pending: Array<[number, string]>;
5469
+ /** Values (64 hex each, concatenated) of the leaves right below `frontier.nextIndex`. */
5470
+ window: string;
5471
+ /** Leaves `[0, verified)` were authenticated against the chain. */
5472
+ verified: number;
5473
+ /** `[leaf, 64 hex]` corrections the chain accepted over the first item for that leaf. */
5474
+ overrides: Array<[number, string]>;
5475
+ /** The chain disproved this stream and a pass from page 0 did not fix it. */
5476
+ mismatch: boolean;
5477
+ }>;
5478
+ /** This wallet's state. Private. */
5479
+ own: {
5480
+ /** Raw items (hex) from pages before `page` that hold a verified or a carried pending note. */
5481
+ items: Array<{
5482
+ seq: number;
5483
+ item: string;
5484
+ }>;
5485
+ /** `mint:leaf:commitmentHex` of every note that verified. */
5486
+ verified: string[];
5487
+ /** Nullifiers (hex) already seen spending one of this wallet's notes. */
5488
+ spent: string[];
5489
+ /** `[mint, leaf, 64 hex]`: the stream's value at each carried pending note's leaf. */
5490
+ pendingLeaves: Array<[string, number, string]>;
5491
+ /** Identities (32 hex) of items rejected for good. */
5492
+ rejected: string[];
5493
+ };
5494
+ }
5495
+ interface RecoverNotesFromIndexParams {
5496
+ /** Relay base URL. Must be on this build's origin allowlist. */
5497
+ relayUrl: string;
5498
+ /** Used for exactly one request: a `getMultipleAccounts` of every listed pool's tree account. */
5499
+ connection: CloakRpc;
5500
+ programId: Address;
5501
+ /** Every active pool mint. Trees are rebuilt and checked for ALL of them, not only where notes are. */
5502
+ poolMints: Address[];
5503
+ /** The wallet's 32-byte viewing base. */
5504
+ viewingKeyNk: Uint8Array;
5505
+ /**
5506
+ * Other 32-byte viewing keys older clients of this wallet encrypted chain notes under (at most
5507
+ * 8). Scan only: every note found through one is returned in `atRisk`, never in `notes`, and a
5508
+ * legacy key never opens a recipient delivery. Costs local trial decryptions, no extra request.
5509
+ * Entries equal to `viewingKeyNk` are ignored.
5510
+ */
5511
+ legacyViewingKeyNks?: Uint8Array[];
5512
+ /** The wallet's long-lived UTXO keypair, with its real private key. */
5513
+ ownerUtxoKeypair: UtxoKeypair;
5514
+ /** The `cursor` of the previous run. Omit for a full sync. */
5515
+ cursor?: NoteIndexCursor;
5516
+ /** Per mint: ignore legacy-shaped (nk-owned) notes at or after this leaf (a release cutoff). */
5517
+ legacyCutoffLeaf?: Record<string, bigint>;
5518
+ /** Pages in flight. Default 6. */
5519
+ concurrency?: number;
5520
+ onProgress?: (p: {
5521
+ pagesDone: number;
5522
+ pagesTotal: number;
5523
+ itemsChecked: number;
5524
+ notesFound: number;
5525
+ }) => void;
5526
+ signal?: AbortSignal;
5527
+ }
5528
+ interface NoteIndexRecoveryStats {
5529
+ /** Pages downloaded and parsed. */
5530
+ pages: number;
5531
+ /** Items checked (known kinds). */
5532
+ items: number;
5533
+ /** Bytes downloaded (decoded). */
5534
+ bytes: number;
5535
+ /** RPC requests sent through `connection`. */
5536
+ rpcCalls: number;
5537
+ ms: number;
5538
+ /**
5539
+ * Candidates rejected for good: commitment not reproducible from the opened values, not at the
5540
+ * declared leaf of the verified tree, a duplicate (mint, leaf), a legacy note past the cutoff, a
5541
+ * keypair that failed the derivePublicKey check, or an item already rejected by an earlier run.
5542
+ */
5543
+ dropped: number;
5544
+ /** Items that opened under this wallet's keys. */
5545
+ decrypted: number;
5546
+ /** Matched candidates before the tree and spent checks. */
5547
+ candidates: number;
5548
+ /** Verified notes whose nullifier the index shows as spent. */
5549
+ spent: number;
5550
+ /** Leaves two items assigned different commitments to. */
5551
+ conflicts: number;
5552
+ /** Pending candidates over the carry limit, not carried to the next run. */
5553
+ pendingDropped: number;
5554
+ /**
5555
+ * Index entries skipped instead of failing the run (each one is treated as not this wallet's):
5556
+ * an item whose body fails its kind's format checks while its framing in the page is intact, and
5557
+ * an item that opened under this wallet's keys but whose contents no derivation accepts (a chain
5558
+ * note salt of 0 or over 96 bits, or anything else that throws while it is matched). Anyone who
5559
+ * can read a legacy viewing key can write such a note, so none of this may abort a restore.
5560
+ */
5561
+ skipped: number;
5562
+ }
5563
+ interface RecoverNotesFromIndexResult {
5564
+ /** Verified, unspent, owned by `ownerUtxoKeypair`; deduped by (mint, leaf). */
5565
+ notes: IndexedRecoveredNote[];
5566
+ /**
5567
+ * Verified, unspent, and either owned by an nk-derived legacy key (spendable by nk holders) or
5568
+ * found only through a `legacyViewingKeyNks` entry (readable by whoever holds that key). Migrate.
5569
+ */
5570
+ atRisk: IndexedRecoveredNote[];
5571
+ /**
5572
+ * Candidates not verifiable yet (tree or root not caught up). Carried in the cursor. It depends on
5573
+ * what this wallet owns (a relay can make it non-zero for the owner of one item), so never let it
5574
+ * decide whether or what to download: gate polls on the public head (epoch, watermark) alone.
5575
+ */
5576
+ pending: number;
5577
+ /** Persist and pass back as `cursor`. */
5578
+ cursor: NoteIndexCursor;
5579
+ stats: NoteIndexRecoveryStats;
5580
+ /** Non-fatal events, e.g. a re-sync from page 0. Generic text: never a key, a mint or a note. */
5581
+ warnings: string[];
5582
+ }
5583
+ /**
5584
+ * The relay's head is behind a watermark this cursor already saw in the same epoch: a cached head
5585
+ * from a stale CDN edge, or a rollback. Nothing was discarded; retry later with the SAME cursor.
5586
+ * If it persists, the index was rolled back without a new epoch (a relay bug): only then drop the
5587
+ * cursor to re-sync from page 0.
5588
+ */
5589
+ declare class NoteIndexHeadBehindError extends Error {
5590
+ readonly cursorWatermark: number;
5591
+ readonly headWatermark: number;
5592
+ readonly retryable: true;
5593
+ constructor(cursorWatermark: number, headWatermark: number);
5594
+ }
5595
+ /**
5596
+ * Restore every verified, unspent note this wallet owns from the relay's note index.
5597
+ *
5598
+ * Downloads every page from the cursor (or page 0), opens each item locally, rebuilds every listed
5599
+ * pool's tree from the index's leaf stream, checks the trees with ONE `getMultipleAccounts`, and
5600
+ * computes spent status from the index's nullifiers. Persist the returned `cursor`; the next run
5601
+ * re-downloads from it, so dedupe against held notes by (mint, leaf).
5602
+ *
5603
+ * Throws `NoteIndexHeadBehindError` (retryable, nothing discarded) when the relay's head is behind
5604
+ * the cursor. An unusable cursor is never an exception: it is ignored with a warning.
5605
+ */
5606
+ declare function recoverNotesFromIndex(params: RecoverNotesFromIndexParams): Promise<RecoverNotesFromIndexResult>;
5607
+
4981
5608
  /**
4982
5609
  * Automatic UTXO Wallet Manager
4983
5610
  *
@@ -5354,12 +5981,27 @@ declare function fundReceiverViaPaymaster(relayUrl: string, receiver: KeyPairSig
5354
5981
  /**
5355
5982
  * Deriving a bridge receiving address.
5356
5983
  *
5357
- * One single-use address per deposit, from the wallet's own key material. Deterministic, offline,
5358
- * and stateless — which is what lets every other function here work on a device that has never
5359
- * seen this deposit before.
5984
+ * One single-use address per deposit, from the wallet's own SPEND-level key material.
5985
+ * Deterministic, offline, and stateless, which is what lets every other function here work on a
5986
+ * device that has never seen this deposit before.
5987
+ *
5988
+ * The receiver is a full Solana signer and bridged funds sit at it in transit, so it must not be
5989
+ * derivable from the viewing key `nk` (which is registered with the relay and may be shared). It is
5990
+ * derived from the wallet's long-lived UTXO private key:
5991
+ *
5992
+ * key = BLAKE3("cloak_bridge_receiver_key_v2" || utxoPrivateKey(32B BE))
5993
+ * seed = HMAC-SHA512(key, "cloak_bridge_escrow_v2:<index>")[0..32]
5994
+ * receiver = ed25519 signer from seed
5995
+ *
5996
+ * Receivers from the first release were HMAC-SHA512(nk, "cloak_bridge_escrow:<index>"). They are
5997
+ * still derived by {@link deriveLegacyBridgeReceiver} so discovery can find in-flight legacy
5998
+ * deposits and finish them; no new deposit is ever routed to one.
5360
5999
  */
5361
6000
 
6001
+ /** LEGACY label: receivers derived from the viewing key `nk`. Discovery only. */
5362
6002
  declare const BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
6003
+ /** Current label: receivers derived from the wallet's spend-level key material. */
6004
+ declare const BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
5363
6005
  /**
5364
6006
  * The index MUST be a small sequential counter (0, 1, 2, …), never a timestamp.
5365
6007
  *
@@ -5377,12 +6019,21 @@ declare const BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
5377
6019
  */
5378
6020
  declare const MAX_RECEIVER_INDEX = 10000;
5379
6021
  /**
6022
+ * Derive the bridge receiving address for `index` from the wallet's long-lived UTXO keypair.
6023
+ *
5380
6024
  * Async because kit derives a signer's public key through WebCrypto's non-extractable ed25519 key
5381
- * import (`signerFromSecretKey`, `solana/signer.ts`) — there is no synchronous path to a kit
5382
- * `KeyPairSigner`. `Keypair.fromSeed(seed)` and `signerFromSecretKey(seed)` (32-byte seed form)
5383
- * derive the identical public key from identical seed bytes; only the sync/async boundary moved.
6025
+ * import (`signerFromSecretKey`, `solana/signer.ts`); there is no synchronous path to a kit
6026
+ * `KeyPairSigner`.
6027
+ */
6028
+ declare function deriveBridgeReceiver(ownerUtxoKeypair: UtxoKeypair, index: number): Promise<KeyPairSigner>;
6029
+ /**
6030
+ * LEGACY. The receiving address the first bridge release derived from the viewing key `nk`.
6031
+ *
6032
+ * Exists only so discovery can find, finish and clean up deposits that were routed to these
6033
+ * addresses before the fix. Never quote or route a new deposit to one: anyone holding `nk` can sign
6034
+ * for it.
5384
6035
  */
5385
- declare function deriveBridgeReceiver(nk: Uint8Array | Buffer, index: number): Promise<KeyPairSigner>;
6036
+ declare function deriveLegacyBridgeReceiver(nk: Uint8Array | Buffer, index: number): Promise<KeyPairSigner>;
5386
6037
 
5387
6038
  type BridgeDepositState =
5388
6039
  /** Nothing ever happened at this index. */
@@ -5427,6 +6078,16 @@ interface BridgeDeposit {
5427
6078
  shieldSignatures?: string[];
5428
6079
  /** Set only when state is "unknown": the failure that made this index's status unconfirmable. */
5429
6080
  error?: string;
6081
+ /**
6082
+ * `true` when the receiver is a LEGACY address derived from a viewing key `nk` (the first bridge
6083
+ * release). Anyone holding that `nk` can sign for it, so funds still sitting there should be
6084
+ * shielded promptly. Re-derive its signer with `deriveLegacyBridgeReceiver(legacyViewingKeyNk,
6085
+ * index)`. Legacy indices are a separate address space from current ones, so they never count
6086
+ * toward the next free current index.
6087
+ */
6088
+ legacyExposed: boolean;
6089
+ /** For a legacy entry: the `nk` its receiver was derived from. */
6090
+ legacyViewingKeyNk?: Uint8Array;
5430
6091
  }
5431
6092
  interface DiscoverOptions {
5432
6093
  /**
@@ -5450,6 +6111,14 @@ interface DiscoverOptions {
5450
6111
  stopAfterUnused?: number;
5451
6112
  programId: Address;
5452
6113
  mint: Address;
6114
+ /**
6115
+ * Also scan the LEGACY nk-derived receivers, so deposits routed to them before the fix are still
6116
+ * found (flagged `legacyExposed`). Default true. The canonical `nk` of `ownerUtxoKeypair` is always
6117
+ * included; add any other viewing keys the wallet has used in `legacyViewingKeyNks`.
6118
+ */
6119
+ includeLegacy?: boolean;
6120
+ /** Extra viewing keys whose legacy receivers should be scanned (deduplicated). */
6121
+ legacyViewingKeyNks?: Uint8Array[];
5453
6122
  }
5454
6123
  /**
5455
6124
  * A terminal state needs TWO conjuncts, never one.
@@ -5460,7 +6129,7 @@ interface DiscoverOptions {
5460
6129
  * Completion therefore requires the shield-pool transaction to be present in the receiver's own
5461
6130
  * history as well.
5462
6131
  */
5463
- declare function listBridgeDeposits(rpc: CloakRpc, nk: Uint8Array | Buffer, opts: DiscoverOptions): Promise<BridgeDeposit[]>;
6132
+ declare function listBridgeDeposits(rpc: CloakRpc, ownerUtxoKeypair: UtxoKeypair, opts: DiscoverOptions): Promise<BridgeDeposit[]>;
5464
6133
 
5465
6134
  interface DepositOutcome {
5466
6135
  signature: string;
@@ -5789,4 +6458,4 @@ declare const VERSION = "0.2.6";
5789
6458
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
5790
6459
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
5791
6460
 
5792
- export { BRIDGE_ESCROW_LABEL, 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, 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 EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, 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, type Network, type NoteData, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, 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 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 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, 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, deriveDepositNoteSecrets, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, 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, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, 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 };
6461
+ 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 SwapRefundShape, 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, deriveSwapRefundKeypair, 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, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, 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 };