@cloak.dev/sdk 0.2.5 → 0.2.6-staging.af2dfc0

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.ts 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
@@ -3431,6 +3439,20 @@ interface TransactOptions {
3431
3439
  * passing nk at every call site — e.g. pass a getter from your key manager.
3432
3440
  */
3433
3441
  getChainNoteViewingKeyNk?: () => Promise<string | Uint8Array | null>;
3442
+ /**
3443
+ * The wallet's long-lived UTXO keypair (`deriveUtxoKeypairFromSpendKey(skSpend)`).
3444
+ *
3445
+ * It OWNS every self-owned note a flow creates: change, merges, send-to-self outputs and swap
3446
+ * refund leaves. The SDK never takes that owner from an input or output note, because a note's
3447
+ * own key may be a legacy key derived from the viewing key `nk`, and `nk` must only ever VIEW.
3448
+ *
3449
+ * When no explicit `chainNoteViewingKeyNk` / `getChainNoteViewingKeyNk` is given, the canonical
3450
+ * `nk` is derived from it (`getNkFromUtxoPrivateKey(privateKey)`).
3451
+ *
3452
+ * Required by `transfer`, `partialWithdraw`, `fullWithdraw`, `swapUtxo` and `swapWithChange`
3453
+ * (see {@link SpendOptions}). Optional for `transact`, which then requires an explicit `nk`.
3454
+ */
3455
+ ownerUtxoKeypair?: UtxoKeypair;
3434
3456
  /**
3435
3457
  * Pin the chain note's 96-bit `noteSalt` instead of drawing a fresh one (VK-01).
3436
3458
  *
@@ -3558,7 +3580,38 @@ interface TransactOptions {
3558
3580
  * relay does not authenticate this way.
3559
3581
  */
3560
3582
  relayAuthBatch?: RelayBatchAuthItemHandle;
3583
+ /**
3584
+ * Referral code attached to fee-bearing relay requests (SDK-001).
3585
+ *
3586
+ * Sent as `affiliate_code`, and signed inside the relay request, only when it is a non-empty
3587
+ * string AND the request is fee-bearing: a withdrawal / send to a public address
3588
+ * (`externalAmount < 0` with a recipient) or a swap intake. Deposits and shield-to-shield sends
3589
+ * never carry it, whatever is passed here. Omitted, every request is byte-identical to one built
3590
+ * without this option (INV-007). Requires a relay that accepts `affiliate_code`.
3591
+ *
3592
+ * @internal For Cloak's own web and mobile apps. Not part of the public API, not documented, and
3593
+ * may change without notice.
3594
+ */
3595
+ affiliateCode?: string;
3596
+ /**
3597
+ * Extra HTTP headers sent with this flow's relay submissions (`POST /transact` and
3598
+ * `POST /transact_swap`), e.g. `{ "X-Cloak-Client": "cloak-mobile/ios/1.4.0" }` (SDK-004).
3599
+ * They never replace a header the SDK sets itself; malformed entries are dropped. Omitted, the
3600
+ * requests are exactly what they were.
3601
+ *
3602
+ * @internal For Cloak's own mobile app. Not part of the public API, and a browser caller should
3603
+ * not set it: a non-safelisted header makes every submission a CORS preflight.
3604
+ */
3605
+ relayHeaders?: Record<string, string>;
3561
3606
  }
3607
+ /**
3608
+ * Options for the spend flows that create self-owned notes (`transfer`, `partialWithdraw`,
3609
+ * `fullWithdraw`, `swapUtxo`, `swapWithChange`): {@link TransactOptions} with the wallet's
3610
+ * long-lived UTXO keypair made mandatory.
3611
+ */
3612
+ type SpendOptions = TransactOptions & {
3613
+ ownerUtxoKeypair: UtxoKeypair;
3614
+ };
3562
3615
  /**
3563
3616
  * Switchboard-style response: a pre-built instruction.
3564
3617
  *
@@ -3611,6 +3664,13 @@ interface TransactRequestBodyParams {
3611
3664
  externalAmount: bigint;
3612
3665
  /** Base64 CLKD1 envelopes, from `buildRecipientDeliveryNotes`. Omitted when the rail is off. */
3613
3666
  recipientDeliveryNotes?: string[];
3667
+ /**
3668
+ * `TransactOptions.affiliateCode`. Only a withdrawal (`externalAmount < 0` with a recipient)
3669
+ * carries it; for any other shape it is ignored.
3670
+ *
3671
+ * @internal
3672
+ */
3673
+ affiliateCode?: string;
3614
3674
  }
3615
3675
  /**
3616
3676
  * Assemble the `/transact` body.
@@ -3676,6 +3736,13 @@ interface SubmitTransactToRelayArgs {
3676
3736
  requestTimeoutMs?: number;
3677
3737
  /** Injection seam for tests; defaults to global fetch. */
3678
3738
  fetchImpl?: typeof fetch;
3739
+ /**
3740
+ * Extra headers for the `/transact` POST, e.g. the mobile app's `X-Cloak-Client` (SDK-004).
3741
+ * Never replace `Content-Type`; omitted, the request headers are exactly what they were.
3742
+ *
3743
+ * @internal
3744
+ */
3745
+ extraHeaders?: Record<string, string>;
3679
3746
  onProgress?: (status: string) => void;
3680
3747
  /** Total window allowed for the on-chain settlement check after a reported success. */
3681
3748
  settlementTimeoutMs?: number;
@@ -3718,24 +3785,31 @@ declare function transact(params: TransactParams, options: TransactOptions): Pro
3718
3785
  * Transfers funds from your UTXOs to another recipient's public key,
3719
3786
  * keeping everything within the shielded pool.
3720
3787
  *
3788
+ * Change (and a send to yourself) is owned by `options.ownerUtxoKeypair`, the wallet's long-lived
3789
+ * UTXO keypair, never by `inputUtxos[0]`'s key. The chain note is encrypted under the wallet's nk
3790
+ * (explicit, or the canonical nk of `ownerUtxoKeypair`).
3791
+ *
3721
3792
  * @param inputUtxos Your UTXOs to spend
3722
3793
  * @param recipientPubkey Recipient's UTXO public key
3723
3794
  * @param amount Amount to transfer
3724
- * @param options Transaction options
3795
+ * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3725
3796
  */
3726
- declare function transfer(inputUtxos: Utxo[], recipientPubkey: bigint, amount: bigint, options: TransactOptions): Promise<TransactResult>;
3797
+ declare function transfer(inputUtxos: Utxo[], recipientPubkey: bigint, amount: bigint, options: SpendOptions): Promise<TransactResult>;
3727
3798
  /**
3728
3799
  * Execute a partial withdrawal
3729
3800
  *
3730
3801
  * Withdraws a portion of funds to an external Solana address,
3731
3802
  * keeping the remainder shielded.
3732
3803
  *
3804
+ * The change note (and any consolidation merge) is owned by `options.ownerUtxoKeypair`, the
3805
+ * wallet's long-lived UTXO keypair, never by `inputUtxos[0]`'s key.
3806
+ *
3733
3807
  * @param inputUtxos Your UTXOs to spend
3734
3808
  * @param recipient External Solana address
3735
3809
  * @param withdrawAmount Amount to withdraw
3736
- * @param options Transaction options
3810
+ * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3737
3811
  */
3738
- declare function partialWithdraw(inputUtxos: Utxo[], recipient: Address, withdrawAmount: bigint, options: TransactOptions): Promise<TransactResult>;
3812
+ declare function partialWithdraw(inputUtxos: Utxo[], recipient: Address, withdrawAmount: bigint, options: SpendOptions): Promise<TransactResult>;
3739
3813
  /**
3740
3814
  * Execute a full withdrawal
3741
3815
  *
@@ -3743,9 +3817,9 @@ declare function partialWithdraw(inputUtxos: Utxo[], recipient: Address, withdra
3743
3817
  *
3744
3818
  * @param inputUtxos Your UTXOs to spend
3745
3819
  * @param recipient External Solana address
3746
- * @param options Transaction options
3820
+ * @param options Transaction options, including the mandatory `ownerUtxoKeypair`
3747
3821
  */
3748
- declare function fullWithdraw(inputUtxos: Utxo[], recipient: Address, options: TransactOptions): Promise<TransactResult>;
3822
+ declare function fullWithdraw(inputUtxos: Utxo[], recipient: Address, options: SpendOptions): Promise<TransactResult>;
3749
3823
  /**
3750
3824
  * Parameters for UTXO swap operation
3751
3825
  */
@@ -3776,20 +3850,19 @@ interface UtxoSwapResult extends TransactResult {
3776
3850
  /** Relay request ID for swap execution status */
3777
3851
  requestId?: string;
3778
3852
  /**
3779
- * V3-04 refund-fallback secret. **Persist this** to recover the swap principal if the swap times
3780
- * out before TX2. On a timeout close the program builds the amount-bound note
3853
+ * V3-04 refund-fallback authorization. On a timeout close the program builds the amount-bound note
3781
3854
  * R_fb = Poseidon(amountAfterFee, publicKey, blinding, WSOL)
3782
3855
  * where `amountAfterFee` is the principal it locked (read authoritatively from the on-chain
3783
- * `SwapState.sol_amount`, = gross swap amount minus the on-chain swap fee). `ClaimRefund` then spends
3784
- * `R_fb` with `privateKey` (a plain ZK membership proof of the refund tree). All values are hex.
3856
+ * `SwapState.sol_amount`, = gross swap amount minus the on-chain swap fee). R_fb is an ordinary
3857
+ * leaf of the main pool tree, spent with the ordinary `transact()` path. All values are hex.
3785
3858
  *
3786
- * VK-02: when `derivedFromNk` is true this secret is ALSO recoverable from the wallet's `nk` plus
3787
- * the swap's public first input nullifier — see `matchSwapRefundLeaf`. Persisting it is still the
3788
- * fast path; losing it is no longer terminal. When false (no `nk` was supplied to the swap) this
3789
- * object is the only copy that will ever exist.
3859
+ * `publicKey` is the wallet's long-lived UTXO public key (`options.ownerUtxoKeypair`), so R_fb is
3860
+ * spent with the wallet's own keypair; the private key is deliberately not repeated here. The
3861
+ * blinding is derived from the wallet's `nk` and the swap's public first input nullifier
3862
+ * (`derivedFromNk` is always true), so `discoverSwapRefunds` finds the leaf again from key
3863
+ * material if this object is lost.
3790
3864
  */
3791
3865
  refund: {
3792
- privateKey: string;
3793
3866
  publicKey: string;
3794
3867
  blinding: string;
3795
3868
  derivedFromNk: boolean;
@@ -3807,7 +3880,7 @@ interface UtxoSwapResult extends TransactResult {
3807
3880
  * @param options Transaction options
3808
3881
  * @returns UtxoSwapResult with SwapState PDA for executing the swap
3809
3882
  */
3810
- declare function swapUtxo(params: UtxoSwapParams, options: TransactOptions): Promise<UtxoSwapResult>;
3883
+ declare function swapUtxo(params: UtxoSwapParams, options: SpendOptions): Promise<UtxoSwapResult>;
3811
3884
  /**
3812
3885
  * Execute a swap with change
3813
3886
  *
@@ -3820,7 +3893,7 @@ declare function swapUtxo(params: UtxoSwapParams, options: TransactOptions): Pro
3820
3893
  * @param minOutputAmount Minimum output (slippage protection)
3821
3894
  * @param options Transaction options
3822
3895
  */
3823
- declare function swapWithChange(inputUtxos: Utxo[], swapAmount: bigint, outputMint: Address, recipientAta: Address, minOutputAmount: bigint, options: TransactOptions, recipientWallet?: Address): Promise<UtxoSwapResult>;
3896
+ declare function swapWithChange(inputUtxos: Utxo[], swapAmount: bigint, outputMint: Address, recipientAta: Address, minOutputAmount: bigint, options: SpendOptions, recipientWallet?: Address): Promise<UtxoSwapResult>;
3824
3897
 
3825
3898
  /**
3826
3899
  * Circuit artifact loading and integrity verification.
@@ -4268,77 +4341,45 @@ declare function parseDeliveryCarrierMemo(data: Uint8Array): ParsedDeliveryCarri
4268
4341
  /**
4269
4342
  * Recoverable deposit notes (VK-01, deposit shape).
4270
4343
  *
4271
- * ── The defect this closes ────────────────────────────────────────────────────────────────────
4272
- * A cold scan holding exactly `(rpc, programId, nk)` — the contract the SDK advertises for viewing
4273
- * keys — found the WITHDRAWAL change note and did NOT find the DEPOSIT. The control that makes the
4274
- * miss attributable is the withdrawal: the same scanner, the same 300-signature window, the same
4275
- * key, one shape found and one not.
4276
- *
4277
- * Two things were missing, and only one of them was visible from the failing arm:
4278
- *
4279
- * 1. `outPubkey0`. The deposit's chain note is v3 (timestamp + noteSalt), and `chainNoteHash` binds
4280
- * `noteSemantics = Poseidon(outAmount0, outPubkey0, isSendToSelfKey0)`. `outPubkey0` is the
4281
- * output note's OWNER key, which is not derivable from `nk` — the key hierarchy runs
4282
- * `skSpend → nk` through BLAKE3 and does not run backwards. So the scanner could decrypt the
4283
- * note and then had to drop it, because the hash it recomputed could never match. That is why
4284
- * the widened arm needed an undocumented `ownUtxoPublicKey`: it was feeding the scanner the one
4285
- * value the advertised contract does not carry.
4286
- * 2. The BLINDING. Even with `ownUtxoPublicKey` the deposit is only VISIBLE, not RECOVERABLE — the
4287
- * blinding came from `randomFieldElement()` inside `createUtxo` and is written nowhere. A note
4288
- * you can see and cannot spend is not a recovered note.
4289
- *
4290
- * ── Why derivation, and not another envelope ──────────────────────────────────────────────────
4291
- * The shielded-send shape was fixed with a CLKD1 delivery envelope because a send's output is owned
4292
- * by SOMEONE ELSE: the only way to reach them is to encrypt to their key. A deposit's output is
4293
- * SELF-owned. There is nobody to deliver to, and an envelope would cost 112 bytes on the one
4294
- * transaction in the protocol that is wallet-signed and already tight against the 1232-byte packet
4295
- * limit (a v4 chain note's extra 41 bytes is measured at 1282 and is exactly why deposits stay v3).
4296
- *
4297
- * So make the existing chain-note path recoverable instead. Both missing values become a PRF of the
4298
- * wallet's own `nk` and the note salt the chain note ALREADY carries:
4299
- *
4300
- * seed = BLAKE3("cloak_deposit_note_v1" || nk || noteSalt(32B BE) || info)
4301
- * privateKey = seed("sk") reduced into the field
4302
- * blinding = seed("blinding") reduced into the field
4303
- * publicKey = PoseidonEx(privateKey, KEYPAIR_) [L-02, matches keypair.circom]
4304
- *
4305
- * A cold scanner decrypts the chain note with `nk` (AES-GCM, HKDF-salted by the output commitment),
4306
- * reads `noteSalt` out of the plaintext, replays those three lines, recomputes
4307
- * `Poseidon(amount, publicKey, blinding, mint)` and requires it to equal a commitment the
4308
- * transaction actually published. That equality is the authentication: it is not a heuristic, and a
4309
- * wrong `nk` cannot produce it. Zero extra bytes on chain, no new envelope, no relay change.
4310
- *
4311
- * This is the same shape already blessed for swap timeout refunds in `notes/swap-refund.ts`
4312
- * (PRF(nk, nullifier0)), for the same reason: unrecoverable randomness becomes recoverable
4313
- * randomness without changing anything an observer can see.
4314
- *
4315
- * ── The consequence to be explicit about ──────────────────────────────────────────────────────
4316
- * The deposit note is owned by a PER-DEPOSIT key rather than by the wallet's single long-lived UTXO
4317
- * keypair. It is still fully spendable — the wallet re-derives `privateKey` from `nk` whenever it
4318
- * needs it — and it is strictly better for privacy, because `outPubkey0` no longer links a wallet's
4319
- * deposits to each other. But it means the caller MUST persist (or be able to re-derive) `nk`, which
4320
- * a Cloak wallet already does, and it means `transact` must be given an explicit `nk` rather than
4321
- * inferring one from the output note's own key. `transact` enforces that rather than trusting it.
4344
+ * ── What a deposit note is ────────────────────────────────────────────────────────────────────
4345
+ * A deposit's output note is owned by the wallet's long-lived UTXO keypair (passed explicitly by
4346
+ * the caller) and carries a blinding derived from the wallet's viewing key:
4347
+ *
4348
+ * blinding = BLAKE3("cloak_deposit_note_v1" || nk || noteSalt(32B BE) || "blinding") -> field
4349
+ * owner = ownerUtxoKeypair (deriveUtxoKeypairFromSpendKey(skSpend)), never derived from nk
4350
+ *
4351
+ * The chain note (encrypted under `nk`) publishes `noteSalt`, so a scan holding `nk` and the
4352
+ * wallet's UTXO PUBLIC key can replay the blinding, recompute `Poseidon(amount, ownerPub, blinding,
4353
+ * mint)` and require it to equal a commitment the transaction actually published. That equality is
4354
+ * the authentication. Spending still needs the owner's PRIVATE key, which `nk` cannot produce: the
4355
+ * nullifier is `Poseidon(commitment, index, Poseidon(privateKey, commitment, index))`.
4356
+ *
4357
+ * ── nk is view-only ───────────────────────────────────────────────────────────────────────────
4358
+ * `nk` is registered with the relay for compliance and may be shared with an auditor, so it must
4359
+ * only ever VIEW. The first version of this module derived the owner private key as well, as
4360
+ * PRF(nk, noteSalt). Notes built that way still exist on chain; they are recovered by
4361
+ * {@link matchDepositNote} through {@link deriveLegacyDepositNoteSecrets} and come back flagged
4362
+ * `legacyExposed: true`, so an app can offer to move them under the wallet's own key. No API here
4363
+ * creates a note in that shape any more.
4322
4364
  *
4323
4365
  * ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
4324
- * [L-02] the public key comes from the capacity-tagged `derivePublicKey`. [H-04-shaped] a zero
4325
- * public key or blinding would be an unspendable note, so the reduction forces non-zero and the
4326
- * derivation refuses to return a degenerate pair. [M-04] `noteSalt` stays a private input to
4327
- * `chainNoteHash`; it is only ever published inside the note's own authenticated ciphertext.
4366
+ * [L-02] public keys come from the capacity-tagged `derivePublicKey`. [H-04-shaped] the reduction
4367
+ * forces a non-zero blinding. [M-04] `noteSalt` stays a private input to `chainNoteHash`; it is
4368
+ * only ever published inside the note's own authenticated ciphertext.
4328
4369
  */
4329
4370
 
4330
4371
  /**
4331
- * The chain note salt is 96 bits — the circuit constrains it with `Num2Bits(96)` and `transact`
4372
+ * The chain note salt is 96 bits: the circuit constrains it with `Num2Bits(96)` and `transact`
4332
4373
  * generates exactly 12 bytes. A salt outside that range would produce a proof the circuit rejects,
4333
4374
  * so it is refused here rather than at proof time.
4334
4375
  */
4335
4376
  declare const CHAIN_NOTE_SALT_BITS = 96;
4336
- /** The secrets a deposit note is built from — and the ones a cold scan re-derives. */
4377
+ /** The secrets a deposit note is built from. */
4337
4378
  interface DepositNoteSecrets {
4338
4379
  keypair: UtxoKeypair;
4339
4380
  blinding: bigint;
4340
4381
  }
4341
- /** A deposit note recovered from `nk` alone, in spendable form. */
4382
+ /** A deposit note recovered by a scan. */
4342
4383
  interface RecoveredDepositNote extends DepositNoteSecrets {
4343
4384
  amount: bigint;
4344
4385
  mintAddress: Address;
@@ -4346,30 +4387,67 @@ interface RecoveredDepositNote extends DepositNoteSecrets {
4346
4387
  commitment: bigint;
4347
4388
  /** The salt the chain note carried, which anchored the derivation. */
4348
4389
  noteSalt: bigint;
4390
+ /**
4391
+ * `false`: the note is owned by the wallet's long-lived UTXO keypair. `keypair` is the owner
4392
+ * keypair the matcher was given, so `keypair.privateKey` is `0n` when only the public key was
4393
+ * supplied (a view-only scan); substitute the wallet's own keypair before spending.
4394
+ *
4395
+ * `true`: a legacy deposit whose owner key was derived from `nk` (the pre-fix shape). `keypair`
4396
+ * is complete and spendable, and the same is true for anyone holding `nk`, so an app should offer
4397
+ * to move these funds into a note owned by the wallet's long-lived keypair.
4398
+ */
4399
+ legacyExposed: boolean;
4349
4400
  }
4350
4401
  /** A fresh 96-bit chain-note salt, from the same fail-closed source `transact` uses. */
4351
4402
  declare function randomDepositNoteSalt(): bigint;
4352
4403
  /**
4353
- * Derive a deposit note's keypair and blinding from `(nk, noteSalt)`.
4404
+ * Derive a deposit note's BLINDING from `(nk, noteSalt)`.
4354
4405
  *
4355
- * Deterministic by design: this is the whole reason a cold scan can rebuild the note. Both the
4356
- * builder and the scanner call it, so there is exactly one definition of what a deposit note is.
4406
+ * Deterministic by design: this is what lets a scan rebuild the commitment. The blinding is a view
4407
+ * secret (it hides the amount and owner inside the commitment); it cannot spend anything, because
4408
+ * spending needs the owner's private key. Both current and legacy deposit notes use this blinding.
4409
+ */
4410
+ declare function deriveDepositNoteBlinding(viewingKeyNk: Uint8Array, noteSalt: bigint): bigint;
4411
+ /**
4412
+ * LEGACY. The secrets of a deposit note built by the first recoverable-deposit release, whose owner
4413
+ * private key was PRF(nk, noteSalt).
4414
+ *
4415
+ * Exists only so scans can still find and spend those notes. Never build a new note from this: the
4416
+ * owner key is derivable by anyone who holds `nk`.
4357
4417
  */
4358
- declare function deriveDepositNoteSecrets(viewingKeyNk: Uint8Array, noteSalt: bigint): Promise<DepositNoteSecrets>;
4418
+ declare function deriveLegacyDepositNoteSecrets(viewingKeyNk: Uint8Array, noteSalt: bigint): Promise<DepositNoteSecrets>;
4419
+ /** Parameters for {@link createRecoverableDepositUtxo}. */
4420
+ interface CreateRecoverableDepositUtxoParams {
4421
+ /** Deposit amount in base units. */
4422
+ amount: bigint;
4423
+ /** The wallet's 32-byte viewing base `nk`. Derives the blinding and encrypts the chain note. */
4424
+ viewingKeyNk: Uint8Array;
4425
+ /**
4426
+ * The wallet's long-lived UTXO keypair, which OWNS the note. Required: a deposit note is never
4427
+ * owned by a key derived from `nk`.
4428
+ */
4429
+ ownerUtxoKeypair: UtxoKeypair;
4430
+ /** Pool mint. Defaults to native SOL. */
4431
+ mintAddress?: Address;
4432
+ /** Pin the 96-bit chain-note salt. Defaults to a fresh random salt. */
4433
+ noteSalt?: bigint;
4434
+ }
4359
4435
  /**
4360
- * Build a deposit output note that a cold `(rpc, programId, nk)` scan can recover.
4436
+ * Build a deposit output note that a scan holding `nk` plus the wallet's UTXO public key can
4437
+ * recover, and that only the holder of the owner's private key can spend.
4361
4438
  *
4362
4439
  * Returns the UTXO to pass as `outputUtxos[0]` AND the salt that anchored it. The SAME salt must be
4363
- * handed to `transact` as `options.chainNoteSalt`, because the chain note is what publishes it — a
4364
- * salt that does not reach the note leaves the deposit exactly as undiscoverable as before.
4440
+ * handed to `transact` as `options.chainNoteSalt`, because the chain note is what publishes it.
4365
4441
  *
4366
4442
  * ```ts
4367
- * const { utxo, noteSalt } = await createRecoverableDepositUtxo(amount, nk, mint);
4443
+ * const { utxo, noteSalt } = await createRecoverableDepositUtxo({
4444
+ * amount, viewingKeyNk: nk, ownerUtxoKeypair, mintAddress: mint,
4445
+ * });
4368
4446
  * await transact({ ..., outputUtxos: [utxo], externalAmount: amount },
4369
- * { chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt, ... });
4447
+ * { chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt, ownerUtxoKeypair, ... });
4370
4448
  * ```
4371
4449
  */
4372
- declare function createRecoverableDepositUtxo(amount: bigint, viewingKeyNk: Uint8Array, mintAddress?: Address, noteSalt?: bigint): Promise<{
4450
+ declare function createRecoverableDepositUtxo(params: CreateRecoverableDepositUtxoParams): Promise<{
4373
4451
  utxo: Utxo;
4374
4452
  noteSalt: bigint;
4375
4453
  }>;
@@ -4378,20 +4456,26 @@ interface MatchDepositNoteParams {
4378
4456
  viewingKeyNk: Uint8Array;
4379
4457
  /** `noteSalt`, read out of the decrypted chain note. */
4380
4458
  noteSalt: bigint;
4381
- /** Candidate note amount — for a shield with no inputs this is the public deposit amount. */
4459
+ /** Candidate note amount. For a shield with no inputs this is the public deposit amount. */
4382
4460
  amount: bigint;
4383
4461
  /** Pool mint the commitment was computed under. */
4384
4462
  mintAddress: Address;
4385
4463
  /** Output commitments the transaction actually published, hex or field elements. */
4386
4464
  outputCommitments: Array<string | bigint>;
4465
+ /**
4466
+ * The wallet's long-lived UTXO keypair. Only `publicKey` is needed for a match; pass
4467
+ * `privateKey: 0n` for a view-only scan, or the real keypair to get a spendable result. Without
4468
+ * it only legacy (nk-owned) deposits can be matched.
4469
+ */
4470
+ ownerUtxoKeypair?: UtxoKeypair;
4387
4471
  }
4388
4472
  /**
4389
- * Decide whether a deposit's published commitment is one this `nk` can rebuild, and if so return
4390
- * the note in spendable form. Returns `null` for everything that is not ours.
4473
+ * Decide whether a deposit's published commitment is one of this wallet's notes, and if so return
4474
+ * it. Returns `null` for everything that is not ours.
4391
4475
  *
4392
- * The commitment equality is the authentication. Nothing here trusts the chain note's own claim
4393
- * about what it describes; the note only supplies `noteSalt`, and the derived secrets have to
4394
- * reproduce a value the transaction published or the candidate is discarded.
4476
+ * Tries the current shape first (owner = `ownerUtxoKeypair`), then the legacy shape (owner derived
4477
+ * from `nk`, flagged `legacyExposed`). The commitment equality is the authentication; nothing here
4478
+ * trusts the chain note's own claim about what it describes.
4395
4479
  */
4396
4480
  declare function matchDepositNote(params: MatchDepositNoteParams): Promise<RecoveredDepositNote | null>;
4397
4481
 
@@ -4433,16 +4517,19 @@ declare function matchDepositNote(params: MatchDepositNoteParams): Promise<Recov
4433
4517
  * derive one blinding, and `transact`'s fail-closed check could not tell which slot it was looking
4434
4518
  * at. With it, every slot has its own answer.
4435
4519
  *
4436
- * ── Why only the blinding, when deposits derive the keypair too ───────────────────────────────
4437
- * A deposit's output note has no prior owner, so `deposit-note.ts` is free to give it a per-deposit
4438
- * key and gains unlinkability by doing so. A change note is different: its owner is already fixed —
4439
- * it is the keypair of the note being spent (`inputUtxos[0].keypair`), which the spender by
4440
- * definition holds, and which callers rely on to keep spending their own change. Re-owning it under
4441
- * a derived key would change `outPubkey0`, break that expectation, and buy nothing, because the
4442
- * spender's key is the one value in a change note that was never at risk. Only the randomness was.
4520
+ * ── Who owns change ───────────────────────────────────────────────────────────────────────────
4521
+ * Change is owned by the wallet's long-lived UTXO keypair, passed explicitly by the caller
4522
+ * (`ownerUtxoKeypair` on the spend flows). It is never inherited from `inputUtxos[0]`: an input may
4523
+ * be a legacy note whose key was derived from `nk`, and inheriting that key would keep the change
4524
+ * spendable by anyone holding the viewing key. Owning change under the wallet key also means that
4525
+ * spending a legacy note produces safe change, which is how legacy funds migrate.
4526
+ *
4527
+ * Only the blinding comes from `nk`. The blinding is a view secret; spending needs the owner's
4528
+ * private key, which `nk` cannot produce.
4443
4529
  *
4444
4530
  * ── What a cold scan can rebuild, and what it cannot ──────────────────────────────────────────
4445
- * For the shape that lost the money — a partial withdrawal — recovery is COMPLETE from `nk` alone.
4531
+ * For the shape that lost the money (a partial withdrawal) a scan holding `nk` finds the note and
4532
+ * rebuilds its commitment; spending it needs the owner's private key, which the wallet holds.
4446
4533
  * `partialWithdraw` emits the change as `outputUtxos[0]`, and a v4 chain note binds
4447
4534
  * `noteSemantics = Poseidon(outAmount0, outPubkey0, isSendToSelfKey0)` and carries all three in its
4448
4535
  * (encrypted, authenticated) plaintext. So a scanner holding `nk` decrypts the note, reads
@@ -4461,8 +4548,7 @@ declare function matchDepositNote(params: MatchDepositNoteParams): Promise<Recov
4461
4548
  * ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
4462
4549
  * [M-04] `noteSalt` stays a private input to `chainNoteHash`; it is only ever published inside the
4463
4550
  * note's own authenticated ciphertext, so nothing an observer can see changes. [H-04-shaped] the
4464
- * reduction forces non-zero, because a zero blinding is an unspendable note. Callers that pass no
4465
- * `nk` keep the previous random-blinding behaviour unchanged, so this is additive.
4551
+ * reduction forces non-zero, because a zero blinding is an unspendable note.
4466
4552
  */
4467
4553
 
4468
4554
  /** A change note recovered from `nk` (plus the owner key the spender already holds). */
@@ -4475,6 +4561,13 @@ interface RecoveredChangeNote {
4475
4561
  commitment: bigint;
4476
4562
  /** The salt the chain note carried, which anchored the derivation. */
4477
4563
  noteSalt: bigint;
4564
+ /**
4565
+ * `true` when the note is NOT owned by the wallet's long-lived UTXO keypair: legacy change that
4566
+ * inherited the key of the note it spent (for example an nk-derived deposit or refund key). Such
4567
+ * a note may be spendable by anyone holding `nk`; an app should offer to migrate it. Only
4568
+ * decidable when the wallet's public key is known, so it is `false` when it was not supplied.
4569
+ */
4570
+ legacyExposed: boolean;
4478
4571
  }
4479
4572
  /** A fresh 96-bit chain-note salt, from the same fail-closed source `transact` uses. */
4480
4573
  declare function randomChangeNoteSalt(): bigint;
@@ -4486,14 +4579,17 @@ declare function randomChangeNoteSalt(): bigint;
4486
4579
  */
4487
4580
  declare function deriveChangeNoteBlinding(viewingKeyNk: Uint8Array, noteSalt: bigint, outputIndex: number): bigint;
4488
4581
  /**
4489
- * Build a change output note whose blinding a cold `(rpc, programId, nk)` scan can re-derive.
4582
+ * Build a change output note whose blinding a scan holding `nk` can re-derive.
4583
+ *
4584
+ * `ownerUtxoKeypair` is the wallet's long-lived UTXO keypair. It is validated (non-zero private key,
4585
+ * public key derived from it), because change must be owned by a key only the wallet holds.
4490
4586
  *
4491
4587
  * Returns the UTXO AND the salt that anchored it. The SAME salt must reach `transact` as
4492
4588
  * `options.chainNoteSalt`, because the chain note is what publishes it — a salt that does not reach
4493
4589
  * the note leaves the change exactly as unrecoverable as before. `partialWithdraw` and `transfer`
4494
4590
  * do this for you; the pairing is only your concern if you call `transact` directly.
4495
4591
  */
4496
- declare function createRecoverableChangeUtxo(amount: bigint, keypair: UtxoKeypair, viewingKeyNk: Uint8Array, mintAddress?: Address, noteSalt?: bigint, outputIndex?: number): Promise<{
4592
+ declare function createRecoverableChangeUtxo(amount: bigint, ownerUtxoKeypair: UtxoKeypair, viewingKeyNk: Uint8Array, mintAddress?: Address, noteSalt?: bigint, outputIndex?: number): Promise<{
4497
4593
  utxo: Utxo;
4498
4594
  noteSalt: bigint;
4499
4595
  }>;
@@ -4515,6 +4611,11 @@ interface MatchChangeNoteParams {
4515
4611
  outputIndex: number;
4516
4612
  /** Output commitments the transaction actually published, hex or field elements. */
4517
4613
  outputCommitments: Array<string | bigint>;
4614
+ /**
4615
+ * The wallet's long-lived UTXO public key. When supplied, a match whose owner differs from it is
4616
+ * flagged `legacyExposed`.
4617
+ */
4618
+ ownerUtxoPublicKey?: bigint;
4518
4619
  }
4519
4620
  /**
4520
4621
  * Decide whether a published commitment is a change note this `nk` can rebuild, and if so return it
@@ -4541,25 +4642,30 @@ declare function matchChangeNote(params: MatchChangeNoteParams): Promise<Recover
4541
4642
  * viewing key and the swap creator's, and found nothing under either.
4542
4643
  *
4543
4644
  * ── The fix, and why it is SDK-only ───────────────────────────────────────────────────────────
4544
- * Derive the refund authorization as a PRF of the owner's `nk` and the swap's own first input
4545
- * nullifier:
4645
+ * The refund leaf is owned by the wallet's long-lived UTXO keypair (passed explicitly), and only
4646
+ * its BLINDING is derived, as a PRF of the owner's `nk` and the swap's own first input nullifier:
4546
4647
  *
4547
- * seed = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0)
4648
+ * blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding") -> field
4649
+ * owner = ownerUtxoKeypair (never derived from nk)
4548
4650
  *
4549
- * `nullifier0` is published in the TransactSwap public inputs, so a cold scanner enumerating
4550
- * program transactions can replay this derivation for every swap it sees, recompute R_fb, and
4551
- * match it against the commitment `CloseSwapState` declared. `nk` is secret, so no third party can
4552
- * predict, front-run or link the refund key — the on-chain artefacts are unchanged in shape and
4553
- * every existing binding still holds.
4651
+ * `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk` and the
4652
+ * wallet's UTXO public key can replay the blinding for every swap it sees, recompute R_fb and match
4653
+ * it against the commitment `CloseSwapState` declared. Spending R_fb needs the owner's private key,
4654
+ * which `nk` cannot produce, so the viewing key stays view-only. Every R_fb is distinct because the
4655
+ * blinding differs per `nullifier0`.
4554
4656
  *
4555
4657
  * This changes NOTHING on chain or in the relay. `refund_pubkey` / `refund_blinding` remain
4556
- * caller-supplied values bound into `computeSwapExtDataHash`; only their provenance changes, from
4557
- * "unrecoverable randomness" to "recoverable randomness".
4658
+ * caller-supplied values bound into `computeSwapExtDataHash`; only their provenance changes.
4659
+ *
4660
+ * ── Legacy refunds ────────────────────────────────────────────────────────────────────────────
4661
+ * The first release of this derivation also derived the refund PRIVATE key from `(nk, nullifier0)`.
4662
+ * Those refunds are still matched (see {@link deriveLegacySwapRefundAuthorization}) and come back
4663
+ * flagged `legacyExposed: true`, because anyone holding `nk` can spend them; an app should migrate
4664
+ * them. No API builds a refund in that shape any more.
4558
4665
  *
4559
4666
  * ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
4560
- * [H-04 / DD-01] the derivation is rejected unless publicKey and blinding are both non-zero, and
4561
- * it is unique per swap because `nullifier0` is unique per spend. [L-02] the public key comes from
4562
- * the capacity-tagged `derivePublicKey`, matching `keypair.circom`.
4667
+ * [H-04 / DD-01] the authorization is rejected unless publicKey and blinding are both non-zero.
4668
+ * [L-02] public keys come from the capacity-tagged `derivePublicKey`, matching `keypair.circom`.
4563
4669
  *
4564
4670
  * ── FORWARD-LOOKING ONLY ──────────────────────────────────────────────────────────────────────
4565
4671
  * Everything here — including `discoverSwapRefunds`, the RPC walker at the bottom of this file —
@@ -4576,20 +4682,44 @@ interface SwapRefundAuthorization {
4576
4682
  publicKey: bigint;
4577
4683
  blinding: bigint;
4578
4684
  }
4579
- /** A refund leaf matched back to its owner, ready to spend. */
4685
+ /** A refund leaf matched back to its owner. */
4580
4686
  interface RecoveredSwapRefund {
4687
+ /**
4688
+ * The owner keypair. For a current refund this is the `ownerUtxoKeypair` the matcher was given
4689
+ * (`privateKey` is `0n` if only the public key was supplied; substitute the wallet's keypair before
4690
+ * spending). For a legacy refund it is the nk-derived keypair, complete and spendable.
4691
+ */
4581
4692
  keypair: UtxoKeypair;
4582
4693
  blinding: bigint;
4583
4694
  amount: bigint;
4584
4695
  /** R_fb as a field element, identical to the commitment `CloseSwapState` appended. */
4585
4696
  commitment: bigint;
4697
+ /**
4698
+ * `true` for a legacy refund whose key was derived from `nk`: spendable by anyone holding `nk`,
4699
+ * so an app should offer to move it under the wallet's own key.
4700
+ */
4701
+ legacyExposed: boolean;
4586
4702
  }
4587
4703
  /**
4588
- * Derive a swap's refund authorization from the owner's `nk` and the swap's first input nullifier.
4704
+ * Derive a swap refund leaf's BLINDING from the owner's `nk` and the swap's first input nullifier.
4589
4705
  *
4590
- * Deterministic by design: this is what makes the refund leaf recoverable from key material alone.
4706
+ * Deterministic by design: this is what makes the refund leaf findable from key material. The
4707
+ * blinding is a view secret and cannot spend the leaf.
4591
4708
  */
4592
- declare function deriveSwapRefundAuthorization(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): Promise<SwapRefundAuthorization>;
4709
+ declare function deriveSwapRefundBlinding(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): bigint;
4710
+ /**
4711
+ * The refund authorization `swapUtxo` binds into the swap ext-data hash: the wallet's long-lived
4712
+ * UTXO keypair as owner, plus the derived blinding.
4713
+ *
4714
+ * `ownerUtxoKeypair` is required and validated. The refund key is never derived from `nk`.
4715
+ */
4716
+ declare function deriveSwapRefundAuthorization(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint, ownerUtxoKeypair: UtxoKeypair): Promise<SwapRefundAuthorization>;
4717
+ /**
4718
+ * LEGACY. The refund authorization of the first derived-refund release, whose private key was
4719
+ * PRF(nk, nullifier0). Exists only so scans can still find and spend those refunds; never bind a new
4720
+ * swap to it, because anyone holding `nk` can spend the leaf.
4721
+ */
4722
+ declare function deriveLegacySwapRefundAuthorization(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): Promise<SwapRefundAuthorization>;
4593
4723
  /**
4594
4724
  * R_fb, exactly as `CloseSwapState` computes it. The swap principal is always WSOL-locked, so the
4595
4725
  * mint term is the native-SOL sentinel.
@@ -4604,11 +4734,18 @@ interface MatchSwapRefundLeafParams {
4604
4734
  amountAfterFee: bigint;
4605
4735
  /** R_fb as appended on chain. */
4606
4736
  commitment: bigint | Uint8Array;
4737
+ /**
4738
+ * The wallet's long-lived UTXO keypair (`privateKey: 0n` is fine for a view-only match). Without
4739
+ * it only legacy refunds can be matched.
4740
+ */
4741
+ ownerUtxoKeypair?: UtxoKeypair;
4607
4742
  }
4608
4743
  /**
4609
- * Decide whether a public refund leaf belongs to the holder of `viewingKeyNk`, and if so return it
4610
- * in spendable form. Returns `null` for every leaf that is not ours — a scanner runs this against
4611
- * every close it can see.
4744
+ * Decide whether a public refund leaf belongs to this wallet, and if so return it. Returns `null`
4745
+ * for every leaf that is not ours; a scanner runs this against every close it can see.
4746
+ *
4747
+ * Tries the current shape first (owner = `ownerUtxoKeypair`, blinding from `nk`), then the legacy
4748
+ * shape (key and blinding both from `nk`, flagged `legacyExposed`).
4612
4749
  */
4613
4750
  declare function matchSwapRefundLeaf(params: MatchSwapRefundLeafParams): Promise<RecoveredSwapRefund | null>;
4614
4751
  /** One recovered refund leaf, with the chain coordinates that produced it. */
@@ -4623,6 +4760,13 @@ interface DiscoveredSwapRefund extends RecoveredSwapRefund {
4623
4760
  swapSignature?: string;
4624
4761
  }
4625
4762
  interface DiscoverSwapRefundsOptions {
4763
+ /**
4764
+ * The wallet's long-lived UTXO keypair: the owner of every refund leaf built by the current SDK.
4765
+ * Required. Pass the real keypair to get spendable results, or `{ privateKey: 0n, publicKey }`
4766
+ * for a view-only scan. Legacy (nk-owned) refunds are found either way and flagged
4767
+ * `legacyExposed`.
4768
+ */
4769
+ ownerUtxoKeypair: UtxoKeypair;
4626
4770
  /** Maximum program signatures to walk. Omit or 0 to walk the whole history. */
4627
4771
  limit?: number;
4628
4772
  /** Stop when this signature is reached (exclusive) — the cursor from a previous run. */
@@ -4638,16 +4782,18 @@ interface DiscoverSwapRefundsOptions {
4638
4782
  poolMint?: Address;
4639
4783
  }
4640
4784
  /**
4641
- * Find every swap timeout-refund leaf on chain that belongs to the holder of `viewingKeyNk`, and
4642
- * return each in spendable form (`keypair`, `blinding`, `amount`, `commitment`).
4785
+ * Find every swap timeout-refund leaf on chain that belongs to this wallet (`viewingKeyNk` plus
4786
+ * `options.ownerUtxoKeypair`), and return each with `keypair`, `blinding`, `amount`, `commitment`
4787
+ * and `legacyExposed`.
4643
4788
  *
4644
4789
  * Key material only — no relay, no local note store, no prior knowledge of the swap. This is the
4645
4790
  * recovery path for the exact situation VK-02 described: `CloseSwapState` appended a funded leaf and
4646
4791
  * its owner could not see it under any key they held.
4647
4792
  *
4648
- * FORWARD-LOOKING ONLY. This finds refunds whose authorization was DERIVED as PRF(nk, nullifier0).
4649
- * A swap whose refund keypair and blinding were drawn from raw randomness — every swap submitted
4650
- * before that derivation shipped, and any swap built without an `nk` — has no derivation to replay,
4793
+ * FORWARD-LOOKING ONLY. This finds refunds whose blinding was DERIVED from (nk, nullifier0), owned
4794
+ * either by the wallet's UTXO keypair (current) or by an nk-derived key (legacy, flagged).
4795
+ * A swap whose refund keypair and blinding were drawn from raw randomness (every swap submitted
4796
+ * before that derivation shipped) has no derivation to replay,
4651
4797
  * and no key-only scan can ever recover it. Those secrets existed solely in the caller's in-memory
4652
4798
  * `UtxoSwapResult.refund`. An empty result is therefore NOT proof that a wallet has no stranded
4653
4799
  * refund; it means none of the leaves in the scanned window were derivable from this `nk`.
@@ -4656,7 +4802,7 @@ interface DiscoverSwapRefundsOptions {
4656
4802
  * @param programId Shield-pool program id.
4657
4803
  * @param viewingKeyNk 32-byte `nk` — the same value chain notes are decrypted with.
4658
4804
  */
4659
- declare function discoverSwapRefunds(connection: CloakRpc, programId: Address, viewingKeyNk: Uint8Array, options?: DiscoverSwapRefundsOptions): Promise<DiscoveredSwapRefund[]>;
4805
+ declare function discoverSwapRefunds(connection: CloakRpc, programId: Address, viewingKeyNk: Uint8Array, options: DiscoverSwapRefundsOptions): Promise<DiscoveredSwapRefund[]>;
4660
4806
 
4661
4807
  /**
4662
4808
  * Compact deterministic chain note format.
@@ -4767,12 +4913,17 @@ interface ScanResult {
4767
4913
  */
4768
4914
  deliveredNotes: DeliveredNote[];
4769
4915
  /**
4770
- * This wallet's OWN deposits, rebuilt in SPENDABLE form from `nk` alone (VK-01).
4916
+ * This wallet's OWN deposits, rebuilt from `nk` plus `ownerUtxoPublicKey` (VK-01).
4771
4917
  *
4772
- * `transactions` records that a deposit happened and for how much. These carry the keypair and
4773
- * blinding as well, which is the difference between seeing a note and being able to spend it.
4774
- * Only deposits built with {@link createRecoverableDepositUtxo} appear here; a deposit whose
4775
- * blinding came from raw randomness has nothing to rebuild and shows up as a history row only.
4918
+ * `transactions` records that a deposit happened and for how much. These carry the owner key and
4919
+ * blinding as well. Only deposits built with {@link createRecoverableDepositUtxo} appear here; a
4920
+ * deposit whose blinding came from raw randomness has nothing to rebuild and shows up as a history
4921
+ * row only.
4922
+ *
4923
+ * Current deposits are owned by the wallet's long-lived UTXO keypair and need `ownerUtxoPublicKey`
4924
+ * to be matched; they come back with `keypair.privateKey === 0n` (nk cannot produce it) and
4925
+ * `legacyExposed: false`, so substitute the wallet's own keypair before spending. Legacy deposits
4926
+ * (owner key derived from nk) come back complete and flagged `legacyExposed: true`.
4776
4927
  *
4777
4928
  * Additive, for the same reason as `deliveredNotes`: note secrets are not compliance rows.
4778
4929
  */
@@ -4783,10 +4934,12 @@ interface ScanResult {
4783
4934
  * `partialWithdraw` and `swapWithChange` emit change as output 0, and a v4 chain note carries
4784
4935
  * `outAmount0`/`outPubkey0`, so `nk` plus the derived blinding is everything the note needs.
4785
4936
  *
4786
- * One difference from `recoveredDepositNotes`: a change note's owner key is NOT derived — it is
4787
- * the keypair of the note that was spent, deliberately, so that holding a viewing key never
4788
- * confers spend authority. So `keypair.privateKey` comes back as `0n` and the caller must supply
4789
- * their own before spending. Everything else is complete.
4937
+ * A change note's owner key is never derived from nk: it is the wallet's long-lived UTXO keypair
4938
+ * (or, for legacy change, the key of the note that was spent). So `keypair.privateKey` comes back
4939
+ * as `0n` and the caller supplies its own before spending. Two exceptions, both flagged
4940
+ * `legacyExposed: true`: change owned by a legacy nk-derived deposit key found in the same scan
4941
+ * comes back with that key's private half filled in, and change whose owner is not
4942
+ * `ownerUtxoPublicKey` (when supplied) is flagged so an app can migrate it.
4790
4943
  */
4791
4944
  recoveredChangeNotes: RecoveredChangeNoteRecord[];
4792
4945
  }
@@ -4844,9 +4997,14 @@ interface ScanOptions {
4844
4997
  */
4845
4998
  includeRecipientDeliveries?: boolean;
4846
4999
  /**
4847
- * This wallet's UTXO public key. Supply it to authenticate each delivery carrier's declared
4848
- * commitment (see `ScanRecipientDeliveryOptions.ownerUtxoPublicKey`). Without it the commitment
4849
- * is reported unverified.
5000
+ * This wallet's long-lived UTXO public key. Supply it to:
5001
+ * - match this wallet's own deposits, which are owned by it (without it only legacy, nk-owned
5002
+ * deposits can be recovered into `recoveredDepositNotes`);
5003
+ * - flag legacy change (`legacyExposed`) whose owner is not this key;
5004
+ * - authenticate each delivery carrier's declared commitment (see
5005
+ * `ScanRecipientDeliveryOptions.ownerUtxoPublicKey`); without it the commitment is reported
5006
+ * unverified.
5007
+ * A public key cannot spend anything, so passing it keeps the scan view-only.
4850
5008
  */
4851
5009
  ownerUtxoPublicKey?: bigint;
4852
5010
  /** Candidate pool mints for delivery-carrier commitment verification. Defaults to native SOL. */
@@ -5317,12 +5475,27 @@ declare function fundReceiverViaPaymaster(relayUrl: string, receiver: KeyPairSig
5317
5475
  /**
5318
5476
  * Deriving a bridge receiving address.
5319
5477
  *
5320
- * One single-use address per deposit, from the wallet's own key material. Deterministic, offline,
5321
- * and stateless — which is what lets every other function here work on a device that has never
5322
- * seen this deposit before.
5478
+ * One single-use address per deposit, from the wallet's own SPEND-level key material.
5479
+ * Deterministic, offline, and stateless, which is what lets every other function here work on a
5480
+ * device that has never seen this deposit before.
5481
+ *
5482
+ * The receiver is a full Solana signer and bridged funds sit at it in transit, so it must not be
5483
+ * derivable from the viewing key `nk` (which is registered with the relay and may be shared). It is
5484
+ * derived from the wallet's long-lived UTXO private key:
5485
+ *
5486
+ * key = BLAKE3("cloak_bridge_receiver_key_v2" || utxoPrivateKey(32B BE))
5487
+ * seed = HMAC-SHA512(key, "cloak_bridge_escrow_v2:<index>")[0..32]
5488
+ * receiver = ed25519 signer from seed
5489
+ *
5490
+ * Receivers from the first release were HMAC-SHA512(nk, "cloak_bridge_escrow:<index>"). They are
5491
+ * still derived by {@link deriveLegacyBridgeReceiver} so discovery can find in-flight legacy
5492
+ * deposits and finish them; no new deposit is ever routed to one.
5323
5493
  */
5324
5494
 
5495
+ /** LEGACY label: receivers derived from the viewing key `nk`. Discovery only. */
5325
5496
  declare const BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
5497
+ /** Current label: receivers derived from the wallet's spend-level key material. */
5498
+ declare const BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
5326
5499
  /**
5327
5500
  * The index MUST be a small sequential counter (0, 1, 2, …), never a timestamp.
5328
5501
  *
@@ -5340,12 +5513,21 @@ declare const BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
5340
5513
  */
5341
5514
  declare const MAX_RECEIVER_INDEX = 10000;
5342
5515
  /**
5516
+ * Derive the bridge receiving address for `index` from the wallet's long-lived UTXO keypair.
5517
+ *
5343
5518
  * Async because kit derives a signer's public key through WebCrypto's non-extractable ed25519 key
5344
- * import (`signerFromSecretKey`, `solana/signer.ts`) — there is no synchronous path to a kit
5345
- * `KeyPairSigner`. `Keypair.fromSeed(seed)` and `signerFromSecretKey(seed)` (32-byte seed form)
5346
- * derive the identical public key from identical seed bytes; only the sync/async boundary moved.
5519
+ * import (`signerFromSecretKey`, `solana/signer.ts`); there is no synchronous path to a kit
5520
+ * `KeyPairSigner`.
5521
+ */
5522
+ declare function deriveBridgeReceiver(ownerUtxoKeypair: UtxoKeypair, index: number): Promise<KeyPairSigner>;
5523
+ /**
5524
+ * LEGACY. The receiving address the first bridge release derived from the viewing key `nk`.
5525
+ *
5526
+ * Exists only so discovery can find, finish and clean up deposits that were routed to these
5527
+ * addresses before the fix. Never quote or route a new deposit to one: anyone holding `nk` can sign
5528
+ * for it.
5347
5529
  */
5348
- declare function deriveBridgeReceiver(nk: Uint8Array | Buffer, index: number): Promise<KeyPairSigner>;
5530
+ declare function deriveLegacyBridgeReceiver(nk: Uint8Array | Buffer, index: number): Promise<KeyPairSigner>;
5349
5531
 
5350
5532
  type BridgeDepositState =
5351
5533
  /** Nothing ever happened at this index. */
@@ -5390,6 +5572,16 @@ interface BridgeDeposit {
5390
5572
  shieldSignatures?: string[];
5391
5573
  /** Set only when state is "unknown": the failure that made this index's status unconfirmable. */
5392
5574
  error?: string;
5575
+ /**
5576
+ * `true` when the receiver is a LEGACY address derived from a viewing key `nk` (the first bridge
5577
+ * release). Anyone holding that `nk` can sign for it, so funds still sitting there should be
5578
+ * shielded promptly. Re-derive its signer with `deriveLegacyBridgeReceiver(legacyViewingKeyNk,
5579
+ * index)`. Legacy indices are a separate address space from current ones, so they never count
5580
+ * toward the next free current index.
5581
+ */
5582
+ legacyExposed: boolean;
5583
+ /** For a legacy entry: the `nk` its receiver was derived from. */
5584
+ legacyViewingKeyNk?: Uint8Array;
5393
5585
  }
5394
5586
  interface DiscoverOptions {
5395
5587
  /**
@@ -5413,6 +5605,14 @@ interface DiscoverOptions {
5413
5605
  stopAfterUnused?: number;
5414
5606
  programId: Address;
5415
5607
  mint: Address;
5608
+ /**
5609
+ * Also scan the LEGACY nk-derived receivers, so deposits routed to them before the fix are still
5610
+ * found (flagged `legacyExposed`). Default true. The canonical `nk` of `ownerUtxoKeypair` is always
5611
+ * included; add any other viewing keys the wallet has used in `legacyViewingKeyNks`.
5612
+ */
5613
+ includeLegacy?: boolean;
5614
+ /** Extra viewing keys whose legacy receivers should be scanned (deduplicated). */
5615
+ legacyViewingKeyNks?: Uint8Array[];
5416
5616
  }
5417
5617
  /**
5418
5618
  * A terminal state needs TWO conjuncts, never one.
@@ -5423,7 +5623,7 @@ interface DiscoverOptions {
5423
5623
  * Completion therefore requires the shield-pool transaction to be present in the receiver's own
5424
5624
  * history as well.
5425
5625
  */
5426
- declare function listBridgeDeposits(rpc: CloakRpc, nk: Uint8Array | Buffer, opts: DiscoverOptions): Promise<BridgeDeposit[]>;
5626
+ declare function listBridgeDeposits(rpc: CloakRpc, ownerUtxoKeypair: UtxoKeypair, opts: DiscoverOptions): Promise<BridgeDeposit[]>;
5427
5627
 
5428
5628
  interface DepositOutcome {
5429
5629
  signature: string;
@@ -5748,8 +5948,8 @@ declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>
5748
5948
  * @packageDocumentation
5749
5949
  */
5750
5950
 
5751
- declare const VERSION = "0.2.5";
5951
+ declare const VERSION = "0.2.6";
5752
5952
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
5753
5953
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
5754
5954
 
5755
- 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 };
5955
+ 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 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 SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, TransactionConfirmationError, type TransactionMetadata, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, type Utxo, UtxoAlreadySpentError, type EncryptedNote as UtxoEncryptedNote, type UtxoKeypair, type UtxoSwapParams, type UtxoSwapResult, UtxoWallet, VARIABLE_FEE_DENOMINATOR, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_RATE, VERSION, type VerifyUtxosResult, type ViewKey, type ViewingKeyPair, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, 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 };