@cloak.dev/sdk 0.2.14 → 0.2.20-staging.456721e

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
@@ -886,6 +886,18 @@ declare function fetchSignaturesForAddress(rpc: Rpc<SolanaRpcApi>, address: Addr
886
886
  limit?: number;
887
887
  commitment?: Commitment;
888
888
  }): Promise<SignatureInfo[]>;
889
+ /** A `jsonParsed` instruction the RPC could not decode: program id, resolved accounts, base58 data. */
890
+ interface ParsedRawInstruction {
891
+ programId: string;
892
+ accounts: string[];
893
+ data: string;
894
+ }
895
+ interface ParsedDecodedInstruction {
896
+ programId: string;
897
+ program: string;
898
+ parsed: unknown;
899
+ }
900
+ type ParsedInstruction = ParsedRawInstruction | ParsedDecodedInstruction;
889
901
 
890
902
  type SignedTransaction = Transaction & TransactionWithLifetime;
891
903
  interface LookupTable {
@@ -1450,6 +1462,44 @@ interface Groth16Proof {
1450
1462
  */
1451
1463
  declare function proofToBytes(proof: Groth16Proof): Uint8Array;
1452
1464
 
1465
+ /**
1466
+ * Exact conversion between an amount a person types and a token's base units.
1467
+ *
1468
+ * Every amount the SDK moves is a `bigint` in base units. A client that converts through a float
1469
+ * (`Number(text) * 10 ** decimals`) loses precision past 2^53 base units, which 0.01 ETH already
1470
+ * exceeds (1e16 wei), and rounds where it should refuse. These two never touch a float.
1471
+ *
1472
+ * They take the token's `decimals` from the network table (`NetworkToken.decimals`: 6 for USDC,
1473
+ * 18 for ETH), so one pair serves every token. Not the SOL-only `parseAmount` in `./fees`, which
1474
+ * returns lamports as a `number` for display.
1475
+ *
1476
+ * Moved from web (`components/bridge/money.ts`, 2026-11-23) so a client using only the SDK, such as
1477
+ * a partner on Base, applies the same refusal rules as the website.
1478
+ */
1479
+ /**
1480
+ * A typed decimal amount to base units of a token with `decimals` places.
1481
+ *
1482
+ * Returns `null`, never a guess, for:
1483
+ * - anything that is not a plain non-negative decimal: a sign, an exponent, a comma, a hex
1484
+ * literal, a leading or trailing point (".5", "1."), or an empty string;
1485
+ * - more fractional digits than the token has ("0.0000001" USDC), which is refused rather than
1486
+ * truncated, because truncating silently moves less than the person typed;
1487
+ * - `decimals` that is not a non-negative integer.
1488
+ *
1489
+ * Surrounding whitespace is ignored. Leading zeros are accepted ("007" is 7).
1490
+ */
1491
+ declare function parseBaseUnits(input: string, decimals: number): bigint | null;
1492
+ /**
1493
+ * Base units to an exact decimal string with every one of the token's places ("1.500000" for
1494
+ * 1.5 USDC, "0.001500000000000000" for 0.0015 ETH). Negative amounts keep their sign.
1495
+ *
1496
+ * For exact figures and for feeding back into `parseBaseUnits`: the two round-trip. Trimming
1497
+ * trailing zeros or grouping digits for a reader is presentation and stays with the caller.
1498
+ *
1499
+ * @throws Error when `decimals` is not a non-negative integer.
1500
+ */
1501
+ declare function formatBaseUnits(amount: bigint, decimals: number): string;
1502
+
1453
1503
  /**
1454
1504
  * Validate a Solana public key
1455
1505
  *
@@ -3539,6 +3589,13 @@ interface TransactOptions {
3539
3589
  * This eliminates the need for `waitForCommitmentIndex` between sequential transactions.
3540
3590
  */
3541
3591
  cachedMerkleTree?: MerkleTree;
3592
+ /**
3593
+ * Default true. False skips rebuilding the post-transaction Merkle tree from the relay when none
3594
+ * was used for the proof (a pure deposit): that rebuild waits for the relay to index the new leaves
3595
+ * and downloads the whole tree, about 1.5 s, only to fill `TransactResult.merkleTree` for a caller
3596
+ * that chains another transaction. A caller that does not read it should not pay for it.
3597
+ */
3598
+ returnMerkleTree?: boolean;
3542
3599
  /**
3543
3600
  * Use chain indexing for Merkle tree instead of relay.
3544
3601
  * When true, commitments are fetched from chain via getSignaturesForAddress (slower).
@@ -3828,6 +3885,8 @@ interface SubmitTransactToRelayArgs {
3828
3885
  settlementTimeoutMs?: number;
3829
3886
  /** Shorter window used to ask "did it land anyway?" after a terminal relay failure. */
3830
3887
  failureProbeTimeoutMs?: number;
3888
+ /** Stops the wait for the relay's source lease to expire; the chain is still checked after. */
3889
+ signal?: AbortSignal;
3831
3890
  }
3832
3891
  /**
3833
3892
  * POST one logical `/transact` request and REPORT ONLY WHAT THE CHAIN CONFIRMS.
@@ -3956,8 +4015,10 @@ interface UtxoSwapResult extends TransactResult {
3956
4015
  * `SwapState.sol_amount`, = gross swap amount minus the on-chain swap fee). R_fb is an ordinary
3957
4016
  * leaf of the main pool tree, spent with the ordinary `transact()` path. All values are hex.
3958
4017
  *
3959
- * `publicKey` is the wallet's long-lived UTXO public key (`options.ownerUtxoKeypair`), so R_fb is
3960
- * spent with the wallet's own keypair; the private key is deliberately not repeated here. The
4018
+ * `publicKey` is a PER-SWAP public key, derived from `options.ownerUtxoKeypair`'s private key and
4019
+ * the swap's first input nullifier, so no two swaps from one wallet share it and it is not the
4020
+ * wallet's UTXO public key. Spend R_fb with `deriveSwapRefundKeypair(owner, nullifier)`; the
4021
+ * private key is deliberately not repeated here and `nk` cannot produce it. The
3961
4022
  * blinding is derived from the wallet's `nk` and the swap's public first input nullifier
3962
4023
  * (`derivedFromNk` is always true), so `discoverSwapRefunds` finds the leaf again from key
3963
4024
  * material if this object is lost.
@@ -4770,26 +4831,34 @@ declare function matchChangeNote(params: MatchChangeNoteParams): Promise<Recover
4770
4831
  * viewing key and the swap creator's, and found nothing under either.
4771
4832
  *
4772
4833
  * ── The fix, and why it is SDK-only ───────────────────────────────────────────────────────────
4773
- * The refund leaf is owned by the wallet's long-lived UTXO keypair (passed explicitly), and only
4774
- * its BLINDING is derived, as a PRF of the owner's `nk` and the swap's own first input nullifier:
4834
+ * The refund leaf's BLINDING is derived as a PRF of the owner's `nk` and the swap's own first input
4835
+ * nullifier, and its OWNER KEY is derived per swap from the wallet's UTXO private key:
4836
+ *
4837
+ * blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding") -> field
4838
+ * priv = BLAKE3("cloak_swap_refund_v2" || ownerPrivateKey || nullifier0 || "sk_v2") -> field
4839
+ * pub = derivePublicKey(priv)
4775
4840
  *
4776
- * blinding = BLAKE3("cloak_swap_refund_v1" || nk || nullifier0 || "blinding") -> field
4777
- * owner = ownerUtxoKeypair (never derived from nk)
4841
+ * `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk` can replay
4842
+ * the blinding for every swap it sees. `refund_pubkey` and `refund_blinding` are ALSO published, in
4843
+ * plain text, in the TransactSwap instruction data (and in SwapState), so a view-only scanner (nk
4844
+ * plus the owner PUBLIC key) reads the per-swap pubkey from there, checks that the published
4845
+ * blinding equals the nk-derived one, and checks that the commitment matches. Spending R_fb needs
4846
+ * `priv`, which needs the owner's private key: `nk` cannot produce it, so the viewing key stays
4847
+ * view-only, and the owner re-derives the spend key from its own private key plus the nullifier.
4778
4848
  *
4779
- * `nullifier0` is published in the TransactSwap public inputs, so a scanner holding `nk` and the
4780
- * wallet's UTXO public key can replay the blinding for every swap it sees, recompute R_fb and match
4781
- * it against the commitment `CloseSwapState` declared. Spending R_fb needs the owner's private key,
4782
- * which `nk` cannot produce, so the viewing key stays view-only. Every R_fb is distinct because the
4783
- * blinding differs per `nullifier0`.
4849
+ * Why not the owner key itself (0.2.6 - 0.2.8)? That shape published the wallet's permanent UTXO
4850
+ * public key as `refund_pubkey` on every swap, so anyone holding a user's receiving key could list
4851
+ * all of that wallet's swaps. A different public key per swap removes the link.
4784
4852
  *
4785
4853
  * This changes NOTHING on chain or in the relay. `refund_pubkey` / `refund_blinding` remain
4786
4854
  * caller-supplied values bound into `computeSwapExtDataHash`; only their provenance changes.
4787
4855
  *
4788
- * ── Legacy refunds ────────────────────────────────────────────────────────────────────────────
4789
- * The first release of this derivation also derived the refund PRIVATE key from `(nk, nullifier0)`.
4790
- * Those refunds are still matched (see {@link deriveLegacySwapRefundAuthorization}) and come back
4791
- * flagged `legacyExposed: true`, because anyone holding `nk` can spend them; an app should migrate
4792
- * them. No API builds a refund in that shape any more.
4856
+ * ── Three refund shapes, all still recognised ─────────────────────────────────────────────────
4857
+ * "per-swap" (0.2.9+) owner = per-swap key from the owner private key (above)
4858
+ * "owner" (0.2.6 - 0.2.8) owner = the wallet's permanent UTXO keypair; linkable across swaps
4859
+ * "legacy-nk" (< 0.2.6) owner key AND blinding from nk; `legacyExposed: true`, because anyone
4860
+ * holding `nk` can spend it. An app should migrate those refunds.
4861
+ * No API builds a refund in the last two shapes any more.
4793
4862
  *
4794
4863
  * ── Guardrails preserved ──────────────────────────────────────────────────────────────────────
4795
4864
  * [H-04 / DD-01] the authorization is rejected unless publicKey and blinding are both non-zero.
@@ -4810,14 +4879,20 @@ interface SwapRefundAuthorization {
4810
4879
  publicKey: bigint;
4811
4880
  blinding: bigint;
4812
4881
  }
4882
+ /** Which key shape owns a refund leaf; see the file header. */
4883
+ type SwapRefundShape = "per-swap" | "owner" | "legacy-nk";
4813
4884
  /** A refund leaf matched back to its owner. */
4814
4885
  interface RecoveredSwapRefund {
4815
4886
  /**
4816
- * The owner keypair. For a current refund this is the `ownerUtxoKeypair` the matcher was given
4817
- * (`privateKey` is `0n` if only the public key was supplied; substitute the wallet's keypair before
4818
- * spending). For a legacy refund it is the nk-derived keypair, complete and spendable.
4887
+ * The key that owns the leaf. `per-swap`: the key derived from the owner private key and the
4888
+ * swap nullifier (`privateKey` is `0n` for a view-only match: the public key is real, but the
4889
+ * spend key needs the owner private key, see {@link deriveSwapRefundKeypair}). `owner`: the
4890
+ * `ownerUtxoKeypair` the matcher was given (`privateKey` `0n` if only the public key was
4891
+ * supplied). `legacy-nk`: the nk-derived keypair, complete and spendable.
4819
4892
  */
4820
4893
  keypair: UtxoKeypair;
4894
+ /** Which of the three shapes matched. */
4895
+ shape: SwapRefundShape;
4821
4896
  blinding: bigint;
4822
4897
  amount: bigint;
4823
4898
  /** R_fb as a field element, identical to the commitment `CloseSwapState` appended. */
@@ -4836,8 +4911,15 @@ interface RecoveredSwapRefund {
4836
4911
  */
4837
4912
  declare function deriveSwapRefundBlinding(viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint): bigint;
4838
4913
  /**
4839
- * The refund authorization `swapUtxo` binds into the swap ext-data hash: the wallet's long-lived
4840
- * UTXO keypair as owner, plus the derived blinding.
4914
+ * The per-swap refund KEYPAIR: a different key for every swap, derived from the owner's private key
4915
+ * and the swap's first input nullifier. `nk` cannot reproduce it. Use this to spend a refund the
4916
+ * swap result reported, or any `per-swap` refund a view-only scan found.
4917
+ */
4918
+ declare function deriveSwapRefundKeypair(ownerUtxoKeypair: UtxoKeypair, inputNullifier: Uint8Array | bigint): Promise<UtxoKeypair>;
4919
+ /**
4920
+ * The refund authorization `swapUtxo` binds into the swap ext-data hash: a per-swap keypair derived
4921
+ * from the wallet's UTXO private key and the swap's first input nullifier, plus the nk-derived
4922
+ * blinding. The public key differs for every swap and differs from the wallet's UTXO public key.
4841
4923
  *
4842
4924
  * `ownerUtxoKeypair` is required and validated. The refund key is never derived from `nk`.
4843
4925
  */
@@ -4864,16 +4946,28 @@ interface MatchSwapRefundLeafParams {
4864
4946
  commitment: bigint | Uint8Array;
4865
4947
  /**
4866
4948
  * The wallet's long-lived UTXO keypair (`privateKey: 0n` is fine for a view-only match). Without
4867
- * it only legacy refunds can be matched.
4949
+ * it only legacy-nk refunds can be matched.
4868
4950
  */
4869
4951
  ownerUtxoKeypair?: UtxoKeypair;
4952
+ /**
4953
+ * `refund_pubkey` as published in the swap's TransactSwap instruction data (bytes 593-624) or its
4954
+ * SwapState. A view-only scanner needs it to match a `per-swap` refund, because it cannot derive
4955
+ * the key. Pass it together with {@link publishedRefundBlinding}.
4956
+ */
4957
+ publishedRefundPubkey?: bigint | Uint8Array;
4958
+ /** `refund_blinding` as published in the same place (bytes 625-656). */
4959
+ publishedRefundBlinding?: bigint | Uint8Array;
4870
4960
  }
4871
4961
  /**
4872
4962
  * Decide whether a public refund leaf belongs to this wallet, and if so return it. Returns `null`
4873
4963
  * for every leaf that is not ours; a scanner runs this against every close it can see.
4874
4964
  *
4875
- * Tries the current shape first (owner = `ownerUtxoKeypair`, blinding from `nk`), then the legacy
4876
- * shape (key and blinding both from `nk`, flagged `legacyExposed`).
4965
+ * Tries, in order: the per-swap shape (published pubkey, or re-derived when the owner private key
4966
+ * is present), the 0.2.6 - 0.2.8 owner-key shape, then the legacy nk shape (`legacyExposed`).
4967
+ * `shape` on the result says which one matched.
4968
+ *
4969
+ * A per-swap match from a view-only scan returns `keypair.privateKey === 0n`; the caller spends it
4970
+ * with {@link deriveSwapRefundKeypair} once it holds the owner private key.
4877
4971
  */
4878
4972
  declare function matchSwapRefundLeaf(params: MatchSwapRefundLeafParams): Promise<RecoveredSwapRefund | null>;
4879
4973
  /** One recovered refund leaf, with the chain coordinates that produced it. */
@@ -4889,9 +4983,11 @@ interface DiscoveredSwapRefund extends RecoveredSwapRefund {
4889
4983
  }
4890
4984
  interface DiscoverSwapRefundsOptions {
4891
4985
  /**
4892
- * The wallet's long-lived UTXO keypair: the owner of every refund leaf built by the current SDK.
4893
- * Required. Pass the real keypair to get spendable results, or `{ privateKey: 0n, publicKey }`
4894
- * for a view-only scan. Legacy (nk-owned) refunds are found either way and flagged
4986
+ * The wallet's long-lived UTXO keypair. Required. Pass the real keypair to get spendable
4987
+ * results (per-swap refunds come back with their derived keypair), or `{ privateKey: 0n,
4988
+ * publicKey }` for a view-only scan: per-swap refunds are then matched from the `refund_pubkey`
4989
+ * published in the swap instruction and come back with `privateKey: 0n` (re-derive it with
4990
+ * `deriveSwapRefundKeypair`). Legacy (nk-owned) refunds are found either way and flagged
4895
4991
  * `legacyExposed`.
4896
4992
  */
4897
4993
  ownerUtxoKeypair: UtxoKeypair;
@@ -4919,7 +5015,7 @@ interface DiscoverSwapRefundsOptions {
4919
5015
  * its owner could not see it under any key they held.
4920
5016
  *
4921
5017
  * FORWARD-LOOKING ONLY. This finds refunds whose blinding was DERIVED from (nk, nullifier0), owned
4922
- * either by the wallet's UTXO keypair (current) or by an nk-derived key (legacy, flagged).
5018
+ * 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).
4923
5019
  * A swap whose refund keypair and blinding were drawn from raw randomness (every swap submitted
4924
5020
  * before that derivation shipped) has no derivation to replay,
4925
5021
  * and no key-only scan can ever recover it. Those secrets existed solely in the caller's in-memory
@@ -5955,6 +6051,410 @@ type Web3Module = {
5955
6051
  };
5956
6052
  };
5957
6053
 
6054
+ /**
6055
+ * Deciding whether a bridge deposit can be honoured — BEFORE the user sends anything.
6056
+ *
6057
+ * WHY THIS EXISTS. Shielding on arrival is mandatory, not a choice: a user who bridges and then
6058
+ * sweeps unshielded has manufactured exactly the `receiver -> them` link the whole design removes.
6059
+ * But "mandatory" moves every failure from the user's account to ours. If someone sends 3 USDC and
6060
+ * the paymaster fee leaves less than the program's 1,000,000-base-unit floor, the shield CANNOT
6061
+ * happen — and under a mandatory model that is the product breaking its own promise, with the money
6062
+ * stranded unshielded at an address the user has never heard of.
6063
+ *
6064
+ * So the check belongs at quote time. The rule is the one the rail-signature check already
6065
+ * established: NEVER SHOW AN ADDRESS YOU CANNOT HONOUR. An unviable deposit is refused before the
6066
+ * deposit address is displayed, not diagnosed after the money has landed.
6067
+ *
6068
+ * All figures are worst-case, taken from the rail's guaranteed floor (`minAmountOut`), never its
6069
+ * target. A quote that only works at the target is a quote that fails on a bad day.
6070
+ */
6071
+ /** programs/shield-pool/src/constants.rs:126 — enforced at transact_spl/deposit.rs:69. */
6072
+ declare const MIN_DEPOSIT_SPL_BASE_UNITS = 1000000n;
6073
+ /**
6074
+ * Live mainnet USDC PoolConfig at deploy time: a flat fee plus a proportional part, charged on
6075
+ * WITHDRAWAL. These are the program's DEFAULTS, not a live read — quote.ts has no RPC client, so it
6076
+ * cannot see a PoolConfig an admin has since changed. Treat this pair as a fallback only: it is
6077
+ * shown to a user as what it will cost to get their money out, and if the live config has moved,
6078
+ * this UNDERSTATES that cost. A caller that has already fetched PoolConfig should pass the real
6079
+ * figures through `BridgeQuoteInput.liveWithdrawFixedFee` / `liveWithdrawFeeBps` instead.
6080
+ */
6081
+ declare const WITHDRAW_FIXED_FEE = 450000n;
6082
+ declare const WITHDRAW_FEE_BPS = 30n;
6083
+ /**
6084
+ * Below this, the fixed costs dominate: a deposit works, but most of it goes to fees.
6085
+ *
6086
+ * It is ADVISORY. `viable` is the hard gate; this only warns and asks for a second confirmation,
6087
+ * because it is the user's money and their call.
6088
+ *
6089
+ * WAS 20 USDC, derived from a 1.21 round trip when the paymaster charged $0.458 for something that
6090
+ * cost it $0.104. Fixed pricing took that to $0.150 on 2026-09-07 (docs/17-PAYMASTER-ECONOMICS.md),
6091
+ * the round trip fell to ~0.90, and leaving the constant alone would have warned people off
6092
+ * deposits that had become perfectly reasonable. If the paymaster fee moves again, recompute
6093
+ * FIXED_ROUND_TRIP rather than editing this number.
6094
+ *
6095
+ * 0.903 / a + 0.003 = 0.063 -> a = 15.05
6096
+ */
6097
+ declare const ECONOMIC_MINIMUM: bigint;
6098
+ /**
6099
+ * What a non-refunding rail (Jupiter/GUM) needs SENT before its collector forwards anything: the
6100
+ * collector forwards at least 3,000,000 after its ~151,500 fee. Below this the funds are stranded
6101
+ * with no refund, so the option is refused outright. Refundable rails (1Click) have no such floor.
6102
+ */
6103
+ declare const NON_REFUNDING_MIN_SEND_BASE_UNITS: bigint;
6104
+ /**
6105
+ * The live paymaster fee (`checkPaymasterReady(...).fee`) plus a safety margin, for
6106
+ * `BridgeQuoteInput.paymasterFee`. Use this instead of a fixed constant: the fee is priced live and
6107
+ * a quote that assumes less than it ends up charged turns a viable quote into dust at shield time.
6108
+ * Rounds up. `marginBps` defaults to 10%.
6109
+ */
6110
+ declare function bufferedPaymasterFee(liveFee: bigint, marginBps?: bigint): bigint;
6111
+ interface BridgeQuoteInput {
6112
+ /** What the user sends on the origin chain, in the destination asset's base units. */
6113
+ sent: bigint;
6114
+ /** The rail's GUARANTEED floor. Assess against this, never `amountOut`. */
6115
+ arrivesMin: bigint;
6116
+ /** The rail's target, for display only. */
6117
+ arrivesTarget: bigint;
6118
+ /** What the paymaster will charge to fund the receiver, buffered, in the same units. Build it from
6119
+ * the LIVE fee with `bufferedPaymasterFee(checkPaymasterReady(...).fee)`, not a fixed constant. */
6120
+ paymasterFee: bigint;
6121
+ /** The option's `refunds` flag. REQUIRED: it is the safety property. Anything but `true` applies
6122
+ * `NON_REFUNDING_MIN_SEND_BASE_UNITS`, so a caller that cannot say fails closed. */
6123
+ refunds: boolean;
6124
+ /**
6125
+ * Live PoolConfig withdraw-fee figures, when the caller has already fetched them on-chain.
6126
+ * Optional: omitting either falls back to the compile-time WITHDRAW_FIXED_FEE / WITHDRAW_FEE_BPS
6127
+ * constants above, which can be stale. quote.ts never fetches these itself — no RPC call belongs
6128
+ * in a pure quote assessment — so the live figures can only arrive this way.
6129
+ */
6130
+ liveWithdrawFixedFee?: bigint;
6131
+ liveWithdrawFeeBps?: bigint;
6132
+ }
6133
+ interface BridgeQuoteAssessment extends BridgeQuoteInput {
6134
+ /** What actually lands shielded, worst case. This is the number to show the user. */
6135
+ shieldedMin: bigint;
6136
+ shieldedTarget: bigint;
6137
+ /** False means REFUSE: the shield is impossible, so the deposit must not be offered. */
6138
+ viable: boolean;
6139
+ /** False means warn: it will work, but the fixed costs dominate. */
6140
+ economic: boolean;
6141
+ /** What it would cost to take it out again, so "shielded" is not mistaken for "free to exit". */
6142
+ withdrawFee: bigint;
6143
+ /** Origin-to-recipient loss if they shielded and immediately withdrew, worst case. */
6144
+ roundTripCost: bigint;
6145
+ roundTripFraction: number;
6146
+ /** Human-readable, ordered most important first. Empty when everything is fine. */
6147
+ reasons: string[];
6148
+ /** The same findings as codes, in the same order, for a caller to word itself:
6149
+ * `strandable` (a non-refunding rail under its forwarding floor), `fee_consumes_delivery` (the
6150
+ * paymaster fee is at least what the rail guarantees), `below_pool_minimum` (what is left is
6151
+ * under the pool minimum), `uneconomic` (viable, but fixed costs dominate). */
6152
+ reasonCodes: BridgeAssessmentReasonCode[];
6153
+ /** The smallest `sent` that clears the pool minimum at this quote's rate, when it does not now;
6154
+ * `NON_REFUNDING_MIN_SEND_BASE_UNITS` when strandable and that is larger. Null when viable. */
6155
+ sendAtLeast: bigint | null;
6156
+ }
6157
+ type BridgeAssessmentReasonCode = "strandable" | "fee_consumes_delivery" | "below_pool_minimum" | "uneconomic";
6158
+ declare function withdrawFeeFor(amount: bigint): bigint;
6159
+ declare function assessBridgeQuote(q: BridgeQuoteInput): BridgeQuoteAssessment;
6160
+ /** The quote screen, as the user must see it BEFORE any address is shown. */
6161
+ declare function renderAssessment(a: BridgeQuoteAssessment): string;
6162
+
6163
+ /**
6164
+ * The networks Cloak moves money across, and the address rules that go with them.
6165
+ *
6166
+ * WHY THIS IS IN THE SDK. The website may only use the SDK, so anything that is a rule rather than
6167
+ * a pixel belongs here: which networks exist, what token each one carries and at which exact
6168
+ * contract, which direction money can flow, and — the load-bearing part — how to read an address.
6169
+ * Web keeps the pickers, the React state and its own proxies.
6170
+ *
6171
+ * WHAT THIS IS NOT. It does not quote, rank rails, or decide whether a given amount can be
6172
+ * honoured. `bridge/quote.ts` already owns that: `MIN_DEPOSIT_SPL_BASE_UNITS` is the program's
6173
+ * floor, `assessBridgeQuote` is the hard gate, and `ECONOMIC_MINIMUM` is the advisory one. The
6174
+ * minimums here are STATIC HINTS for a picker to show before any amount exists — per this repo's
6175
+ * standing rule that SDK constants are UX estimates and the deployed program plus the live route
6176
+ * are authoritative. Never gate a transfer on a number from this file.
6177
+ *
6178
+ * THE MODEL. The private balance has no network. An entry describes a BOUNDARY where money crosses
6179
+ * in or out, not a place a balance lives. `deposit` and `payout` are separate because they really
6180
+ * differ: Bitcoin and Zcash can come in and cannot go out.
6181
+ *
6182
+ * THE ADDRESS PICKS THE NETWORK, EXCEPT FOR EVM. A Solana, Sui, Bitcoin or Zcash address names its
6183
+ * own network. Every EVM network shares one format, so `0x` + 40 hex is equally valid on Base,
6184
+ * Ethereum, Arbitrum and Polygon, and the user MUST be asked which one with no default — guessing
6185
+ * sends real money to a chain the recipient may not control, unrecoverably. `mustAskNetwork()`
6186
+ * derives that from the list so a fifth EVM network cannot forget to ask.
6187
+ */
6188
+
6189
+ type NetworkFamily = "solana" | "evm" | "sui" | "bitcoin" | "zcash";
6190
+ /** Which rail carries the money. Rails quote; they are not wallets. */
6191
+ type NetworkRail = "oneclick" | "jupiter";
6192
+ interface NetworkToken {
6193
+ symbol: string;
6194
+ /**
6195
+ * The exact contract, because "USDC" is not specific enough to send money against. Polygon is the
6196
+ * live example: native USDC (`0x3c49…`) and bridged USDC.e are different tokens, and a deposit
6197
+ * sent as the wrong one does not arrive. Absent for a native asset.
6198
+ */
6199
+ contract?: string;
6200
+ decimals: number;
6201
+ /**
6202
+ * 1Click's own asset id for this token (`nep141:...`), the single source for both the origin
6203
+ * asset a deposit quote must name and the destination asset a payout quote must name. Absent
6204
+ * where 1Click has none or it has not been pinned. Read it with `oneClickAssetId`.
6205
+ */
6206
+ oneClickAssetId?: string;
6207
+ /**
6208
+ * Sui only: the exact Move coin type a Sui node knows this token by, for balance reads and
6209
+ * transfers. Case-sensitive. `contract` is NOT a substitute: it is the lowercase spelling the
6210
+ * bridge service quotes with (services `rails/tokens.rs`), and a Sui node treats
6211
+ * `::usdc::usdc` and `::usdc::USDC` as different types, so a read against `contract` finds
6212
+ * nothing. Absent on every other family.
6213
+ */
6214
+ coinType?: string;
6215
+ }
6216
+ interface NetworkDirection {
6217
+ rails: NetworkRail[];
6218
+ /**
6219
+ * The symbols offered in this direction, each one a row of the network's `tokens`. Declared,
6220
+ * never inferred from the table: the table says what exists and how 1Click names it, this says
6221
+ * what a user may pick today. Offering another token is adding its symbol here (its id is
6222
+ * already checked against 1Click's list by the tests). Read it with `depositTokens`.
6223
+ */
6224
+ tokens: readonly string[];
6225
+ /**
6226
+ * A static hint, in USDC base units (6 decimals), for a picker to show before the user has typed
6227
+ * an amount. Every hint in this table is a USDC figure, including on networks whose gas token is
6228
+ * something else: 3_000_000n on Base means 3 USDC, never 3_000_000 wei. Read it with
6229
+ * `depositMinimumHint`, which returns it only for USDC. Absent where it has not been measured —
6230
+ * Bitcoin and Zcash quote in BTC and ZEC, and a number invented for them would be fiction.
6231
+ *
6232
+ * NOT a gate. It is at best the program floor plus rail headroom as measured on one day. The real
6233
+ * answer comes from the live quote via `assessBridgeQuote`; a consumer with no value here must
6234
+ * take it from the quote and must not imply there is no floor.
6235
+ */
6236
+ minimumHint?: bigint;
6237
+ /** Where `minimumHint` came from: the route's own minimum, or the pool floor plus headroom. */
6238
+ minimumHintSource?: "route" | "pool";
6239
+ }
6240
+ interface NetworkEntry {
6241
+ /**
6242
+ * The bridge service's own spelling, forwarded as a plain string with no normalisation on either
6243
+ * side. Must match `services/api/bridge/src/rails/oneclick.rs` `origin_asset()` and
6244
+ * `rails/gum.rs` `source_chain_id()`. A mismatch here is a route a user picks and then fails on.
6245
+ */
6246
+ id: string;
6247
+ /**
6248
+ * Where a person looks up a transaction or an address on this network, as templates with one
6249
+ * `{}` for the value. Use `explorerUrl`, not these strings, so every caller encodes the same way.
6250
+ */
6251
+ explorer: {
6252
+ tx: string;
6253
+ address: string;
6254
+ };
6255
+ label: string;
6256
+ family: NetworkFamily;
6257
+ /**
6258
+ * EVM networks only: the chain id an EIP-1193 wallet reports (`eth_chainId`) and must be switched
6259
+ * to before it sends. Every EVM network shares one address format, so this is what tells a wallet
6260
+ * on Polygon apart from one on Base, and a transfer sent on the wrong one does not arrive. Read it
6261
+ * with `evmChainIdHex`, look a reported id up with `evmNetworkForChainId`. Absent on every other
6262
+ * family.
6263
+ */
6264
+ evmChainId?: number;
6265
+ /**
6266
+ * What the sender's own wallet pays the network in. Worth surfacing before they commit, because a
6267
+ * wallet holding USDC and no gas cannot send, and that failure is otherwise mystifying.
6268
+ */
6269
+ gas: string;
6270
+ tokens: NetworkToken[];
6271
+ deposit: NetworkDirection | null;
6272
+ payout: NetworkDirection | null;
6273
+ /**
6274
+ * `planned` means this lineage cannot reach it yet. Such a row is worth listing and disabling
6275
+ * rather than hiding: "can I use Polygon?" is better answered visibly than by absence.
6276
+ */
6277
+ status: "live" | "planned";
6278
+ }
6279
+ /**
6280
+ * How each family's addresses look.
6281
+ *
6282
+ * These are SHAPE checks, not validity checks. A Solana address matching the base58 pattern can
6283
+ * still fail to decode to 32 bytes, and an EVM address matching this can still be a checksum
6284
+ * mismatch. Use them to route and to write validation copy; where certainty matters, decode.
6285
+ */
6286
+ declare const ADDRESS_SHAPES: Record<NetworkFamily, {
6287
+ pattern: RegExp;
6288
+ shape: string;
6289
+ }>;
6290
+ /** SUI, the coin a Sui wallet pays its network fee in, as a Sui node names it. */
6291
+ declare const SUI_NATIVE_COIN_TYPE = "0x2::sui::SUI";
6292
+ /**
6293
+ * Circle's native USDC on Sui mainnet, as a Sui node names it (case-sensitive). The Sui row's USDC
6294
+ * `coinType`. Its lowercase form is that row's `contract`, the bridge service's quote spelling.
6295
+ */
6296
+ declare const SUI_MAINNET_USDC_COIN_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
6297
+ declare const NETWORKS: readonly NetworkEntry[];
6298
+ /**
6299
+ * A link to `value` (a transaction hash or an address) on `networkId`'s explorer, or undefined for
6300
+ * an unknown network or an empty value. A Sui or EVM address is never sent to a Solana explorer.
6301
+ */
6302
+ declare function explorerUrl(networkId: string, kind: "tx" | "address", value: string): string | undefined;
6303
+ /** Lookup by the service's id. Returns undefined rather than throwing: an unknown id is data. */
6304
+ declare function networkById(id: string): NetworkEntry | undefined;
6305
+ /**
6306
+ * 1Click's asset id for `symbol` on `networkId`, or undefined when the network or token is unknown
6307
+ * or has no pinned id. Callers that bind a signed quote to an asset must treat undefined as a
6308
+ * refusal, never as "skip the check".
6309
+ */
6310
+ declare function oneClickAssetId(networkId: string, symbol: string): string | undefined;
6311
+ /**
6312
+ * The tokens a deposit from `networkId` may start from, as declared by its `deposit.tokens`, in
6313
+ * that order. Empty for an unknown network or one that takes no deposits.
6314
+ */
6315
+ declare function depositTokens(networkId: string): NetworkToken[];
6316
+ /**
6317
+ * The token a deposit from `networkId` starts on: the first one its `deposit.tokens` offers.
6318
+ * Undefined for an unknown network or one that takes no deposits.
6319
+ */
6320
+ declare function defaultDepositToken(networkId: string): NetworkToken | undefined;
6321
+ /**
6322
+ * The token named `symbol` that a deposit from `networkId` OFFERS, or undefined.
6323
+ *
6324
+ * Offered, not merely listed: the table also lists tokens that are pinned but not offered yet
6325
+ * (USDT on Polygon), and a deposit started from one of those is refused by the bridge service.
6326
+ * Looking a token up in `networkById(id).tokens` instead skips that rule. With no `symbol`, the
6327
+ * network's default deposit token.
6328
+ */
6329
+ declare function resolveDepositToken(networkId: string, symbol?: string): NetworkToken | undefined;
6330
+ /**
6331
+ * Networks money can come in from, in display order.
6332
+ *
6333
+ * Includes `planned` rows by default, because a picker lists those as coming soon. Pass
6334
+ * `{ liveOnly: true }` for the networks a deposit may actually start from today: a client that
6335
+ * forgets the filter offers a route the bridge service refuses.
6336
+ */
6337
+ declare function depositNetworks(opts?: {
6338
+ liveOnly?: boolean;
6339
+ }): NetworkEntry[];
6340
+ /**
6341
+ * Networks Cloak can pay out to, in display order. Includes `planned` rows by default; pass
6342
+ * `{ liveOnly: true }` for the ones a payout may go to today.
6343
+ */
6344
+ declare function payoutNetworks(opts?: {
6345
+ liveOnly?: boolean;
6346
+ }): NetworkEntry[];
6347
+ /** What `depositMinimumHint` returns: the hint, the token it is denominated in, and its source. */
6348
+ interface DepositMinimumHint {
6349
+ amount: bigint;
6350
+ token: NetworkToken;
6351
+ source: "route" | "pool";
6352
+ }
6353
+ /**
6354
+ * The static minimum hint for a deposit of `symbol` from `networkId`, or undefined.
6355
+ *
6356
+ * Every `minimumHint` in the table is a USDC figure, so this returns it only when `symbol` is the
6357
+ * network's USDC. For any other token (ETH on Base) the floor comes from the live quote, and
6358
+ * undefined here means "ask the quote", never "there is no minimum".
6359
+ *
6360
+ * A HINT for a picker, not a gate. `assessBridgeQuote` judges the live quote; see the header.
6361
+ */
6362
+ declare function depositMinimumHint(networkId: string, symbol: string): DepositMinimumHint | undefined;
6363
+ /**
6364
+ * The chain id `networkId` uses, as the `0x`-prefixed hex an EIP-1193 wallet takes in
6365
+ * `wallet_switchEthereumChain` and returns from `eth_chainId`. Undefined for a network that is not
6366
+ * EVM or is unknown.
6367
+ */
6368
+ declare function evmChainIdHex(networkId: string): string | undefined;
6369
+ /**
6370
+ * The EVM network with this chain id, given as a number (8453) or as the hex a wallet reports
6371
+ * ("0x2105"). Undefined when no network in the table uses it, which a caller must treat as "wrong
6372
+ * chain", never as a default. Planned networks are included: a wallet can be on Ethereum even
6373
+ * though deposits from it are not offered yet.
6374
+ */
6375
+ declare function evmNetworkForChainId(chainId: number | string): NetworkEntry | undefined;
6376
+ /** Every network sharing `family`'s address format — what decides whether the user must be asked. */
6377
+ declare function networksSharingAddressFormat(family: NetworkFamily): NetworkEntry[];
6378
+ /**
6379
+ * Must the user say which network, for an address of this family?
6380
+ *
6381
+ * True exactly when more than one network shares the format, which today means EVM. Derived from
6382
+ * the list rather than hard-coded, so adding a fifth EVM network cannot forget to ask.
6383
+ */
6384
+ declare function mustAskNetwork(family: NetworkFamily): boolean;
6385
+ /**
6386
+ * Which family's format this address matches, or null.
6387
+ *
6388
+ * Shape only — see `ADDRESS_SHAPES`. Sui is tested before EVM because both start `0x`; their hex
6389
+ * lengths differ, so the order is defensive rather than load-bearing. A non-null answer does NOT
6390
+ * identify a network: for `"evm"` the caller must still ask which one.
6391
+ */
6392
+ declare function familyOfAddress(address: string): NetworkFamily | null;
6393
+ /**
6394
+ * The networks an address of `family` can be paid on today: those with a payout direction that are
6395
+ * live. For `"evm"` this is the list a person must choose from (Base, Polygon); for `"sui"` it is
6396
+ * Sui alone; for Solana it is empty, because paying a Solana address is a plain withdrawal, not a
6397
+ * payout. Building a picker from this and checking a stored choice against it keeps the two from
6398
+ * disagreeing.
6399
+ */
6400
+ declare function livePayoutNetworksFor(family: NetworkFamily): NetworkEntry[];
6401
+ /**
6402
+ * What a typed recipient is, before anything is sent to it.
6403
+ *
6404
+ * - `"solana"`: decodes to a 32-byte Solana address. A plain withdrawal, not a payout.
6405
+ * - `"sui"`, `"evm"`: an address on another network. A payout; for `"evm"` the network must still
6406
+ * be chosen (`mustAskNetwork`).
6407
+ * - `"domain"`: a `.sol` name, which the caller resolves to a Solana address first.
6408
+ * - `"unsupported"`: a well-formed address on a network nothing pays out to (Bitcoin, Zcash).
6409
+ * - `"invalid"`, `"empty"`: neither.
6410
+ *
6411
+ * The Solana check decodes the address rather than matching its shape, so a base58 string of the
6412
+ * wrong length is `"invalid"`, not `"solana"`.
6413
+ */
6414
+ type RecipientKind = "empty" | "solana" | "sui" | "evm" | "domain" | "unsupported" | "invalid";
6415
+ declare function classifyRecipient(input: string): RecipientKind;
6416
+
6417
+ /** A response reduced to what the SDK reads: the HTTP status and the parsed JSON body (`{}` when
6418
+ * the body was not JSON). Same shape as the payout transport's. */
6419
+ interface BridgeCarriedResponse {
6420
+ status: number;
6421
+ body: unknown;
6422
+ }
6423
+ interface BridgeTransport {
6424
+ /** GET a service path, query included (`/bridge/status?deposit_address=...&rail=...`). */
6425
+ get(path: string): Promise<BridgeCarriedResponse>;
6426
+ /** POST a JSON body to a service path (`/bridge/quote`). */
6427
+ post(path: string, body: unknown): Promise<BridgeCarriedResponse>;
6428
+ }
6429
+ /** Reads a `Response` into the carried shape. An unreadable body reads as `{}`, the status still
6430
+ * says what happened. */
6431
+ declare function carryBridgeResponse(res: Response): Promise<BridgeCarriedResponse>;
6432
+ /** The transport straight to Cloak's service on the relay origin. The origin lock applies. */
6433
+ declare function relayBridgeTransport(relayUrl: string): BridgeTransport;
6434
+ /**
6435
+ * A transport over the caller's own request function, for a website that routes the bridge through
6436
+ * its own proxy. `send` gets the service path and a ready `RequestInit`; where it sends them is the
6437
+ * caller's decision and the caller's egress, not the SDK's.
6438
+ */
6439
+ declare function bridgeTransportFromFetch(send: (path: string, init: {
6440
+ method: "GET" | "POST";
6441
+ headers?: Record<string, string>;
6442
+ body?: string;
6443
+ }) => Promise<Response>): BridgeTransport;
6444
+ /**
6445
+ * The service's one error body (`services/api/bridge/src/error.rs`: `{ error, message, code,
6446
+ * retryable }`), typed. Match on `code`, never on `message`. `status` is the HTTP status.
6447
+ */
6448
+ declare class BridgeApiError extends Error {
6449
+ readonly status: number;
6450
+ readonly code: string | undefined;
6451
+ readonly retryable: boolean;
6452
+ constructor(message: string, status: number, code: string | undefined, retryable: boolean);
6453
+ }
6454
+ declare function isBridgeApiError(e: unknown, code?: string): e is BridgeApiError;
6455
+ /** The body of a 2xx response, or a `BridgeApiError` built from the service's error body. */
6456
+ declare function readBridgeBody<T>(res: BridgeCarriedResponse, what: string): T;
6457
+
5958
6458
  /**
5959
6459
  * What a quote option attests, which is NOT the same question as whether the rail worked.
5960
6460
  *
@@ -5992,20 +6492,80 @@ interface BridgeRailQuoteOption {
5992
6492
  * where nothing has been reserved and there is nothing to send to yet. */
5993
6493
  depositAddress?: string;
5994
6494
  attestation: BridgeRailAttestation;
6495
+ /**
6496
+ * What was sent, valued in the destination asset's base units from the signed quote (see
6497
+ * `BoundDeposit.sentInDestinationUnits`). Present on verified options only. Use it as a viability
6498
+ * check's `sent`: `amountBaseUnits` is in the origin token's units, which may not be the same.
6499
+ */
6500
+ sentInDestinationUnits?: bigint;
5995
6501
  }
6502
+ /**
6503
+ * Why an option was not used, as a code a caller maps to its own words. `reason` is the SDK's
6504
+ * English, for logs.
6505
+ *
6506
+ * - `rail_not_requested`: the request named its rails and this is not one of them.
6507
+ * - `unknown_origin_asset`: no 1Click id for this network and token, so a signed quote cannot be bound.
6508
+ * - `signature_unverified`: the signed quote failed verification or does not bind to this request.
6509
+ * - `malformed_amount`: an unsigned option carried an amount that is not a whole number.
6510
+ * - `no_destination_value`: nothing says what the transfer is worth on arrival, so it cannot be judged.
6511
+ * - `rail_unavailable`: the service reported the rail as down or refusing.
6512
+ */
6513
+ type BridgeOptionRefusalCode = "rail_not_requested" | "unknown_origin_asset" | "signature_unverified" | "malformed_amount" | "no_destination_value" | "rail_unavailable";
5996
6514
  interface BridgeRailProblem {
5997
6515
  rail: string;
5998
6516
  reason: string;
6517
+ /** Absent only on problems built by older callers. */
6518
+ code?: BridgeOptionRefusalCode;
6519
+ }
6520
+ /**
6521
+ * The rail whose quotes are signed and which refunds. Its options must always verify.
6522
+ */
6523
+ declare const BRIDGE_SIGNED_RAIL = "oneclick";
6524
+ /**
6525
+ * The rails a deposit from `networkId` may use: the network table's `deposit.rails` (today the
6526
+ * signed, refunding rail everywhere). Empty for a network that takes no deposits.
6527
+ */
6528
+ declare function bridgeDepositRails(networkId: string): string[];
6529
+ /**
6530
+ * Why a quote request was refused before anything was sent.
6531
+ *
6532
+ * - `token_not_offered`: the network does not offer this token for deposits.
6533
+ * - `owner_required`: no `solanaOwner`.
6534
+ * - `no_deposits`: the network takes no deposits.
6535
+ * - `rail_not_offered`: a named rail is not one this network's deposits use.
6536
+ * - `allocate_needs_one_rail`: an allocating quote must name exactly one rail.
6537
+ */
6538
+ type BridgeQuoteRequestErrorCode = "token_not_offered" | "owner_required" | "no_deposits" | "rail_not_offered" | "allocate_needs_one_rail";
6539
+ declare class BridgeQuoteRequestError extends Error {
6540
+ readonly code: BridgeQuoteRequestErrorCode;
6541
+ constructor(code: BridgeQuoteRequestErrorCode, message: string);
5999
6542
  }
6543
+ declare function isBridgeQuoteRequestError(e: unknown, code?: BridgeQuoteRequestErrorCode): e is BridgeQuoteRequestError;
6000
6544
  interface BridgeRailQuoteRequest {
6001
6545
  /** The derived receiving address R. Base58, on Solana. */
6002
6546
  recipient: string;
6547
+ /**
6548
+ * The Solana wallet whose keys will control the shielded note (base58): the party putting money
6549
+ * into the pool, and so the one the service screens. Required: the service answers 400 without
6550
+ * it, never an unscreened quote. `recipient` is freshly derived and is not screened in its place.
6551
+ */
6552
+ solanaOwner: string;
6003
6553
  originChain: string;
6004
6554
  /** Base units on the origin chain, as a bigint — a JS `number` loses precision above 2^53 and
6005
6555
  * this can be an arbitrary token amount. */
6006
6556
  amountBaseUnits: bigint;
6007
6557
  /** Origin-chain address an unfillable 1Click order refunds to. Required for that rail. */
6008
6558
  refundTo?: string;
6559
+ /**
6560
+ * What is sent, by its symbol in the origin network's token table ("ETH", "USDT", ...). Default
6561
+ * "USDC". The quote is asked for as that token (`origin_token`: its contract, or "native") and a
6562
+ * signed quote must be pinned to that token's 1Click id. `amountBaseUnits` is in ITS units.
6563
+ */
6564
+ originToken?: string;
6565
+ /**
6566
+ * The rails to ask. Default: the network's deposit rails (`bridgeDepositRails`). A rail outside
6567
+ * them is refused before anything is sent. With `allocate: true`, exactly one rail.
6568
+ */
6009
6569
  rails?: string[];
6010
6570
  /** False (the default) sends `dry: true` to 1Click and skips GUM's allocation probes: nothing is
6011
6571
  * reserved and no `depositAddress` comes back. Requesting an allocation for a deposit the quote
@@ -6027,12 +6587,46 @@ interface BridgeRailQuoteResponse {
6027
6587
  * value 1Click returns.
6028
6588
  */
6029
6589
  type BridgeDeliveryState = "pending" | "delivered" | "refunded" | "expired" | "unknown";
6590
+ /** Where a `"pending"` order is. Display only: `state` is what a caller acts on. */
6591
+ type BridgePendingStage = "awaiting_deposit" | "deposit_received" | "processing";
6592
+ /**
6593
+ * An amount with the token it is counted in. `token` is null when the caller did not say what the
6594
+ * order sent (`status(..., origin)` absent): the number is then in units this client cannot name,
6595
+ * and must not be printed as USDC.
6596
+ */
6597
+ interface BridgeTokenAmount {
6598
+ baseUnits: bigint;
6599
+ token: NetworkToken | null;
6600
+ }
6601
+ /**
6602
+ * What the rail reports it moved (`status.rs`'s `Delivery`), parsed once. A report, not a ledger.
6603
+ * `amountIn` and `refundedAmount` are ORIGIN-token base units (wei for ETH), `amountOut` is the
6604
+ * destination asset's (Solana USDC). Zero or unreadable amounts are null.
6605
+ */
6606
+ interface BridgeDeliveryFacts {
6607
+ stage: BridgePendingStage | null;
6608
+ amountIn: BridgeTokenAmount | null;
6609
+ amountOut: bigint | null;
6610
+ refundedAmount: BridgeTokenAmount | null;
6611
+ originTxHashes: string[];
6612
+ /** Origin hashes the service could not read and left out. Display can ignore them. */
6613
+ originTxHashesUnreadable: number;
6614
+ destinationTxHashes: string[];
6615
+ }
6030
6616
  interface BridgeRailStatusResult {
6031
6617
  /** The rail that answered, echoed from the service. */
6032
6618
  rail: string;
6033
6619
  state: BridgeDeliveryState;
6034
6620
  /** The service's own explanation of `state`, e.g. why a `"jupiter"` query is `"unknown"`. */
6035
6621
  detail: string;
6622
+ /** Null when the service sent none (GUM, an older service). */
6623
+ delivery: BridgeDeliveryFacts | null;
6624
+ }
6625
+ /** What the order sent, so status amounts carry their token. */
6626
+ interface BridgeStatusOrigin {
6627
+ originChain: string;
6628
+ /** Symbol in the network's token table. Default "USDC", as for a quote. */
6629
+ originToken?: string;
6036
6630
  }
6037
6631
  interface BridgeRail {
6038
6632
  readonly id: string;
@@ -6041,111 +6635,110 @@ interface BridgeRail {
6041
6635
  * `rail` is the `rail` of the quote option whose `depositAddress` this is: the service keys its
6042
6636
  * status lookup on (address, rail) because the two rails have unrelated status surfaces.
6043
6637
  */
6044
- status(depositAddress: string, rail: string): Promise<BridgeRailStatusResult>;
6638
+ status(depositAddress: string, rail: string, origin?: BridgeStatusOrigin): Promise<BridgeRailStatusResult>;
6639
+ }
6640
+ interface RawBridgeAttestation {
6641
+ kind: "ed25519" | "none";
6642
+ verified?: boolean;
6643
+ signer?: string;
6644
+ checks?: string[];
6645
+ note?: string;
6045
6646
  }
6647
+ /** A quote option exactly as the service serialises it (`rails::QuoteOption`). */
6648
+ interface RawBridgeQuoteOption {
6649
+ rail: string;
6650
+ refunds: boolean;
6651
+ address_lifetime: string;
6652
+ amount_out: string;
6653
+ min_amount_out: string;
6654
+ time_estimate_s?: number;
6655
+ expires_at?: string;
6656
+ deposit_address?: string;
6657
+ attestation: RawBridgeAttestation;
6658
+ /** The rail's own response body, forwarded byte-for-byte (`RawValue` on the service side, never
6659
+ * a re-serialised struct) precisely so this client's signature check runs over what the rail
6660
+ * actually produced. */
6661
+ rail_response?: unknown;
6662
+ }
6663
+ /** What one option is checked against. */
6664
+ interface BridgeOptionVetRequest {
6665
+ recipient: string;
6666
+ amountBaseUnits: bigint;
6667
+ refundTo?: string;
6668
+ allocate: boolean;
6669
+ /** When named, an option on any other rail is refused. */
6670
+ rails?: readonly string[];
6671
+ /** The 1Click id of what is sent (`oneClickAssetId(network, symbol)`). Without it a signed option
6672
+ * cannot be bound to the right chain and token, so it is refused. */
6673
+ originAsset?: string;
6674
+ }
6675
+ type BridgeOptionVetResult = {
6676
+ ok: true;
6677
+ option: BridgeRailQuoteOption;
6678
+ } | {
6679
+ ok: false;
6680
+ problem: BridgeRailProblem;
6681
+ };
6682
+ /**
6683
+ * THE CHECK A QUOTE OPTION MUST PASS before its address or amounts are shown, decided from what the
6684
+ * option IS, never from what the service says about it.
6685
+ *
6686
+ * The service's `attestation` is its own opinion of its own honesty, and a server that wants to skip
6687
+ * verification would simply label a 1Click option "none". So the rail id picks the check: every
6688
+ * `oneclick` option must carry a `rail_response` whose signature verifies AND whose signed payload
6689
+ * binds to this request (recipient, amount, origin asset, refund, deposit address, freshness),
6690
+ * whatever the service claims; its amounts and (allocated) expiry come from the signed payload. Any
6691
+ * other rail is unsigned by nature and is returned as unsigned, whatever its label claims.
6692
+ *
6693
+ * `cloakBridgeRail().quote` runs this on every option; it is exported for a client that receives
6694
+ * options some other way. Never throws: a malformed option is a refusal.
6695
+ */
6696
+ declare function vetBridgeQuoteOption(opt: RawBridgeQuoteOption, req: BridgeOptionVetRequest, nowMs: number): BridgeOptionVetResult;
6697
+ /** `status.rs`'s `delivery`, parsed once. Anything malformed is left out, as the service does. */
6698
+ declare function parseBridgeDelivery(raw: unknown, origin?: BridgeStatusOrigin): BridgeDeliveryFacts | null;
6699
+ /**
6700
+ * How an order that closed by itself ended, for a caller to word. Only for `"refunded"` and
6701
+ * `"expired"` statuses; null for any other state.
6702
+ *
6703
+ * - `refunded`: the rail reports it returned the money (`delivery.refundedAmount` says how much,
6704
+ * when it says).
6705
+ * - `closed-received`: it closed after the rail reports receiving `amountIn`. That report is
6706
+ * trusted only when the caller saw its own deposit leave (`depositSeen`) or the order was paid by
6707
+ * hand (`manual`, no wallet hash to see): an unproven "received" must not claim money moved.
6708
+ * - `expired-no-deposit`: expired and no deposit was ever seen.
6709
+ * - `closed-unfinished`: closed after a deposit was seen, with no amount reported.
6710
+ */
6711
+ type BridgeTerminalKind = "refunded" | "closed-received" | "expired-no-deposit" | "closed-unfinished";
6712
+ declare function classifyBridgeTerminal(status: Pick<BridgeRailStatusResult, "state" | "delivery">, ctx: {
6713
+ depositSeen: boolean;
6714
+ manual?: boolean;
6715
+ }): BridgeTerminalKind | null;
6046
6716
  /**
6047
6717
  * The one constructor this package exposes for talking to the bridge rails — always through
6048
6718
  * Cloak's own service, never through a rail's API or Kora.
6049
6719
  *
6050
- * `relayUrl` is checked HERE, at construction, in addition to the check `relayFetch` repeats on
6051
- * every call: a caller who mistypes a rail's own base URL (or Kora's) finds out immediately rather
6052
- * than on first use, and `assertAllowedRelayOrigin` in this function's own body is what lets
6053
- * `relay-origin-lock.test.ts` enumerate this door the same way it enumerates `RelayService`'s
6054
- * constructor.
6720
+ * Given a relay URL, it is checked HERE, at construction, in addition to the check `relayFetch`
6721
+ * repeats on every call: a caller who mistypes a rail's own base URL (or Kora's) finds out
6722
+ * immediately rather than on first use, and `assertAllowedRelayOrigin` in this function's own body
6723
+ * is what lets `relay-origin-lock.test.ts` enumerate this door the same way it enumerates
6724
+ * `RelayService`'s constructor.
6725
+ *
6726
+ * Given a `BridgeTransport` (a website's own proxy, `bridgeTransportFromFetch`), requests go where
6727
+ * that transport sends them. Every check on what comes back still runs here, unchanged: the signed
6728
+ * quote is verified and bound to the request whatever the transport is.
6055
6729
  */
6056
- declare function cloakBridgeRail(relayUrl: string): BridgeRail;
6730
+ declare function cloakBridgeRail(target: string | BridgeTransport): BridgeRail;
6057
6731
 
6058
6732
  /**
6059
- * The paymaster client — the SOL top-up that lets a bridge receiver R (which arrives holding only
6060
- * bridged tokens, no SOL) shield without the user's own wallet ever appearing on chain.
6733
+ * Deriving a bridge receiving address.
6061
6734
  *
6062
- * Talks ONLY to Cloak's own bridge service (`api.cloak.ag/bridge/paymaster/*`), never to Kora
6063
- * directly: under fixed pricing (docs/00-DECISION-STATE.md, PAYMASTER ECONOMICS) the Kora API key is
6064
- * worth real money to whoever holds it, and a browser bundle is not a place that can keep a secret.
6735
+ * One single-use address per deposit, from the wallet's own SPEND-level key material.
6736
+ * Deterministic, offline, and stateless, which is what lets every other function here work on a
6737
+ * device that has never seen this deposit before.
6065
6738
  *
6066
- * ── The two-round-trip shape, and why it is not one call ─────────────────────────────────────
6067
- * `prepare` returns an UNSIGNED transaction the service built and priced, plus a voucher that MACs
6068
- * the exact message bytes. The client's receiving key R signs it — R never leaves the client, and
6069
- * this is the only place it signs anything for the paymaster flow — and hands the bytes back
6070
- * unchanged to `cosign`, which recognises them via the voucher and only THEN asks Kora to co-sign as
6071
- * fee payer. The paymaster's key never leaves the server; R's key never leaves the client; neither
6072
- * round trip needs the other's secret. See `services/api/bridge/src/api/paymaster.rs` for the
6073
- * server half of this contract.
6074
- *
6075
- * ── Why the shape check below is not optional ────────────────────────────────────────────────
6076
- * `cosign` answers exactly one question — "is this the message I built?" — and answers it by MAC,
6077
- * not by re-deriving policy from an arbitrary transaction. That makes `prepare`'s response the ONLY
6078
- * point where an unexpected instruction could sneak in (a compromised service, a MITM'd response, a
6079
- * bug that built the wrong thing), because nothing downstream re-checks it. `validate
6080
- * PaymasterTopUpTransaction` is that one check, and it runs BEFORE R signs anything: signing is the
6081
- * one irreversible step in this flow from the client's point of view, so the check that matters has
6082
- * to sit in front of it, not after.
6083
- */
6084
-
6085
- /** What `prepare`'s response is checked against before R ever signs it. */
6086
- interface PaymasterTopUpExpectation {
6087
- /** R — the only account this transaction may fund or spend from. */
6088
- recipient: Address;
6089
- /** The lamports we asked for. `ix0.lamports` may come in at or under this, never over. */
6090
- maxGrantLamports: bigint;
6091
- feeMint: Address;
6092
- /** The fee Kora actually quoted at `prepare` time. `ix1.amount`, if `ix1` exists, must equal this
6093
- * exactly — not "at most", because the fee is a quote the service already committed to, not a
6094
- * ceiling. */
6095
- feeTokenAmount: bigint;
6096
- /** The paymaster's own token account owner, from `prepare`'s `payment_address`. `ix1`'s
6097
- * destination must be exactly THIS address's ATA for `feeMint` — nothing else, and never an ATA
6098
- * derived from `recipient` or from an address the caller does not already trust. */
6099
- paymentAddress: Address;
6100
- }
6101
- /**
6102
- * The one check standing between `prepare`'s response and R's signature.
6103
- *
6104
- * Two instructions, and the shape IS the security story (`paymaster/topup.rs`'s own words, mirrored
6105
- * here on the verifying side):
6106
- *
6107
- * ix0 System transfer, paymaster -> recipient, <= the lamports we asked for
6108
- * ix1 (optional) SPL transfer, recipient's fee-mint ATA -> paymaster's fee-mint ATA, authority
6109
- * = recipient, amount == the quoted fee
6110
- *
6111
- * Anything else — a third instruction, a different destination, a different authority, an amount
6112
- * that does not match the quote — is refused. This function throws rather than returning a verdict:
6113
- * there is no partial-trust path here, and a caller that wants to keep going after a refusal is a
6114
- * caller papering over a corrupted or hostile response.
6115
- *
6116
- * Async (unlike the web3.js original): the paymaster's own fee-mint ATA (`expectedDestination`
6117
- * below) is derived through kit's PDA path, which goes through WebCrypto and has no sync form.
6118
- */
6119
- declare function validatePaymasterTopUpTransaction(tx: Transaction, expect: PaymasterTopUpExpectation): Promise<void>;
6120
- interface PaymasterTopUpResult {
6121
- /** Fully signed by both R and the paymaster. The caller submits it — Kora's own
6122
- * `signAndSendTransaction` is disabled service-side, and the broadcast should not carry the
6123
- * service's IP any more than the deposit itself should carry R's. */
6124
- transaction: Transaction;
6125
- feeTokenAmount: bigint;
6126
- feeMint: string;
6127
- paymentAddress: string;
6128
- }
6129
- /**
6130
- * The whole paymaster flow: prepare, verify the shape, sign as R, cosign, return the fully-signed
6131
- * transaction for the caller to submit.
6132
- *
6133
- * `receiver` is the derived bridge receiving key (`deriveBridgeReceiver`). It signs here and only
6134
- * here in this file's flow, and its secret never leaves this function — nothing above needs it, and
6135
- * nothing here sends it anywhere.
6136
- */
6137
- declare function fundReceiverViaPaymaster(relayUrl: string, receiver: KeyPairSigner, grantLamports: bigint): Promise<PaymasterTopUpResult>;
6138
-
6139
- /**
6140
- * Deriving a bridge receiving address.
6141
- *
6142
- * One single-use address per deposit, from the wallet's own SPEND-level key material.
6143
- * Deterministic, offline, and stateless, which is what lets every other function here work on a
6144
- * device that has never seen this deposit before.
6145
- *
6146
- * The receiver is a full Solana signer and bridged funds sit at it in transit, so it must not be
6147
- * derivable from the viewing key `nk` (which is registered with the relay and may be shared). It is
6148
- * derived from the wallet's long-lived UTXO private key:
6739
+ * The receiver is a full Solana signer and bridged funds sit at it in transit, so it must not be
6740
+ * derivable from the viewing key `nk` (which is registered with the relay and may be shared). It is
6741
+ * derived from the wallet's long-lived UTXO private key:
6149
6742
  *
6150
6743
  * key = BLAKE3("cloak_bridge_receiver_key_v2" || utxoPrivateKey(32B BE))
6151
6744
  * seed = HMAC-SHA512(key, "cloak_bridge_escrow_v2:<index>")[0..32]
@@ -6176,6 +6769,38 @@ declare const BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
6176
6769
  * being documented and it being enforced.
6177
6770
  */
6178
6771
  declare const MAX_RECEIVER_INDEX = 10000;
6772
+ /**
6773
+ * Deposit receivers use indices in `[0, BRIDGE_DEPOSIT_INDEX_LIMIT)`.
6774
+ *
6775
+ * The indices from here up to `MAX_RECEIVER_INDEX` are derived the same way (`deriveBridgeReceiver`,
6776
+ * same keypair, same label) but belong to payouts: the payout refund key is `PAYOUT_REFUND_INDEX`
6777
+ * (8_999) and the payout collectors are `PAYOUT_COLLECTOR_INDEX_BASE` (9_000) through
6778
+ * `MAX_RECEIVER_INDEX` (`../payouts`). A deposit handed one of those indices would share an
6779
+ * on-chain address with a payout, which links the two, and a deposit scan reaching them would
6780
+ * report payout money as a deposit. So a deposit index is checked against this limit, not against
6781
+ * `MAX_RECEIVER_INDEX`. A test pins it equal to `PAYOUT_REFUND_INDEX`.
6782
+ */
6783
+ declare const BRIDGE_DEPOSIT_INDEX_LIMIT = 8999;
6784
+ /**
6785
+ * True for an index a deposit receiver may use: an integer in `[0, BRIDGE_DEPOSIT_INDEX_LIMIT)`.
6786
+ *
6787
+ * The one check for every place that reads a deposit index back (a saved order record, a pending
6788
+ * marker, a reservation), so a value that is not a number, is fractional, or falls in the payout
6789
+ * range is refused the same way everywhere.
6790
+ */
6791
+ declare function isBridgeDepositIndex(n: unknown): n is number;
6792
+ /**
6793
+ * The identity of a discovered deposit receiver: `current:<index>` or `legacy:<index>`.
6794
+ *
6795
+ * The index alone is not an identity. A legacy receiver (derived from a viewing key `nk`, the first
6796
+ * bridge release) and a current one (derived from the UTXO keypair) are different addresses in
6797
+ * different address spaces, and can carry the same index. Anything that remembers which receivers
6798
+ * it has handled, such as a retry list or an attempt counter, keys them by this.
6799
+ */
6800
+ declare function bridgeDepositKey(deposit: {
6801
+ index: number;
6802
+ legacyExposed?: boolean;
6803
+ }): string;
6179
6804
  /**
6180
6805
  * Derive the bridge receiving address for `index` from the wallet's long-lived UTXO keypair.
6181
6806
  *
@@ -6193,6 +6818,87 @@ declare function deriveBridgeReceiver(ownerUtxoKeypair: UtxoKeypair, index: numb
6193
6818
  */
6194
6819
  declare function deriveLegacyBridgeReceiver(nk: Uint8Array | Buffer, index: number): Promise<KeyPairSigner>;
6195
6820
 
6821
+ interface DepositOutcome {
6822
+ signature: string;
6823
+ noteIndex: number;
6824
+ amount: bigint;
6825
+ txSize: number;
6826
+ rBefore: number;
6827
+ rAfter: number;
6828
+ rentExempt: boolean;
6829
+ /** The proof's two input nullifiers (zero-value padding for a pure deposit, but each one is a
6830
+ * genuine Poseidon hash over a random salt — NOT the literal zero sentinel the program treats
6831
+ * as "no PDA needed". See phase4-adversarial.ts case (c). */
6832
+ inputNullifiers: bigint[];
6833
+ /** The three program accounts the funding seam read off the built tx, and what it sent each —
6834
+ * 0 if the account already held enough. Exposed so a caller can independently verify their
6835
+ * on-chain state afterward, including after a thrown error (see `DepositError` below). */
6836
+ fundedAccounts: {
6837
+ name: string;
6838
+ address: string;
6839
+ lamportsSent: number;
6840
+ }[];
6841
+ /** The note this deposit created, spendable and carrying its leaf `index`, so a wallet can store
6842
+ * it the moment the deposit confirms. Without it a caller's only way to the note is a rescan,
6843
+ * which on the relay's Note Index waits for the slot to finalize (~13 s). A rescan still finds
6844
+ * it: the note is deterministic from the spend key and the salt published on chain. */
6845
+ note: Utxo;
6846
+ }
6847
+ /** One account `depositFromDerivedKey` needs funded before its deposit can land, and how many
6848
+ * lamports it is short. Handed to `opts.fundAccounts`. */
6849
+ interface DepositFundingTarget {
6850
+ /** "receiver" (R itself), "risk_nonce", "nullifier_0" or "nullifier_1". */
6851
+ name: string;
6852
+ address: Address;
6853
+ lamports: bigint;
6854
+ }
6855
+ /** Thrown by `depositFromDerivedKey` in place of a bare `Error` whenever the funding seam ran
6856
+ * before the failure, so a caller can see exactly what already landed on chain despite the
6857
+ * overall deposit failing. `fundedAccounts` / `measuredSize` are `undefined` only if the seam
6858
+ * never ran at all (failure before signing was attempted). */
6859
+ declare class DepositError extends Error {
6860
+ readonly fundedAccounts: DepositOutcome["fundedAccounts"];
6861
+ readonly measuredTxSize: number;
6862
+ constructor(message: string, fundedAccounts: DepositOutcome["fundedAccounts"], measuredTxSize: number);
6863
+ }
6864
+ /**
6865
+ * Fund R minimally, then deposit with R as the only signer.
6866
+ *
6867
+ * `grantOverride` replaces the computed grant (rent floor + deposit fee + cleanup fee) with an
6868
+ * arbitrary lamport amount. Only phase4-adversarial.ts case (a) passes it, to reproduce the
6869
+ * "funded R with just its fee, not its floor" mistake deliberately; every other caller omits it
6870
+ * and gets the same grant this function has always sent.
6871
+ */
6872
+ declare function depositFromDerivedKey(rpc: CloakRpc, R: KeyPairSigner, funder: KeyPairSigner, amount: bigint, log: ((s: string) => void) | undefined, grantOverride: number | undefined,
6873
+ /**
6874
+ * relayUrl, programId and mint are all REQUIRED — no default, for any of the three, on any
6875
+ * environment. They used to fall back to the module-level RELAY/PROGRAM/MINT constants above,
6876
+ * each evaluated once at import time, and that is exactly how a live mainnet deposit got built
6877
+ * against the local program id while the banner said api.cloak.ag: the default filled the hole
6878
+ * silently instead of the caller having to say so. There is nothing left to fall into.
6879
+ */
6880
+ opts: {
6881
+ relayUrl: string;
6882
+ programId: Address;
6883
+ mint: Address;
6884
+ noteSpendKey: Uint8Array;
6885
+ /**
6886
+ * Fund R and the deposit's three program accounts in ONE caller-built transaction, at signing
6887
+ * time, instead of a top-up of R before the proof plus a funding transaction from `funder`
6888
+ * after it. Called once with every account still short, R first; it must not return until
6889
+ * that funding has confirmed. `funder` is unused when this is set.
6890
+ *
6891
+ * For a paymaster-funded receiver this is one Solana transaction fewer. Its fee, if it takes one
6892
+ * from R's tokens, has to be known BEFORE this call: `amount` is proved first, so it must
6893
+ * already leave room for it.
6894
+ *
6895
+ * R holds no SOL until this runs, so a deposit that needs R to pay for anything earlier (its
6896
+ * own lookup table, when the relay will not extend the shared one) fails before anything is
6897
+ * funded. A caller that expects that path should not set this.
6898
+ */
6899
+ fundAccounts?: (targets: DepositFundingTarget[]) => Promise<void>;
6900
+ }): Promise<DepositOutcome>;
6901
+
6196
6902
  type BridgeDepositState =
6197
6903
  /** Nothing ever happened at this index. */
6198
6904
  "unused"
@@ -6204,6 +6910,13 @@ type BridgeDepositState =
6204
6910
  | "complete"
6205
6911
  /** Shielded, but the token account is still open and holding its rent. */
6206
6912
  | "needs-cleanup"
6913
+ /**
6914
+ * Never shielded; its tokens were moved out to a wallet in public (`moveReceiverFundsToWallet`)
6915
+ * and it holds none now. Terminal: nothing is waiting here, and this index must not be reused,
6916
+ * because the address is linked to wherever the tokens went. Money that lands again later
6917
+ * reports as "arrived".
6918
+ */
6919
+ | "moved-out"
6207
6920
  /**
6208
6921
  * An RPC read failed while checking this index. This is NOT evidence of absence — it is the
6209
6922
  * opposite of "unused" in every way that matters to a caller: a rate-limited or dropped read
@@ -6234,6 +6947,9 @@ interface BridgeDeposit {
6234
6947
  indexReused?: boolean;
6235
6948
  /** Every shield-pool signature found at this receiver, most recent first. Present only when indexReused. */
6236
6949
  shieldSignatures?: string[];
6950
+ /** The transaction that moved this receiver's tokens out without shielding them, most recent first
6951
+ * in its history. Set when state is "moved-out". */
6952
+ moveSignature?: string;
6237
6953
  /** Set only when state is "unknown": the failure that made this index's status unconfirmable. */
6238
6954
  error?: string;
6239
6955
  /**
@@ -6256,13 +6972,17 @@ interface DiscoverOptions {
6256
6972
  * reason to believe a deposit landed further out (a CLI --index flag, a resumed session that
6257
6973
  * knows its own counter) MUST pass a larger scanDepth explicitly — anything past the configured
6258
6974
  * depth is simply never read, and reports as neither found nor absent, because it was not looked
6259
- * at. Clamped to MAX_RECEIVER_INDEX + 1 (the count of valid indices, 0 through MAX_RECEIVER_INDEX
6260
- * inclusive): deriveBridgeReceiver throws past that ceiling, and without the clamp a caller who
6261
- * over-estimates scanDepth turns that into a mid-scan crash that discards every deposit already
6262
- * found in the same call.
6975
+ * at. Current receivers are clamped to BRIDGE_DEPOSIT_INDEX_LIMIT (8,999): the indices from there
6976
+ * up are the payout refund key and collectors, derived the same way, and a scan reaching them would
6977
+ * report a payout's money as a deposit. Legacy receivers (their own address space, nothing else
6978
+ * derives there) are clamped to MAX_RECEIVER_INDEX + 1: deriveLegacyBridgeReceiver throws past
6979
+ * that ceiling, and without the clamp a caller who over-estimates scanDepth turns that into a
6980
+ * mid-scan crash that discards every deposit already found in the same call.
6263
6981
  */
6264
6982
  scanDepth?: number;
6265
- /** Stop after this many consecutive unused indices. An "unknown" index (RPC failure) neither
6983
+ /** Stop after this many consecutive unused indices (default 20). Abandoned allocations leave gaps,
6984
+ * and a shorter run once put a later PAID receiver outside recovery; a caller that knows its
6985
+ * highest allocated index should raise this together with `scanDepth`. An "unknown" index (RPC failure) neither
6266
6986
  * counts toward nor resets this run — it carries no information about presence or absence, so
6267
6987
  * letting it break a real run of unused indices early would reintroduce the same false-absence
6268
6988
  * failure this file exists to prevent. */
@@ -6278,6 +6998,12 @@ interface DiscoverOptions {
6278
6998
  /** Extra viewing keys whose legacy receivers should be scanned (deduplicated). */
6279
6999
  legacyViewingKeyNks?: Uint8Array[];
6280
7000
  }
7001
+ /**
7002
+ * True when `instructions` hold a top-level SPL Token (or Token-2022) transfer out of
7003
+ * `tokenAccount`: how `moveReceiverFundsToWallet` leaves a receiver. The shield transaction moves
7004
+ * tokens out too, but it is recognised first by the program id, so it never reaches this check.
7005
+ */
7006
+ declare function movesTokensOut(instructions: readonly ParsedInstruction[], tokenAccount: Address): boolean;
6281
7007
  /**
6282
7008
  * A terminal state needs TWO conjuncts, never one.
6283
7009
  *
@@ -6289,80 +7015,232 @@ interface DiscoverOptions {
6289
7015
  */
6290
7016
  declare function listBridgeDeposits(rpc: CloakRpc, ownerUtxoKeypair: UtxoKeypair, opts: DiscoverOptions): Promise<BridgeDeposit[]>;
6291
7017
 
6292
- interface DepositOutcome {
6293
- signature: string;
6294
- noteIndex: number;
6295
- amount: bigint;
6296
- txSize: number;
6297
- rBefore: number;
6298
- rAfter: number;
6299
- rentExempt: boolean;
6300
- /** The proof's two input nullifiers (zero-value padding for a pure deposit, but each one is a
6301
- * genuine Poseidon hash over a random salt — NOT the literal zero sentinel the program treats
6302
- * as "no PDA needed". See phase4-adversarial.ts case (c). */
6303
- inputNullifiers: bigint[];
6304
- /** The three program accounts the funding seam read off the built tx, and what it sent each —
6305
- * 0 if the account already held enough. Exposed so a caller can independently verify their
6306
- * on-chain state afterward, including after a thrown error (see `DepositError` below). */
6307
- fundedAccounts: {
6308
- name: string;
6309
- address: string;
6310
- lamportsSent: number;
6311
- }[];
6312
- }
6313
- /** Thrown by `depositFromDerivedKey` in place of a bare `Error` whenever the funding seam ran
6314
- * before the failure, so a caller can see exactly what already landed on chain despite the
6315
- * overall deposit failing. `fundedAccounts` / `measuredSize` are `undefined` only if the seam
6316
- * never ran at all (failure before signing was attempted). */
6317
- declare class DepositError extends Error {
6318
- readonly fundedAccounts: DepositOutcome["fundedAccounts"];
6319
- readonly measuredTxSize: number;
6320
- constructor(message: string, fundedAccounts: DepositOutcome["fundedAccounts"], measuredTxSize: number);
6321
- }
6322
7018
  /**
6323
- * Fund R minimally, then deposit with R as the only signer.
7019
+ * Mutual exclusion for bridge operations that must not interleave: two allocations reading the same
7020
+ * ledger and handing out one index, or a shield and a move-to-wallet racing on one receiver.
6324
7021
  *
6325
- * `grantOverride` replaces the computed grant (rent floor + deposit fee + cleanup fee) with an
6326
- * arbitrary lamport amount. Only phase4-adversarial.ts case (a) passes it, to reproduce the
6327
- * "funded R with just its fee, not its floor" mistake deliberately; every other caller omits it
6328
- * and gets the same grant this function has always sent.
7022
+ * Within one JavaScript realm the lock is an in-process queue per name, so it works in Node and in
7023
+ * any browser. Where the Web Locks API exists (every current browser), the queue also holds that
7024
+ * lock, so two tabs of one site exclude each other too. A partner running several server processes
7025
+ * against one database needs its own cross-process lock: pass it where a function takes `lock`.
7026
+ *
7027
+ * No DOM types: `navigator.locks` is feature-detected through `globalThis`.
6329
7028
  */
6330
- declare function depositFromDerivedKey(rpc: CloakRpc, R: KeyPairSigner, funder: KeyPairSigner, amount: bigint, log: ((s: string) => void) | undefined, grantOverride: number | undefined,
6331
7029
  /**
6332
- * relayUrl, programId and mint are all REQUIRED — no default, for any of the three, on any
6333
- * environment. They used to fall back to the module-level RELAY/PROGRAM/MINT constants above,
6334
- * each evaluated once at import time, and that is exactly how a live mainnet deposit got built
6335
- * against the local program id while the banner said api.cloak.ag: the default filled the hole
6336
- * silently instead of the caller having to say so. There is nothing left to fall into.
7030
+ * Runs `fn` while holding the lock `name`. With `ifAvailable`, a lock someone else holds is not
7031
+ * waited for: it throws `BridgeLockBusyError` and `fn` never runs. A partner's own lock must keep
7032
+ * that contract.
6337
7033
  */
6338
- opts: {
6339
- relayUrl: string;
6340
- programId: Address;
6341
- mint: Address;
6342
- noteSpendKey: Uint8Array;
6343
- }): Promise<DepositOutcome>;
6344
-
6345
- interface CleanupResult {
6346
- closed: boolean;
6347
- dustSwept: bigint;
6348
- rentReturned: bigint;
6349
- destination: string | null;
6350
- signature: string | null;
6351
- note: string;
7034
+ type BridgeLock = <T>(name: string, fn: () => Promise<T>, opts?: {
7035
+ ifAvailable?: boolean;
7036
+ }) => Promise<T>;
7037
+ /** The lock was held and the caller asked not to wait. Nothing ran. */
7038
+ declare class BridgeLockBusyError extends Error {
7039
+ readonly lockName: string;
7040
+ readonly code = "BRIDGE_LOCK_BUSY";
7041
+ constructor(lockName: string);
6352
7042
  }
7043
+ /** Matches by `code`, so it holds across two loaded copies of the SDK. */
7044
+ declare function isBridgeLockBusy(e: unknown): boolean;
7045
+ /** Prefix for every lock this SDK takes, so its names never collide with an application's own. */
7046
+ declare const BRIDGE_LOCK_PREFIX = "cloak-sdk:bridge:";
6353
7047
  /**
6354
- * @param dustDestination where post-deposit dust goes, if the caller wants it swept at all.
6355
- * LEAVE IT UNDEFINED unless the user has been told the cost: any destination they control
6356
- * publishes `R -> them` and deanonymises the deposit R just made. It is never Cloak's, because
6357
- * capturing user funds off-chain would be an off-chain fee, which the team rule forbids.
6358
- * Undefined means "close if empty, otherwise leave it alone and report it".
6359
- * @param mint the shielded asset R was funded for. Defaults to mainnet USDC so a caller written
6360
- * before this parameter existed keeps compiling and keeps recovering the same account it always
6361
- * has; a bridge for any other asset MUST pass its own mint, since R's token account and the
6362
- * dust sitting in it both belong to whatever mint the rail actually delivered, not to this
6363
- * default.
7048
+ * The SDK's default lock: an in-process queue per name, plus the Web Lock of the same name when the
7049
+ * runtime has one. A failure inside `fn` releases the lock and rethrows.
6364
7050
  */
6365
- declare function cleanupReceivingAddress(rpc: CloakRpc, R: KeyPairSigner, dustDestination?: Address, mint?: Address): Promise<CleanupResult>;
7051
+ declare const withBridgeLock: BridgeLock;
7052
+ /**
7053
+ * Runs `fn` holding the lock for `receiver`, refusing at once (`BridgeLockBusyError`) when another
7054
+ * operation on that receiver holds it. Every operation that spends from or empties a receiver takes
7055
+ * it: the shield (`finishBridgeDeposit`, `prepareBridgeShield`) and the move to the wallet.
7056
+ */
7057
+ declare function withReceiverLock<T>(receiver: string, fn: () => Promise<T>, lock?: BridgeLock): Promise<T>;
7058
+ /**
7059
+ * The lock name for one receiver address. Every operation that spends from or empties a receiver
7060
+ * (the shield in `finishBridgeDeposit`, `moveReceiverFundsToWallet`) takes it, so they exclude each
7061
+ * other whatever page or module starts them.
7062
+ */
7063
+ declare function bridgeReceiverLockName(receiver: string): string;
7064
+
7065
+ /**
7066
+ * Which receiver index a new bridge order gets, and the record that keeps it from ever being handed
7067
+ * out twice.
7068
+ *
7069
+ * ── The rule ────────────────────────────────────────────────────────────────────────────────────
7070
+ * Two orders on one receiver link their deposits on chain, and a receiver can still be paid after
7071
+ * its order was settled or abandoned (a transfer already on its way). So an index, once offered, is
7072
+ * never offered again. Three sources say an index was used, and a new order goes past all of them:
7073
+ *
7074
+ * 1. discovery: receivers that hold or held funds (`listBridgeDeposits`, current receivers only);
7075
+ * 2. reservations: orders this ledger allocated and has not settled, which discovery cannot see
7076
+ * while their money is still on the way (age-bounded, `BRIDGE_ORDER_MAX_LIVE_MS`);
7077
+ * 3. the high-water mark: the largest index this ledger ever allocated. Only ever raised, so it
7078
+ * still holds after a reservation is settled or expires.
7079
+ *
7080
+ * And the index is recorded BEFORE the rail is asked for an address (`allocate`): the rail may
7081
+ * create the address even if its answer never comes back.
7082
+ *
7083
+ * Deposit indices live in `[0, BRIDGE_DEPOSIT_INDEX_LIMIT)`. The range above belongs to payouts
7084
+ * (the refund key and collectors are derived the same way), so a full deposit range throws rather
7085
+ * than reaching into it.
7086
+ *
7087
+ * ── Storage ─────────────────────────────────────────────────────────────────────────────────────
7088
+ * Behind `BridgeIndexStore`, as payouts are behind `PayoutStore`: `memoryBridgeIndexStore()` for
7089
+ * tests and scripts, `browserBridgeIndexStore()` over `localStorage` (or any `getItem`/`setItem`), or
7090
+ * a partner's database. The store only keeps values; every rule (raise-only, the deposit range, the
7091
+ * age bound, refusing malformed records) is applied here, so a store cannot weaken it. Read-modify-
7092
+ * write runs under a lock (`withBridgeLock` by default; a multi-process partner passes its own).
7093
+ */
7094
+
7095
+ /**
7096
+ * How long an order can still deliver to its receiver. The 1Click rail quotes a deadline six hours
7097
+ * out and its status turns `expired` after it; the Jupiter/GUM rail has no status at all. 24 h is
7098
+ * four times the longest window any rail states. A reservation lives this long unless settled.
7099
+ */
7100
+ declare const BRIDGE_ORDER_MAX_LIVE_MS: number;
7101
+ /** Discovery reads this many indices past the high-water mark, so abandoned allocations (gaps) never
7102
+ * end a scan before the highest index ever handed out. */
7103
+ declare const BRIDGE_DISCOVERY_GAP = 21;
7104
+ type Awaitable<T> = T | Promise<T>;
7105
+ /** One unsettled order. */
7106
+ interface BridgeReservation {
7107
+ index: number;
7108
+ /** Unix ms. Past this, the reservation no longer counts (the high-water mark still does). */
7109
+ expiresAtMs: number;
7110
+ }
7111
+ /**
7112
+ * Where a ledger keeps its two values, per `ownerKey`. Values only: the ledger validates everything
7113
+ * it reads, so a store returns what it holds and writes what it is given.
7114
+ */
7115
+ interface BridgeIndexStore {
7116
+ getHighWater(ownerKey: string): Awaitable<number | null>;
7117
+ setHighWater(ownerKey: string, index: number): Awaitable<void>;
7118
+ getReservations(ownerKey: string): Awaitable<BridgeReservation[]>;
7119
+ setReservations(ownerKey: string, reservations: BridgeReservation[]): Awaitable<void>;
7120
+ }
7121
+ type BridgeIndexErrorCode =
7122
+ /** Every deposit index for this owner is used. */
7123
+ "BRIDGE_INDEX_EXHAUSTED"
7124
+ /** An index outside `[0, BRIDGE_DEPOSIT_INDEX_LIMIT)` was given to the ledger. */
7125
+ | "BRIDGE_INDEX_NOT_A_DEPOSIT_INDEX";
7126
+ declare class BridgeIndexError extends Error {
7127
+ readonly code: BridgeIndexErrorCode;
7128
+ constructor(code: BridgeIndexErrorCode, message: string);
7129
+ }
7130
+ declare function isBridgeIndexError(e: unknown, code?: BridgeIndexErrorCode): e is BridgeIndexError;
7131
+ /**
7132
+ * The next never-used deposit index: one past the largest of discovery (current receivers only),
7133
+ * the reserved indices and the high-water mark. Legacy receivers are a separate address space and
7134
+ * never count. Out-of-range values are ignored, and a full range throws `BRIDGE_INDEX_EXHAUSTED`.
7135
+ * Pure: records nothing.
7136
+ */
7137
+ declare function nextBridgeReceiverIndex(deposits: readonly Pick<BridgeDeposit, "index" | "legacyExposed">[], used?: {
7138
+ reserved?: readonly number[];
7139
+ highWater?: number | null;
7140
+ }): number;
7141
+ /** True for a deposit whose closing transaction is in its receiver's history: shielded, or moved to
7142
+ * the wallet. Nothing more is waiting for it, so its reservation can be settled. A legacy receiver
7143
+ * is never one of this ledger's orders. */
7144
+ declare function isBridgeOrderSettled(d: Pick<BridgeDeposit, "state" | "legacyExposed">): boolean;
7145
+ interface BridgeOrderLedger {
7146
+ readonly ownerKey: string;
7147
+ /** The largest index ever allocated, or null. */
7148
+ highWater(): Promise<number | null>;
7149
+ /** Indices allocated and not yet settled or expired, ascending. */
7150
+ reserved(): Promise<number[]>;
7151
+ /** The index `allocate` would hand out now. Records nothing: for a dry quote. */
7152
+ peekNextIndex(deposits: readonly Pick<BridgeDeposit, "index" | "legacyExposed">[]): Promise<number>;
7153
+ /**
7154
+ * Picks the next index and records it (high-water raised, reservation written) in one locked step.
7155
+ * Call it BEFORE asking the rail to allocate an address; if no address comes back, `abandon` it.
7156
+ */
7157
+ allocate(deposits: readonly Pick<BridgeDeposit, "index" | "legacyExposed">[]): Promise<number>;
7158
+ /** Records `index` as allocated and refreshes its reservation (raise-only for the high-water). For
7159
+ * an order resumed after a reload. Throws for an index outside the deposit range. */
7160
+ reserve(index: number): Promise<void>;
7161
+ /** The order at `index` was shielded, refunded, expired or moved out: drop its reservation. Never
7162
+ * lowers the high-water mark, so the index is not handed out again. */
7163
+ settle(index: number): Promise<void>;
7164
+ /** The order at `index` got an address but nothing was sent: drop its reservation. Same effect as
7165
+ * `settle`, named for the call site. */
7166
+ abandon(index: number): Promise<void>;
7167
+ /** Settles every discovered deposit that `isBridgeOrderSettled`. Returns the indices settled. */
7168
+ settleFinished(deposits: readonly Pick<BridgeDeposit, "index" | "state" | "legacyExposed">[]): Promise<number[]>;
7169
+ }
7170
+ interface BridgeOrderLedgerOptions {
7171
+ /** Default `Date.now`. */
7172
+ now?: () => number;
7173
+ /** Default `BRIDGE_ORDER_MAX_LIVE_MS`. */
7174
+ maxLiveMs?: number;
7175
+ /** Default `withBridgeLock` (in-process, plus Web Locks across tabs). */
7176
+ lock?: BridgeLock;
7177
+ }
7178
+ /**
7179
+ * The ledger for one owner. `ownerKey` names the owner in the store: anything stable for the keys
7180
+ * the receivers derive from (Cloak's website uses the wallet address).
7181
+ */
7182
+ declare function createBridgeOrderLedger(store: BridgeIndexStore, ownerKey: string, opts?: BridgeOrderLedgerOptions): BridgeOrderLedger;
7183
+ /** A ledger store in memory. For tests, scripts and short-lived processes. */
7184
+ declare function memoryBridgeIndexStore(): BridgeIndexStore;
7185
+ /** What `browserBridgeIndexStore` needs from a storage: `localStorage`'s two methods. */
7186
+ interface BridgeKeyValueStorage {
7187
+ getItem(key: string): string | null;
7188
+ setItem(key: string, value: string): void;
7189
+ }
7190
+ /** The `localStorage` keys `browserBridgeIndexStore` uses. The high-water key and its plain-decimal
7191
+ * value are the ones Cloak's website already wrote, so a website moving onto this store keeps every
7192
+ * index it handed out. */
7193
+ declare function browserBridgeIndexStoreKeys(ownerKey: string): {
7194
+ highWater: string;
7195
+ reservations: string;
7196
+ };
7197
+ /**
7198
+ * A ledger store over `localStorage`, or any object with `getItem`/`setItem`. Holds one integer and a
7199
+ * short list of `{ index, expiresAtMs }` per owner: no address, amount or key.
7200
+ *
7201
+ * A read that fails or does not parse reads as empty; a write that fails throws, so a caller never
7202
+ * believes an index was recorded when it was not.
7203
+ */
7204
+ declare function browserBridgeIndexStore(storage?: BridgeKeyValueStorage): BridgeIndexStore;
7205
+ /**
7206
+ * Allocates the next receiver for a new order and derives it: `ledger.allocate` (recorded before any
7207
+ * rail call) then `deriveBridgeReceiver`. `deposits` is a fresh discovery (`discoverBridgeDeposits`).
7208
+ */
7209
+ declare function allocateBridgeReceiver(owner: UtxoKeypair, deposits: readonly Pick<BridgeDeposit, "index" | "legacyExposed">[], ledger: BridgeOrderLedger): Promise<{
7210
+ index: number;
7211
+ receiver: KeyPairSigner;
7212
+ }>;
7213
+ /**
7214
+ * Discovery that reaches every index the ledger ever handed out, then settles the orders it shows as
7215
+ * finished. Scans at least `BRIDGE_DISCOVERY_GAP` past the high-water mark (both `scanDepth` and
7216
+ * `stopAfterUnused`), so a run of abandoned indices never ends the scan early. Larger values in
7217
+ * `opts` win.
7218
+ */
7219
+ declare function discoverBridgeDeposits(rpc: CloakRpc, owner: UtxoKeypair, opts: DiscoverOptions, ledger: BridgeOrderLedger): Promise<BridgeDeposit[]>;
7220
+
7221
+ /** How long a proved deposit waits for the bridged USDC before letting go. */
7222
+ declare const PREPARED_SHIELD_HOLD_MS = 30000;
7223
+ /** How often R's token balance is read while holding. */
7224
+ declare const PREPARED_SHIELD_POLL_MS = 500;
7225
+ /** Why a prepared shield let go before anything moved. The ordinary path takes over. */
7226
+ type PreparedShieldLetGo = "receiver_busy" | "self_funded_alt" | "no_paymaster_quote" | "would_burn" | "below_minimum" | "different_amount" | "hold_expired" | "released" | "failed_before_funds";
7227
+ interface PreparedBridgeShield {
7228
+ readonly receiver: string;
7229
+ /** The shield, or null when it let go before money moved (see `letGo`). Rejects only once the
7230
+ * paymaster top-up was sent. */
7231
+ readonly outcome: Promise<BridgeFinishOutcome | null>;
7232
+ /** Stop holding. A shield past the hold (already funding) is not interrupted. */
7233
+ release(): void;
7234
+ /** Why it let go, once `outcome` resolved null. */
7235
+ letGo(): PreparedShieldLetGo | null;
7236
+ }
7237
+ declare function prepareBridgeShield(ctx: FinishBridgeContext, R: KeyPairSigner, noteSpendKey: Uint8Array, expected: bigint, opts?: {
7238
+ holdMs?: number;
7239
+ pollMs?: number;
7240
+ signal?: AbortSignal;
7241
+ now?: () => number;
7242
+ sleep?: (ms: number) => Promise<void>;
7243
+ }): PreparedBridgeShield;
6366
7244
 
6367
7245
  /** Rent for a 0-byte System account. `utils/pda.rs:99` -> `minimum_balance(0)`. */
6368
7246
  declare const MAINNET_RENT_0 = 890880;
@@ -6408,6 +7286,22 @@ declare function deriveFundingTargets(d: DepositRef): Promise<{
6408
7286
  riskNonce: _solana_nominal_types.NominalType<"brand", "Address"> & _solana_nominal_types.NominalType<"stringEncoding", "base58"> & string;
6409
7287
  depositorAta: Address<string>;
6410
7288
  }>;
7289
+ /** Rent of a receiver-built lookup table (measured), plus its two transactions' fees. */
7290
+ declare const SELF_FUNDED_ALT_RENT_LAMPORTS = 1975896;
7291
+ declare const SELF_FUNDED_ALT_FEE_LAMPORTS = 20000;
7292
+ declare const SELF_FUNDED_ALT_BUDGET_LAMPORTS: number;
7293
+ /**
7294
+ * Lamports the paymaster grants for one deposit: what R itself is short of (a 0-byte account's rent
7295
+ * plus the deposit and cleanup fees, less what R already holds) plus the deposit's program accounts
7296
+ * (one 0-byte and two 1-byte accounts), plus the self-funded lookup table when the relay cannot
7297
+ * extend its own. Rent is the live figure when given, never below the mainnet constants.
7298
+ *
7299
+ * `heldLamports` 0 is the fresh-receiver figure, for asking a price before anything has arrived.
7300
+ */
7301
+ declare function bridgeTopUpTotal(heldLamports: bigint, opts?: {
7302
+ rent?: RentRates;
7303
+ selfFundedAlt?: boolean;
7304
+ }): bigint;
6411
7305
  interface RentRates {
6412
7306
  zero: bigint;
6413
7307
  one: bigint;
@@ -6426,110 +7320,492 @@ interface FundingPlan {
6426
7320
  warnings: string[];
6427
7321
  }
6428
7322
 
6429
- declare const ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
7323
+ interface RelayCapability {
7324
+ reachable: boolean;
7325
+ hasSupplementalAlt: boolean;
7326
+ servesMint: boolean;
7327
+ detail: string;
7328
+ }
7329
+ /** Read the relay's `/health` answer for one pool. */
7330
+ declare function readRelayCapability(health: unknown, mint: string): RelayCapability;
7331
+ /** The relay's capability for `mint`, never throwing: an unreachable relay is an answer. */
7332
+ declare function fetchRelayCapability(relayUrl: string, mint: string): Promise<RelayCapability>;
7333
+ /** May a deposit be quoted at all? Fails closed: a quote is cheap to refuse, a stranded deposit is not. */
7334
+ declare function canServeDeposits(cap: RelayCapability): boolean;
7335
+ /** Will R build its own lookup table? True whenever the shared one is not confirmed present:
7336
+ * over-funding costs reclaimable rent, under-funding strands the balance. */
7337
+ declare function needsSelfFundedAlt(cap: RelayCapability): boolean;
7338
+ /**
7339
+ * What R must hold before the deposit can run, measured rather than assumed: R's own rent floor,
7340
+ * the three one-byte PDAs the deposit creates (two nullifiers, the risk nonce), R's token account
7341
+ * if the rail did not pay for it, two fees, and a self-built lookup table when the relay offers
7342
+ * none. Rent is read live, with the SDK constants as a floor: a fixed number was wrong in both
7343
+ * directions once and stranded a deposit twice ("insufficient lamports 274392, need 897840").
7344
+ */
7345
+ declare function receiverGrantLamports(rpc: CloakRpc, receiver: Address, mint: Address, selfFundedAlt: boolean): Promise<bigint>;
7346
+ /**
7347
+ * The paymaster, as a caller reaches it. The SDK's own reaches the bridge service on the relay's
7348
+ * origin; a website passes one that goes through its proxy. Both must verify the top-up's shape
7349
+ * before R signs it (`fundReceiverViaPaymaster` / the website's equivalent do).
7350
+ */
7351
+ interface BridgePaymaster {
7352
+ /** Its fee, in the deposit token's base units, for granting `grantLamports` to `receiver`.
7353
+ * May throw when the service has no quote endpoint; the two-step top-up runs instead. */
7354
+ quoteFee(receiver: Address, grantLamports: bigint): Promise<bigint>;
7355
+ /** Optional, preferred over `quoteFee` when present: the fee AND what the top-up would burn now
7356
+ * (USDC at `receiver` that no screened deposit explains, at most `DUST_BURN_CEILING`), so the
7357
+ * shield is proved without the burned part. Same failure contract as `quoteFee`. */
7358
+ quoteTopUp?(receiver: Address, grantLamports: bigint): Promise<{
7359
+ feeTokenAmount: bigint;
7360
+ burnAmount: bigint;
7361
+ }>;
7362
+ /** A top-up of `grantLamports` to `receiver` (or to `commit.grants`), signed by R and the paymaster. */
7363
+ topUp(receiver: KeyPairSigner, grantLamports: bigint, commit?: {
7364
+ grants: {
7365
+ address: Address;
7366
+ lamports: bigint;
7367
+ }[];
7368
+ feeTokenAmount: bigint;
7369
+ }): Promise<{
7370
+ transaction: Transaction;
7371
+ feeTokenAmount: bigint;
7372
+ burnedBaseUnits?: bigint;
7373
+ }>;
7374
+ }
6430
7375
  /**
6431
- * The exact string this rail signs over, exported so a second implementation can be checked against
6432
- * it rather than reasoned about.
6433
- *
6434
- * A Rust twin of `stable()` has to reproduce JavaScript's key ordering and number formatting byte
6435
- * for byte, and the two languages do not agree by default: `Object.keys().sort()` orders by UTF-16
6436
- * code unit while Rust's `sort()` orders by UTF-8 byte. They coincide for ASCII and diverge above
6437
- * it. This is the same class of bug as `canonicalJson` versus Rust's `keys.sort_unstable()` in the
6438
- * relay-auth payload, and it fails in the worst direction: a verifier that rejects HONEST quotes
6439
- * looks like a rail outage, and teaches whoever is on call to ignore it.
6440
- *
6441
- * So the cross-language test compares THIS string, not just the boolean verdict. Two verifiers can
6442
- * agree on a signature by both being wrong in the same place; they cannot agree on the bytes by
6443
- * accident.
7376
+ * What arrived, less the paymaster's fee, is under the pool's minimum deposit. Retrying cannot fix
7377
+ * it: stop, and tell the user the funds stay at their receiving address. Thrown before any top-up
7378
+ * or proving.
6444
7379
  */
6445
- declare function canonicalPayloadString(resp: any): string;
6446
- declare function verifyQuoteSignature(resp: any): {
6447
- valid: boolean;
6448
- reason?: string;
7380
+ declare class BridgeDepositBelowMinimumError extends Error {
7381
+ readonly arrived: bigint;
7382
+ readonly fee: bigint;
7383
+ readonly minimum: bigint;
7384
+ /** Stable brand: match on this (see `isBridgeDepositBelowMinimum`), not `instanceof`. */
7385
+ readonly code = "BRIDGE_DEPOSIT_BELOW_MINIMUM";
7386
+ readonly net: bigint;
7387
+ constructor(arrived: bigint, fee: bigint, minimum?: bigint);
7388
+ }
7389
+ /**
7390
+ * Is `e` a `BridgeDepositBelowMinimumError`? Checks `code` and `name` rather than `instanceof`,
7391
+ * which is false across two loaded copies of this SDK (a bundler duplicate, a web app plus a
7392
+ * dependency), exactly when a caller most needs the answer.
7393
+ */
7394
+ declare function isBridgeDepositBelowMinimum(e: unknown): boolean;
7395
+ /** Refuses, before any top-up or proof, a deposit whose net of the fee is under the pool minimum. */
7396
+ declare function assertShieldable(base: bigint, fee: bigint): void;
7397
+ interface FinishBridgeContext {
7398
+ rpc: CloakRpc;
7399
+ relayUrl: string;
7400
+ programId: Address;
7401
+ mint: Address;
7402
+ paymaster: BridgePaymaster;
7403
+ log?: (line: string) => void;
7404
+ /** The receiver lock. Default `withBridgeLock` (in-process, plus Web Locks across tabs). A
7405
+ * partner running several processes passes its own. */
7406
+ lock?: BridgeLock;
7407
+ }
7408
+ /** What `finishBridgeDeposit` returns: the deposit, and any outside-Cloak dust the top-up burned. */
7409
+ type BridgeFinishOutcome = DepositOutcome & {
7410
+ burnedBaseUnits: bigint;
7411
+ };
7412
+ interface FinishBridgeOptions {
7413
+ /** A shield proved while the bridge was still delivering (`prepareBridgeShield`) for this same
7414
+ * receiver. Awaited first; when it lets go before anything moved, the ordinary path runs. */
7415
+ prepared?: PreparedBridgeShield;
7416
+ /** The order this deposit closes: settled in its ledger on success and on the terminal
7417
+ * below-minimum refusal, never on any other failure. */
7418
+ order?: {
7419
+ ledger: Pick<BridgeOrderLedger, "settle">;
7420
+ index: number;
7421
+ };
7422
+ }
7423
+ /**
7424
+ * Shield what R holds into a note owned by `noteSpendKey`, the paymaster paying R's SOL.
7425
+ *
7426
+ * `amount` is what the caller last read at R; the deposit uses what R holds NOW when that is less
7427
+ * (the paymaster's fee once left R between the two reads and the token program refused the
7428
+ * deposit after the SOL had already moved). Safe to call again after a partial success: R is only
7429
+ * topped up to what it lacks.
7430
+ *
7431
+ * Holds the receiver lock (`withReceiverLock`) and refuses at once with `BridgeLockBusyError` when
7432
+ * another shield or a move to the wallet holds it. Refuses an amount whose net of the paymaster fee
7433
+ * is under the pool minimum (`BridgeDepositBelowMinimumError`, terminal) before any top-up or proof.
7434
+ */
7435
+ declare function finishBridgeDeposit(ctx: FinishBridgeContext, R: KeyPairSigner, noteSpendKey: Uint8Array, amount: bigint, opts?: FinishBridgeOptions): Promise<BridgeFinishOutcome>;
7436
+ /** The signer for a discovered receiver: current ones from the wallet's UTXO keypair, legacy ones
7437
+ * from the viewing key they were derived from. */
7438
+ declare function bridgeReceiverSigner(deposit: Pick<BridgeDeposit, "index" | "legacyExposed" | "legacyViewingKeyNk">, owner: UtxoKeypair): Promise<KeyPairSigner>;
7439
+ /** Receivers holding USDC that has not been shielded. */
7440
+ declare function waitingBridgeDeposits(deposits: readonly BridgeDeposit[]): BridgeDeposit[];
7441
+ /** A waiting receiver holding at most the pool minimum: nothing can ever shield it (the fee alone
7442
+ * takes it under), so it is reported, never attempted. Its way out is the move to the wallet. */
7443
+ declare function isBridgeDust(d: Pick<BridgeDeposit, "tokenBalance">): boolean;
7444
+ /** Waiting receivers, split into what can be shielded and dust, with totals. */
7445
+ declare function splitWaitingBridgeDeposits(deposits: readonly BridgeDeposit[]): {
7446
+ shieldable: BridgeDeposit[];
7447
+ dust: BridgeDeposit[];
7448
+ shieldableTotal: bigint;
7449
+ dustTotal: bigint;
6449
7450
  };
7451
+ /**
7452
+ * How one recovery attempt ended. `dust`: under the pool minimum, never attempted. `below-minimum`:
7453
+ * refused before any top-up (terminal). `busy`: another shield or a move holds the receiver.
7454
+ * `failed`: anything else; `error` says what.
7455
+ */
7456
+ type BridgeRecoveryStatus = "done" | "dust" | "below-minimum" | "busy" | "failed";
7457
+ interface BridgeRecoveryResult {
7458
+ deposit: BridgeDeposit;
7459
+ status: BridgeRecoveryStatus;
7460
+ outcome?: BridgeFinishOutcome;
7461
+ error?: string;
7462
+ }
7463
+ /** The status a finish error means. */
7464
+ declare function bridgeRecoveryStatusOf(e: unknown): Exclude<BridgeRecoveryStatus, "done" | "dust">;
7465
+ /**
7466
+ * Find every receiver of these keys that holds USDC and shield each one, one at a time.
7467
+ *
7468
+ * The way out for bridged funds that no page finished: anything holding the wallet's keys (the
7469
+ * website on load, a script, support with the user's backup) can run it. Sequential, because each
7470
+ * charges the paymaster. Dust is reported and skipped (`skipDust`, default true). One failure does
7471
+ * not stop the rest unless `stopOnFailure`; nothing is retried here (`createBridgeRecovery` does).
7472
+ * With `ledger`, discovery reaches the ledger's high-water mark and finished orders are settled.
7473
+ */
7474
+ declare function recoverBridgeDeposits(ctx: FinishBridgeContext & {
7475
+ owner: UtxoKeypair;
7476
+ noteSpendKey: Uint8Array;
7477
+ discover?: Partial<DiscoverOptions>;
7478
+ }, opts?: {
7479
+ onDeposit?: (r: BridgeRecoveryResult) => void;
7480
+ /** Discovery depth and gap tolerance (see `DiscoverOptions`). Win over `ctx.discover`. A caller
7481
+ * that knows its highest allocated receiver index should scan past it. */
7482
+ scanDepth?: number;
7483
+ stopAfterUnused?: number;
7484
+ /** Default true. */
7485
+ skipDust?: boolean;
7486
+ /** Stop at the first `failed` (each attempt may charge the paymaster). Default false. */
7487
+ stopOnFailure?: boolean;
7488
+ /** Only deposits this predicate accepts, asked just before each attempt (e.g. not yet tried). */
7489
+ only?: (d: BridgeDeposit) => boolean;
7490
+ ledger?: BridgeOrderLedger;
7491
+ }): Promise<BridgeRecoveryResult[]>;
6450
7492
 
6451
7493
  /**
6452
- * Deciding whether a bridge deposit can be honoured — BEFORE the user sends anything.
7494
+ * The paymaster client — the SOL top-up that lets a bridge receiver R (which arrives holding only
7495
+ * bridged tokens, no SOL) shield without the user's own wallet ever appearing on chain.
6453
7496
  *
6454
- * WHY THIS EXISTS. Shielding on arrival is mandatory, not a choice: a user who bridges and then
6455
- * sweeps unshielded has manufactured exactly the `receiver -> them` link the whole design removes.
6456
- * But "mandatory" moves every failure from the user's account to ours. If someone sends 3 USDC and
6457
- * the paymaster fee leaves less than the program's 1,000,000-base-unit floor, the shield CANNOT
6458
- * happen — and under a mandatory model that is the product breaking its own promise, with the money
6459
- * stranded unshielded at an address the user has never heard of.
7497
+ * Talks ONLY to Cloak's own bridge service (`api.cloak.ag/bridge/paymaster/*`), never to Kora
7498
+ * directly: under fixed pricing (docs/00-DECISION-STATE.md, PAYMASTER ECONOMICS) the Kora API key is
7499
+ * worth real money to whoever holds it, and a browser bundle is not a place that can keep a secret.
6460
7500
  *
6461
- * So the check belongs at quote time. The rule is the one the rail-signature check already
6462
- * established: NEVER SHOW AN ADDRESS YOU CANNOT HONOUR. An unviable deposit is refused before the
6463
- * deposit address is displayed, not diagnosed after the money has landed.
7501
+ * ── The two-round-trip shape, and why it is not one call ─────────────────────────────────────
7502
+ * `prepare` returns an UNSIGNED transaction the service built and priced, plus a voucher that MACs
7503
+ * the exact message bytes. The client's receiving key R signs it — R never leaves the client, and
7504
+ * this is the only place it signs anything for the paymaster flow — and hands the bytes back
7505
+ * unchanged to `cosign`, which recognises them via the voucher and only THEN asks Kora to co-sign as
7506
+ * fee payer. The paymaster's key never leaves the server; R's key never leaves the client; neither
7507
+ * round trip needs the other's secret. See `services/api/bridge/src/api/paymaster.rs` for the
7508
+ * server half of this contract.
6464
7509
  *
6465
- * All figures are worst-case, taken from the rail's guaranteed floor (`minAmountOut`), never its
6466
- * target. A quote that only works at the target is a quote that fails on a bad day.
7510
+ * ── Why the shape check below is not optional ────────────────────────────────────────────────
7511
+ * `cosign` answers exactly one question — "is this the message I built?" — and answers it by MAC,
7512
+ * not by re-deriving policy from an arbitrary transaction. That makes `prepare`'s response the ONLY
7513
+ * point where an unexpected instruction could sneak in (a compromised service, a MITM'd response, a
7514
+ * bug that built the wrong thing), because nothing downstream re-checks it. `validate
7515
+ * PaymasterTopUpTransaction` is that one check, and it runs BEFORE R signs anything: signing is the
7516
+ * one irreversible step in this flow from the client's point of view, so the check that matters has
7517
+ * to sit in front of it, not after.
6467
7518
  */
6468
- /** programs/shield-pool/src/constants.rs:126 — enforced at transact_spl/deposit.rs:69. */
6469
- declare const MIN_DEPOSIT_SPL_BASE_UNITS = 1000000n;
7519
+
7520
+ /** What `prepare`'s response is checked against before R ever signs it. */
7521
+ interface PaymasterTopUpExpectation {
7522
+ /** R — the only account this transaction may fund or spend from. */
7523
+ recipient: Address;
7524
+ /** The lamports we asked for. `ix0.lamports` may come in at or under this, never over. With
7525
+ * `grants`, the total across them. */
7526
+ maxGrantLamports: bigint;
7527
+ /** Several destinations instead of R alone (R and the program accounts its deposit creates),
7528
+ * in the order requested. Each transfer must match its grant EXACTLY, address and lamports:
7529
+ * the service builds what it was asked for, so anything else is not that. */
7530
+ grants?: readonly PaymasterGrant[];
7531
+ feeMint: Address;
7532
+ /** The fee Kora actually quoted at `prepare` time. `ix1.amount`, if `ix1` exists, must equal this
7533
+ * exactly — not "at most", because the fee is a quote the service already committed to, not a
7534
+ * ceiling. */
7535
+ feeTokenAmount: bigint;
7536
+ /** The paymaster's own token account owner, from `prepare`'s `payment_address`. `ix1`'s
7537
+ * destination must be exactly THIS address's ATA for `feeMint` — nothing else, and never an ATA
7538
+ * derived from `recipient` or from an address the caller does not already trust. */
7539
+ paymentAddress: Address;
7540
+ /** The dust burn the service declared in `prepare`'s `burn_amount` (absent = 0, an older service).
7541
+ * The transaction may carry a `BurnChecked` of exactly this amount, and must carry one when it is
7542
+ * above zero. Never above `DUST_BURN_CEILING`. */
7543
+ burnAmount?: bigint;
7544
+ }
7545
+ /** The most the service may burn from R in one top-up: 1 USDC in base units. Dust someone sent to R
7546
+ * to block the deposit is a fraction of this; a service that asks for more is refused, so a
7547
+ * compromised one cannot burn R's real funds. */
7548
+ declare const DUST_BURN_CEILING = 1000000n;
7549
+ /** One destination of a multi-destination top-up. */
7550
+ interface PaymasterGrant {
7551
+ address: Address;
7552
+ lamports: bigint;
7553
+ }
6470
7554
  /**
6471
- * Live mainnet USDC PoolConfig at deploy time: a flat fee plus a proportional part, charged on
6472
- * WITHDRAWAL. These are the program's DEFAULTS, not a live read — quote.ts has no RPC client, so it
6473
- * cannot see a PoolConfig an admin has since changed. Treat this pair as a fallback only: it is
6474
- * shown to a user as what it will cost to get their money out, and if the live config has moved,
6475
- * this UNDERSTATES that cost. A caller that has already fetched PoolConfig should pass the real
6476
- * figures through `BridgeQuoteInput.liveWithdrawFixedFee` / `liveWithdrawFeeBps` instead.
7555
+ * The one check standing between `prepare`'s response and R's signature.
7556
+ *
7557
+ * The shape IS the security story (`paymaster/topup.rs`'s own words, mirrored here on the
7558
+ * verifying side):
7559
+ *
7560
+ * ix0 System transfer, paymaster -> recipient, <= the lamports we asked for
7561
+ * (with `grants`: one transfer per grant, paymaster -> that address, exactly that amount)
7562
+ * ixB (optional) SPL Token `BurnChecked` of the recipient's own fee-mint ATA, mint = the fee
7563
+ * mint, authority = recipient, decimals = 6, amount == `burnAmount` (the service's declared
7564
+ * `burn_amount`). At most one, and before the fee transfer.
7565
+ * ixN (optional) SPL transfer, recipient's fee-mint ATA -> paymaster's fee-mint ATA, authority
7566
+ * = recipient, amount == the quoted fee
7567
+ *
7568
+ * Why the burn is safe to sign: when someone sends a little USDC to R that no screened order
7569
+ * explains (to block the deposit), the service discards it in the same top-up so nothing unscreened
7570
+ * is ever shielded. It can only destroy tokens, never move them; it is capped at 1 USDC
7571
+ * (`DUST_BURN_CEILING`), it touches only R's own account for the fee mint, and its amount must equal
7572
+ * the `burn_amount` the service declared, exactly. A `burn_amount` with no burn, a burn with no
7573
+ * `burn_amount`, a plain (unchecked) `Burn`, a second burn, or a burn after the fee transfer are
7574
+ * all refused.
7575
+ *
7576
+ * Anything else — a third instruction, a different destination, a different authority, an amount
7577
+ * that does not match the quote — is refused. This function throws rather than returning a verdict:
7578
+ * there is no partial-trust path here, and a caller that wants to keep going after a refusal is a
7579
+ * caller papering over a corrupted or hostile response.
7580
+ *
7581
+ * Async (unlike the web3.js original): the paymaster's own fee-mint ATA (`expectedDestination`
7582
+ * below) is derived through kit's PDA path, which goes through WebCrypto and has no sync form.
6477
7583
  */
6478
- declare const WITHDRAW_FIXED_FEE = 450000n;
6479
- declare const WITHDRAW_FEE_BPS = 30n;
7584
+ declare function validatePaymasterTopUpTransaction(tx: Transaction, expect: PaymasterTopUpExpectation): Promise<void>;
7585
+ interface PaymasterTopUpResult {
7586
+ /** Fully signed by both R and the paymaster. The caller submits it — Kora's own
7587
+ * `signAndSendTransaction` is disabled service-side, and the broadcast should not carry the
7588
+ * service's IP any more than the deposit itself should carry R's. */
7589
+ transaction: Transaction;
7590
+ feeTokenAmount: bigint;
7591
+ feeMint: string;
7592
+ paymentAddress: string;
7593
+ /** USDC base units of dust (from outside Cloak, unscreened) the top-up discards from R. 0 when none. */
7594
+ burnedBaseUnits: bigint;
7595
+ }
7596
+ /** A fee agreed beforehand (`quotePaymasterTopUp`) and the destinations it pays for. */
7597
+ interface PaymasterTopUpCommit {
7598
+ /** R and the program accounts its deposit creates, in order. Each is funded exactly. */
7599
+ grants: readonly PaymasterGrant[];
7600
+ /** The fee the deposit's proof left room for. `prepare` must charge exactly this. */
7601
+ feeTokenAmount: bigint;
7602
+ }
7603
+ interface PaymasterTopUpQuote {
7604
+ /** In the fee mint's base units (USDC). */
7605
+ feeTokenAmount: bigint;
7606
+ /** What the top-up would burn from R now (outside-Cloak dust, at most `DUST_BURN_CEILING`). */
7607
+ burnAmount: bigint;
7608
+ }
6480
7609
  /**
6481
- * Below this, the fixed costs dominate: a deposit works, but most of it goes to fees.
7610
+ * `POST /bridge/paymaster/quote`: the fee for granting `grantLamports` to `receiver` (and its
7611
+ * deposit's accounts), and what the top-up would burn now. Asked before the deposit proves its
7612
+ * amount, since the fee comes out of the same USDC; `runPaymasterTopUp(..., commit)` then holds the
7613
+ * service to it. A burn above `DUST_BURN_CEILING` is refused here, as it would be at signing.
7614
+ */
7615
+ declare function quotePaymasterTopUp(target: string | BridgeTransport, receiver: Address, grantLamports: bigint): Promise<PaymasterTopUpQuote>;
7616
+ /**
7617
+ * The whole paymaster flow over any transport: prepare, verify the shape, sign as R, cosign, return
7618
+ * the fully-signed transaction for the caller to submit.
6482
7619
  *
6483
- * It is ADVISORY. `viable` is the hard gate; this only warns and asks for a second confirmation,
6484
- * because it is the user's money and their call.
7620
+ * `receiver` is the derived bridge receiving key (`deriveBridgeReceiver`). It signs here and only
7621
+ * here in this flow, and its secret never leaves this function — nothing above needs it, and
7622
+ * nothing here sends it anywhere.
6485
7623
  *
6486
- * WAS 20 USDC, derived from a 1.21 round trip when the paymaster charged $0.458 for something that
6487
- * cost it $0.104. Fixed pricing took that to $0.150 on 2026-09-07 (docs/17-PAYMASTER-ECONOMICS.md),
6488
- * the round trip fell to ~0.90, and leaving the constant alone would have warned people off
6489
- * deposits that had become perfectly reasonable. If the paymaster fee moves again, recompute
6490
- * FIXED_ROUND_TRIP rather than editing this number.
7624
+ * With `commit`, the top-up funds `commit.grants` (R and its deposit's program accounts) at the fee
7625
+ * agreed beforehand; a `prepare` that charges any other fee is refused before R signs. Without it,
7626
+ * R alone is funded at whatever the fee is now.
7627
+ */
7628
+ declare function runPaymasterTopUp(target: string | BridgeTransport, receiver: KeyPairSigner, grantLamports: bigint, commit?: PaymasterTopUpCommit): Promise<PaymasterTopUpResult>;
7629
+ /**
7630
+ * `runPaymasterTopUp` straight to Cloak's relay origin, R alone, at the current fee. Kept for
7631
+ * callers of 0.2.x; new code passes a transport or uses `relayBridgePaymaster`.
7632
+ */
7633
+ declare function fundReceiverViaPaymaster(relayUrl: string, receiver: KeyPairSigner, grantLamports: bigint): Promise<PaymasterTopUpResult>;
7634
+ /**
7635
+ * The SDK's own `BridgePaymaster`, over Cloak's service: what `finishBridgeDeposit` takes. Pass a
7636
+ * relay URL to call the service directly, or a transport to go through a proxy. Every check runs
7637
+ * in the SDK either way (the fee match, the voucher expiry, the shape check before R signs).
7638
+ */
7639
+ declare function relayBridgePaymaster(target: string | BridgeTransport): BridgePaymaster;
7640
+ /**
7641
+ * Whether the paymaster can fund a receiver RIGHT NOW, asked before any money moves on the other
7642
+ * chain.
6491
7643
  *
6492
- * 0.903 / a + 0.003 = 0.063 -> a = 15.05
7644
+ * A deposit from another chain lands at a receiver holding no SOL; only the paymaster can make it
7645
+ * spendable. Funds that land while the paymaster is unreachable wait at an address only the user's
7646
+ * keys control: never lost, but stuck until it returns. So the user is asked to send only after a
7647
+ * real round trip to it succeeds. `quoteFee` must be a call that reaches the paymaster itself (the
7648
+ * bridge's `/bridge/paymaster/quote` asks Kora for an estimate), never a read of configuration: a
7649
+ * service that is configured is not a service that answers.
7650
+ *
7651
+ * `arrivesMin` is what the rail guarantees will land; a fee at or above it would leave nothing to
7652
+ * shield, which is refused too.
6493
7653
  */
6494
- declare const ECONOMIC_MINIMUM: bigint;
6495
- interface BridgeQuoteInput {
6496
- /** What the user sends on the origin chain, in the destination asset's base units. */
6497
- sent: bigint;
6498
- /** The rail's GUARANTEED floor. Assess against this, never `amountOut`. */
6499
- arrivesMin: bigint;
6500
- /** The rail's target, for display only. */
6501
- arrivesTarget: bigint;
6502
- /** What the paymaster will charge to fund the receiver, buffered, in the same units. */
7654
+ /**
7655
+ * Why the paymaster is not ready: it did not answer (`paymaster_unreachable`), it answered without a
7656
+ * usable price (`no_price`), or its fee is at or above what the rail guarantees to land
7657
+ * (`fee_exceeds_delivery`).
7658
+ */
7659
+ type PaymasterNotReadyCode = "paymaster_unreachable" | "no_price" | "fee_exceeds_delivery";
7660
+ declare function checkPaymasterReady(quoteFee: () => Promise<bigint>, arrivesMin?: bigint, opts?: {
7661
+ timeoutMs?: number;
7662
+ }): Promise<{
7663
+ ok: true;
7664
+ fee: bigint;
7665
+ } | {
7666
+ ok: false;
7667
+ reason: string;
7668
+ code: PaymasterNotReadyCode;
7669
+ }>;
7670
+
7671
+ /**
7672
+ * Deciding on a bridge deposit quote: judging each vetted option, picking the one to offer, whether
7673
+ * an allocated address may still be paid, whether a quote still belongs to what the user typed,
7674
+ * what the receiver's top-up costs, and whether the deposit can be offered at all.
7675
+ *
7676
+ * Pure decisions, plus two checks that ask the service (`checkBridgeReceiverFundable`,
7677
+ * `assertRelayServesDeposits`). Every refusal carries a code; wording is the caller's.
7678
+ * Moved from the website (`lib/bridge-token.ts`, `lib/bridge-quote-vetting.ts`,
7679
+ * `lib/deposit-binding.ts`, the two `pickBest` copies and the hand-summed grants).
7680
+ */
7681
+
7682
+ /**
7683
+ * What was sent, in the destination's base units, for the viability check; null when it cannot be
7684
+ * known and the option must be refused. The signed figure when the quote carries one; for USDC alone
7685
+ * the typed amount (USDC to USDC is the same unit); never a raw 18-decimal amount compared with USDC.
7686
+ */
7687
+ declare function bridgeViabilitySent(option: Pick<BridgeRailQuoteOption, "sentInDestinationUnits">, token: Pick<NetworkToken, "symbol">, amountBaseUnits: bigint): bigint | null;
7688
+ type BridgeOptionAssessment = {
7689
+ ok: true;
7690
+ assessment: BridgeQuoteAssessment;
7691
+ } | {
7692
+ ok: false;
7693
+ problem: BridgeRailProblem;
7694
+ };
7695
+ interface BridgeAssessmentContext {
7696
+ token: Pick<NetworkToken, "symbol">;
7697
+ /** What the user typed, in the origin token's base units. */
7698
+ amountBaseUnits: bigint;
7699
+ /** The live paymaster fee, unbuffered (`checkBridgeReceiverFundable(...).fee`). Buffered here. */
6503
7700
  paymasterFee: bigint;
6504
- /**
6505
- * Live PoolConfig withdraw-fee figures, when the caller has already fetched them on-chain.
6506
- * Optional: omitting either falls back to the compile-time WITHDRAW_FIXED_FEE / WITHDRAW_FEE_BPS
6507
- * constants above, which can be stale. quote.ts never fetches these itself — no RPC call belongs
6508
- * in a pure quote assessment — so the live figures can only arrive this way.
6509
- */
7701
+ /** Live PoolConfig withdraw-fee figures, when the caller has them. */
6510
7702
  liveWithdrawFixedFee?: bigint;
6511
7703
  liveWithdrawFeeBps?: bigint;
6512
7704
  }
6513
- interface BridgeQuoteAssessment extends BridgeQuoteInput {
6514
- /** What actually lands shielded, worst case. This is the number to show the user. */
6515
- shieldedMin: bigint;
6516
- shieldedTarget: bigint;
6517
- /** False means REFUSE: the shield is impossible, so the deposit must not be offered. */
6518
- viable: boolean;
6519
- /** False means warn: it will work, but the fixed costs dominate. */
6520
- economic: boolean;
6521
- /** What it would cost to take it out again, so "shielded" is not mistaken for "free to exit". */
6522
- withdrawFee: bigint;
6523
- /** Origin-to-recipient loss if they shielded and immediately withdrew, worst case. */
6524
- roundTripCost: bigint;
6525
- roundTripFraction: number;
6526
- /** Human-readable, ordered most important first. Empty when everything is fine. */
6527
- reasons: string[];
7705
+ /** The one place a vetted option becomes a viability assessment. Never throws for a bad option. */
7706
+ declare function assessBridgeOption(option: BridgeRailQuoteOption, ctx: BridgeAssessmentContext): BridgeOptionAssessment;
7707
+ interface JudgedBridgeOption {
7708
+ option: BridgeRailQuoteOption;
7709
+ assessment: BridgeQuoteAssessment;
6528
7710
  }
6529
- declare function withdrawFeeFor(amount: bigint): bigint;
6530
- declare function assessBridgeQuote(q: BridgeQuoteInput): BridgeQuoteAssessment;
6531
- /** The quote screen, as the user must see it BEFORE any address is shown. */
6532
- declare function renderAssessment(a: BridgeQuoteAssessment): string;
7711
+ /** Every option judged; those that cannot be join `unavailable` with their reason. */
7712
+ declare function assessBridgeOptions(options: readonly BridgeRailQuoteOption[], ctx: BridgeAssessmentContext): {
7713
+ judged: JudgedBridgeOption[];
7714
+ unavailable: BridgeRailProblem[];
7715
+ };
7716
+ /**
7717
+ * The option to offer: viable ones first (if any is), then economic over not, then the larger
7718
+ * worst-case shielded amount, then a verified signature over none. Null when nothing was judged.
7719
+ * A non-viable result is still returned so a caller can say why (`assessment.reasonCodes`); it must
7720
+ * not be offered for payment.
7721
+ */
7722
+ declare function pickBestBridgeOption(judged: readonly JudgedBridgeOption[]): JudgedBridgeOption | null;
7723
+ /** How much of the signed window must remain to ask the wallet to send: a prompt can sit open. */
7724
+ declare const BRIDGE_SEND_WINDOW_MARGIN_MS = 120000;
7725
+ /**
7726
+ * Whether an allocated option may still be paid. Its `expiresAt` is the SIGNED deadline
7727
+ * (`vetBridgeQuoteOption`), so paying after it sends money to an address the rail has stopped
7728
+ * watching. No parseable expiry counts as closed: nothing vouches for it.
7729
+ */
7730
+ declare function isBridgeSendWindowOpen(option: Pick<BridgeRailQuoteOption, "expiresAt">, nowMs: number, marginMs?: number): boolean;
7731
+ /** What a quote was made for. */
7732
+ interface BridgeQuoteBinding {
7733
+ originChain: string;
7734
+ originToken: string;
7735
+ amountBaseUnits: bigint;
7736
+ }
7737
+ /**
7738
+ * A quote counts only for the exact chain, token and typed amount it was made for: both for what is
7739
+ * displayed and as the last check before sending. An unknown current value never matches.
7740
+ */
7741
+ declare function bridgeQuoteMatches(quote: BridgeQuoteBinding, current: {
7742
+ originChain: string;
7743
+ originToken: string | null | undefined;
7744
+ amountBaseUnits: bigint | null | undefined;
7745
+ }): boolean;
7746
+
7747
+ /**
7748
+ * Whether the paymaster can fund `receiver` RIGHT NOW, asked before money moves on the other chain
7749
+ * and again just before an address is allocated. A real round trip (`paymaster.quoteFee`), never a
7750
+ * read of configuration. `arrivesMin` refuses a fee that would take everything that lands.
7751
+ */
7752
+ declare function checkBridgeReceiverFundable(paymaster: Pick<BridgePaymaster, "quoteFee">, receiver: Address, opts?: {
7753
+ arrivesMin?: bigint;
7754
+ heldLamports?: bigint;
7755
+ rent?: RentRates;
7756
+ timeoutMs?: number;
7757
+ }): Promise<{
7758
+ ok: true;
7759
+ fee: bigint;
7760
+ grantLamports: bigint;
7761
+ } | {
7762
+ ok: false;
7763
+ code: PaymasterNotReadyCode;
7764
+ reason: string;
7765
+ }>;
7766
+ /** A deposit cannot be offered right now. `relay_capability`: the relay cannot shield into this
7767
+ * pool; `paymaster`: the paymaster cannot fund the receiver (see `paymasterCode`). */
7768
+ declare class BridgeUnavailableError extends Error {
7769
+ readonly code: "relay_capability" | "paymaster";
7770
+ readonly paymasterCode?: PaymasterNotReadyCode | undefined;
7771
+ constructor(code: "relay_capability" | "paymaster", message: string, paymasterCode?: PaymasterNotReadyCode | undefined);
7772
+ }
7773
+ /**
7774
+ * The relay gate, run at quote time AND again before an address is allocated (minutes can pass in
7775
+ * between). Resolves the capability when the relay can serve deposits into the pool; throws
7776
+ * `BridgeUnavailableError("relay_capability")` otherwise, before anything is reserved or sent.
7777
+ */
7778
+ declare function assertRelayServesDeposits(readCapability: () => Promise<RelayCapability>): Promise<RelayCapability>;
7779
+ /**
7780
+ * Why the deposit form cannot go ahead, in order (the first that applies wins), or `ready`.
7781
+ *
7782
+ * - `connect_wallet`: no Solana owner yet. `enter_amount`: nothing typed.
7783
+ * - `origin_unsupported`: no signer can send from this network. `connect_origin_wallet`: one can, but
7784
+ * none is connected.
7785
+ * - `quote_problem`: the last quote was refused (its own error says why). `quoting`: no current
7786
+ * quote yet (none, in flight, or one for other input).
7787
+ * - `below_minimum`: the best route would not land the pool minimum (`minimum` says the minimum,
7788
+ * `sendAtLeast` how much to send). `no_route`: nothing could be judged.
7789
+ */
7790
+ type BridgeDepositReadiness = {
7791
+ ready: true;
7792
+ } | {
7793
+ ready: false;
7794
+ code: "connect_wallet" | "enter_amount" | "origin_unsupported" | "connect_origin_wallet" | "quote_problem" | "quoting" | "below_minimum" | "no_route";
7795
+ minimum?: bigint;
7796
+ sendAtLeast?: bigint | null;
7797
+ };
7798
+ declare function bridgeDepositReadiness(input: {
7799
+ ownerConnected: boolean;
7800
+ amountBaseUnits: bigint | null | undefined;
7801
+ originSigner: "connected" | "disconnected" | "unsupported";
7802
+ quoteProblem: boolean;
7803
+ /** The best judged option for the CURRENT input (`bridgeQuoteMatches`), or null/undefined while
7804
+ * there is none. */
7805
+ best: JudgedBridgeOption | null | undefined;
7806
+ /** True once a quote for the current input has come back, even with no usable option. */
7807
+ quoted: boolean;
7808
+ }): BridgeDepositReadiness;
6533
7809
 
6534
7810
  /**
6535
7811
  * Deciding whether a failed shield attempt may be retried.
@@ -6606,14 +7882,2510 @@ interface RetryHooks {
6606
7882
  */
6607
7883
  declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>, hooks?: RetryHooks): Promise<T>;
6608
7884
 
7885
+ /** Waits between attempts at one arrived-but-unfinished deposit; the last repeats. */
7886
+ declare const BRIDGE_FINISH_BACKOFF_MS: readonly number[];
7887
+ /**
7888
+ * Whether a failed shield is safe to try again, from evidence rather than hope: R's token balance
7889
+ * after the failure (`classifyPostFailure`). Unchanged means the deposit did not consume it; zero
7890
+ * means it landed despite the error; anything else is not interpretable and is NOT retryable. A
7891
+ * below-minimum refusal is terminal; a busy receiver is retryable (nothing ran).
7892
+ */
7893
+ declare function assessBridgeFinishFailure(rpc: CloakRpc, receiver: Address, mint: Address, attempted: bigint, error: unknown): Promise<{
7894
+ status: Exclude<BridgeRecoveryStatus, "done" | "dust">;
7895
+ verdict: PostFailureVerdict | null;
7896
+ retryable: boolean;
7897
+ }>;
7898
+ interface BridgeRecovery {
7899
+ /** One pass over the waiting receivers that are due. Never runs two passes at once. */
7900
+ run(): Promise<BridgeRecoveryResult[]>;
7901
+ /** No further attempt starts; one in flight finishes. */
7902
+ stop(): void;
7903
+ /** Ms until the earliest failed deposit is due again, or null when none is waiting on a retry. */
7904
+ nextDueInMs(): number | null;
7905
+ }
7906
+ /**
7907
+ * Recovery with memory: each waiting receiver is tried once; a failure is retried on
7908
+ * `BRIDGE_FINISH_BACKOFF_MS`; a busy receiver is tried again on the next pass; done, dust and
7909
+ * below-minimum are not tried again at the same balance (more money landing resets it).
7910
+ */
7911
+ declare function createBridgeRecovery(ctx: Parameters<typeof recoverBridgeDeposits>[0], opts?: {
7912
+ ledger?: BridgeOrderLedger;
7913
+ backoffMs?: readonly number[];
7914
+ onDeposit?: (r: BridgeRecoveryResult) => void;
7915
+ scanDepth?: number;
7916
+ stopAfterUnused?: number;
7917
+ now?: () => number;
7918
+ }): BridgeRecovery;
7919
+ /** The Note Index lists a deposit once its slot is finalized (~13 s) plus its own lag. */
7920
+ declare const BRIDGE_NOTE_INDEX_DELAY_MS = 8000;
7921
+ declare const BRIDGE_NOTE_INDEX_POLL_MS = 1500;
7922
+ declare const BRIDGE_NOTE_INDEX_GIVE_UP_MS = 60000;
7923
+ /**
7924
+ * Bring a shield's note into the caller's store as soon as the Note Index lists it: wait out most
7925
+ * of finality, then poll `sync` (the caller's own note sync, true once it added the note) until it
7926
+ * reports the note or `giveUpMs` passes. Resolves true when found. A failing `sync` is reported to
7927
+ * `onError` and polled again, never thrown: the note is deterministic and a later sync still finds it.
7928
+ */
7929
+ declare function waitForNoteInIndex(sync: () => Promise<boolean>, opts?: {
7930
+ delayMs?: number;
7931
+ pollMs?: number;
7932
+ giveUpMs?: number;
7933
+ signal?: AbortSignal;
7934
+ onError?: (e: unknown) => void;
7935
+ sleep?: (ms: number) => Promise<void>;
7936
+ now?: () => number;
7937
+ }): Promise<boolean>;
7938
+
7939
+ /** How often the receiver's balance is read. */
7940
+ declare const BRIDGE_ONCHAIN_POLL_MS = 2000;
7941
+ /** The status call is rate limited upstream, so it runs far less often than the chain read. */
7942
+ declare const BRIDGE_STATUS_POLL_MS = 10000;
7943
+ /** No change for this long and the caller is told (once) that it is taking longer than usual. */
7944
+ declare const BRIDGE_STALL_AFTER_MS: number;
7945
+ interface ArrivalTickDeps {
7946
+ now: () => number;
7947
+ /** Absent for a rail with no status call: the chain read is then the only signal. */
7948
+ fetchStatus?: () => Promise<Pick<BridgeRailStatusResult, "state" | "delivery">>;
7949
+ /** Base units at the receiver, 0n when nothing is there. May throw (a transient read). */
7950
+ readArrived: () => Promise<bigint>;
7951
+ /** The balance that counts as arrived: the rail's guaranteed minimum. At least 1. */
7952
+ arriveAt: bigint;
7953
+ onArrived: (amount: bigint) => void;
7954
+ /** Something is there, below `arriveAt`. Called once per distinct amount; the watch goes on. */
7955
+ onPartial?: (amount: bigint) => void;
7956
+ /** The order closed by itself (refunded/expired), with what the receiver holds (below `arriveAt`). */
7957
+ onTerminal: (status: Pick<BridgeRailStatusResult, "state" | "delivery">, held: bigint) => void;
7958
+ onStalled?: () => void;
7959
+ statusPollMs?: number;
7960
+ stallAfterMs?: number;
7961
+ }
7962
+ interface ArrivalTick {
7963
+ run: () => Promise<void>;
7964
+ /** After this, a tick in flight finishes quietly: it calls none of the `on*` callbacks. */
7965
+ cancel: () => void;
7966
+ }
7967
+ declare function createArrivalTick(deps: ArrivalTickDeps): ArrivalTick;
7968
+ type BridgeArrivalResult = {
7969
+ kind: "arrived";
7970
+ amount: bigint;
7971
+ } | {
7972
+ kind: "closed";
7973
+ status: Pick<BridgeRailStatusResult, "state" | "delivery">;
7974
+ /** What the receiver holds (below the guarantee; may be 0). */
7975
+ held: bigint;
7976
+ terminal: BridgeTerminalKind | null;
7977
+ } | {
7978
+ kind: "aborted";
7979
+ };
7980
+ interface WatchBridgeArrivalOrder {
7981
+ receiver: Address;
7982
+ option: Pick<BridgeRailQuoteOption, "rail" | "attestation" | "depositAddress" | "minAmountOut">;
7983
+ /** What the order sent, so status amounts carry their token. */
7984
+ origin?: BridgeStatusOrigin;
7985
+ /** Closes the order in the ledger when it closes with nothing at the receiver. */
7986
+ ledger?: Pick<BridgeOrderLedger, "settle">;
7987
+ index?: number;
7988
+ }
7989
+ /**
7990
+ * Watch until arrival, close or abort. Status is asked only for a signed-rail option with a deposit
7991
+ * address (the other rail has no status API). `depositSeen` / `manual` decide how a close reads
7992
+ * (`classifyBridgeTerminal`). A close with an empty receiver settles the order in `ledger`; a close
7993
+ * with something left keeps it open (that money still needs a way out).
7994
+ */
7995
+ declare function watchBridgeArrival(ctx: {
7996
+ rpc: CloakRpc;
7997
+ mint: Address;
7998
+ rail?: BridgeRail;
7999
+ tokenProgram?: Address;
8000
+ }, order: WatchBridgeArrivalOrder, opts?: {
8001
+ signal?: AbortSignal;
8002
+ onPartial?: (amount: bigint) => void;
8003
+ onStalled?: () => void;
8004
+ depositSeen?: () => boolean;
8005
+ manual?: boolean;
8006
+ pollMs?: number;
8007
+ statusPollMs?: number;
8008
+ stallAfterMs?: number;
8009
+ now?: () => number;
8010
+ }): Promise<BridgeArrivalResult>;
8011
+
8012
+ /**
8013
+ * A bridge deposit order, end to end: reveal a receiving route for a judged quote, send on the
8014
+ * origin chain (the caller's callback), watch the arrival, and shield it. Everything a partner needs
8015
+ * to run a deposit with the SDK alone; the website runs the same thing under its own UI.
8016
+ *
8017
+ * Three layers:
8018
+ * - `nextBridgeOrderState(state, event)`: the lifecycle as a pure reducer. An event that is not
8019
+ * legal in a state returns the state unchanged.
8020
+ * - `revealBridgeRoute(ctx, input)`: the step that allocates an address, with every gate before it.
8021
+ * - `runBridgeDeposit(ctx, input, hooks)`: the whole flow in one call, reporting each state.
8022
+ */
8023
+
8024
+ /** How the origin-chain transfer is getting to the deposit address. The address stays valid in
8025
+ * every branch: a wallet that refuses or fails never costs the user the address. */
8026
+ type BridgeSendState =
8027
+ /** Not asked yet. */
8028
+ {
8029
+ kind: "idle";
8030
+ } | {
8031
+ kind: "signing";
8032
+ } | {
8033
+ kind: "sent";
8034
+ hash: string;
8035
+ }
8036
+ /** No signer for this origin: the address is the interface. Not a failure. */
8037
+ | {
8038
+ kind: "manual";
8039
+ } | {
8040
+ kind: "failed";
8041
+ code: "rejected" | "failed";
8042
+ message?: string;
8043
+ };
8044
+ /** An order with an allocated address. */
8045
+ interface BridgeOrder {
8046
+ index: number;
8047
+ receiver: Address;
8048
+ /** The ALLOCATED option (signed deadline, deposit address). */
8049
+ option: BridgeRailQuoteOption;
8050
+ /** The allocated option judged again with the fresh paymaster fee. */
8051
+ assessment: BridgeQuoteAssessment;
8052
+ /** What was typed: the order sends exactly this. */
8053
+ binding: BridgeQuoteBinding;
8054
+ token: NetworkToken;
8055
+ solanaOwner: string;
8056
+ refundTo?: string;
8057
+ /** The live paymaster fee the assessment used. */
8058
+ paymasterFee: bigint;
8059
+ }
8060
+ type BridgeOrderFailureCode =
8061
+ /** The origin transfer the order sent reverted on chain. */
8062
+ "origin_reverted"
8063
+ /** What arrived, less the fee, is under the pool minimum. Terminal. */
8064
+ | "below_minimum"
8065
+ /** Another shield or a move to the wallet holds the receiver. */
8066
+ | "receiver_busy" | "finish_failed";
8067
+ type BridgeOrderState = {
8068
+ kind: "waiting";
8069
+ order: BridgeOrder;
8070
+ send: BridgeSendState;
8071
+ } | {
8072
+ kind: "arrived";
8073
+ order: BridgeOrder;
8074
+ amount: bigint;
8075
+ } | {
8076
+ kind: "funding";
8077
+ order: BridgeOrder;
8078
+ amount: bigint;
8079
+ } | {
8080
+ kind: "shielded";
8081
+ order: BridgeOrder;
8082
+ outcome: BridgeFinishOutcome;
8083
+ } | {
8084
+ kind: "closed";
8085
+ order: BridgeOrder;
8086
+ terminal: BridgeTerminalKind | null;
8087
+ held: bigint;
8088
+ } | {
8089
+ kind: "failed";
8090
+ order: BridgeOrder;
8091
+ code: BridgeOrderFailureCode;
8092
+ message: string;
8093
+ /** Where a retry resumes, or null when nothing can (terminal). */
8094
+ retryFrom: "arrived" | null;
8095
+ amount?: bigint;
8096
+ };
8097
+ type BridgeOrderEvent = {
8098
+ type: "send_started";
8099
+ } | {
8100
+ type: "send_sent";
8101
+ hash: string;
8102
+ } | {
8103
+ type: "send_manual";
8104
+ } | {
8105
+ type: "send_failed";
8106
+ code: "rejected" | "failed";
8107
+ message?: string;
8108
+ } | {
8109
+ type: "origin_reverted";
8110
+ hash: string;
8111
+ } | {
8112
+ type: "arrived";
8113
+ amount: bigint;
8114
+ } | {
8115
+ type: "closed";
8116
+ terminal: BridgeTerminalKind | null;
8117
+ held: bigint;
8118
+ } | {
8119
+ type: "funding";
8120
+ } | {
8121
+ type: "shielded";
8122
+ outcome: BridgeFinishOutcome;
8123
+ } | {
8124
+ type: "finish_failed";
8125
+ code: Exclude<BridgeOrderFailureCode, "origin_reverted">;
8126
+ message: string;
8127
+ } | {
8128
+ type: "retry";
8129
+ };
8130
+ /** The lifecycle. Illegal events leave the state as it is. */
8131
+ declare function nextBridgeOrderState(state: BridgeOrderState, event: BridgeOrderEvent): BridgeOrderState;
8132
+ /**
8133
+ * Whether the origin wallet may be asked to send now: the order is waiting and not already sent or
8134
+ * signing, the allocated quote is still viable, and its SIGNED deadline is more than the send margin
8135
+ * away. The amount and token are the order's own binding, never whatever is typed now.
8136
+ */
8137
+ declare function canSendBridgeOrder(state: BridgeOrderState, nowMs: number): {
8138
+ ok: true;
8139
+ to: string;
8140
+ amountBaseUnits: bigint;
8141
+ token: NetworkToken;
8142
+ originChain: string;
8143
+ } | {
8144
+ ok: false;
8145
+ reason: "not_waiting" | "already_sent" | "no_address" | "not_viable" | "window_closed";
8146
+ };
8147
+ /** A prepared shield needs the exact arrival: the quote's target equals its guarantee and the
8148
+ * transfer was sent. */
8149
+ declare function canPrepareBridgeShield(state: BridgeOrderState): boolean;
8150
+ type BridgeOrderErrorCode =
8151
+ /** The quote was made for another chain, token or amount than the one typed now. */
8152
+ "quote_mismatch" | "token_not_offered" | "rail_not_offered"
8153
+ /** The allocating quote returned no address for the rail. */
8154
+ | "no_address"
8155
+ /** The allocated option could not be judged. */
8156
+ | "not_assessable";
8157
+ declare class BridgeOrderError extends Error {
8158
+ readonly code: BridgeOrderErrorCode;
8159
+ constructor(code: BridgeOrderErrorCode, message: string);
8160
+ }
8161
+ interface BridgeOrderContext {
8162
+ rail: BridgeRail;
8163
+ paymaster: BridgePaymaster;
8164
+ ledger: BridgeOrderLedger;
8165
+ /** The wallet's UTXO keypair: receivers derive from it. */
8166
+ owner: UtxoKeypair;
8167
+ /** The relay's capability for the pool (`() => fetchRelayCapability(relayUrl, mint)`). */
8168
+ readRelayCapability: () => Promise<RelayCapability>;
8169
+ now?: () => number;
8170
+ }
8171
+ interface RevealBridgeRouteInput {
8172
+ /** The judged option the user confirmed, and what its quote was made for. */
8173
+ quote: {
8174
+ binding: BridgeQuoteBinding;
8175
+ judged: JudgedBridgeOption;
8176
+ };
8177
+ /** What is typed NOW. Must match the quote's binding exactly. */
8178
+ current: {
8179
+ originChain: string;
8180
+ originToken: string | null | undefined;
8181
+ amountBaseUnits: bigint | null | undefined;
8182
+ };
8183
+ /** A fresh discovery (`discoverBridgeDeposits`). */
8184
+ deposits: readonly Pick<BridgeDeposit, "index" | "legacyExposed">[];
8185
+ solanaOwner: string;
8186
+ /** Origin-chain address an unfillable order refunds to: the sender's own wallet. */
8187
+ refundTo?: string;
8188
+ }
8189
+ /**
8190
+ * Allocate a deposit address for a confirmed quote. In order, nothing reserved before its gate:
8191
+ * the quote still matches what is typed; the token and rail are offered; the relay can take the
8192
+ * deposit and the paymaster can fund the receiver (both asked again here, minutes after the quote);
8193
+ * then the index is recorded (`ledger.allocate`) BEFORE the rail is asked for the address; then the
8194
+ * allocated quote is judged again with the fresh fee. A failure before an address exists abandons
8195
+ * the reservation. The returned order may be not viable (`assessment.viable` false): the address
8196
+ * exists, but `canSendBridgeOrder` refuses to send to it.
8197
+ */
8198
+ declare function revealBridgeRoute(ctx: BridgeOrderContext, input: RevealBridgeRouteInput): Promise<{
8199
+ state: Extract<BridgeOrderState, {
8200
+ kind: "waiting";
8201
+ }>;
8202
+ receiver: KeyPairSigner;
8203
+ }>;
8204
+ interface RunBridgeDepositHooks {
8205
+ /**
8206
+ * Send `amountBaseUnits` of `token` to `to` on `originChain`, from the user's origin wallet, and
8207
+ * return the transaction hash (e.g. `sendEvmDeposit`). Absent: the order is paid by hand and the
8208
+ * flow waits for the money.
8209
+ */
8210
+ send?: (args: {
8211
+ to: string;
8212
+ amountBaseUnits: bigint;
8213
+ token: NetworkToken;
8214
+ originChain: string;
8215
+ order: BridgeOrder;
8216
+ }) => Promise<string>;
8217
+ /** Classify a send failure: "rejected" when the user declined (default "failed"). */
8218
+ classifySendError?: (e: unknown) => "rejected" | "failed";
8219
+ /** Watch the origin transfer's receipt (e.g. `watchEvmReceipt`). A "failed" verdict ends the order. */
8220
+ watchOriginReceipt?: (hash: string, signal: AbortSignal) => Promise<"confirmed" | "failed" | "cancelled" | "unknown">;
8221
+ /** Every state, in order. */
8222
+ onState?: (state: BridgeOrderState) => void;
8223
+ onPartial?: (amount: bigint) => void;
8224
+ onStalled?: () => void;
8225
+ /** Pre-prove the shield while the bridge delivers, when the quote is exact. Default true. */
8226
+ prepare?: boolean;
8227
+ signal?: AbortSignal;
8228
+ }
8229
+ /**
8230
+ * One deposit, start to finish: reveal (`revealBridgeRoute`), send through `hooks.send`, watch the
8231
+ * receipt and the arrival, then shield once (prepared when the quote is exact), settling the order
8232
+ * in the ledger. Resolves with the last state: `shielded`, `closed`, `failed`, or `waiting` when it
8233
+ * stopped before the money moved (not viable, window closed, the wallet refused, aborted). Throws
8234
+ * only from the reveal, before any address is in the user's hands.
8235
+ */
8236
+ declare function runBridgeDeposit(ctx: BridgeOrderContext & FinishBridgeContext & {
8237
+ noteSpendKey: Uint8Array;
8238
+ }, input: RevealBridgeRouteInput, hooks?: RunBridgeDepositHooks): Promise<BridgeOrderState>;
8239
+
8240
+ /** The Token-2022 program. A mint owned by it takes the same instructions under this program id. */
8241
+ declare const TOKEN_2022_PROGRAM_ADDRESS: Address;
8242
+ type ReceiverMoveErrorCode =
8243
+ /** The receiver holds none of this token. Nothing was asked of the wallet. */
8244
+ "RECEIVER_MOVE_NOTHING_TO_MOVE"
8245
+ /** The wallet has too little SOL for the network fee (and its token account's rent, when it has
8246
+ * none for this mint). `needLamports` / `haveLamports` are set. Nothing was asked of the wallet. */
8247
+ | "RECEIVER_MOVE_WALLET_NEEDS_SOL"
8248
+ /** The wallet refused to sign. Nothing was sent. */
8249
+ | "RECEIVER_MOVE_WALLET_REJECTED"
8250
+ /** The network refused the signed transaction at submission (preflight). Nothing was sent. */
8251
+ | "RECEIVER_MOVE_SEND_REFUSED"
8252
+ /** Sent, but not seen confirmed in time. `signature` is set. Calling again is safe: if this one
8253
+ * landed, the next call finds nothing to move. */
8254
+ | "RECEIVER_MOVE_UNCONFIRMED";
8255
+ declare class ReceiverMoveError extends Error {
8256
+ readonly code: ReceiverMoveErrorCode;
8257
+ readonly signature?: string;
8258
+ readonly needLamports?: bigint;
8259
+ readonly haveLamports?: bigint;
8260
+ constructor(code: ReceiverMoveErrorCode, message: string, opts?: {
8261
+ signature?: string;
8262
+ cause?: unknown;
8263
+ needLamports?: bigint;
8264
+ haveLamports?: bigint;
8265
+ });
8266
+ }
8267
+ /**
8268
+ * Is `e` a `ReceiverMoveError` (with `code`, when given)? Checks `name` and `code`, not
8269
+ * `instanceof`, which is false across two loaded copies of this SDK.
8270
+ */
8271
+ declare function isReceiverMoveError(e: unknown, code?: ReceiverMoveErrorCode): e is ReceiverMoveError;
8272
+ /** True when `e` is a wallet's refusal to sign. Exported for tests and for callers with their own
8273
+ * signing step. */
8274
+ declare function isWalletRejection(e: unknown): boolean;
8275
+ /**
8276
+ * The token balance `owner` holds of `mint`, in base units. 0n only when its token account does
8277
+ * not exist; an RPC failure throws rather than reading as zero.
8278
+ *
8279
+ * Read-only, and unguarded like `listBridgeDeposits`: it signs and submits nothing, so it works on
8280
+ * whatever RPC the caller has. Moving what it finds goes through the guarded
8281
+ * `moveReceiverFundsToWallet`.
8282
+ *
8283
+ * @param tokenProgram the mint's token program, when the caller already knows it; saves reading
8284
+ * the mint on every call. Default: read from the mint's owner.
8285
+ */
8286
+ declare function readReceiverTokenBalance(rpc: CloakRpc, owner: Address, mint: Address, tokenProgram?: Address): Promise<bigint>;
8287
+ /** The wallet's fee budget for a move: two signatures, plus headroom for a priority fee a wallet
8288
+ * adds on its own (Solflare's guard sets a compute-unit price). */
8289
+ declare const MOVE_FEE_BUDGET_LAMPORTS = 20000n;
8290
+ interface MoveReceiverFundsResult {
8291
+ signature: string;
8292
+ /** Exactly what moved: the balance read when the transaction was built. */
8293
+ amount: bigint;
8294
+ /** The receiver's token account, left open and empty. */
8295
+ tokenAccount: Address;
8296
+ }
8297
+ /**
8298
+ * Move everything `receiver` holds of `mint` to `wallet`'s own token account, paid by `wallet`.
8299
+ *
8300
+ * `receiver` is any one-time address signer: `deriveBridgeReceiver(owner, i)`,
8301
+ * `bridgeReceiverSigner(deposit, owner)` for a legacy one, or `derivePayoutRefundKey(owner)`.
8302
+ * Creates the wallet's token account if it is missing (the wallet pays its rent). Throws a
8303
+ * `ReceiverMoveError`, before asking the wallet, with `RECEIVER_MOVE_NOTHING_TO_MOVE` when the
8304
+ * balance is zero and `RECEIVER_MOVE_WALLET_NEEDS_SOL` when the wallet cannot pay; after, with
8305
+ * `RECEIVER_MOVE_WALLET_REJECTED` when the wallet refuses, `RECEIVER_MOVE_SEND_REFUSED` when the
8306
+ * network refuses it at submission, and `RECEIVER_MOVE_UNCONFIRMED` when it was sent but not
8307
+ * confirmed in time.
8308
+ *
8309
+ * PUBLIC: see the file comment. Never call it for a receiver that already shielded a deposit
8310
+ * (`needs-cleanup`): that links a private deposit to the wallet.
8311
+ */
8312
+ declare function moveReceiverFundsToWallet(params: {
8313
+ rpc: CloakRpc;
8314
+ receiver: KeyPairSigner;
8315
+ mint: Address;
8316
+ wallet: TransactionSigner;
8317
+ onStep?: (step: string) => void;
8318
+ /** Confirmation wait. Default 90 s. */
8319
+ confirmTimeoutMs?: number;
8320
+ }): Promise<MoveReceiverFundsResult>;
8321
+
8322
+ interface CleanupResult {
8323
+ closed: boolean;
8324
+ dustSwept: bigint;
8325
+ rentReturned: bigint;
8326
+ destination: string | null;
8327
+ signature: string | null;
8328
+ note: string;
8329
+ }
8330
+ /**
8331
+ * @param dustDestination where post-deposit dust goes, if the caller wants it swept at all.
8332
+ * LEAVE IT UNDEFINED unless the user has been told the cost: any destination they control
8333
+ * publishes `R -> them` and deanonymises the deposit R just made. It is never Cloak's, because
8334
+ * capturing user funds off-chain would be an off-chain fee, which the team rule forbids.
8335
+ * Undefined means "close if empty, otherwise leave it alone and report it".
8336
+ * @param mint the shielded asset R was funded for. Defaults to mainnet USDC so a caller written
8337
+ * before this parameter existed keeps compiling and keeps recovering the same account it always
8338
+ * has; a bridge for any other asset MUST pass its own mint, since R's token account and the
8339
+ * dust sitting in it both belong to whatever mint the rail actually delivered, not to this
8340
+ * default.
8341
+ */
8342
+ declare function cleanupReceivingAddress(rpc: CloakRpc, R: KeyPairSigner, dustDestination?: Address, mint?: Address): Promise<CleanupResult>;
8343
+
8344
+ declare const ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
8345
+ /**
8346
+ * The exact string this rail signs over, exported so a second implementation can be checked against
8347
+ * it rather than reasoned about.
8348
+ *
8349
+ * A Rust twin of `stable()` has to reproduce JavaScript's key ordering and number formatting byte
8350
+ * for byte, and the two languages do not agree by default: `Object.keys().sort()` orders by UTF-16
8351
+ * code unit while Rust's `sort()` orders by UTF-8 byte. They coincide for ASCII and diverge above
8352
+ * it. This is the same class of bug as `canonicalJson` versus Rust's `keys.sort_unstable()` in the
8353
+ * relay-auth payload, and it fails in the worst direction: a verifier that rejects HONEST quotes
8354
+ * looks like a rail outage, and teaches whoever is on call to ignore it.
8355
+ *
8356
+ * So the cross-language test compares THIS string, not just the boolean verdict. Two verifiers can
8357
+ * agree on a signature by both being wrong in the same place; they cannot agree on the bytes by
8358
+ * accident.
8359
+ */
8360
+ declare function canonicalPayloadString(resp: any): string;
8361
+ declare function verifyQuoteSignature(resp: any): {
8362
+ valid: boolean;
8363
+ reason?: string;
8364
+ };
8365
+ /** Solana USDC's 1Click asset id: the destination of every bridge deposit into the pool. */
8366
+ declare const SOLANA_USDC_ONECLICK_ASSET = "nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near";
8367
+ interface ExpectedDeposit {
8368
+ /** The derived receiver R. */
8369
+ recipient: string;
8370
+ amountBaseUnits: bigint;
8371
+ refundTo?: string;
8372
+ allocate: boolean;
8373
+ /** The option's own deposit address, required (non-empty) to match the signed one when `allocate`. */
8374
+ depositAddress?: string;
8375
+ /** The origin chain's USDC 1Click asset id (`oneClickAssetId(chain, "USDC")`), compared exactly. */
8376
+ originAsset: string;
8377
+ /** Widest `amountOut` -> `minAmountOut` gap accepted, in basis points. Default 300. */
8378
+ maxSlippageBps?: number;
8379
+ }
8380
+ type BoundDeposit = {
8381
+ ok: true;
8382
+ amountOut: bigint;
8383
+ minAmountOut: bigint;
8384
+ deadlineMs: number;
8385
+ /**
8386
+ * What was sent, in the DESTINATION asset's base units, from signed fields only. The same
8387
+ * asset on both sides is the signed `amount` itself; otherwise the quote's own signed rate
8388
+ * converts it: amountInUsd x amountOut / amountOutUsd. This is the `sent` a viability check
8389
+ * needs: an 18-decimal ETH amount compared with USDC base units is nonsense.
8390
+ */
8391
+ sentInDestinationUnits: bigint;
8392
+ } | {
8393
+ ok: false;
8394
+ reason: string;
8395
+ };
8396
+ /**
8397
+ * Bind a signed 1Click DEPOSIT quote to the request that produced it. `verifyQuoteSignature` only
8398
+ * proves 1Click signed SOME quote; this proves it is THIS one. Call it after a valid signature, or
8399
+ * use `vetOneClickDepositOption`, which does both.
8400
+ *
8401
+ * Every field below is covered by the signature (see `signedRequest` / `signedQuote`), which is
8402
+ * why it can be trusted here and the wire fields beside it cannot. Amounts returned are the SIGNED
8403
+ * ones. `nowMs` is injectable so freshness is testable; it only matters when `allocate`, because a
8404
+ * dry quote's `quote.deadline` is not signed and no address exists to expire.
8405
+ */
8406
+ declare function bindDepositQuote(railResponse: unknown, expect: ExpectedDeposit, nowMs?: number): BoundDeposit;
8407
+ type VettedOneClickDeposit = BoundDeposit;
8408
+ /**
8409
+ * The ONE check a 1Click deposit option must pass before anyone displays its address or amounts:
8410
+ * the ed25519 signature verifies, the signed payload binds to what was asked for, and it has not
8411
+ * expired. Both this SDK's `fetchBridgeQuote` and a web app's own proxy path call it, so neither
8412
+ * can drift. The bridge service, any proxy, and the option's own `attestation` label are
8413
+ * untrusted; only the signature is. The amounts returned are the signed ones.
8414
+ */
8415
+ declare function vetOneClickDepositOption(railResponse: unknown, expect: ExpectedDeposit, nowMs: number): VettedOneClickDeposit;
8416
+
8417
+ /**
8418
+ * The EVM side of a deposit from Base or Polygon: the transfer the sender's wallet signs, the
8419
+ * chain it must be on, the receipt that says it landed, and the balance and gas reads around it.
8420
+ *
8421
+ * WHY THIS IS IN THE SDK. A client using only the SDK, such as a partner whose users hold funds on
8422
+ * Base, needs exactly what the website's EVM hooks did: send the deposit to the rail's verified
8423
+ * address without the user retyping it, refuse to send on the wrong chain, and know whether the
8424
+ * transfer was mined. Moved from web (`lib/evm-send.ts`, `lib/evm-receipt.ts`,
8425
+ * `app/privacy/bridge/_hooks/useEvmWallet.ts`) on 2026-11-23.
8426
+ *
8427
+ * NO EVM LIBRARY. Everything goes through one function with the EIP-1193 `request` shape
8428
+ * (`provider.request({ method, params })`), which an injected browser wallet, an embedded wallet
8429
+ * (Privy, Coinbase) and most server-side clients already expose. An ERC-20 transfer is one static
8430
+ * call, `transfer(address,uint256)`, so it is encoded by hand rather than pulling in an ABI codec.
8431
+ * A caller that sends with its own stack can take `buildEvmTransfer`'s parameters, send them, and
8432
+ * hand the hash to `watchEvmReceipt`.
8433
+ *
8434
+ * THE CHAIN IS ASSERTED, NOT ASSUMED. A wallet serves one chain at a time and the user may have
8435
+ * moved it since the quote. Every EVM network shares one address format, so a transfer sent on the
8436
+ * wrong chain goes to an address that may not be the deposit address there, and the money is lost.
8437
+ * `sendEvmDeposit` switches, re-reads the chain, and refuses if it is still wrong.
8438
+ */
8439
+
8440
+ /** The EIP-1193 request function: pass `(args) => provider.request(args)`. */
8441
+ type EvmRequest = (args: {
8442
+ method: string;
8443
+ params?: unknown[];
8444
+ }) => Promise<unknown>;
8445
+ /** The transaction object for `eth_sendTransaction`. `data` is present only for a token transfer. */
8446
+ interface EvmTxParams {
8447
+ from: string;
8448
+ to: string;
8449
+ /** Hex quantity, as JSON-RPC expects. "0x0" for a token transfer. */
8450
+ value: string;
8451
+ data?: string;
8452
+ }
8453
+ type EvmOriginErrorCode =
8454
+ /** `networkId` is not an EVM network with a chain id in the table. */
8455
+ "EVM_NOT_EVM_NETWORK"
8456
+ /** The transfer could not be built: a bad deposit address, token contract or amount. Nothing was asked. */
8457
+ | "EVM_INVALID_TRANSFER"
8458
+ /** The person declined in their wallet (EIP-1193 4001), at the chain switch or the send. */
8459
+ | "EVM_REJECTED"
8460
+ /** The wallet does not know this chain yet (EIP-1193 4902); it must be added first. */
8461
+ | "EVM_CHAIN_NOT_ADDED"
8462
+ /** The wallet is still on another chain after the switch. Nothing was sent. */
8463
+ | "EVM_WRONG_CHAIN"
8464
+ /** The wallet accepted the send but returned no transaction hash. The transfer may still go out. */
8465
+ | "EVM_NO_HASH"
8466
+ /** A balance read came back malformed, or empty where a token contract should answer. */
8467
+ | "EVM_BALANCE_UNREADABLE";
8468
+ /** Every refusal from this module. Match on `code`, never on the message. */
8469
+ declare class EvmOriginError extends Error {
8470
+ readonly code: EvmOriginErrorCode;
8471
+ readonly cause?: unknown | undefined;
8472
+ constructor(code: EvmOriginErrorCode, message: string, cause?: unknown | undefined);
8473
+ }
8474
+ /** True when `e` is an `EvmOriginError`, and has `code` when one is given. */
8475
+ declare function isEvmOriginError(e: unknown, code?: EvmOriginErrorCode): e is EvmOriginError;
8476
+ /**
8477
+ * What an error thrown by a wallet's `request` means: the person said no (4001), the chain is not
8478
+ * in the wallet yet (4902), or something else. For callers driving a wallet themselves; the
8479
+ * functions here already turn these into `EvmOriginError` codes.
8480
+ */
8481
+ declare function classifyEvmProviderError(e: unknown): "rejected" | "unknown-chain" | "other";
8482
+ /** A transaction hash: `0x` and 64 hex digits. Anything else is never sent to a provider. */
8483
+ declare function isEvmTxHash(hash: unknown): hash is string;
8484
+ /**
8485
+ * The transfer of `amountBaseUnits` of `token` to `to`, for `eth_sendTransaction`.
8486
+ *
8487
+ * - The network's own coin (a token with no `contract`, such as ETH on Base): a value transfer to
8488
+ * `to`, with no data.
8489
+ * - An ERC-20 (USDC): a call to the token's contract, `transfer(address,uint256)`, selector
8490
+ * `0xa9059cbb`, recipient and amount each left-padded to 32 bytes.
8491
+ *
8492
+ * Validates before anything is asked of a wallet: `to` and the contract must be EVM addresses and
8493
+ * the amount must be above zero. Throws `EvmOriginError` `EVM_INVALID_TRANSFER` otherwise.
8494
+ */
8495
+ declare function buildEvmTransfer(args: {
8496
+ from: string;
8497
+ to: string;
8498
+ token: Pick<NetworkToken, "contract">;
8499
+ amountBaseUnits: bigint;
8500
+ }): EvmTxParams;
8501
+ /**
8502
+ * Make sure the wallet behind `request` is on `networkId`'s chain: read `eth_chainId`, ask for
8503
+ * `wallet_switchEthereumChain` if it differs, then read it again and refuse if it is still wrong.
8504
+ *
8505
+ * Throws `EvmOriginError`: `EVM_NOT_EVM_NETWORK`, `EVM_REJECTED` (declined the switch),
8506
+ * `EVM_CHAIN_NOT_ADDED` (4902), or `EVM_WRONG_CHAIN`.
8507
+ */
8508
+ declare function ensureEvmChain(request: EvmRequest, networkId: string): Promise<void>;
8509
+ /**
8510
+ * Send a deposit from an EVM wallet: build the transfer (validated before the wallet is asked
8511
+ * anything), make sure the wallet is on `networkId`'s chain, send it, and return the transaction
8512
+ * hash once the wallet has accepted it.
8513
+ *
8514
+ * Accepted is not mined: follow it with `watchEvmReceipt`. `to` must be the deposit address from a
8515
+ * verified quote; `from` is the wallet's account.
8516
+ *
8517
+ * Throws `EvmOriginError`: any code from `buildEvmTransfer` and `ensureEvmChain`, `EVM_REJECTED`
8518
+ * when the send is declined, `EVM_NO_HASH` when the wallet answers without a hash.
8519
+ */
8520
+ declare function sendEvmDeposit(request: EvmRequest, args: {
8521
+ networkId: string;
8522
+ token: Pick<NetworkToken, "contract">;
8523
+ from: string;
8524
+ to: string;
8525
+ amountBaseUnits: bigint;
8526
+ }): Promise<string>;
8527
+ /** How long `watchEvmReceipt` waits by default before answering "unknown". */
8528
+ declare const EVM_RECEIPT_DEADLINE_MS: number;
8529
+ /**
8530
+ * - `confirmed` / `failed`: the chain returned a receipt (status 0x1 / 0x0). A failed transfer
8531
+ * moved nothing.
8532
+ * - `cancelled`: the caller stopped watching.
8533
+ * - `unknown`: no verdict, because the hash was malformed or no receipt came before the deadline.
8534
+ * NOT a failure: the transfer may still land, so never present it as one.
8535
+ */
8536
+ type EvmReceiptVerdict = "confirmed" | "failed" | "cancelled" | "unknown";
8537
+ /**
8538
+ * Poll `eth_getTransactionReceipt` for `hash` until it is mined, the deadline passes, or `signal`
8539
+ * aborts. A provider error is not a verdict: it asks again.
8540
+ */
8541
+ declare function watchEvmReceipt(request: EvmRequest, hash: string, opts?: {
8542
+ signal?: AbortSignal;
8543
+ intervalMs?: number;
8544
+ deadlineMs?: number;
8545
+ now?: () => number;
8546
+ sleep?: (ms: number) => Promise<void>;
8547
+ }): Promise<EvmReceiptVerdict>;
8548
+ /**
8549
+ * `holder`'s balance of `token`, in base units: `eth_getBalance` for the network's own coin,
8550
+ * `balanceOf(address)` (selector `0x70a08231`) for an ERC-20. Reads whatever chain the wallet or
8551
+ * endpoint is on, so call `ensureEvmChain` first when that matters.
8552
+ *
8553
+ * Throws `EvmOriginError` `EVM_BALANCE_UNREADABLE` for an answer that is not a hex quantity. That
8554
+ * includes the empty `"0x"` a token read returns when no contract answers at that address, which
8555
+ * means the wrong chain or the wrong contract, never a balance of zero.
8556
+ */
8557
+ declare function readEvmBalance(request: EvmRequest, holder: string, token: Pick<NetworkToken, "contract">): Promise<bigint>;
8558
+ /** Gas a plain value transfer uses. */
8559
+ declare const EVM_TRANSFER_GAS_UNITS = 21000n;
8560
+ /**
8561
+ * Headroom over `eth_gasPrice`: the price moves between the estimate and the send, and a wallet may
8562
+ * add a priority fee. Over-reserving leaves the user a sliver of dust; under-reserving fails the send.
8563
+ */
8564
+ declare const EVM_GAS_SAFETY_FACTOR = 3n;
8565
+ /** What a send of the network's own coin should keep back for gas, from a gas price; null without a usable price. */
8566
+ declare function nativeGasReserve(gasPriceWei: bigint | null): bigint | null;
8567
+ /** `eth_gasPrice` turned into `nativeGasReserve`; null when the wallet gives no usable price or the read fails. */
8568
+ declare function readEvmGasReserve(request: EvmRequest): Promise<bigint | null>;
8569
+ /**
8570
+ * The least a send of the network's own coin leaves behind for gas, whatever the estimate says:
8571
+ * 0.0001 of the coin (10^(decimals-4) base units, 1e14 wei for ETH). On an L2 such as Base,
8572
+ * `eth_gasPrice` covers only execution; the L1 data fee comes on top, so 21000 x price x 3 can be
8573
+ * far too little, and a MAX send would leave the wallet unable to pay.
8574
+ */
8575
+ declare function nativeGasFloor(token: Pick<NetworkToken, "decimals">): bigint;
8576
+ /**
8577
+ * True when sending `amount` of the network's own coin would leave less than it must keep for gas
8578
+ * (the larger of `gasReserve` and `nativeGasFloor`). Never true for a token transfer: it pays gas
8579
+ * in the network's coin, not in the token. Check that separately with `evmCannotPayGas`.
8580
+ */
8581
+ declare function leavesTooLittleForGas(token: Pick<NetworkToken, "contract" | "decimals">, balance: bigint, amount: bigint, gasReserve: bigint | null): boolean;
8582
+ /**
8583
+ * The most a MAX button may send, or null when MAX must be disabled. A token transfer may send the
8584
+ * whole token balance. The network's own coin keeps its gas back, and with no gas estimate, or a
8585
+ * balance that does not cover it, the answer is null rather than a guess.
8586
+ */
8587
+ declare function maxSendableEvm(token: Pick<NetworkToken, "contract" | "decimals">, balance: bigint, gasReserve: bigint | null): bigint | null;
8588
+ /**
8589
+ * True when the wallet certainly cannot pay gas: its balance of the network's own coin is zero.
8590
+ * A wallet holding USDC and no ETH cannot send the USDC, and the wallet's own error for that is
8591
+ * often unclear, so say it before asking. Only a known zero blocks; an unread balance (null) does
8592
+ * not, because refusing on a failed read would stop a wallet that could have paid.
8593
+ */
8594
+ declare function evmCannotPayGas(nativeBalance: bigint | null): boolean;
8595
+
8596
+ /**
8597
+ * Why money is waiting outside the private balance.
8598
+ *
8599
+ * - `deposit_failed`: a bridged deposit arrived and adding it failed (outside money at the address,
8600
+ * or repeated failures).
8601
+ * - `below_minimum`: what arrived is too small to ever be added.
8602
+ * - `payout_refund`: a payout the rail refunded, at the wallet's payout refund key.
8603
+ * - `payout_unsent`: a payout collected at a one-time address that will never be sent on.
8604
+ */
8605
+ type MoveReason = "deposit_failed" | "below_minimum" | "payout_refund" | "payout_unsent";
8606
+ /**
8607
+ * How a move ended. Map each to words; never present `unconfirmed` as a failure.
8608
+ *
8609
+ * - `moved`: confirmed. `amount` is what the wallet received.
8610
+ * - `nothing`: the address held none of the token. Nothing was asked of the wallet.
8611
+ * - `cancelled`: declined in the wallet before signing. Nothing was sent.
8612
+ * - `needs_sol`: the wallet cannot pay the network fee; it needs about `needLamports`. Nothing was
8613
+ * asked of the wallet.
8614
+ * - `unconfirmed`: signed, and not seen confirmed. It may still land; a second attempt is safe,
8615
+ * because if this one landed the next finds nothing to move.
8616
+ * - `failed`: nothing moved. `code` says why: `REFUSED` (the network refused it), `NOT_ARRIVED`
8617
+ * (`moveBridgeDepositToWallet` on a deposit that is not waiting), `ERROR` (anything else before
8618
+ * signing).
8619
+ */
8620
+ type MoveOutcome = {
8621
+ status: "moved";
8622
+ signature: string;
8623
+ amount: bigint;
8624
+ } | {
8625
+ status: "nothing";
8626
+ }
8627
+ /** The address is being added to the private balance right now (its lock is held). Nothing was
8628
+ * asked of the wallet; try again once that finishes. */
8629
+ | {
8630
+ status: "busy";
8631
+ } | {
8632
+ status: "cancelled";
8633
+ } | {
8634
+ status: "needs_sol";
8635
+ needLamports: bigint;
8636
+ } | {
8637
+ status: "unconfirmed";
8638
+ signature?: string;
8639
+ } | {
8640
+ status: "failed";
8641
+ code: "REFUSED" | "NOT_ARRIVED" | "ERROR";
8642
+ message: string;
8643
+ };
8644
+ /**
8645
+ * `moveReceiverFundsToWallet`, classified and never thrown. The order matters: what is known to
8646
+ * have moved nothing comes first; a refusal counts as `cancelled` only if the wallet had not yet
8647
+ * signed; anything unexplained after signing is `unconfirmed`, never `failed`, because the
8648
+ * transaction may be on its way.
8649
+ */
8650
+ declare function moveToWalletOutcome(params: {
8651
+ rpc: CloakRpc;
8652
+ receiver: KeyPairSigner;
8653
+ mint: Address;
8654
+ wallet: TransactionSigner;
8655
+ onStep?: (step: string) => void;
8656
+ confirmTimeoutMs?: number;
8657
+ }): Promise<MoveOutcome>;
8658
+ /**
8659
+ * Whether the address's balance may have changed, so a caller should read it again: after a move
8660
+ * that confirmed or may still land, and after `nothing` (the view was stale). Not after a
8661
+ * cancellation, a busy address, a missing fee, or a failure, which moved nothing.
8662
+ */
8663
+ declare function moveMayHaveChangedBalance(outcome: MoveOutcome): boolean;
8664
+ /**
8665
+ * Whether to offer "move it to my wallet" for a discovered deposit, and why. Null means do not.
8666
+ *
8667
+ * Only for a deposit that is waiting (`state: "arrived"`). Then: `below_minimum` when it is too
8668
+ * small to ever be added (`belowMinimum`, from the same floor adding uses), and `deposit_failed`
8669
+ * once an attempt to add it has failed (`addFailed`). Never before: arrived money is normally
8670
+ * private seconds later, and offering a public exit next to it invites giving up privacy for
8671
+ * nothing.
8672
+ */
8673
+ declare function moveReasonForDeposit(deposit: Pick<BridgeDeposit, "state">, opts: {
8674
+ belowMinimum: boolean;
8675
+ addFailed: boolean;
8676
+ }): MoveReason | null;
8677
+ /**
8678
+ * Move a waiting bridge deposit to the wallet, as `moveToWalletOutcome` reports it.
8679
+ *
8680
+ * Refuses (`failed`, `NOT_ARRIVED`) anything but `state: "arrived"`: a receiver that already
8681
+ * shielded, or whose money already left, must never be moved, since that would link a private
8682
+ * deposit to the wallet. Takes the receiver's lock (`withReceiverLock`), the lock adding to the
8683
+ * balance holds too, without waiting: while an add holds it, the answer is `busy` at once rather
8684
+ * than a silent wait through a proof. Pass `lock` when several processes can act on the same wallet.
8685
+ */
8686
+ declare function moveBridgeDepositToWallet(params: {
8687
+ rpc: CloakRpc;
8688
+ /** Only its identity and state are read: a discovered deposit, or the order's own index. */
8689
+ deposit: Pick<BridgeDeposit, "index" | "legacyExposed" | "legacyViewingKeyNk" | "state">;
8690
+ owner: UtxoKeypair;
8691
+ mint: Address;
8692
+ wallet: TransactionSigner;
8693
+ lock?: BridgeLock;
8694
+ onStep?: (step: string) => void;
8695
+ confirmTimeoutMs?: number;
8696
+ }): Promise<MoveOutcome>;
8697
+
8698
+ /**
8699
+ * Payouts from the private balance to another network: Sui, Base and Polygon.
8700
+ *
8701
+ * ── The route ─────────────────────────────────────────────────────────────────────────────────
8702
+ * The deposit path run backwards. Cloak's bridge service (`POST /bridge/payout/quote`) asks 1Click
8703
+ * for an order that takes Solana USDC in and delivers native USDC on the named network; the private
8704
+ * balance then withdraws straight to the order's deposit address:
8705
+ *
8706
+ * private balance --withdraw (relay)--> 1Click deposit address --1Click--> USDC on `network`
8707
+ *
8708
+ * 1Click's deposit addresses are ordinary on-curve wallets, so the withdrawal pays them directly.
8709
+ * The Sui payouts this replaces went through a one-time wallet first (GUM's addresses are PDAs,
8710
+ * which the relay will not withdraw to), and a failed forward out of that wallet stranded the funds.
8711
+ *
8712
+ * ── What this client verifies, and why it does not trust the service ─────────────────────────
8713
+ * The service proxies; this client checks. Before a quote is handed to a caller, the rail's own
8714
+ * signature is verified over the bytes the rail produced (forwarded unmodified as `rail_response`),
8715
+ * and the SIGNED request is compared field by field against what the caller asked for: the
8716
+ * destination asset, the amount, the recipient, the refund address and the dry/allocate mode. So a
8717
+ * substituted recipient or deposit address is caught here even if the service substituted it. An
8718
+ * allocated deposit address must also be on-curve, or the relay would refuse the withdrawal after
8719
+ * the user had been shown a quote.
8720
+ *
8721
+ * ── When the direct route does not apply ──────────────────────────────────────────────────────
8722
+ * A 1Click order expects ONE deposit of the quoted amount. A payout that spends several notes is
8723
+ * several withdrawals, which would reach the deposit address as several transfers. Those payouts
8724
+ * go through a collector instead: the withdrawals land at a one-time wallet derived from the
8725
+ * wallet's own keys, which forwards exactly the payout's amount in one transfer
8726
+ * (`choosePayoutRoute`). The collector index is chosen from the caller's saved records, not from a
8727
+ * per-browser counter, and every payout is saved BEFORE money moves (`PayoutStore`), so any device
8728
+ * with the wallet's keys and the record can finish it.
8729
+ */
8730
+
8731
+ /**
8732
+ * The networks a payout can be delivered on. Solana itself is a plain withdrawal, not a payout.
8733
+ * Exactly the `live` rows of `NETWORKS` with a payout direction (a test pins the two together):
8734
+ * Ethereum and Arbitrum are listed there as `planned` and are not in v1.
8735
+ */
8736
+ declare const PAYOUT_NETWORKS: readonly ["sui", "base", "polygon"];
8737
+ type PayoutNetwork = (typeof PAYOUT_NETWORKS)[number];
8738
+ declare function isPayoutNetwork(value: string): value is PayoutNetwork;
8739
+ /**
8740
+ * The payout network for `address`, or null when paying it is not a payout.
8741
+ *
8742
+ * A Sui address names its own network. An EVM address does not: Base and Polygon share its format,
8743
+ * so it is a payout only with `chosenNetwork` set to a live EVM payout network, and null otherwise.
8744
+ * Guessing would send real money to a chain the recipient may not control. A Solana address, a
8745
+ * domain or anything else is null: paying it is a plain withdrawal or nothing.
8746
+ */
8747
+ declare function payoutNetworkFor(address: string, chosenNetwork?: string | null): PayoutNetwork | null;
8748
+ /**
8749
+ * The least a payout to `network` may deliver, in USDC base units, or undefined where the table
8750
+ * sets none (the live quote then decides). Today only Sui has one: 3.5 USDC, so that a payout can
8751
+ * still fall back to its second route if the first cannot quote (see the Sui row in `NETWORKS`).
8752
+ */
8753
+ declare function payoutMinimum(network: PayoutNetwork): bigint | undefined;
8754
+ /**
8755
+ * Why a recipient cannot be paid as asked. Map these to words; never show the code.
8756
+ *
8757
+ * - `not_a_payout_address`: not an address on another network (a Solana address is a plain
8758
+ * withdrawal; a domain must be resolved first).
8759
+ * - `network_required`: an EVM address with no network chosen.
8760
+ * - `network_unavailable`: the chosen network is not one Cloak pays out to today, or is not an
8761
+ * EVM network.
8762
+ * - `token_unsupported`: payouts to that network carry only its payout tokens (USDC).
8763
+ * - `below_minimum`: under `payoutMinimum(network)`, which comes back as `minimum`.
8764
+ */
8765
+ type PayoutRecipientProblem = "not_a_payout_address" | "network_required" | "network_unavailable" | "token_unsupported" | "below_minimum";
8766
+ type PayoutRecipientCheck = {
8767
+ ok: true;
8768
+ network: PayoutNetwork;
8769
+ } | {
8770
+ ok: false;
8771
+ reason: PayoutRecipientProblem;
8772
+ minimum?: bigint;
8773
+ };
8774
+ /**
8775
+ * Can `address` be paid `amountBaseUnits` of `token` on another network? One answer for every
8776
+ * caller, before any quote is asked for.
8777
+ *
8778
+ * `network` is the network the person chose. It is required for an EVM address and ignored for a
8779
+ * Sui one, whose address names its network. `token` is the symbol leaving the private balance.
8780
+ * `amountBaseUnits`, when given, is checked against `payoutMinimum`. Leave it out to check the
8781
+ * recipient alone.
8782
+ *
8783
+ * This is the client's rule, not an enforcement point: the bridge service screens the recipient
8784
+ * and the rail refuses what it cannot fill.
8785
+ */
8786
+ declare function checkPayoutRecipient(params: {
8787
+ address: string;
8788
+ network?: string | null;
8789
+ token: string;
8790
+ amountBaseUnits?: bigint;
8791
+ }): PayoutRecipientCheck;
8792
+ /** 1Click's asset id for Solana USDC: what every payout spends. */
8793
+ declare const PAYOUT_ORIGIN_ASSET: string;
8794
+ /**
8795
+ * 1Click's USDC asset id per payout network, read from `NETWORKS` (the one table): native USDC
8796
+ * everywhere (Polygon's `omdep` id, not the deprecated HOT one and not USDC.e). The check that the
8797
+ * SIGNED request names this exact asset is the client's, not the service's.
8798
+ */
8799
+ declare const PAYOUT_DESTINATION_ASSETS: Readonly<Record<PayoutNetwork, string>>;
8800
+ /**
8801
+ * The receiver index of the wallet's payout refund key. One fixed index rather than one per
8802
+ * payout: a refund is the failure case, and a fixed key is one any device finds without a record.
8803
+ * The trade-off is that refunded payouts of one wallet share that address with each other; none of
8804
+ * them is linked to the wallet's public address. Below the collector range, and far above any
8805
+ * index deposit discovery scans (it walks 0…N from zero).
8806
+ */
8807
+ declare const PAYOUT_REFUND_INDEX = 8999;
8808
+ /** Collector wallets for multi-withdrawal payouts. 9000+ is the range the Sui exit already used,
8809
+ * so an old one-time wallet is found by the same derivation. */
8810
+ declare const PAYOUT_COLLECTOR_INDEX_BASE = 9000;
8811
+ /** The Solana address a payout's order refunds to, if the rail cannot fill it. */
8812
+ declare function derivePayoutRefundKey(owner: UtxoKeypair): Promise<KeyPairSigner>;
8813
+ /** The one-time wallet that collects a multi-withdrawal payout before forwarding it. */
8814
+ declare function derivePayoutCollector(owner: UtxoKeypair, index: number): Promise<KeyPairSigner>;
8815
+ type PayoutRoute = "direct" | "collector";
8816
+ type PayoutRail = "oneclick" | "jupiter";
8817
+ /**
8818
+ * Direct when the payout is a single withdrawal; a collector otherwise. A 1Click order is filled by
8819
+ * one deposit of the quoted amount, and each withdrawal is a separate transfer.
8820
+ */
8821
+ declare function choosePayoutRoute(withdrawals: number): PayoutRoute;
8822
+ interface PayoutQuoteRequest {
8823
+ network: PayoutNetwork;
8824
+ /** The address on `network` the USDC is for. */
8825
+ recipient: string;
8826
+ /** Solana USDC base units that will ARRIVE at the deposit address: what the withdrawal delivers
8827
+ * after Cloak's on-chain fee, not what leaves the balance. 1Click fills an order with this
8828
+ * exact input; less is refunded. */
8829
+ amountBaseUnits: bigint;
8830
+ /** On-curve Solana address the order refunds to: `derivePayoutRefundKey(owner).address`. */
8831
+ refundTo: string;
8832
+ /** True reserves an order and returns its deposit address. False (the default) reserves nothing. */
8833
+ allocate?: boolean;
8834
+ }
8835
+ interface PayoutQuote {
8836
+ network: PayoutNetwork;
8837
+ /** The recipient exactly as the rail signed it. Show this one. */
8838
+ recipient: string;
8839
+ amountIn: bigint;
8840
+ /** The least the deposit address may receive and still fill (the order is FLEX_INPUT). A
8841
+ * withdrawal sized for `amountIn` must net at least this after Cloak's fee, or it is refunded. */
8842
+ minAmountIn: bigint;
8843
+ /** What should arrive on `network`. */
8844
+ amountOut: bigint;
8845
+ /** The signed floor: what is promised. Lead with this, never `amountOut`. */
8846
+ minAmountOut: bigint;
8847
+ /** At or below this, the rail's own delivery fee takes everything (Solana USDC base units). */
8848
+ routeMinimum: bigint;
8849
+ /** Present only when allocated; verified on-curve and covered by the rail's signature. */
8850
+ depositAddress?: string;
8851
+ /** The rail's signed deadline for the order, when allocated. */
8852
+ deadline?: string;
8853
+ timeEstimateSeconds?: number;
8854
+ }
8855
+ /** A quote this client refuses to hand to a caller. Nothing has moved when it is thrown. */
8856
+ declare class PayoutQuoteRejected extends Error {
8857
+ constructor(reason: string);
8858
+ }
8859
+ interface ExpectedPayout {
8860
+ network: PayoutNetwork;
8861
+ recipient: string;
8862
+ amountBaseUnits: bigint;
8863
+ refundTo: string;
8864
+ allocate: boolean;
8865
+ }
8866
+ interface VerifiedPayout {
8867
+ recipient: string;
8868
+ amountIn: bigint;
8869
+ minAmountIn: bigint;
8870
+ amountOut: bigint;
8871
+ minAmountOut: bigint;
8872
+ withdrawFee?: bigint;
8873
+ depositAddress?: string;
8874
+ deadline?: string;
8875
+ timeEstimateSeconds?: number;
8876
+ }
8877
+ /** True for an address the pool can withdraw to: a plain wallet, not a PDA. */
8878
+ declare function isDirectlyPayable(value: string): boolean;
8879
+ /**
8880
+ * Check a 1Click payout response against what was asked for. Throws `PayoutQuoteRejected` naming
8881
+ * the first mismatch. Exported so a caller holding a saved response can re-check it, and so the
8882
+ * checks are testable against real rail bytes.
8883
+ */
8884
+ declare function verifyPayoutQuote(railResponse: unknown, expect: ExpectedPayout): VerifiedPayout;
8885
+ /** Thrown for a refusal by the service: a screened-out recipient (`code: "screening_rejected"`),
8886
+ * an unsupported network, an outage (`retryable`). Nothing has moved when it is thrown. */
8887
+ declare class PayoutServiceError extends Error {
8888
+ readonly status: number;
8889
+ readonly code?: string | undefined;
8890
+ readonly retryable: boolean;
8891
+ constructor(message: string, status: number, code?: string | undefined, retryable?: boolean);
8892
+ }
8893
+ /** The request path, relative to the bridge service's base, for a caller that transports it. */
8894
+ declare const PAYOUT_QUOTE_PATH = "/bridge/payout/quote";
8895
+ /**
8896
+ * The JSON body for `POST /bridge/payout/quote`, after the checks that need no network. For a
8897
+ * caller that carries the request itself (the website goes through its own `/api/bridge/*` proxy,
8898
+ * which the SDK's origin lock cannot reach): it sends these bytes and hands the answer to
8899
+ * `readPayoutQuoteResponse`, so every rule stays here.
8900
+ */
8901
+ declare function payoutQuoteRequestBody(req: PayoutQuoteRequest): Record<string, unknown>;
8902
+ /**
8903
+ * Ask Cloak's bridge service for a payout quote, then verify it independently.
8904
+ *
8905
+ * Call with `allocate: false` to show a price, and with `allocate: true` right before the
8906
+ * withdrawal, which reserves the order and returns the deposit address to withdraw to.
8907
+ */
8908
+ declare function fetchPayoutQuote(relayUrl: string, req: PayoutQuoteRequest): Promise<PayoutQuote>;
8909
+ /**
8910
+ * Turn the service's answer into a verified `PayoutQuote`, or throw. The whole check: a refusal
8911
+ * becomes `PayoutServiceError`, and a success is verified against the rail's own signed bytes
8912
+ * (`verifyPayoutQuote`) and against the service's echo of the recipient. Whoever carried the
8913
+ * request, nothing reaches the caller unverified.
8914
+ */
8915
+ declare function readPayoutQuoteResponse(status: number, body: unknown, req: PayoutQuoteRequest): PayoutQuote;
8916
+ type PayoutState =
8917
+ /** Order reserved, nothing withdrawn yet. */
8918
+ "allocated"
8919
+ /** Withdrawals under way (to the deposit address, or to the collector). */
8920
+ | "withdrawing"
8921
+ /** Collector route: withdrawals done, the single forward not yet confirmed. */
8922
+ | "forwarding"
8923
+ /** The full amount reached the deposit address; the rail is delivering. */
8924
+ | "sent" | "delivered"
8925
+ /** The rail refunded to `refundTo`. */
8926
+ | "refunded" | "failed";
8927
+ interface PayoutRecord {
8928
+ v: 1;
8929
+ id: string;
8930
+ network: PayoutNetwork;
8931
+ recipient: string;
8932
+ /** Solana USDC base units the order expects at the deposit address, as a decimal string. */
8933
+ amountBaseUnits: string;
8934
+ refundTo: string;
8935
+ depositAddress: string;
8936
+ deadline?: string;
8937
+ /** Which rail filled the order: `oneclick` normally, `jupiter` for the Sui fallback through GUM.
8938
+ * The status lookup needs it. */
8939
+ rail: PayoutRail;
8940
+ route: PayoutRoute;
8941
+ /** Collector route only. */
8942
+ collectorIndex?: number;
8943
+ state: PayoutState;
8944
+ /** Withdrawal signatures, in order. */
8945
+ withdrawals: string[];
8946
+ /** Collector route: the forward to the deposit address. */
8947
+ forward?: string;
8948
+ /** Solana USDC base units the withdrawals took out of the private balance in total, before
8949
+ * Cloak's on-chain fee, as a decimal string. Absent on a record saved before it existed. */
8950
+ withdrawnBaseUnits?: string;
8951
+ /** What the rail reports: while pending, its step; once settled, what it moved. Absent on a rail
8952
+ * that reports none (the Sui fallback through GUM). */
8953
+ delivery?: PayoutDelivery;
8954
+ createdAt: string;
8955
+ updatedAt: string;
8956
+ }
8957
+ /** The rail's own account of a settled payout. Hashes and base units only; build links with
8958
+ * `explorerUrl(record.network, "tx", destinationTx)`. */
8959
+ interface PayoutDelivery {
8960
+ /** While pending: where the rail is. Display only. */
8961
+ stage?: PayoutPendingStage;
8962
+ /** Solana USDC base units the rail received at its deposit address, as a decimal string. */
8963
+ amountIn?: string;
8964
+ /** The transaction on the destination network that paid the recipient. */
8965
+ destinationTx?: string;
8966
+ /** Destination USDC base units that arrived, as a decimal string. */
8967
+ amountOut?: string;
8968
+ /** Solana USDC base units the rail returned to `refundTo`, as a decimal string. */
8969
+ refundedAmount?: string;
8970
+ }
8971
+ /** The steps inside a pending payout, in order. */
8972
+ type PayoutPendingStage = "awaiting_deposit" | "deposit_received" | "processing";
8973
+ /** Read the delivery fields of the bridge service's status answer. Malformed values are dropped:
8974
+ * they are shown to a person, never acted on. */
8975
+ declare function readPayoutDelivery(body: unknown): PayoutDelivery | undefined;
8976
+ /**
8977
+ * Where a payout's money went, in Solana USDC base units, from what the record holds. Every field is
8978
+ * undefined until known; nothing is estimated.
8979
+ *
8980
+ * - `fromBalance`: what the withdrawals took out of the private balance.
8981
+ * - `cloakFee`: Cloak's fee, taken on-chain by the program (direct route: what left the balance less
8982
+ * what reached the rail). On the collector route this also holds the collector's network fee,
8983
+ * so it is reported as `fees` there instead.
8984
+ * - `intoRail`: what the rail received. `railCost`: what the rail kept, `intoRail - arrived`
8985
+ * (USDC on both sides, same decimals). `arrived`: what reached the recipient.
8986
+ */
8987
+ declare function payoutBreakdown(record: PayoutRecord): {
8988
+ fromBalance?: bigint;
8989
+ cloakFee?: bigint;
8990
+ fees?: bigint;
8991
+ intoRail?: bigint;
8992
+ railCost?: bigint;
8993
+ arrived?: bigint;
8994
+ };
8995
+ /** Where the caller keeps payout records. The website backs it with its own storage; the SDK never
8996
+ * touches a browser API. */
8997
+ interface PayoutStore {
8998
+ list(): Promise<PayoutRecord[]>;
8999
+ save(record: PayoutRecord): Promise<void>;
9000
+ }
9001
+ declare function isTerminalPayout(record: PayoutRecord): boolean;
9002
+ /**
9003
+ * The lowest collector index no unfinished payout holds. Indices are reused once a payout is
9004
+ * finished, so a wallet never runs out of them; the caller must still check the collector holds no
9005
+ * USDC before using it (an old one-time wallet from before records existed may), and move to the
9006
+ * next index if it does.
9007
+ */
9008
+ declare function nextCollectorIndex(records: readonly PayoutRecord[], skip?: readonly number[]): number;
9009
+ /** The record to save right after an allocated quote, before the first withdrawal. */
9010
+ declare function newPayoutRecord(params: {
9011
+ id: string;
9012
+ quote: PayoutQuote;
9013
+ refundTo: string;
9014
+ route: PayoutRoute;
9015
+ collectorIndex?: number;
9016
+ now?: Date;
9017
+ }): PayoutRecord;
9018
+ /** A copy of `record` moved to `state`, with any new signatures appended. Refuses to leave a
9019
+ * terminal state, so a late retry can never reopen a finished payout. */
9020
+ declare function advancePayout(record: PayoutRecord, state: PayoutState, extra?: {
9021
+ withdrawal?: string;
9022
+ forward?: string;
9023
+ now?: Date;
9024
+ }): PayoutRecord;
9025
+ /**
9026
+ * GUM's Solana deposit address for a payout to `suiAddress`, from Cloak's bridge service, which
9027
+ * screens `suiAddress` before answering. The fallback when `fetchPayoutQuote` cannot serve Sui:
9028
+ * GUM's addresses are PDAs, so this route is always a collector payout (`newFallbackPayoutRecord`).
9029
+ * GUM takes no refund address and its own minimum is 3 USDC.
9030
+ */
9031
+ declare function fetchSuiFallbackDepositAddress(relayUrl: string, suiAddress: string): Promise<string>;
9032
+ /** The GUM deposit address out of the service's answer, or a `PayoutServiceError`. For a caller
9033
+ * that carries `GET /bridge/sui-exit/deposit-address?to=…` itself. */
9034
+ declare function readSuiFallbackResponse(status: number, body: unknown): string;
9035
+ /** GUM's minimum for a payout to Sui, in Solana USDC base units. */
9036
+ declare const SUI_FALLBACK_MINIMUM_BASE_UNITS = 3000000n;
9037
+ /** The record for a Sui payout through GUM: always the collector route, rail `jupiter`. */
9038
+ declare function newFallbackPayoutRecord(params: {
9039
+ id: string;
9040
+ recipient: string;
9041
+ amountBaseUnits: bigint;
9042
+ depositAddress: string;
9043
+ collectorIndex: number;
9044
+ now?: Date;
9045
+ }): PayoutRecord;
9046
+ interface ForwardResult {
9047
+ /** The forward's signature: new, or the one a previous attempt already landed. */
9048
+ signature: string;
9049
+ forwarded: bigint;
9050
+ /** USDC left at the collector afterwards (headroom the paymaster fee did not use). It stays
9051
+ * there: sweeping it anywhere the user controls would link the payout to them. */
9052
+ left: bigint;
9053
+ /** True when a previous attempt had already landed and nothing new was sent. */
9054
+ alreadyLanded: boolean;
9055
+ }
9056
+ /** Nothing was forwarded; the funds are still at the collector, and the same call can resume. */
9057
+ declare class PayoutNotReady extends Error {
9058
+ constructor(message: string);
9059
+ }
9060
+ /**
9061
+ * Move a collector payout to its deposit address in ONE transfer of exactly the record's amount.
9062
+ *
9063
+ * Safe to call again after any failure: it first checks whether a saved forward already landed
9064
+ * (so a confirmation timeout never turns into a second transfer), then waits for the withdrawals
9065
+ * to reach the collector, covers the collector's SOL through the paymaster (whose fee comes out of
9066
+ * the collector's own USDC, so nothing links it to the user's wallet), and transfers. It forwards
9067
+ * the record's amount, never "everything the collector holds", so a reused collector can never
9068
+ * carry an older payout's money to a new recipient.
9069
+ *
9070
+ * Save the record with `state: "forwarding"` before calling, and with the returned signature
9071
+ * after.
9072
+ */
9073
+ declare function forwardCollectedPayout(params: {
9074
+ rpc: CloakRpc;
9075
+ /** The bridge service, for the paymaster top-up. Not needed when `topUp` is given. */
9076
+ relayUrl?: string;
9077
+ /**
9078
+ * Carries the paymaster top-up for a caller that reaches the bridge service through its own
9079
+ * proxy. It must return the fully signed top-up transaction; this function submits it. Default:
9080
+ * `fundReceiverViaPaymaster(relayUrl, …)`.
9081
+ */
9082
+ topUp?: (collector: KeyPairSigner, grantLamports: bigint) => Promise<{
9083
+ transaction: Transaction;
9084
+ }>;
9085
+ collector: KeyPairSigner;
9086
+ record: PayoutRecord;
9087
+ mint?: Address;
9088
+ /** How long to wait for the withdrawals to land at the collector. Default 120 s. */
9089
+ waitMs?: number;
9090
+ pollMs?: number;
9091
+ onStep?: (step: string) => void;
9092
+ }): Promise<ForwardResult>;
9093
+ /** Where the rail is with a payout whose full amount has reached its deposit address. */
9094
+ declare function fetchPayoutDelivery(relayUrl: string, record: PayoutRecord): Promise<BridgeDeliveryState>;
9095
+ /** The record after a delivery answer: `delivered` and `refunded` are final; anything else leaves
9096
+ * it as it was, to ask again later. */
9097
+ declare function settlePayout(record: PayoutRecord, delivery: BridgeDeliveryState, now?: Date): PayoutRecord;
9098
+ /** What the paymaster takes from a collector for the network fee, in USDC base units: its fixed
9099
+ * 0.15 USDC plus the service's 1% headroom. A collector payout forwards this much less than its
9100
+ * withdrawals deliver. An estimate: a higher real fee stops the forward with nothing lost. */
9101
+ declare const COLLECTOR_FEE_ESTIMATE_BASE_UNITS = 151500n;
9102
+ /** A quote's deadline minus this is when a payout is treated as expired, leaving time for the
9103
+ * withdrawal to land before 1Click would refund it. */
9104
+ declare const PAYOUT_DEADLINE_MARGIN_MS: number;
9105
+ /** One answer from the bridge service, however it was carried. */
9106
+ interface CarriedResponse {
9107
+ status: number;
9108
+ body: unknown;
9109
+ }
9110
+ /** How the flow reaches Cloak's bridge service. The SDK's own (`relayPayoutTransport`) goes to the
9111
+ * relay origin; a website passes its same-origin proxy. Bytes only: every check stays in the SDK.
9112
+ *
9113
+ * Rate limits: the bridge service keys its per-client limits and paymaster budget on the address
9114
+ * it sees. A server-side proxy therefore makes every user behind it ONE client, sharing one
9115
+ * bucket. Cloak's own website signs each user's address to the bridge (`X-Cloak-Client-*`, with a
9116
+ * secret only Cloak's deployments hold); a third-party proxy cannot, so expect its users to share
9117
+ * its address's limits. */
9118
+ interface PayoutTransport {
9119
+ /** POST the body of `payoutQuoteRequestBody` to `/bridge/payout/quote`. */
9120
+ quote(body: Record<string, unknown>): Promise<CarriedResponse>;
9121
+ /** GET `/bridge/sui-exit/deposit-address?to=<suiAddress>`. */
9122
+ suiFallback(suiAddress: string): Promise<CarriedResponse>;
9123
+ /** GET `/bridge/status?deposit_address=…&rail=…`. */
9124
+ status(depositAddress: string, rail: PayoutRail): Promise<CarriedResponse>;
9125
+ /** The paymaster top-up for a collector, fully signed. */
9126
+ topUp(collector: KeyPairSigner, grantLamports: bigint): Promise<{
9127
+ transaction: Transaction;
9128
+ }>;
9129
+ }
9130
+ /** The transport straight to Cloak's relay origin (the SDK's origin lock applies). */
9131
+ declare function relayPayoutTransport(relayUrl: string): PayoutTransport;
9132
+ interface PayoutContext {
9133
+ /** The key the refund address and collectors derive from: the wallet's UTXO keypair, or for a
9134
+ * payment link claimed without a wallet, the link's own keypair. */
9135
+ owner: UtxoKeypair;
9136
+ store: PayoutStore;
9137
+ transport: PayoutTransport;
9138
+ rpc: CloakRpc;
9139
+ mint?: Address;
9140
+ }
9141
+ interface PreparedPayout {
9142
+ record: PayoutRecord;
9143
+ /** Where the withdrawals go: the rail's deposit address (direct) or the collector. */
9144
+ withdrawTo: string;
9145
+ /** Collector route only. */
9146
+ collector?: KeyPairSigner;
9147
+ /** Absent on the Sui fallback through GUM, which signs no quote. */
9148
+ quote?: PayoutQuote;
9149
+ }
9150
+ /** True when 1Click could not answer at all (an outage, a timeout, a 5xx), so the Sui fallback may
9151
+ * take over. A refusal (screening, a bad request) or a quote that failed verification never falls
9152
+ * back: those must reach the user, not be routed around. */
9153
+ declare function payoutRailUnavailable(e: unknown): boolean;
9154
+ /** The lowest collector no unfinished payout holds and that holds no USDC on chain. */
9155
+ declare function freePayoutCollector(ctx: Pick<PayoutContext, "owner" | "rpc" | "mint">, records: readonly PayoutRecord[]): Promise<{
9156
+ index: number;
9157
+ signer: KeyPairSigner;
9158
+ }>;
9159
+ /**
9160
+ * Reserve a payout and save its record, BEFORE any money moves.
9161
+ *
9162
+ * `deliveredBaseUnits` is what the withdrawals will deliver in total, after Cloak's on-chain fee.
9163
+ * The route follows from `withdrawals`: one pays the rail's deposit address directly and quotes
9164
+ * that whole amount; several, or the Sui fallback through GUM (always a collector), quote it less
9165
+ * `COLLECTOR_FEE_ESTIMATE_BASE_UNITS`, which the collector's network fee comes out of.
9166
+ */
9167
+ declare function preparePayout(ctx: PayoutContext, req: {
9168
+ id: string;
9169
+ network: PayoutNetwork;
9170
+ recipient: string;
9171
+ deliveredBaseUnits: bigint;
9172
+ withdrawals: number;
9173
+ now?: Date;
9174
+ }): Promise<PreparedPayout>;
9175
+ interface PayoutPreview {
9176
+ route: PayoutRoute;
9177
+ rail: PayoutRail;
9178
+ /** What reaches the rail's deposit address (the collector's network fee already held back). */
9179
+ amountIn: bigint;
9180
+ /** The signed floor of what arrives on the network: the honest "Arrives on X" figure. Absent on
9181
+ * the Sui fallback through GUM, which signs no quote. */
9182
+ minAmountOut?: bigint;
9183
+ amountOut?: bigint;
9184
+ routeMinimum?: bigint;
9185
+ }
9186
+ /**
9187
+ * What a payout would deliver, without reserving anything: a dry quote, sized and verified exactly
9188
+ * as `preparePayout` would size and verify the real one. For the "Arrives on X ≈ amount" line.
9189
+ * Throws as `preparePayout` does (a screening refusal, a quote that fails verification); when 1Click
9190
+ * is unavailable for Sui, says the fallback would carry it, with no signed figure.
9191
+ */
9192
+ declare function previewPayout(ctx: Pick<PayoutContext, "owner" | "transport">, req: {
9193
+ network: PayoutNetwork;
9194
+ recipient: string;
9195
+ deliveredBaseUnits: bigint;
9196
+ withdrawals: number;
9197
+ }): Promise<PayoutPreview>;
9198
+ /** True when the order's signed deadline is too close to withdraw into: re-prepare instead. A
9199
+ * record with money already moved is never "expired" here; it is finished or followed. */
9200
+ declare function isPayoutExpired(record: PayoutRecord, now?: Date): boolean;
9201
+ /** Save a landed withdrawal against its payout. */
9202
+ declare function recordPayoutWithdrawal(store: PayoutStore, record: PayoutRecord, signature: string,
9203
+ /** What this withdrawal took out of the private balance, before Cloak's fee. */
9204
+ grossBaseUnits?: bigint): Promise<PayoutRecord>;
9205
+ /**
9206
+ * After the withdrawals: a direct payout is now at the rail; a collector payout forwards its exact
9207
+ * amount once (`forwardCollectedPayout`, safe to repeat). Returns the record and the signature that
9208
+ * put the full amount at the deposit address. A direct payout with no recorded withdrawal is
9209
+ * refused: it would be marked sent with nothing sent.
9210
+ */
9211
+ declare function finishPayout(ctx: Omit<PayoutContext, "owner"> & {
9212
+ owner?: UtxoKeypair;
9213
+ collector?: KeyPairSigner;
9214
+ onStep?: (s: string) => void;
9215
+ }, record: PayoutRecord): Promise<{
9216
+ record: PayoutRecord;
9217
+ signature: string;
9218
+ }>;
9219
+ /** Payouts where money has already moved but the payout is not finished, optionally for one
9220
+ * recipient. A caller checks these BEFORE paying the same recipient again: finish, never re-pay. */
9221
+ declare function unfinishedPayouts(store: PayoutStore, match?: {
9222
+ network?: PayoutNetwork;
9223
+ recipient?: string;
9224
+ }): Promise<PayoutRecord[]>;
9225
+ /** A key-value store a payout store can sit on: `localStorage`, React Native's AsyncStorage, or a
9226
+ * server's own. Either sync or async. */
9227
+ interface PayoutStorage {
9228
+ getItem(key: string): string | null | Promise<string | null>;
9229
+ setItem(key: string, value: string): void | Promise<void>;
9230
+ }
9231
+ /**
9232
+ * The storage key for one owner's payout records: a wallet address, or `{ link: id }` for a payment
9233
+ * link claimed without a wallet. Same format as the website has always used
9234
+ * (`cloak:payouts:v1:<wallet>`, `cloak:payouts:v1:link:<id>`), so its saved records stay readable.
9235
+ */
9236
+ declare function payoutStoreKey(owner: string | {
9237
+ link: string;
9238
+ }): string;
9239
+ /**
9240
+ * A `PayoutStore` over any key-value storage, under `key` (see `payoutStoreKey`). The SDK touches no
9241
+ * browser API itself: the caller passes the storage. A read that does not parse is an empty list, so
9242
+ * a corrupted entry never blocks a new payout; a save replaces the record with the same id.
9243
+ */
9244
+ declare function storagePayoutStore(storage: PayoutStorage, key: string): PayoutStore;
9245
+ /** A `PayoutStore` in memory, for tests and short-lived scripts. Records do not survive the process. */
9246
+ declare function memoryPayoutStore(initial?: readonly PayoutRecord[]): PayoutStore;
9247
+ /** The payout a transaction belongs to: one of its withdrawals, or a collector payout's forward. */
9248
+ declare function findPayoutBySignature(store: PayoutStore, signature: string): Promise<PayoutRecord | undefined>;
9249
+ /**
9250
+ * Never pay the same recipient twice. If an earlier payout to this recipient on this network has
9251
+ * money moving and is not finished, finish THAT one (`finishPayout`) and return it instead of
9252
+ * reserving a new payout; otherwise `preparePayout`. A `"finished"` answer means the money from the
9253
+ * earlier attempt is now on its way: tell the person, and do not send again.
9254
+ */
9255
+ declare function preparePayoutOrFinish(ctx: PayoutContext & {
9256
+ onStep?: (step: string) => void;
9257
+ }, req: {
9258
+ id: string;
9259
+ network: PayoutNetwork;
9260
+ recipient: string;
9261
+ deliveredBaseUnits: bigint;
9262
+ withdrawals: number;
9263
+ now?: Date;
9264
+ }): Promise<{
9265
+ kind: "finished";
9266
+ record: PayoutRecord;
9267
+ signature: string;
9268
+ } | {
9269
+ kind: "prepared";
9270
+ prepared: PreparedPayout;
9271
+ }>;
9272
+ /**
9273
+ * Before paying into a reservation that may have sat a while (a batch, a slow approval): if its
9274
+ * signed deadline is too close (`isPayoutExpired`), retire it and reserve a fresh one, since the rail
9275
+ * would refund a deposit that arrives late. Otherwise return it unchanged.
9276
+ *
9277
+ * The old record is marked `failed` only after checking on chain that no USDC reached the address
9278
+ * it pays into; if some did (a withdrawal that landed but was never saved), this throws instead,
9279
+ * and that payout must be finished rather than replaced. `req` is the original request with a NEW
9280
+ * `id` for the fresh reservation.
9281
+ */
9282
+ declare function ensureFreshPayout(ctx: PayoutContext, prepared: PreparedPayout, req: {
9283
+ id: string;
9284
+ network: PayoutNetwork;
9285
+ recipient: string;
9286
+ deliveredBaseUnits: bigint;
9287
+ withdrawals: number;
9288
+ now?: Date;
9289
+ }): Promise<PreparedPayout>;
9290
+ /** The steps of a payout as a person follows it. `failed` only for a refund. */
9291
+ interface PayoutProgress {
9292
+ /** Left the private balance: always done once there is a record to show. */
9293
+ left: "done";
9294
+ /** The rail has the money (it saw the deposit, or the payout settled). */
9295
+ rail: "done" | "current";
9296
+ /** It arrived on the network, or came back. */
9297
+ arrival: "done" | "current" | "ahead" | "failed";
9298
+ /** The rail's own step while pending, for wording ("converting and sending"). */
9299
+ stage?: PayoutPendingStage;
9300
+ }
9301
+ /** Where a payout is, from its record alone. The website's tracker, as data. */
9302
+ declare function payoutProgress(record: Pick<PayoutRecord, "state" | "delivery">): PayoutProgress;
9303
+ /** A pool's withdraw fee, as the program charges it: `fixedFee + amount * variableNumerator / variableDenominator` (floor). */
9304
+ interface PoolFeeConfig {
9305
+ fixedFee: bigint;
9306
+ variableNumerator: bigint;
9307
+ variableDenominator: bigint;
9308
+ }
9309
+ /**
9310
+ * `mint`'s withdraw fee, read live from its on-chain PoolConfig and checked as a proof would check
9311
+ * it. Size withdrawals with this, never with compile-time constants: the pool's fee can change.
9312
+ */
9313
+ declare function readPoolFeeConfig(rpc: CloakRpc, mint: Address, programId?: Address): Promise<PoolFeeConfig>;
9314
+ /** What one withdrawal of `gross` delivers after the pool's fee. Never negative. */
9315
+ declare function withdrawalNetFor(gross: bigint, fee: PoolFeeConfig): bigint;
9316
+ /**
9317
+ * How much to withdraw so that `net` arrives after the pool's fee.
9318
+ *
9319
+ * One withdrawal (`legs` 1, the default): the smallest gross whose `withdrawalNetFor` reaches `net`.
9320
+ * Several (`legs` > 1): the total gross across them, each paying the fixed fee once; a planning
9321
+ * figure that rounds up, since how it splits across the legs is the caller's. This is what a
9322
+ * payout's `deliveredBaseUnits` must be withdrawn as, or the rail receives less than it quoted and
9323
+ * refunds.
9324
+ */
9325
+ declare function withdrawalGrossFor(net: bigint, fee: PoolFeeConfig, legs?: number): bigint;
9326
+ /**
9327
+ * Whether a payout's order deadline has passed. No deadline, or one that does not parse, has not:
9328
+ * "unknown" must never read as "over", because that is what makes collected money movable.
9329
+ * Deliberately not `isPayoutExpired`, which asks whether an order may still be STARTED and is false
9330
+ * for any record whose withdrawals landed, which is exactly the record that can hold money.
9331
+ */
9332
+ declare function isPayoutDeadlinePassed(record: Pick<PayoutRecord, "deadline">, now?: Date): boolean;
9333
+ /**
9334
+ * Whether money collected for this payout at its one-time address may be moved to the wallet: only
9335
+ * when it will never be sent on. `failed`, or still open (`allocated`, `withdrawing`, `forwarding`)
9336
+ * past its deadline. A live payout is never movable (the move would race the forward for the same
9337
+ * money), and a direct payout holds nothing at an address of ours.
9338
+ */
9339
+ declare function isCollectorMovable(record: PayoutRecord, now?: Date): boolean;
9340
+ /** Payout money waiting outside the private balance, at an address only the wallet's keys control. */
9341
+ interface OutsideFunds {
9342
+ /** Stable per address: `refund:<address>` or `collector:<address>`. */
9343
+ id: string;
9344
+ reason: "payout_refund" | "payout_unsent";
9345
+ amount: bigint;
9346
+ /** The one-time address's signer, for `moveToWalletOutcome`. Keep it in memory; never store it. */
9347
+ receiver: KeyPairSigner;
9348
+ }
9349
+ /**
9350
+ * Payout money that will not reach anyone unless it is moved: the refund key's balance (a payout the
9351
+ * rail refunded), and every collector a record says can no longer be sent on (`isCollectorMovable`).
9352
+ * A collector index is reused once its payout finishes, so each address is read once, and only if
9353
+ * the newest record there is not live.
9354
+ *
9355
+ * The refund key is found from the keys alone. Collectors need the records in `store`, so a device
9356
+ * without them sees refunds only. An RPC failure THROWS: a balance that could not be read is never
9357
+ * reported as zero.
9358
+ */
9359
+ declare function findPayoutFundsOutside(params: {
9360
+ rpc: CloakRpc;
9361
+ owner: UtxoKeypair;
9362
+ store: PayoutStore;
9363
+ mint?: Address;
9364
+ now?: Date;
9365
+ }): Promise<OutsideFunds[]>;
9366
+ /** One withdrawal of a planned payout: the notes it spends (one or two) and what it moves. */
9367
+ interface PayoutWithdrawalLeg<N> {
9368
+ notes: N[];
9369
+ /** What this withdrawal takes from the private balance (the amount to withdraw). */
9370
+ grossBaseUnits: bigint;
9371
+ /** What it delivers after the pool's fee. */
9372
+ netBaseUnits: bigint;
9373
+ }
9374
+ interface PayoutWithdrawalPlan<N> {
9375
+ legs: PayoutWithdrawalLeg<N>[];
9376
+ grossBaseUnits: bigint;
9377
+ /** What the legs deliver in total: at least the asked amount, and what the payout must be
9378
+ * prepared for (`deliveredBaseUnits`, with `withdrawals: legs.length`). */
9379
+ deliveredBaseUnits: bigint;
9380
+ }
9381
+ /** The notes cannot deliver the amount. `shortBaseUnits` is how much more net they would need. */
9382
+ declare class PayoutPlanError extends Error {
9383
+ readonly shortBaseUnits: bigint;
9384
+ constructor(message: string, shortBaseUnits: bigint);
9385
+ }
9386
+ /**
9387
+ * Which notes a payout spends and how much each withdrawal takes, so that `netBaseUnits` arrives
9388
+ * after the pool's fee. The money rules the website applied by hand:
9389
+ *
9390
+ * - The fee is charged per TRANSACTION, and a transaction spends up to two notes, so notes are
9391
+ * paired: k notes cost ceil(k/2) fixed fees, not k.
9392
+ * - Each withdrawal is sized to what is still owed (`withdrawalGrossFor`), not to its notes' whole
9393
+ * value, so the rest stays private as change.
9394
+ * - The fewest notes that can do it, largest first. A leg whose notes cannot even cover the fixed
9395
+ * fee is never planned: it would fail on chain after earlier legs had already paid.
9396
+ *
9397
+ * Pure: `notes` are the caller's unspent notes of the pool's mint, already filtered for anything it
9398
+ * must not spend. Throws `PayoutPlanError` when all of them together cannot deliver the amount.
9399
+ */
9400
+ declare function planPayoutWithdrawals<N extends {
9401
+ amount: bigint;
9402
+ }>(notes: readonly N[], netBaseUnits: bigint, fee: PoolFeeConfig): PayoutWithdrawalPlan<N>;
9403
+ /** `checkPayoutRecipient` said no. Nothing was reserved and nothing moved. */
9404
+ declare class PayoutRefused extends Error {
9405
+ readonly reason: PayoutRecipientProblem;
9406
+ readonly minimum?: bigint | undefined;
9407
+ constructor(reason: PayoutRecipientProblem, minimum?: bigint | undefined);
9408
+ }
9409
+ /** One withdrawal of a payout, as `payOutFromPrivateBalance` makes it. */
9410
+ type PayoutWithdraw<N> = (notes: N[], to: string, grossBaseUnits: bigint) => Promise<{
9411
+ signature: string;
9412
+ }>;
9413
+ /**
9414
+ * The withdrawal `payOutFromPrivateBalance` needs, made with `partialWithdraw` and the caller's
9415
+ * spend options (connection, relay, signer, owner keypair, nk). It carries the Merkle tree from one
9416
+ * leg to the next and keeps every result, so the caller can store the change notes:
9417
+ * `results` holds each leg's `TransactResult` in order.
9418
+ */
9419
+ declare function payoutWithdrawer(options: SpendOptions): PayoutWithdraw<Utxo> & {
9420
+ results: TransactResult[];
9421
+ };
9422
+ /**
9423
+ * A whole payout from the private balance to another network, in one call: the website's send
9424
+ * path, for any client.
9425
+ *
9426
+ * 1. Refuses up front what cannot be paid (`checkPayoutRecipient`; throws `PayoutRefused`).
9427
+ * 2. Plans which notes to spend and how much each withdrawal takes from the pool's live fee
9428
+ * (`planPayoutWithdrawals`; pass `fee` to skip the read).
9429
+ * 3. Never pays twice: an earlier payout to this recipient with money moving is finished instead
9430
+ * (`kind: "finished-earlier"`; nothing new is withdrawn).
9431
+ * 4. Reserves the payout and saves its record before anything moves, then makes each withdrawal to
9432
+ * the rail's deposit address (one) or the one-time collector (several), saving each as it
9433
+ * lands. A save that fails does not stop the rest: the withdrawal already happened.
9434
+ * 5. Finishes: a direct payout is at the rail; a collector forwards exactly the payout's amount.
9435
+ *
9436
+ * `withdraw` makes one withdrawal (usually `payoutWithdrawer(spendOptions)`). Follow the result
9437
+ * with `watchPayout` for delivery.
9438
+ */
9439
+ declare function payOutFromPrivateBalance<N extends {
9440
+ amount: bigint;
9441
+ }>(ctx: PayoutContext & {
9442
+ onStep?: (step: string) => void;
9443
+ }, req: {
9444
+ id: string;
9445
+ network: string;
9446
+ recipient: string;
9447
+ netBaseUnits: bigint;
9448
+ notes: readonly N[];
9449
+ withdraw: PayoutWithdraw<N>;
9450
+ token?: string;
9451
+ fee?: PoolFeeConfig;
9452
+ now?: Date;
9453
+ }): Promise<{
9454
+ kind: "finished-earlier";
9455
+ record: PayoutRecord;
9456
+ signature: string;
9457
+ } | {
9458
+ kind: "sent";
9459
+ record: PayoutRecord;
9460
+ signature: string;
9461
+ withdrawals: {
9462
+ signature: string;
9463
+ grossBaseUnits: bigint;
9464
+ }[];
9465
+ }>;
9466
+ /** Ask the rail where a sent payout is, and save the answer. */
9467
+ declare function refreshPayout(ctx: Pick<PayoutContext, "store" | "transport">, record: PayoutRecord): Promise<PayoutRecord>;
9468
+ /**
9469
+ * Ask the rail until the payout is delivered or refunded, saving each change. Resolves with the
9470
+ * last record: terminal when the rail settled it, still `sent` if `timeoutMs` ran out first (ask
9471
+ * again later; nothing is lost by stopping). A failed status read is retried on the next tick,
9472
+ * never treated as a settlement.
9473
+ */
9474
+ declare function watchPayout(ctx: Pick<PayoutContext, "store" | "transport">, record: PayoutRecord, opts?: {
9475
+ intervalMs?: number;
9476
+ timeoutMs?: number;
9477
+ signal?: AbortSignal;
9478
+ onUpdate?: (r: PayoutRecord) => void;
9479
+ }): Promise<PayoutRecord>;
9480
+
9481
+ /**
9482
+ * Where Cloak keeps what it needs between sessions: wallet profiles, wallet links, stored account
9483
+ * keys (for wallets that cannot sign repeatably), and later saved notes and open orders.
9484
+ *
9485
+ * Any key-value store fits: the browser's localStorage, a partner database, a KMS-backed vault.
9486
+ * Protection at rest is the store's job. Values written here are either public (profiles) or
9487
+ * already sealed under a wallet-derived key (links); a stored account key is the one exception,
9488
+ * so a store that keeps those must encrypt at rest (business mode's `encryptedStorage`).
9489
+ */
9490
+ interface CloakStorage {
9491
+ get(key: string): Promise<string | null>;
9492
+ set(key: string, value: string): Promise<void>;
9493
+ delete(key: string): Promise<void>;
9494
+ /**
9495
+ * True only when the store encrypts values at rest or never writes them to disk, so it may hold
9496
+ * an account key. Cloak refuses to put a key anywhere this is not set.
9497
+ */
9498
+ readonly protectsSecrets?: boolean;
9499
+ }
9500
+ /**
9501
+ * In memory only: forgets everything when the process ends (tests, short-lived servers). It never
9502
+ * writes to disk, so it may hold a key; a key kept only here is lost with the process unless its
9503
+ * backup was saved.
9504
+ */
9505
+ declare function memoryStorage(initial?: Record<string, string>): CloakStorage & {
9506
+ dump(): Record<string, string>;
9507
+ };
9508
+ interface WebStorageLike {
9509
+ getItem(key: string): string | null;
9510
+ setItem(key: string, value: string): void;
9511
+ removeItem(key: string): void;
9512
+ }
9513
+ /**
9514
+ * The browser's localStorage (or any Web Storage object), under a prefix. Values are readable by
9515
+ * any script on the page, so it is suitable for profiles and sealed links, not for stored keys.
9516
+ */
9517
+ declare function webStorage(store?: WebStorageLike, prefix?: string): CloakStorage;
9518
+
9519
+ /**
9520
+ * A Cloak account: one 32-byte spend key and everything that derives from it.
9521
+ *
9522
+ * ── Where the spend key comes from ────────────────────────────────────────────────────────────
9523
+ * - A wallet signature over {@link CLOAK_ACCOUNT_MESSAGE}. For a Solana wallet this is the mobile
9524
+ * app's scheme to the byte (mobile `lib/cloak-spend-key.ts`): `SHA-512(signature)[0..32]` of the
9525
+ * raw 64-byte ed25519 signature, so the same Phantom or Solflare wallet opens the same account in
9526
+ * the app and here. EVM and Sui wallets have no earlier scheme; theirs is defined below, with its
9527
+ * own domain tag and a canonical signature form so one wallet always gives one key.
9528
+ * - A cloak.ag Cloak Key or a mobile in-app wallet phrase (`./cloak-key`).
9529
+ * - The raw key, held by a partner (business mode) or passed by a 0.2.16 integration.
9530
+ *
9531
+ * ── What derives from it (identical to cloak.ag `deriveMyCloakIdentity`) ──────────────────────
9532
+ * owner = deriveUtxoKeypairFromSpendKey(spendKey) owns deposits and change
9533
+ * viewingKeyNk = getNkFromUtxoPrivateKey(owner.privateKey) chain notes; relay-registered
9534
+ * deliveryKey = deriveViewingKeyFromNk(viewingKeyNk) v2 address key slot
9535
+ * requestRoot = deriveRequestKeyRoot({ nk: viewingKeyNk }) payment-request keys
9536
+ * legacyViewKey= deriveViewKey(spendKey) v1 address (mobile shows it)
9537
+ *
9538
+ * ── Viewing keys other clients used for the same account ──────────────────────────────────────
9539
+ * Notes another client made are encrypted under ITS nk, so finding them needs that nk too:
9540
+ * - the mobile in-app wallet: `expandSpendKey(spendKey).nsk`;
9541
+ * - mobile external wallets: `SHA-512(walletPubkey || "cloak-vk-v1")[0..32]`, per Solana wallet.
9542
+ * The second one is a public function of the wallet address. Notes made under it with the 0.2.5
9543
+ * deposit shape have owner keys derived from it, so ANYONE can rebuild them. The scan returns those
9544
+ * flagged `legacyExposed`; moving them under the owner key is what secures them.
9545
+ */
9546
+
9547
+ /**
9548
+ * The message every wallet signs to open its Cloak account. It is the mobile app's, byte for byte.
9549
+ * Changing one character moves every signature-made account to a new key and strands its notes, so
9550
+ * this is protocol surface, not copy.
9551
+ */
9552
+ declare const CLOAK_ACCOUNT_MESSAGE = "Cloak shielded transfer key v1\n\nSigning this message derives your private Cloak receive address on this device. It does not approve a transaction and moves no funds.";
9553
+ /** How a wallet produced the signature, which fixes its canonical form. */
9554
+ type AccountSignatureScheme =
9555
+ /** Raw 64-byte ed25519 signature over the message bytes (Solana wallets). */
9556
+ "solana"
9557
+ /** 65-byte `personal_sign` (EIP-191) signature, r || s || v (EVM wallets). */
9558
+ | "evm"
9559
+ /** Serialized Sui signature (flag || signature || public key) from `signPersonalMessage`. */
9560
+ | "sui";
9561
+ /**
9562
+ * The wallet's signatures cannot be turned into a stable key: a smart-contract or passkey wallet,
9563
+ * a zkLogin or multisig Sui address. Such a wallet needs a stored account key instead.
9564
+ */
9565
+ declare class NonRepeatableSignatureError extends Error {
9566
+ constructor(reason: string);
9567
+ }
9568
+ /**
9569
+ * The account spend key a wallet signature opens.
9570
+ * - solana: `SHA-512(sig64)[0..32]`, the mobile app's exact rule.
9571
+ * - evm: `SHA-512("cloak_account_evm_v1" || r || lowS(s))[0..32]`; v is dropped (wallets
9572
+ * disagree on 0/1 vs 27/28 and it carries nothing secret). Anything but 65 bytes is a
9573
+ * contract-wallet signature and throws `NonRepeatableSignatureError`.
9574
+ * - sui: `SHA-512("cloak_account_sui_v1" || flag || sig64)[0..32]` for ed25519 (flag 0x00) and
9575
+ * secp256k1/secp256r1 (0x01/0x02, low-s); multisig, zkLogin and passkey throw.
9576
+ * Deterministic only if the wallet signs deterministically; callers check that once at setup by
9577
+ * signing twice (`./wallet-account`), since the SDK cannot see how a wallet signs.
9578
+ */
9579
+ declare function spendKeyFromSignature(scheme: AccountSignatureScheme, signature: Uint8Array): Uint8Array;
9580
+ /** Everything an account's spend key determines. */
9581
+ interface CloakAccountKeys {
9582
+ readonly spendKey: Uint8Array;
9583
+ /** Owns the account's deposits and change. Its private key spends them. */
9584
+ readonly owner: UtxoKeypair;
9585
+ /** The account's viewing key: chain notes are encrypted under it and it is relay-registered. */
9586
+ readonly viewingKeyNk: Uint8Array;
9587
+ /** X25519 pair senders seal deliveries to; its public half is the v2 address key slot. */
9588
+ readonly deliveryKey: ViewingKeyPair;
9589
+ /** Root of the per-request receive keys (payment requests). */
9590
+ readonly requestRoot: Uint8Array;
9591
+ /** Legacy view key: the v1 address key slot (what the mobile app shows). */
9592
+ readonly legacyViewKey: ViewKey;
9593
+ /** The `cloak_` address to share (v2). */
9594
+ readonly address: string;
9595
+ /** The same account's v1 address, as the mobile app displays it. Receives nothing new. */
9596
+ readonly legacyAddress: string;
9597
+ }
9598
+ /** Derive an account's keys and addresses from its spend key, exactly as cloak.ag does. */
9599
+ declare function deriveCloakAccountKeys(spendKey: Uint8Array): Promise<CloakAccountKeys>;
9600
+
9601
+ /**
9602
+ * Opening a Cloak account with a wallet, and linking more wallets to it.
9603
+ *
9604
+ * ── The rules that keep money findable ────────────────────────────────────────────────────────
9605
+ * 1. An account key may come from a signature only if the wallet signs repeatably. The first time
9606
+ * a wallet is seen it signs TWICE; different signatures (passkey and smart wallets, some MPC
9607
+ * wallets) would give a different account each session and strand every note, so such a
9608
+ * wallet gets a stored key instead (rule 3).
9609
+ * 2. Later sessions sign once, and a check value saved at setup must match. A wallet whose
9610
+ * signature changed is refused loudly rather than shown an empty account.
9611
+ * 3. A stored key is a random master seed. It is created only when the app opts in and the
9612
+ * storage protects secrets; its backup is the seed's 24 words, which cloak.ag imports too.
9613
+ * 4. A linked wallet opens the account it was linked to: its record holds that account's spend
9614
+ * key sealed (AES-256-GCM) under a key derived from the linked wallet's OWN signature, bound to
9615
+ * the wallet and the account. The record is useless without that wallet.
9616
+ *
9617
+ * A Solana wallet's own account is the Cloak mobile app's account for that wallet, byte for byte.
9618
+ */
9619
+
9620
+ type AccountWalletChain = "solana" | "evm" | "sui";
9621
+ /** The one thing account opening needs from a wallet: sign the account message. */
9622
+ interface AccountWallet {
9623
+ readonly chain: AccountWalletChain;
9624
+ /** Base58 for Solana; 0x-hex for EVM (20 bytes) and Sui (32 bytes). */
9625
+ readonly address: string;
9626
+ /**
9627
+ * Sign the UTF-8 bytes of `CLOAK_ACCOUNT_MESSAGE` and return the signature in the chain's raw
9628
+ * form: Solana 64-byte ed25519; EVM the 65-byte personal_sign result; Sui the serialized
9629
+ * signature (flag || signature || public key).
9630
+ */
9631
+ signAccountMessage(message: Uint8Array): Promise<Uint8Array>;
9632
+ }
9633
+ type AccountSource = "wallet" | "linked" | "stored";
9634
+ interface WalletAccount {
9635
+ keys: CloakAccountKeys;
9636
+ source: AccountSource;
9637
+ /** `chain:address` of the wallet that opened it. */
9638
+ wallet: string;
9639
+ /** The opening wallet's own signature-made account key, when it is linked to another account. */
9640
+ walletOwnSpendKey?: Uint8Array;
9641
+ /** Set when this call created a stored account: show these 24 words to the user now. */
9642
+ backupWords?: string[];
9643
+ }
9644
+ interface OpenWalletAccountOptions {
9645
+ /**
9646
+ * Allow creating a stored account for a wallet that cannot sign repeatably. Requires a storage
9647
+ * with `protectsSecrets`; the caller must show `backupWords` to the user.
9648
+ */
9649
+ allowStoredAccount?: boolean;
9650
+ }
9651
+ /** The wallet signed differently than when it was set up. */
9652
+ declare class WalletSignatureChangedError extends Error {
9653
+ readonly wallet: string;
9654
+ constructor(wallet: string);
9655
+ }
9656
+ /** The wallet cannot sign repeatably and no stored account may be created for it. */
9657
+ declare class StoredAccountRequiredError extends Error {
9658
+ readonly wallet: string;
9659
+ constructor(wallet: string, reason: string);
9660
+ }
9661
+ /**
9662
+ * Open the account a wallet gives access to: the account it was linked to, else its own
9663
+ * signature-made account (the mobile app's, for a Solana wallet), else its stored account.
9664
+ */
9665
+ declare function openWalletAccount(wallet: AccountWallet, storage: CloakStorage, options?: OpenWalletAccountOptions): Promise<WalletAccount>;
9666
+ /**
9667
+ * Link `wallet` to `account`, so that wallet opens it from now on (in this storage). Signs once
9668
+ * (twice the first time the wallet is seen). Returns the wallet's own account key, so the caller
9669
+ * can still find any funds that account holds. Refuses to move a wallet already linked elsewhere
9670
+ * unless `replace` is set.
9671
+ */
9672
+ declare function linkWallet(account: CloakAccountKeys, wallet: AccountWallet, storage: CloakStorage, options?: {
9673
+ replace?: boolean;
9674
+ }): Promise<{
9675
+ wallet: string;
9676
+ walletOwnSpendKey: Uint8Array;
9677
+ }>;
9678
+ /** Forget a wallet's link. The wallet opens its own account again; no funds move. */
9679
+ declare function unlinkWallet(wallet: Pick<AccountWallet, "chain" | "address">, storage: CloakStorage): Promise<void>;
9680
+
9681
+ /**
9682
+ * Wallets, normalised.
9683
+ *
9684
+ * `createCloak` takes whatever wallet the user has: a browser extension, a mobile wallet, Privy, a
9685
+ * hardware wallet or a key on a server. Each one is recognised once (`recognizeWallet`) and becomes
9686
+ * a {@link WalletHandle}: who it is, whether it can open the account, and what it can do on its own
9687
+ * chain. Nothing past recognition knows which library the wallet came from.
9688
+ *
9689
+ * Not to be confused with `src/wallet/`, which is the local NOTE store. This directory is about the
9690
+ * user's external wallets, the ones that sign.
9691
+ */
9692
+
9693
+ type WalletChain = "solana" | "evm" | "sui";
9694
+ /** How the SDK recognised a wallet. */
9695
+ type WalletKind =
9696
+ /** `@solana/wallet-adapter`: the `useWallet()` context, or an adapter. */
9697
+ "wallet-adapter"
9698
+ /** A Wallet Standard wallet: Phantom, Solflare, Backpack, Slush, Suiet, a registered Privy wallet. */
9699
+ | "wallet-standard"
9700
+ /** A `@solana/kit` signer: a key pair, or a Privy server wallet (`createSolanaKitSigner`). */
9701
+ | "kit-signer"
9702
+ /** A `@solana/web3.js` `Keypair`. */
9703
+ | "keypair"
9704
+ /** An EIP-1193 provider: MetaMask, Rabby, Coinbase Wallet, Phantom's EVM side, Privy embedded. */
9705
+ | "eip1193"
9706
+ /** An EIP-1193 provider found through EIP-6963 discovery. */
9707
+ | "eip6963"
9708
+ /** A viem `WalletClient`, including one built on a Privy server wallet (`createViemAccount`). */
9709
+ | "viem"
9710
+ /** An ethers `Signer` connected to a JSON-RPC provider. */
9711
+ | "ethers"
9712
+ /** A key that can sign messages but cannot send: a viem local account, a Sui key pair. */
9713
+ | "signing-key"
9714
+ /** The catch-all {@link CustomWallet}. */
9715
+ | "custom";
9716
+ /** A wallet as `cloak.wallets` lists it. */
9717
+ interface ConnectedWallet {
9718
+ /** `solana:<base58>`, `evm:<0x lowercase>` or `sui:<0x lowercase>`. */
9719
+ readonly id: string;
9720
+ readonly name: string;
9721
+ readonly chain: WalletChain;
9722
+ readonly address: string;
9723
+ /** The networks this wallet can move money on: `["solana"]`, `["base", "polygon"]`, `["sui"]`. */
9724
+ readonly networks: readonly string[];
9725
+ readonly kind: WalletKind;
9726
+ /** False when the wallet cannot sign the account message (a Ledger on Solana). */
9727
+ readonly canOpenAccount: boolean;
9728
+ /** False when the wallet can open the account but cannot move money (a signing-only key). */
9729
+ readonly canSend: boolean;
9730
+ }
9731
+ interface SolanaWalletCapability {
9732
+ /**
9733
+ * Signs deposits. Never a sending signer: the SDK submits every transaction itself, so a wallet
9734
+ * that would broadcast through its own RPC (Privy's kit signer) is handed over without that part.
9735
+ */
9736
+ readonly signer: TransactionSigner;
9737
+ }
9738
+ interface EvmWalletCapability {
9739
+ /**
9740
+ * The EIP-1193 `request` function. For a server key (viem, ethers) it is a shim that serves the
9741
+ * key's one chain and signs `eth_sendTransaction` with the key; everything else goes to its node.
9742
+ */
9743
+ readonly request: EvmRequest;
9744
+ /**
9745
+ * False when `request` cannot read the chain (a {@link CustomWallet}): no receipt, balance or
9746
+ * gas reads go through it, and a deposit is followed on Solana instead.
9747
+ */
9748
+ readonly readsChain: boolean;
9749
+ }
9750
+ /** A Sui transaction in the Wallet Standard form: `toJSON()` resolves to the version-2 JSON. */
9751
+ interface SuiTransactionJson {
9752
+ toJSON(): Promise<string>;
9753
+ }
9754
+ interface SuiWalletCapability {
9755
+ /** Sign and execute `transaction` in the user's Sui wallet; resolves to the transaction digest. */
9756
+ signAndExecute(transaction: SuiTransactionJson, signal?: AbortSignal): Promise<string>;
9757
+ }
9758
+ /** A recognised wallet: what it is, and what it can do. */
9759
+ interface WalletHandle extends ConnectedWallet {
9760
+ /** Signs the account message. Absent when `canOpenAccount` is false. */
9761
+ readonly account?: AccountWallet;
9762
+ readonly solana?: SolanaWalletCapability;
9763
+ readonly evm?: EvmWalletCapability;
9764
+ readonly sui?: SuiWalletCapability;
9765
+ }
9766
+ /** What a {@link CustomWallet} on an EVM network is asked to send. */
9767
+ interface EvmTransactionRequest {
9768
+ /** The SDK's network id: `base` or `polygon`. */
9769
+ network: string;
9770
+ chainId: number;
9771
+ from: string;
9772
+ to: string;
9773
+ /** Hex quantity in wei; `0x0` for a token transfer. */
9774
+ value: string;
9775
+ /** Call data for a token transfer; absent for a native transfer. */
9776
+ data?: string;
9777
+ }
9778
+ /**
9779
+ * The catch-all: any object with these fields works as a wallet, for anything the SDK does not
9780
+ * recognise by itself.
9781
+ *
9782
+ * - `signMessage` signs the message's bytes and opens the account. Solana: the 64-byte ed25519
9783
+ * signature. EVM: the `personal_sign` (EIP-191) signature, as bytes or `0x` hex. Sui: the
9784
+ * serialized signature (flag, signature, public key), as bytes or base64.
9785
+ * - `signTransaction` (Solana) signs a transaction given its wire bytes and returns the signed
9786
+ * wire bytes.
9787
+ * - `sendTransaction` sends and returns the hash: on EVM, an {@link EvmTransactionRequest}; on Sui,
9788
+ * a {@link SuiTransactionJson} to execute (`Transaction.from(await tx.toJSON())` in `@mysten/sui`).
9789
+ */
9790
+ interface CustomWallet {
9791
+ chain: WalletChain;
9792
+ address: string;
9793
+ name?: string;
9794
+ signMessage?: (message: Uint8Array) => Promise<Uint8Array | string>;
9795
+ signTransaction?: (transaction: Uint8Array) => Promise<Uint8Array>;
9796
+ sendTransaction?: (transaction: EvmTransactionRequest | SuiTransactionJson) => Promise<string>;
9797
+ }
9798
+
9799
+ /**
9800
+ * Finishing what a call left open, so a stopped deposit or payout never needs a separate step:
9801
+ *
9802
+ * - a bridge deposit that reached its receiving address but was not shielded (a network blip on
9803
+ * the last step, a closed tab, a deposit sent with `wait: false`): shielded now, the same way
9804
+ * `createBridgeRecovery` finished the stuck Sui deposit on 2026-11-26;
9805
+ * - a payout whose withdrawal landed but which was not forwarded or confirmed: finished now
9806
+ * (`finishPayout`), and asked once where it is (`refreshPayout`).
9807
+ *
9808
+ * `createCloak` runs one pass when it starts (and again while an order is open or a failed finish
9809
+ * is due), and `cloak.resume()` runs one on demand. A pass never starts anything new: it completes
9810
+ * orders the user already made, to the destinations they already chose.
9811
+ */
9812
+
9813
+ /** Something a pass finished. */
9814
+ interface ResumedItem {
9815
+ kind: "deposit" | "payout";
9816
+ status: "shielded" | "sent" | "delivered" | "on its way";
9817
+ token: string;
9818
+ amount: string;
9819
+ txs: Record<string, string>;
9820
+ }
9821
+ /** Something a pass tried and could not finish yet. */
9822
+ interface ResumeProblem {
9823
+ kind: "deposit" | "payout";
9824
+ /** The deposit's receiving-address index, or the payout's id. */
9825
+ id: string;
9826
+ message: string;
9827
+ /** True when a later pass tries again by itself. */
9828
+ retrying: boolean;
9829
+ }
9830
+ interface ResumeResult {
9831
+ finished: ResumedItem[];
9832
+ problems: ResumeProblem[];
9833
+ /** Deposits still open (an address handed out, nothing shielded yet). */
9834
+ openDeposits: number;
9835
+ /** Sends to another chain still open (BRS to Base: withdrawn to its one-time sender, not bridged yet). */
9836
+ openSends?: number;
9837
+ }
9838
+
9839
+ /**
9840
+ * Which tokens move where, and amounts as people write them.
9841
+ *
9842
+ * Every call names its token; none is ever assumed. The private balance holds four tokens on
9843
+ * Solana, each in its own pool. Money from other chains arrives as USDC (ETH from Base is converted
9844
+ * on the way in), except BRS from Base, which LayerZero carries 1:1; money to other chains leaves as
9845
+ * USDC, or as BRS to Base, the same way. A call the route cannot carry stops before anything moves
9846
+ * and says what would work.
9847
+ *
9848
+ * in: Solana SOL, USDC, USDT, BRS -> the same token
9849
+ * Base USDC, ETH -> USDC
9850
+ * Base BRS -> BRS (LayerZero; the Base wallet pays its fee in ETH)
9851
+ * Polygon USDC -> USDC
9852
+ * Sui USDC -> USDC
9853
+ * out: a Cloak user or a Solana address: SOL, USDC, USDT, BRS
9854
+ * Base: USDC, or BRS (LayerZero; its fee is paid in SOL from the private balance)
9855
+ * Polygon, Sui: USDC
9856
+ *
9857
+ * Amounts are decimal strings in the token's own units ("1.5" USDC, "0.0014" ETH) and are turned
9858
+ * into base units exactly, never through a float.
9859
+ */
9860
+
9861
+ /** A token the private balance holds. */
9862
+ type CloakToken = "USDC" | "USDT" | "SOL" | "BRS";
9863
+ interface CloakTokenInfo {
9864
+ symbol: CloakToken;
9865
+ mint: Address;
9866
+ decimals: number;
9867
+ }
9868
+ declare const CLOAK_TOKENS: Readonly<Record<CloakToken, CloakTokenInfo>>;
9869
+
9870
+ interface CreateCloakOptions {
9871
+ /** The user's wallet: anything a wallet library hands out (see `recognizeWallet`). */
9872
+ wallet?: unknown;
9873
+ /** Several wallets at once. The first one that can sign opens the account; the others are linked to it. */
9874
+ wallets?: readonly unknown[];
9875
+ /**
9876
+ * A cloak.ag account, opened from its 24-word Cloak Key (or the Cloak mobile app's in-app wallet
9877
+ * words). Wallets passed with it are linked to it, so next time the wallet alone opens it.
9878
+ */
9879
+ cloakKey?: string;
9880
+ /**
9881
+ * Business mode: an account key the caller holds (32 bytes, or 64 hex characters). No wallet
9882
+ * signature opens it, and no wallet is linked to it.
9883
+ */
9884
+ account?: Uint8Array | string;
9885
+ /**
9886
+ * Where links, profiles, open orders and payouts are kept. Default: the browser's localStorage,
9887
+ * else memory. A server passes its own; a stored account key needs one with `protectsSecrets`.
9888
+ */
9889
+ storage?: CloakStorage;
9890
+ /** A Solana RPC URL or a `CloakRpc`. Default: the public mainnet endpoint (rate-limited). */
9891
+ rpc?: string | CloakRpc;
9892
+ /**
9893
+ * For a wallet that cannot sign the same message the same way twice (a passkey smart wallet):
9894
+ * create a stored account key, kept in `storage`, and return its 24 backup words once in
9895
+ * `cloak.backupWords`. Default false: such a wallet is refused.
9896
+ */
9897
+ allowStoredAccount?: boolean;
9898
+ /** web3.js `{ VersionedTransaction }`, for a legacy Solana adapter (Ledger) in a bundled app. */
9899
+ web3?: Web3Module;
9900
+ /** An approved Cloak partner code, attached to fee-bearing relay requests. */
9901
+ affiliateCode?: string;
9902
+ /**
9903
+ * Move notes an older client left readable or spendable by others (the "at risk" notes) into
9904
+ * the account before they are spent, and whenever a balance read finds them. Default true.
9905
+ */
9906
+ secureExposedNotes?: boolean;
9907
+ /** Non-fatal events: a wallet that could not be linked, a partner code that was dropped. */
9908
+ onWarning?: (message: string) => void;
9909
+ /**
9910
+ * Finish what earlier calls left open (a deposit that arrived but was not shielded, a payout
9911
+ * withdrawn but not forwarded) shortly after start, and again while an order is open. Each is
9912
+ * reported through `cloak.on("finished", …)`. Default true; `cloak.resume()` runs a pass on demand.
9913
+ */
9914
+ resume?: boolean;
9915
+ /**
9916
+ * @internal Cloak's own local test stacks only (a fork with its own program id). A production
9917
+ * app never sets it.
9918
+ */
9919
+ programId?: Address;
9920
+ }
9921
+ /** The private balance, per token, as decimal strings. */
9922
+ type CloakBalance = Record<CloakToken, string>;
9923
+ /** A note in the private balance, as `cloak.notes()` lists it. */
9924
+ interface CloakNoteView {
9925
+ token: CloakToken;
9926
+ amount: string;
9927
+ /** How it came in: a deposit, change from a spend, a payment received, a swap refund. */
9928
+ from: "deposit" | "change" | "received" | "refund" | "created";
9929
+ /** The transaction that created it, when known. */
9930
+ tx?: string;
9931
+ /** True when an older client left it readable by others; it is moved before it is spent. */
9932
+ exposed: boolean;
9933
+ }
9934
+ /** A chain name, or a connected wallet (from `cloak.wallets`, or the wallet object itself). */
9935
+ type WalletRef = string | ConnectedWallet | object;
9936
+ /** `cloak.notes()`: the notes, and a way to save them encrypted. */
9937
+ type CloakNoteList = CloakNoteView[] & {
9938
+ /**
9939
+ * Every note this account holds, in one string encrypted under `secret` (32+ bytes, or a
9940
+ * passphrase of 12+ characters), bound to this account and network. `restoreNotes` and
9941
+ * `cloak.importNotes` read it back. `unsafePlaintext: true` writes it unencrypted, marked so.
9942
+ */
9943
+ encryptToSave(secret: string | Uint8Array, options?: {
9944
+ unsafePlaintext?: boolean;
9945
+ }): Promise<string>;
9946
+ };
9947
+ interface ShieldRequest {
9948
+ /** Where the money is: "solana", "base", "polygon", "sui", or a connected wallet. */
9949
+ from: WalletRef;
9950
+ /** With an EVM wallet as `from`: which network ("base" or "polygon"). */
9951
+ chain?: string;
9952
+ token: string;
9953
+ amount: string;
9954
+ /**
9955
+ * A business reference ("invoice-1042"): the shield happens once. Asking again with the same ref
9956
+ * returns the first receipt (`repeated: true`) and moves nothing.
9957
+ */
9958
+ ref?: string;
9959
+ onProgress?: (step: string) => void;
9960
+ signal?: AbortSignal;
9961
+ }
9962
+ interface SendRequest {
9963
+ /** A `cloak_` address, a Solana address, a Base/Polygon/Sui address, or a connected wallet. */
9964
+ to: string | WalletRef;
9965
+ /** For an EVM address: "base" or "polygon". */
9966
+ chain?: string;
9967
+ token: string;
9968
+ amount: string;
9969
+ /** For a payout to another chain: resolve once it is delivered (default) or as soon as it is sent. */
9970
+ wait?: boolean;
9971
+ /** A business reference ("payout-77"): the send happens once; asking again returns the first receipt. */
9972
+ ref?: string;
9973
+ onProgress?: (step: string) => void;
9974
+ signal?: AbortSignal;
9975
+ }
9976
+ type WithdrawRequest = SendRequest;
9977
+ interface QuoteRequest {
9978
+ /** A shield: where the money comes from. */
9979
+ from?: WalletRef;
9980
+ /** A send or withdrawal: where it goes. */
9981
+ to?: string | WalletRef;
9982
+ chain?: string;
9983
+ token: string;
9984
+ amount: string;
9985
+ }
9986
+ interface CloakQuote {
9987
+ /** What arrives, at least. */
9988
+ arrives: {
9989
+ token: string;
9990
+ atLeast: string;
9991
+ network: string;
9992
+ };
9993
+ /** Every fee on the way, in the arriving token. */
9994
+ fee: string;
9995
+ /** A fee paid in another chain's own coin (BRS from Base: the LayerZero fee, in ETH). */
9996
+ networkFee?: {
9997
+ token: string;
9998
+ amount: string;
9999
+ };
10000
+ }
10001
+ interface CreatePaymentLinkRequest {
10002
+ token: string;
10003
+ amount: string;
10004
+ /**
10005
+ * A business reference ("invoice-1042"): the link's secret is derived from the account key and
10006
+ * this ref, so the same ref always rebuilds the same link, and asking again returns it rather
10007
+ * than funding a second one.
10008
+ */
10009
+ ref?: string;
10010
+ /** Where the link opens. Default https://cloak.ag (its /pay page claims it). */
10011
+ base?: string;
10012
+ onProgress?: (step: string) => void;
10013
+ }
10014
+ interface PaymentLinkResult {
10015
+ /** `https://cloak.ag/pay#…`: the secret is the part after #. Whoever has it can claim the money. */
10016
+ url: string;
10017
+ token: string;
10018
+ amount: string;
10019
+ ref?: string;
10020
+ /** The funding transaction; absent when an existing link was returned for its ref. */
10021
+ receipt?: CloakReceipt;
10022
+ }
10023
+ interface PaymentLinkView {
10024
+ url: string;
10025
+ token: string;
10026
+ amount: string;
10027
+ ref?: string;
10028
+ createdAt: string;
10029
+ /** True once anyone, the creator included, has claimed it. */
10030
+ claimed: boolean;
10031
+ }
10032
+ interface ClaimPaymentLinkOptions {
10033
+ /** Claim to this Solana address (the website's way; the withdrawal fee comes off). Default: into this private balance, free. */
10034
+ to?: string | WalletRef;
10035
+ onProgress?: (step: string) => void;
10036
+ }
10037
+ interface RequestPaymentRequest {
10038
+ token: string;
10039
+ amount: string;
10040
+ /** Free text shown to the payer, up to 32 bytes. Never verified. */
10041
+ label?: string;
10042
+ base?: string;
10043
+ }
10044
+ interface PaymentRequestView {
10045
+ url: string;
10046
+ /** The request id, hex: it comes back in the note that pays it. */
10047
+ id: string;
10048
+ token: string;
10049
+ amount: string;
10050
+ label: string;
10051
+ createdAt: string;
10052
+ paid: boolean;
10053
+ paidTx?: string;
10054
+ }
10055
+ interface CloakReceipt {
10056
+ status: "shielded" | "sent" | "withdrawn" | "delivered" | "on its way" | "claimed";
10057
+ token: string;
10058
+ /** What arrived (or will arrive), in the arriving token. */
10059
+ amount: string;
10060
+ /** Every fee on the way, in the arriving token. */
10061
+ fee: string;
10062
+ /** For a shield from another chain: what left the origin wallet ("6 USDC", "0.0014 ETH"). */
10063
+ sent?: string;
10064
+ /** A fee paid in another chain's own coin (BRS from Base: the LayerZero fee, in ETH). */
10065
+ networkFee?: {
10066
+ token: string;
10067
+ amount: string;
10068
+ };
10069
+ /** Transaction ids per network: `{ solana: "…", base: "0x…" }`. */
10070
+ txs: Record<string, string>;
10071
+ /** Notes this call spent and created. */
10072
+ notes: {
10073
+ spent: number;
10074
+ created: number;
10075
+ };
10076
+ /** True when this is the stored receipt of an earlier call with the same `ref`: nothing moved now. */
10077
+ repeated?: boolean;
10078
+ /** For a payout returned before delivery (`wait: false`): resolves with the delivered receipt. */
10079
+ track?: () => Promise<CloakReceipt>;
10080
+ }
10081
+ type CloakEvent = "progress" | "warning" | "secured" | "finished";
10082
+ interface Cloak {
10083
+ /** The `cloak_` address to share to get paid. */
10084
+ readonly address: string;
10085
+ /** A public id of the account (hex), stable across devices and wallets. */
10086
+ readonly accountId: string;
10087
+ /** The wallets this object can use, as `{ name, chain, address, networks }`. */
10088
+ readonly wallets: readonly ConnectedWallet[];
10089
+ /** Set once, when this session created a stored account: show these 24 words to the user now. */
10090
+ readonly backupWords?: readonly string[];
10091
+ /** Add a wallet: linked to this account (one signature) when it can sign, usable to move money either way. */
10092
+ connect(wallet: unknown, options?: {
10093
+ replace?: boolean;
10094
+ }): Promise<ConnectedWallet[]>;
10095
+ /** Stop using a wallet in this session; `unlink` also forgets its link to this account. */
10096
+ disconnect(wallet: ConnectedWallet | string, options?: {
10097
+ unlink?: boolean;
10098
+ }): Promise<void>;
10099
+ balance(options?: {
10100
+ refresh?: boolean;
10101
+ }): Promise<CloakBalance>;
10102
+ notes(options?: {
10103
+ refresh?: boolean;
10104
+ }): Promise<CloakNoteList>;
10105
+ /**
10106
+ * Add notes saved with `encryptToSave` (or restored with `restoreNotes`). Each must belong to this
10107
+ * account, spend with its own key, match its commitment and be unspent on chain; others are skipped.
10108
+ */
10109
+ importNotes(saved: string, secret: string | Uint8Array): Promise<{
10110
+ imported: number;
10111
+ skipped: number;
10112
+ }>;
10113
+ quote(request: QuoteRequest): Promise<CloakQuote>;
10114
+ shield(request: ShieldRequest): Promise<CloakReceipt>;
10115
+ send(request: SendRequest): Promise<CloakReceipt>;
10116
+ withdraw(request: WithdrawRequest): Promise<CloakReceipt>;
10117
+ /** Move exposed notes into the account now. Resolves with how many were moved. */
10118
+ secureExposedNotes(): Promise<number>;
10119
+ /** Finish open deposits and payouts now: one pass, reported in the result and as `finished` events. */
10120
+ resume(): Promise<ResumeResult>;
10121
+ /** A link that holds money: whoever opens it can claim it. cloak.ag's format; the website claims it too. */
10122
+ createPaymentLink(request: CreatePaymentLinkRequest): Promise<PaymentLinkResult>;
10123
+ /** Claim a payment link (one cloak.ag made, or this SDK): into this private balance, or `to` a Solana address. */
10124
+ claimPaymentLink(url: string, options?: ClaimPaymentLinkOptions): Promise<CloakReceipt>;
10125
+ /** The links this account made, and whether each was claimed. */
10126
+ paymentLinks(): Promise<PaymentLinkView[]>;
10127
+ /** A link that asks for money. When it is paid, the note arrives in this private balance. */
10128
+ requestPayment(request: RequestPaymentRequest): Promise<PaymentRequestView>;
10129
+ /** Pay a payment request (one cloak.ag made, or this SDK) from this private balance. */
10130
+ payRequest(url: string, options?: {
10131
+ onProgress?: (step: string) => void;
10132
+ }): Promise<CloakReceipt>;
10133
+ /** The requests this account made, and whether each was paid. */
10134
+ requests(): Promise<PaymentRequestView[]>;
10135
+ /** `finished` carries a {@link ResumedItem}; `warning` a message; `secured` `{ moved }`. */
10136
+ on(event: CloakEvent, handler: (payload: unknown) => void): () => void;
10137
+ }
10138
+ /** Open the account the options name, link the other wallets to it, and return the Cloak object. */
10139
+ declare function createCloak(options: CreateCloakOptions): Promise<Cloak>;
10140
+
10141
+ /** Any store with `get` and `set` (and `delete`), synchronous or not: a database table, Redis, KV. */
10142
+ interface KeyValueStore {
10143
+ get(key: string): string | null | undefined | Promise<string | null | undefined>;
10144
+ set(key: string, value: string): void | Promise<void>;
10145
+ delete?(key: string): void | Promise<void>;
10146
+ }
10147
+ interface EncryptedStorageOptions {
10148
+ /**
10149
+ * What the values are bound to besides their key. Default: this build's relay origin, so values
10150
+ * a staging build wrote never open in a production build, and the reverse.
10151
+ */
10152
+ network?: string;
10153
+ }
10154
+ /** `store` with every value encrypted under `secret`. */
10155
+ declare function encryptedStorage(store: KeyValueStore, secret: string | Uint8Array, options?: EncryptedStorageOptions): CloakStorage;
10156
+
10157
+ /** A restored note, ready to spend. */
10158
+ interface RestoredNote {
10159
+ token: string;
10160
+ utxo: Utxo;
10161
+ kind?: string;
10162
+ tx?: string;
10163
+ }
10164
+ interface RestoredNotes {
10165
+ /** The account the notes belong to (its public id). */
10166
+ account: string;
10167
+ network: string;
10168
+ notes: RestoredNote[];
10169
+ }
10170
+ /** The notes in a string `encryptToSave` wrote. Throws `notes.wrong_secret` for another secret or network. */
10171
+ declare function restoreNotes(saved: string, secret: string | Uint8Array, options?: {
10172
+ network?: string;
10173
+ }): Promise<RestoredNotes>;
10174
+
10175
+ /**
10176
+ * Payment links: bearer links that hold money (v1, v2), and the router that reads any of them.
10177
+ *
10178
+ * https://cloak.ag/pay#<payload> the payload stays in the fragment, which is never sent
10179
+ *
10180
+ * ── Compatibility contract ────────────────────────────────────────────────────────────────────
10181
+ * Byte-for-byte cloak.ag (web `lib/payment-link-v2.ts`, `lib/payment-links.ts`), which the mobile
10182
+ * app mirrors; pinned by `__tests__/client-compat-vectors.test.ts`. A link made here claims on the
10183
+ * website and in the app, and the other way round.
10184
+ *
10185
+ * v2 (issued today), base58 of:
10186
+ * u8 2 || seed[32] || varint amount || varint (amount - net, 0 = none) ||
10187
+ * u8 mintCode (0 SOL, 1 USDC, 2 USDT, 0xFF + 32 raw bytes) || varint leafIndex || blake3[0..4]
10188
+ * The link note is owned by `sk` and blinded by `r`, both from the seed under separate domains:
10189
+ * sk = BE(blake3("cloak-paylink-v2:sk" || seed)) mod (r_field >> 4), r likewise with ":r".
10190
+ * `amount` is the note's own value (what the claim spends); `net` is what the claimer receives
10191
+ * after the withdraw fee when the sender grossed up for it.
10192
+ *
10193
+ * v1 (claim only): base64url (no padding) of the JSON `{v:1, sk, r, amt, utxoAmt?, net?, mint,
10194
+ * idx, cm, sib, sig}`, with hex secrets and decimal commitments.
10195
+ *
10196
+ * v3 is a payment REQUEST (`./payment-request`): no secret, nothing to claim.
10197
+ */
10198
+
10199
+ /** Any bearer link, reduced to what a claim needs. */
10200
+ interface ClaimablePaymentLink {
10201
+ version: 1 | 2;
10202
+ sk: bigint;
10203
+ r: bigint;
10204
+ /** What the claim withdraws. */
10205
+ amount: bigint;
10206
+ /** The note's own value; differs from `amount` only on old v1 links. */
10207
+ utxoAmount: bigint;
10208
+ net?: bigint;
10209
+ mint: string;
10210
+ leafIndex: number;
10211
+ /** v1 only. v2 recomputes the commitment from the secrets. */
10212
+ commitment?: bigint;
10213
+ /** v1 only. v2 reads the sibling from the relay. */
10214
+ siblingCommitment?: bigint;
10215
+ }
10216
+ /**
10217
+ * Read any bearer link (v1 or v2; a full URL or its fragment) into its claim inputs, exactly as
10218
+ * cloak.ag's claim page does. A v3 request throws "This is a payment request, not a claim link".
10219
+ */
10220
+ declare function decodeClaimablePaymentLink(urlOrFragment: string): ClaimablePaymentLink;
10221
+
10222
+ /** A decoded payment request. */
10223
+ interface PaymentRequestLink {
10224
+ v: 3;
10225
+ /** The requester's UTXO owner public key. */
10226
+ utxoPubkey: bigint;
10227
+ /** The requester's 32-byte delivery key. */
10228
+ viewingPubkey: Uint8Array;
10229
+ mint: string;
10230
+ amount: bigint;
10231
+ /** 16 bytes; comes back in the paid note's blinding. */
10232
+ requestId: Uint8Array;
10233
+ /** Free text set by the requester. Never verified: show it as such. */
10234
+ label: string;
10235
+ }
10236
+ /** Decode a request payload. Strict: version, checksum, lengths, utf8, no control characters. */
10237
+ declare function decodePaymentRequestLink(fragment: string): PaymentRequestLink;
10238
+
10239
+ /**
10240
+ * The error the one-call API throws (`createCloak`, its wallets, shield, send, withdraw, payment
10241
+ * links). It says three things a partner can act on:
10242
+ *
10243
+ * - `code`, stable and dotted (`wallet.not_connected`, `deposit.finish.network`): match on it,
10244
+ * never on the message;
10245
+ * - `retryable`: whether the same call can succeed if made again;
10246
+ * - when money is in flight, `moneyAt` (where it is now) and `next` (what happens to it).
10247
+ *
10248
+ * The message is written for a person and already includes `moneyAt` and `next`.
10249
+ */
10250
+
10251
+ type CloakErrorCategory = CloakError["category"];
10252
+ interface CloakCallErrorDetails {
10253
+ /** Where the money is now, in words: "still in your wallet", "at your receiving address on Solana". */
10254
+ moneyAt?: string;
10255
+ /** What happens next, in words: "nothing moved; try again", "it is added the next time Cloak starts". */
10256
+ next?: string;
10257
+ /** The underlying error, kept for logs. Never shown as the message. */
10258
+ cause?: unknown;
10259
+ }
10260
+ declare class CloakCallError extends CloakError {
10261
+ readonly code: string;
10262
+ readonly moneyAt?: string;
10263
+ readonly next?: string;
10264
+ constructor(code: string, message: string, category: CloakErrorCategory, retryable: boolean, details?: CloakCallErrorDetails);
10265
+ /** `CloakError [code], retryable` and the message, the way a log line should read. */
10266
+ toString(): string;
10267
+ }
10268
+ /** True for a {@link CloakCallError}, and for one with `code` (or a code under `code.`) when given. */
10269
+ declare function isCloakCallError(e: unknown, code?: string): e is CloakCallError;
10270
+
10271
+ interface RecognizeWalletOptions {
10272
+ /** web3.js `VersionedTransaction`, for a legacy Solana wallet adapter (Ledger) in a bundled app. */
10273
+ web3?: Web3Module;
10274
+ /** Ask a wallet that has no connected account to connect, showing its prompt. Default true. */
10275
+ connect?: boolean;
10276
+ }
10277
+ /** The handles for one wallet. Throws `wallet.unrecognized` for anything else. */
10278
+ declare function recognizeWallet(input: unknown, options?: RecognizeWalletOptions): Promise<WalletHandle[]>;
10279
+ /**
10280
+ * The handles for several wallets, in order. A wallet passed twice is kept once, except one EVM
10281
+ * key passed once per network (a client per chain), which becomes one wallet serving them all.
10282
+ */
10283
+ declare function recognizeWallets(inputs: readonly unknown[], options?: RecognizeWalletOptions): Promise<WalletHandle[]>;
10284
+
10285
+ /** An EIP-6963 provider detail: `{ info: { uuid, name, icon, rdns }, provider }`. */
10286
+ interface Eip6963ProviderDetail {
10287
+ info: {
10288
+ uuid: string;
10289
+ name: string;
10290
+ icon: string;
10291
+ rdns: string;
10292
+ };
10293
+ provider: {
10294
+ request: EvmRequest;
10295
+ };
10296
+ }
10297
+ /**
10298
+ * Every EVM wallet installed in this browser, found through EIP-6963: the SDK asks, each wallet
10299
+ * answers with its name and provider. Pass any of them to `createCloak` as a wallet. Resolves to
10300
+ * an empty list outside a browser.
10301
+ */
10302
+ declare function discoverEvmWallets(options?: {
10303
+ timeoutMs?: number;
10304
+ }): Promise<Eip6963ProviderDetail[]>;
10305
+
10306
+ type CloakKeyErrorCode = "empty" | "word_count" | "unknown_word" | "checksum";
10307
+ /** A phrase could not be read. `message` is written for the end user, as on cloak.ag. */
10308
+ declare class CloakKeyError extends Error {
10309
+ readonly code: CloakKeyErrorCode;
10310
+ /** 1-based positions of words that are not in the wordlist. */
10311
+ readonly unknownPositions: number[];
10312
+ constructor(code: CloakKeyErrorCode, message: string, unknownPositions?: number[]);
10313
+ }
10314
+ /** The 24 words for a 32-byte master seed. */
10315
+ declare function masterSeedToCloakKey(seed: Uint8Array): string[];
10316
+ /**
10317
+ * Read a Cloak Key back into its master seed, or throw a `CloakKeyError` naming exactly what is
10318
+ * wrong. Same rules, order of checks and messages as cloak.ag.
10319
+ */
10320
+ declare function cloakKeyToMasterSeed(input: string): Uint8Array;
10321
+ /** One numbered word per line ("1. train"), the form cloak.ag copies; it reads back as is. */
10322
+ declare function formatCloakKey(words: readonly string[]): string;
10323
+ /** The account spend key a cloak.ag Cloak Key opens: `BLAKE3(master_seed || "cloak_spend_key")`. */
10324
+ declare function spendKeyFromCloakKey(input: string): Uint8Array;
10325
+
10326
+ /**
10327
+ * The `cloak_` address: what a Cloak user shares to be paid privately.
10328
+ *
10329
+ * ── Compatibility contract ────────────────────────────────────────────────────────────────────
10330
+ * Byte-for-byte cloak.ag's codec (web `lib/shielded-transfer.ts`), pinned against vectors from its
10331
+ * own code in `__tests__/client-compat-vectors.test.ts`:
10332
+ *
10333
+ * "cloak_" || base58( version(1) || key(32) || utxoPubkey_BE(32) || SHA-512(first 65 bytes)[0..4] )
10334
+ *
10335
+ * - v2 (current): `key` is the account's delivery viewing key, `deriveViewingKeyFromNk(nk)
10336
+ * .publicKey`. A send seals output 0 to it (`recipientViewingPublicKey`), and the recipient
10337
+ * finds the carrier with `nk` alone.
10338
+ * - v1 (retired): `key` is the legacy `deriveViewKey(sk).pvk`. The Cloak mobile app still shows
10339
+ * v1 addresses. They parse, so saved contacts still resolve, but nothing can be sent to one: the
10340
+ * envelope rail it names is refused at relay intake, so a note sent there could never be found
10341
+ * by its owner. `assertSendableCloakAddress` refuses with the website's own message.
10342
+ *
10343
+ * The bare base58 body (no `cloak_`) is accepted on parse, as on the website. The SDK is stricter
10344
+ * in one place only: a `utxoPubkey` outside the BN254 scalar field is refused instead of being
10345
+ * silently reduced, since a commitment to a reduced key belongs to nobody.
10346
+ */
10347
+ type CloakAddressVersion = 1 | 2;
10348
+ interface CloakAddress {
10349
+ /** 1 = retired envelope rail (parse only), 2 = SDK delivery rail. */
10350
+ version: CloakAddressVersion;
10351
+ /** UTXO field-element public key the recipient's note commits to. */
10352
+ utxoPubkey: bigint;
10353
+ /** v2 only: the X25519 delivery key a send seals output 0 to (32 bytes). */
10354
+ viewingPubkey?: Uint8Array;
10355
+ /** v1 only: the retired X25519 envelope key (32 bytes). Never used to send. */
10356
+ pvk?: Uint8Array;
10357
+ }
10358
+ /** Thrown for a `cloak_` string that does not parse. */
10359
+ declare class InvalidCloakAddressError extends Error {
10360
+ constructor(reason: string);
10361
+ }
10362
+ /** Thrown when a v1 (retired) address is used as a destination. */
10363
+ declare class RetiredCloakAddressError extends Error {
10364
+ constructor();
10365
+ }
10366
+ /** Encode a Cloak address. The key slot holds `viewingPubkey` for v2 and `pvk` for v1. */
10367
+ declare function encodeCloakAddress(address: CloakAddress): string;
10368
+ /** Parse a `cloak_` address (or its bare base58 body). Throws `InvalidCloakAddressError`. */
10369
+ declare function parseCloakAddress(input: string): CloakAddress;
10370
+ /** True when `input` parses as a Cloak address (either version). */
10371
+ declare function isCloakAddress(input: string): boolean;
10372
+ /**
10373
+ * Parse a destination address and require that it can receive (v2). A v1 address throws
10374
+ * `RetiredCloakAddressError`, with the message cloak.ag shows.
10375
+ */
10376
+ declare function assertSendableCloakAddress(input: string): CloakAddress & {
10377
+ version: 2;
10378
+ viewingPubkey: Uint8Array;
10379
+ };
10380
+
6609
10381
  /**
6610
10382
  * Cloak SDK - TypeScript SDK for Private Transactions on Solana
6611
10383
  *
6612
10384
  * @packageDocumentation
6613
10385
  */
6614
10386
 
6615
- declare const VERSION = "0.2.14";
10387
+ declare const VERSION = "0.2.20";
6616
10388
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
6617
10389
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
6618
10390
 
6619
- export { BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BridgeDeliveryState, type BridgeDeposit, type BridgeDepositState, type BridgeQuoteAssessment, type BridgeQuoteInput, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, type ChainNoteTxType, type CircuitVerificationResult, type CleanupResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, type CloakRpc, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type CreateRecoverableDepositUtxoParams, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, type DeliveredNote, DepositError, type DepositInstructionParams, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EXPECTED_CIRCUIT_HASHES, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type ErrorCategory, type ExpandedSpendKey, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MAX_REQUEST_KEYS, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, NATIVE_SOL_MINT, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NoteData, type NoteIndexCursor, type NoteIndexDeliveryItem, type NoteIndexFetchOptions, NoteIndexFormatError, type NoteIndexHead, NoteIndexHeadBehindError, type NoteIndexItem, type NoteIndexPage, type NoteIndexRecoveryStats, type NoteIndexSwapRefundItem, type NoteIndexTxItem, ONECLICK_PUBKEY_B58, type OnchainMerkleProof, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterTopUpExpectation, type PaymasterTopUpResult, type PendingDeposit, type PendingWithdrawal, type PostFailureVerdict, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, REQUEST_KEY_GAP_LIMIT, REQUEST_KEY_ROOT_SOURCE, type RecipientDeliveryNote, type RecoverNotesFromIndexParams, type RecoverNotesFromIndexResult, type RecoveredChangeNote, type RecoveredChangeNoteRecord, type RecoveredDepositNote, type RecoveredDepositNoteRecord, type RecoveredSwapRefund, type RelayAuthMode, type RelayAuthPreimage, type RelayAuthSigner, RelayBatchAuthCoordinator, type RelayBatchAuthCoordinatorOptions, type RelayBatchAuthEnvelope, type RelayBatchAuthFields, type RelayBatchAuthItemHandle, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RequestKeyRootSource, type RequestKeys, type RetryHooks, type RiskQuoteInstructionResponse, RootNotFoundError, SCANNER_SUPPORTS_TRANSACT_SWAP, SIGN_IN_MESSAGE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, type SignedRelayAuthPayload, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, type SubmitTransactToRelayArgs, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapResult, type SweepResult, TERMINAL_FAILURE, TRANSACTION_CIRCUITS_VERSION, TRANSACT_AUTH_FIELDS, TRANSACT_SWAP_AUTH_FIELDS, type TransactBatchItem, type TransactBatchItemOutcome, type TransactBatchOptions, type TransactBatchResult, type TransactOptions, type TransactParams, type TransactRequestBodyParams, type TransactResult, type TransactionBytesWallet, 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, WALLET_ADDED_PROGRAMS, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAdapterBridgeOptions, type WalletSigner$1 as WalletSigner, type WalletUtxo, type Web3Module, type WithdrawOptions, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, assertDirectSubmissionLanded, assertInputMints, assertTransactionCircuitIntegrity, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, buildAuthTransactionMessage, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canRebuildMerkleTreeFromChain, canonicalJson, canonicalPayloadString, chainNoteFromBase64, chainNoteToBase64, classifyPostFailure, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, depositFromDerivedKey, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePublicKey, deriveRequestKeyRange, deriveRequestKeyRoot, deriveRequestKeys, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverSwapRefunds, downloadNote, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, expandSpendKey, explainRelayAuthRejection, exportKeys, exportNote, exportWalletKeys, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findProgramAddress, formatAmount, formatComplianceCsv, formatErrorForLogging, formatSol, fullWithdraw, fundReceiverViaPaymaster, generateCloakKeys, generateCommitmentAsync, generateMasterSeed, generateNoteFromWallet, generateUtxoKeypair, generateViewingKeyPair, getAddressExplorerUrl, getChainNoteRegistryPDA, getCircuitsPath, getDeliveryRegistryPDA, getDistributableAmount, getExplorerUrl, getNkFromUtxoPrivateKey, getNullifierPDA, getPendingOperationsSummary, getPoolAuthorityConfigPDA, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getSwapStatePDA, getViewKey, hasPendingOperations, hexToBigint$1 as hexToBigint, hexToBytes, importKeys, importWalletKeys, isBrowser, isBrowserLike, isDebugEnabled, isMessageSigner, isPlausibleSignature, isReactNative, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isValidHex, isValidRelayClientId, isValidRpcUrl, isValidSolanaAddress, isWithdrawAmountSufficient, isWithdrawable, listBridgeDeposits, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, mayRetry, messageSignerFromCallback, normalizeAffiliateCode, openRecipientDeliveryNote, parseAmount, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, poseidonHash, preflightCheck, preflightNullifiers, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readMerkleTreeState, readRent, recipientDeliveryNoteToBase64, recoverNotesFromIndex, registerViewingKey, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, retryDelayMs, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromTransactionBytes, signerFromWalletAdapter, splitTo2Limbs, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, sweepToWalletKey, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyQuoteSignature, verifyUtxos, waitForRoot, walletAuthTransactionMessageBinds, withShieldRetries, withTiming, withdrawFeeFor };
10391
+ export { ADDRESS_SHAPES, type AccountSignatureScheme, type AccountWallet, type ArrivalTick, type ArrivalTickDeps, BRIDGE_DEPOSIT_INDEX_LIMIT, BRIDGE_DISCOVERY_GAP, BRIDGE_ESCROW_LABEL, BRIDGE_ESCROW_LABEL_V2, BRIDGE_FINISH_BACKOFF_MS, BRIDGE_LOCK_PREFIX, BRIDGE_NOTE_INDEX_DELAY_MS, BRIDGE_NOTE_INDEX_GIVE_UP_MS, BRIDGE_NOTE_INDEX_POLL_MS, BRIDGE_ONCHAIN_POLL_MS, BRIDGE_ORDER_MAX_LIVE_MS, BRIDGE_SEND_WINDOW_MARGIN_MS, BRIDGE_SIGNED_RAIL, BRIDGE_STALL_AFTER_MS, BRIDGE_STATUS_POLL_MS, BUILD_ALLOWS_LOCAL_ENDPOINTS, type BoundDeposit, BridgeApiError, type BridgeArrivalResult, type BridgeAssessmentContext, type BridgeAssessmentReasonCode, type BridgeCarriedResponse, type BridgeDeliveryFacts, type BridgeDeliveryState, type BridgeDeposit, BridgeDepositBelowMinimumError, type BridgeDepositReadiness, type BridgeDepositState, type BridgeFinishOutcome, BridgeIndexError, type BridgeIndexErrorCode, type BridgeIndexStore, type BridgeKeyValueStorage, type BridgeLock, BridgeLockBusyError, type BridgeOptionAssessment, type BridgeOptionRefusalCode, type BridgeOptionVetRequest, type BridgeOptionVetResult, type BridgeOrder, type BridgeOrderContext, BridgeOrderError, type BridgeOrderErrorCode, type BridgeOrderEvent, type BridgeOrderFailureCode, type BridgeOrderLedger, type BridgeOrderLedgerOptions, type BridgeOrderState, type BridgePaymaster, type BridgePendingStage, type BridgeQuoteAssessment, type BridgeQuoteBinding, type BridgeQuoteInput, BridgeQuoteRequestError, type BridgeQuoteRequestErrorCode, type BridgeRail, type BridgeRailAttestation, type BridgeRailProblem, type BridgeRailQuoteOption, type BridgeRailQuoteRequest, type BridgeRailQuoteResponse, type BridgeRailStatusResult, type BridgeRecovery, type BridgeRecoveryResult, type BridgeRecoveryStatus, type BridgeReservation, type BridgeSendState, type BridgeStatusOrigin, type BridgeTerminalKind, type BridgeTokenAmount, type BridgeTransport, BridgeUnavailableError, type BuildRecipientDeliveryNotesParams, CHAIN_NOTE_SALT_BITS, CLEANUP_FEE_BUDGET, CLOAK_ACCOUNT_MESSAGE, CLOAK_PRODUCTION_RELAY_URL, CLOAK_PROGRAM_ID, CLOAK_TOKENS, COLLECTOR_FEE_ESTIMATE_BASE_UNITS, type CarriedResponse, type ChainNoteTxType, type CircuitVerificationResult, type ClaimPaymentLinkOptions, type ClaimablePaymentLink, type CleanupResult, type Cloak, type CloakAccountKeys, type CloakAddress, type CloakBalance, CloakCallError, type CloakCallErrorDetails, type CloakConfig, CloakError, type CloakErrorCategory, type CloakEvent, CloakKeyError, type CloakKeyPair, type CloakNote, type CloakNoteList, type CloakNoteView, type CloakQuote, type CloakReceipt, type CloakRpc, type CloakStorage, type CloakToken, type CloakTokenInfo, type CommitmentEntry, type CommitmentsResponse, type CompactChainNote, type ComplianceReport, type ComplianceTxType, type ConfirmSettlementParams, type ConnectedWallet, type CreateCloakOptions, type CreatePaymentLinkRequest, type CreateRecoverableDepositUtxoParams, type CustomWallet, DEFAULT_CIRCUITS_URL, DEFAULT_TRANSACTION_CIRCUITS_URL, DELIVERY_MEMO_TAG, DELIVERY_REGISTRY_SEED, DUST_BURN_CEILING, type DeliveredNote, DepositError, type DepositFundingTarget, type DepositInstructionParams, type DepositMinimumHint, type DepositNoteSecrets, type DepositOptions, type DepositOutcome, type DepositRef, type DepositResult, type DepositStatus, type DiscoverOptions, type DiscoverSwapRefundsOptions, type DiscoveredSwapRefund, DoNotRetry, ECONOMIC_MINIMUM, EVM_GAS_SAFETY_FACTOR, EVM_RECEIPT_DEADLINE_MS, EVM_TRANSFER_GAS_UNITS, EXPECTED_CIRCUIT_HASHES, type Eip6963ProviderDetail, type EncodeNoteIndexPageParams, type EncryptedMetadataBundle, type EncryptedNote$1 as EncryptedNote, type EncryptedStorageOptions, type ErrorCategory, EvmOriginError, type EvmOriginErrorCode, type EvmReceiptVerdict, type EvmRequest, type EvmTransactionRequest, type EvmTxParams, type ExpandedSpendKey, type ExpectedDeposit, type ExternalFeePayerAdapter, FEE_BUDGET, FIXED_FEE_LAMPORTS, type FinishBridgeContext, type FinishBridgeOptions, type ForwardResult, type FundingPlan, type Groth16Proof, type IndexedRecoveredNote, type IndexedRecoveredNoteKind, InsecureRandomnessError, InvalidCloakAddressError, type JudgedBridgeOption, type KeyValueStore, LAMPORTS_PER_SOL, type LegacyWalletAdapter, type WalletSigner as LegacyWalletSigner, LocalStorageAdapter, type LogLevel, type Logger, type LookupTable, MAINNET_RENT_0, MAINNET_RENT_1, MAX_RECEIVER_INDEX, MAX_REQUEST_KEYS, MERKLE_TREE_HEIGHT, MIN_DEPOSIT_LAMPORTS, MIN_DEPOSIT_SPL_BASE_UNITS, MOVE_FEE_BUDGET_LAMPORTS, type MasterKey, type MatchChangeNoteParams, type MatchDepositNoteParams, type MatchSwapRefundLeafParams, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, MerkleTree, type MessageSigner, type MoveOutcome, type MoveReason, type MoveReceiverFundsResult, NATIVE_SOL_MINT, NETWORKS, NON_REFUNDING_MIN_SEND_BASE_UNITS, NOTE_INDEX_NO_LEAF, NOTE_INDEX_PAGE_SIZE, type Network, type NetworkDirection, type NetworkEntry, type NetworkFamily, type NetworkRail, type NetworkToken, NonRepeatableSignatureError, 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 OpenWalletAccountOptions, type OutsideFunds, PAYOUT_COLLECTOR_INDEX_BASE, PAYOUT_DEADLINE_MARGIN_MS, PAYOUT_DESTINATION_ASSETS, PAYOUT_NETWORKS, PAYOUT_ORIGIN_ASSET, PAYOUT_QUOTE_PATH, PAYOUT_REFUND_INDEX, PREPARED_SHIELD_HOLD_MS, PREPARED_SHIELD_POLL_MS, type ParseNoteIndexPageOptions, type ParsedDeliveryCarrier, type PaymasterGrant, type PaymasterNotReadyCode, type PaymasterTopUpCommit, type PaymasterTopUpExpectation, type PaymasterTopUpQuote, type PaymasterTopUpResult, type PaymentLinkResult, type PaymentLinkView, type PaymentRequestLink, type PaymentRequestView, type PayoutContext, type PayoutDelivery, type PayoutNetwork, PayoutNotReady, type PayoutPendingStage, PayoutPlanError, type PayoutPreview, type PayoutProgress, type PayoutQuote, PayoutQuoteRejected, type PayoutQuoteRequest, type PayoutRail, type PayoutRecipientCheck, type PayoutRecipientProblem, type PayoutRecord, PayoutRefused, type PayoutRoute, PayoutServiceError, type PayoutState, type PayoutStorage, type PayoutStore, type PayoutTransport, type PayoutWithdraw, type PayoutWithdrawalLeg, type PayoutWithdrawalPlan, type PendingDeposit, type PendingWithdrawal, type PoolFeeConfig, type PostFailureVerdict, type PreparedBridgeShield, type PreparedPayout, type PreparedShieldLetGo, type QuoteRequest, RECIPIENT_DELIVERY_CIPHERTEXT_LEN, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN, RECIPIENT_DELIVERY_NONCE_LEN, RECIPIENT_DELIVERY_NOTE_BYTES, RECIPIENT_DELIVERY_PLAINTEXT_LEN, RECIPIENT_DELIVERY_TAG_LEN, RELAY_BATCH_AUTH_MAX_ITEMS, RELAY_ORIGIN_ALLOWLIST, REQUEST_AUTH_BATCH_DOMAIN, REQUEST_AUTH_BATCH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_AGE_SECONDS, REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, REQUEST_KEY_GAP_LIMIT, REQUEST_KEY_ROOT_SOURCE, type RawBridgeAttestation, type RawBridgeQuoteOption, ReceiverMoveError, type ReceiverMoveErrorCode, type RecipientDeliveryNote, type RecipientKind, type RecognizeWalletOptions, 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, type RelayCapability, RelayInternalError, RelayService, type RelaySubmissionResult, type RentRates, type RequestKeyRootSource, type RequestKeys, type RequestPaymentRequest, type RestoredNote, type RestoredNotes, type ResumeProblem, type ResumeResult, type ResumedItem, RetiredCloakAddressError, type RetryHooks, type RevealBridgeRouteInput, type RiskQuoteInstructionResponse, RootNotFoundError, type RunBridgeDepositHooks, SCANNER_SUPPORTS_TRANSACT_SWAP, SELF_FUNDED_ALT_BUDGET_LAMPORTS, SELF_FUNDED_ALT_FEE_LAMPORTS, SELF_FUNDED_ALT_RENT_LAMPORTS, SIGN_IN_MESSAGE, SOLANA_USDC_ONECLICK_ASSET, SUI_FALLBACK_MINIMUM_BASE_UNITS, SUI_MAINNET_USDC_COIN_TYPE, SUI_NATIVE_COIN_TYPE, SanctionsQuoteError, type ScanOptions, type ScanRecipientDeliveryOptions, type ScanResult, type ScanSummary, type ScannedTransaction, type SendRequest, type SettlementConnection, type SettlementContext, type SettlementStatus, type SettlementVerdict, SettlementVerificationError, ShieldPoolErrors, type ShieldPoolPDAs, type ShieldRequest, type SignedRelayAuthPayload, SimpleWallet, type SpendKey, type SpendOptions, type StorageAdapter, StoredAccountRequiredError, type SubmitTransactToRelayArgs, type SuiTransactionJson, type SwapOptions, type SwapParams, type SwapRefundAuthorization, type SwapRefundShape, type SwapResult, type SweepResult, TERMINAL_FAILURE, TOKEN_2022_PROGRAM_ADDRESS, 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, type TransactionBytesWallet, 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 VettedOneClickDeposit, type ViewKey, type ViewingKeyPair, WALLET_ADDED_PROGRAMS, WITHDRAW_FEE_BPS, WITHDRAW_FIXED_FEE, type WalletAccount, type WalletAdapterBridgeOptions, type WalletChain, type WalletKind, type WalletRef, WalletSignatureChangedError, type WalletSigner$1 as WalletSigner, type WalletUtxo, type WatchBridgeArrivalOrder, type Web3Module, type WithdrawOptions, type WithdrawRequest, type WithdrawSubmissionResult, accountMeta, addressBytes, addressFromBytes, addressFromPublicKey, advancePayout, allocateBridgeReceiver, assertDirectSubmissionLanded, assertInputMints, assertRelayServesDeposits, assertSendableCloakAddress, assertShieldable, assertTransactionCircuitIntegrity, assessBridgeFinishFailure, assessBridgeOption, assessBridgeOptions, assessBridgeQuote, bigintToBytes32$1 as bigintToBytes32, bigintToHex, bindDepositQuote, bridgeDepositKey, bridgeDepositRails, bridgeDepositReadiness, bridgeQuoteMatches, bridgeReceiverLockName, bridgeReceiverSigner, bridgeRecoveryStatusOf, bridgeTopUpTotal, bridgeTransportFromFetch, bridgeViabilitySent, browserBridgeIndexStore, browserBridgeIndexStoreKeys, bufferedPaymasterFee, buildAuthTransactionMessage, buildEvmTransfer, buildMerkleTree, buildMerkleTreeFromChain, buildMerkleTreeFromRelay, buildRecipientDeliveryNotes, buildRelayAuthPreimage, buildRelayBatchAuthMessage, buildTransactRequestBody, buildTransactionMessage, bytesToHex, calculateFee, calculateFeeBigint, calculateRelayFee, canPrepareBridgeShield, canRebuildMerkleTreeFromChain, canSendBridgeOrder, canServeDeposits, canonicalJson, canonicalPayloadString, carryBridgeResponse, chainNoteFromBase64, chainNoteToBase64, checkBridgeReceiverFundable, checkPaymasterReady, checkPayoutRecipient, choosePayoutRoute, classifyBridgeTerminal, classifyEvmProviderError, classifyPostFailure, classifyRecipient, classifyRelayError, cleanupReceivingAddress, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, cloakBridgeRail, cloakKeyToMasterSeed, computeChainNoteHash, computeExtDataHash, computeMerkleRoot, computeNoteIndexChain, computeProofForLatestDeposit, computeProofFromChain, computeSignature, computeSwapRefundCommitment, computeCommitment as computeUtxoCommitment, computeNullifier as computeUtxoNullifier, confirmSignature, confirmTransactSettlement, copyNoteToClipboard, createArrivalTick, createBridgeOrderLedger, createBridgeRecovery, createCloak, createCloakError, createCloakRpc, createDepositInstruction, createLogger, createRecoverableChangeUtxo, createRecoverableDepositUtxo, createRelayBatchAuthCoordinator, createUtxo, createZeroUtxo, decodeClaimablePaymentLink, decodePaymentRequestLink, decryptCompactChainNote, decryptComplianceMetadataWithMasterKey, decryptTransactionMetadata, defaultDepositToken, depositFromDerivedKey, depositMinimumHint, depositNetworks, depositTokens, deriveBridgeReceiver, deriveChangeNoteBlinding, deriveCloakAccountKeys, deriveDepositNoteBlinding, deriveDiversifiedViewingKey, deriveDiversifier, deriveFundingTargets, deriveInputNullifierPdas, deriveLegacyBridgeReceiver, deriveLegacyDepositNoteSecrets, deriveLegacySwapRefundAuthorization, derivePayoutCollector, derivePayoutRefundKey, derivePublicKey, deriveRequestKeyRange, deriveRequestKeyRoot, deriveRequestKeys, deriveSpendKey, deriveSwapRefundAuthorization, deriveSwapRefundBlinding, deriveSwapRefundKeypair, deriveUserCompliancePublicKey, deriveUserComplianceScalar, deriveUtxoKeypairFromSpendKey, deriveViewKey, deriveViewingKeyFromNk, deriveViewingKeyFromSpendKey, deriveViewingKeyFromUtxoPrivateKey, deserializeUtxo, detectNetworkFromRpcUrl, discoverBridgeDeposits, discoverEvmWallets, discoverSwapRefunds, downloadNote, encodeCloakAddress, encodeDeliveryCarrierMemo, encodeNoteIndexItem, encodeNoteIndexPage, encodeNoteSimple, encodeRecipientDeliveryNote, encryptCompactChainNote, encryptNoteForRecipient, encryptTransactionMetadata, encryptTransactionMetadataBundle, encryptedStorage, ensureEvmChain, ensureFreshPayout, evmCannotPayGas, evmChainIdHex, evmNetworkForChainId, expandSpendKey, explainRelayAuthRejection, explorerUrl, exportKeys, exportNote, exportWalletKeys, familyOfAddress, fetchAccountBytes, fetchCommitments, fetchLatestBlockhash, fetchLookupTables, fetchNoteIndexHead, fetchNoteIndexPage, fetchPayoutDelivery, fetchPayoutQuote, fetchRelayCapability, fetchRiskQuoteInstruction, fetchRiskQuoteIx, fetchSignaturesForAddress, fetchSuiFallbackDepositAddress, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, findPayoutBySignature, findPayoutFundsOutside, findProgramAddress, finishBridgeDeposit, finishPayout, formatAmount, formatBaseUnits, formatCloakKey, formatComplianceCsv, formatErrorForLogging, formatSol, forwardCollectedPayout, freePayoutCollector, 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, isBridgeApiError, isBridgeDepositBelowMinimum, isBridgeDepositIndex, isBridgeDust, isBridgeIndexError, isBridgeLockBusy, isBridgeOrderSettled, isBridgeQuoteRequestError, isBridgeSendWindowOpen, isBrowser, isBrowserLike, isCloakAddress, isCloakCallError, isCollectorMovable, isDebugEnabled, isDirectlyPayable, isEvmOriginError, isEvmTxHash, isMessageSigner, isPayoutDeadlinePassed, isPayoutExpired, isPayoutNetwork, isPlausibleSignature, isReactNative, isReceiverMoveError, isRootNotFoundError, isSubmissionOutcomeUnknownResponse, isTerminalFailure, isTerminalPayout, isValidHex, isValidRelayClientId, isValidRpcUrl, isValidSolanaAddress, isWalletRejection, isWithdrawAmountSufficient, isWithdrawable, leavesTooLittleForGas, linkWallet, listBridgeDeposits, livePayoutNetworksFor, loadPendingDeposits, loadPendingWithdrawals, loadVerifiedCircuitArtifacts, masterSeedToCloakKey, matchChangeNote, matchDepositNote, matchSwapRefundLeaf, maxSendableEvm, mayRetry, memoryBridgeIndexStore, memoryPayoutStore, memoryStorage, messageSignerFromCallback, moveBridgeDepositToWallet, moveMayHaveChangedBalance, moveReasonForDeposit, moveReceiverFundsToWallet, moveToWalletOutcome, movesTokensOut, mustAskNetwork, nativeGasFloor, nativeGasReserve, needsSelfFundedAlt, networkById, networksSharingAddressFormat, newFallbackPayoutRecord, newPayoutRecord, nextBridgeOrderState, nextBridgeReceiverIndex, nextCollectorIndex, normalizeAffiliateCode, oneClickAssetId, openRecipientDeliveryNote, openWalletAccount, parseAmount, parseBaseUnits, parseBridgeDelivery, parseCloakAddress, parseDeliveryCarrierMemo, parseError, parseNote, parseNoteIndexItem, parseNoteIndexPage, parseRelayErrorResponse, parseRelayErrorSignature, parseTransactionError, partialWithdraw, partiallySignTransaction, payOutFromPrivateBalance, payoutBreakdown, payoutMinimum, payoutNetworkFor, payoutNetworks, payoutProgress, payoutQuoteRequestBody, payoutRailUnavailable, payoutStoreKey, payoutWithdrawer, pickBestBridgeOption, planPayoutWithdrawals, poseidonHash, preflightCheck, preflightNullifiers, prepareBridgeShield, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, preparePayout, preparePayoutOrFinish, previewPayout, programInstruction, proofToBytes, pubkeyToFieldElement, pubkeyToLimbs, quotePaymasterTopUp, randomBytes, randomChangeNoteSalt, randomDepositNoteSalt, randomFieldElement, readBridgeBody, readEvmBalance, readEvmGasReserve, readMerkleTreeState, readPayoutDelivery, readPayoutQuoteResponse, readPoolFeeConfig, readReceiverTokenBalance, readRelayCapability, readRent, readSuiFallbackResponse, receiverGrantLamports, recipientDeliveryNoteToBase64, recognizeWallet, recognizeWallets, recordPayoutWithdrawal, recoverBridgeDeposits, recoverNotesFromIndex, refreshPayout, registerViewingKey, relayBridgePaymaster, relayBridgeTransport, relayPayoutTransport, relayRequestDigestHex, removePendingDeposit, removePendingWithdrawal, renderAssessment, resolveCircuitsBase, resolveDepositToken, restoreNotes, retryDelayMs, revealBridgeRoute, runBridgeDeposit, runPaymasterTopUp, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, scanRecipientDeliveryNotes, scanTransactions, sdkLogger, selectUtxos, sendEvmDeposit, sendInstructions, sendRawTransaction, sendTransaction, serializeAuthTransactionMessage, serializeNote, serializeUtxo, setCircuitsPath, setDebugMode, settlePayout, signCompiledTransaction, signMessageBytes, signRelayAuthPayload, signTransaction, signerFromKeypair, signerFromSecretKey, signerFromTransactionBytes, signerFromWalletAdapter, spendKeyFromCloakKey, spendKeyFromSignature, splitTo2Limbs, splitWaitingBridgeDeposits, storagePayoutStore, submitTransactToRelay, sumUtxoAmounts, swapUtxo, swapWithChange, sweepToWalletKey, toAddress, toComplianceReport, transact, transactBatch, transactionBase64, transactionBytes, transactionFromBytes, transactionWireSize, transfer, truncate, tryDecryptNote, unfinishedPayouts, unlinkWallet, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, bigintToBytes32 as utxoBigintToBytes32, utxoEquals, hexToBigint as utxoHexToBigint, validateDepositParams, validateNote, validateOutputsSum, validatePaymasterTopUpTransaction, validateRoot, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity, verifyPayoutQuote, verifyQuoteSignature, verifyUtxos, vetBridgeQuoteOption, vetOneClickDepositOption, waitForNoteInIndex, waitForRoot, waitingBridgeDeposits, walletAuthTransactionMessageBinds, watchBridgeArrival, watchEvmReceipt, watchPayout, webStorage, withBridgeLock, withReceiverLock, withShieldRetries, withTiming, withdrawFeeFor, withdrawalGrossFor, withdrawalNetFor };