@cloak.dev/sdk 0.2.14 → 0.2.20-staging.9533cda

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,41 +7,75 @@ the README's "Version and compatibility" section and in the git history.
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ## [0.2.14]
11
-
12
- ### Fixed
10
+ ## [0.2.20] - unreleased
13
11
 
14
- * A Ledger driven through Phantom, Solflare or Backpack can authenticate to the relay again. With
15
- the hardware-wallet envelope on, these wallets change the 0 SOL auth transaction before the device
16
- signs it (Phantom adds compute-budget instructions to a transaction that has none, Solflare adds
17
- its guard instructions), so the signature covered the wallet's message while the relay rebuilt
18
- the SDK's and refused it. In production this stopped every such user at viewing-key registration
19
- with "Signature verification failed". `signRelayAuthPayload` now returns the message the wallet
20
- signed as `txMessage` when it differs from ours and still binds the payload (the wallet as fee
21
- payer and only signer, `sha256(payload)` as the blockhash, our 0-lamport self-transfer still in
22
- it), and every relay request carries it as `auth_tx_message` (`tx_message` on
23
- `/viewing-key/register`). The wallet may add only what wallets add on their own: instructions of
24
- ComputeBudget (Phantom, Solflare) and Lighthouse (Solflare), the programs seen in real Phantom and
25
- Solflare messages. Anything else next to the transfer is how a phishing page would disguise the
26
- envelope, so it is refused, as is a message that fails the relay's `sanitize()` rules or whose
27
- signature does not cover it. All of these are refused before anything is sent. A wallet that signs the
28
- envelope unchanged sends exactly what it sent before. Needs the matching relay release; an older
29
- relay ignores the field.
12
+ One call per action. `createCloak({ wallet })` takes whatever wallet the user has, opens the
13
+ account from one wallet signature (the Cloak mobile app's scheme) or a cloak.ag Cloak Key, and
14
+ shields, sends, withdraws, pays out, makes payment links and requests, and reads the balance with
15
+ one call each. Everything earlier stays exported for full control. See
16
+ `examples/one-call/partner.ts`.
30
17
 
31
18
  ### Added
32
19
 
33
- * `walletAuthTransactionMessageBinds(sender, payload, bytes)`, the client copy of the relay's
34
- `wallet_tx_message_binds` (pinned to it by a shared corpus,
35
- `src/__tests__/fixtures/wallet-tx-message-corpus.json`), `WALLET_ADDED_PROGRAMS`, and the
36
- `SignedRelayAuthPayload` type. `WALLET_ADDED_PROGRAMS` mirrors the relay and grows when a new
37
- wallet is seen adding another program; read it from the SDK version you run, do not copy it.
20
+ * **`createCloak`.** `shield` (from Solana: SOL, USDC, USDT, BRS, each into its own pool; from Base:
21
+ USDC or ETH; from Polygon and Sui: USDC; all three arrive as USDC), `send` (to a `cloak_` address
22
+ privately, or to a Base, Polygon or Sui address), `withdraw` (to a Solana address: exactly the
23
+ amount arrives, the fee on top; or to another chain), `balance`, `quote`, `notes`. Every call
24
+ names its token and refuses a route that cannot carry it before anything moves. Receipts are
25
+ plain decimal strings with every transaction id.
26
+ * **BRS between Solana and Base through LayerZero, both ways, 1:1.** `shield({ from: baseWallet,
27
+ token: "BRS" })` sends the BRS through BRS's own OFT to a receiving address on Solana, and asks
28
+ LayerZero's executor to drop the SOL that address needs, so the shield pays for itself: the Base
29
+ wallet pays one fee in ETH (about 0.00145 on 2026-11-27) and needs no SOL. `send({ to: "0x…",
30
+ chain: "base", token: "BRS" })` withdraws the BRS and the SOL for LayerZero's fee (about 0.0154,
31
+ from the private SOL balance) to a one-time sender derived from the account, which bridges it;
32
+ no wallet of the user's is involved. Both are finished by `resume` if they stop halfway. The
33
+ calls are hand-encoded (no LayerZero SDK) and pinned to live transactions; every account of the
34
+ Solana send is read from LayerZero's own configuration and the route is refused, before any money
35
+ moves, on any change this version cannot build for. Both directions are also refused
36
+ (`route.unavailable`) while the relay does not serve the BRS pool, the same rule the 1Click route
37
+ applies, so no BRS is left waiting at a receiving address. Receipts and quotes report the fee paid
38
+ in the other chain's coin as `networkFee`.
39
+ * **Wallets from anywhere.** One recognizer (`recognizeWallet`) for the wallet-adapter context and
40
+ adapters, Wallet Standard wallets (Phantom, Solflare, Backpack, Slush, Suiet; driven with bytes,
41
+ no web3.js), kit signers and web3.js key pairs (a signer that can also send, such as Privy's
42
+ server signer, is handed over without that part), Privy 2.x and 3.x, legacy adapters (Ledger),
43
+ EIP-1193 providers and EIP-6963 discovery (`discoverEvmWallets`), viem `WalletClient` and ethers
44
+ `Signer` server keys (one key passed once per network becomes one wallet), Sui key pairs, and a
45
+ five-field catch-all. A shield from Sui builds the version-2 transaction JSON the user's wallet
46
+ completes, from coins read through Mysten's Sui GraphQL (a new pinned egress).
47
+ * **Accounts and addresses, compatible with cloak.ag and the mobile app.** `CLOAK_ACCOUNT_MESSAGE`,
48
+ `spendKeyFromSignature` (Solana: the mobile app's exact scheme; EVM and Sui: canonical, low-s),
49
+ `deriveCloakAccountKeys`, Cloak Keys (`cloakKeyToMasterSeed`, `masterSeedToCloakKey`), `cloak_`
50
+ addresses (`encodeCloakAddress`, `parseCloakAddress`; v1 is refused for sending, as on the
51
+ website), linked wallets (`openWalletAccount`, `linkWallet`), and a stored account key with 24
52
+ backup words for a wallet that cannot sign repeatably (passkeys). Pinned by 61 vectors generated
53
+ from the website's and the mobile app's own code.
54
+ * **No Solana wallet needed.** Relay requests are signed by a key derived from the account
55
+ (`account/relay-signer.ts`), so an EVM-only or business account never needs SOL, and spends ask
56
+ for no wallet prompt.
57
+ * **Notes older clients left exposed** (mobile external-wallet deposits, mobile in-app wallet notes)
58
+ are found through the viewing keys those clients used and moved into the account before they are
59
+ spent (`secureExposedNotes`, on by default).
60
+ * **Payment links and requests** in cloak.ag's formats: `createPaymentLink` (its secret derived from
61
+ the account key, so a lost URL can be rebuilt), `claimPaymentLink` (into the private balance, or to
62
+ a Solana address), `paymentLinks`, `requestPayment`, `payRequest`, `requests`,
63
+ `decodeClaimablePaymentLink`, `decodePaymentRequestLink`.
64
+ * **Business mode.** `encryptedStorage(db, secret)` (AES-256-GCM bound to key and network),
65
+ `notes().encryptToSave(secret)`, `restoreNotes`, `cloak.importNotes`, and `ref` on shield, send and
66
+ withdraw (one money call per business reference).
67
+ * **Finishing what stopped.** Open bridge deposits and unfinished payouts are finished shortly after
68
+ start, again while an order is open, and by `cloak.resume()`; each is reported as a `finished`
69
+ event. A shield from another chain checks the wallet's funds and gas before any address is
70
+ reserved.
71
+ * **`CloakCallError`** (`isCloakCallError`): a stable dotted `code`, `retryable`, and when money is in
72
+ flight, `moneyAt` and `next`.
38
73
 
39
74
  ### Changed
40
75
 
41
- * `signRelayAuthPayload` verifies the signature a transaction-only wallet returns over the message
42
- it returned, before anything is sent: a wallet that signed other bytes is refused with a sentence
43
- instead of a 401 after the proof. Message-mode signatures are returned unchecked, as before, so
44
- callers that verify them and fall back to the envelope (web's affiliate signer) keep working.
76
+ * The relay-origin egress lock lists one more chokepoint, `wallets/sui.ts::suiGraphqlFetch`, checked
77
+ by `assertAllowedSuiEndpoint` against the one pinned Sui GraphQL endpoint. `createCloak` guards
78
+ its RPC on entry, so a production build refuses a local RPC before any wallet is asked anything.
45
79
  * `TransactOptions.affiliateCode`, `TransactOptions.onWarning` and `normalizeAffiliateCode` are now
46
80
  public API. Any approved Cloak partner can pass their code from their own app and earn commission
47
81
  on the withdrawals, sends to an address and swaps it makes; before, only Cloak's own web and
@@ -49,6 +83,257 @@ the README's "Version and compatibility" section and in the git history.
49
83
  on fee-bearing requests, normalised, signed inside the request, and left out (reported through
50
84
  `onWarning`) when invalid. Counting codes from other apps needs the matching relay release.
51
85
 
86
+ ### Fixed
87
+
88
+ * A Ledger behind Phantom, Solflare or Backpack can authenticate to the relay again: when the wallet
89
+ changes the 0 SOL auth transaction before the device signs it, the message it signed is sent as
90
+ `auth_tx_message` (`tx_message` on `/viewing-key/register`), only when it still binds the
91
+ request and adds nothing but ComputeBudget and Lighthouse instructions
92
+ (`walletAuthTransactionMessageBinds`, `WALLET_ADDED_PROGRAMS`). A transaction-only wallet's
93
+ signature is checked locally before anything is sent; message-mode signatures are returned
94
+ unchecked, as before. Port of cloak-ag/sdk#84 (0.2.14 on main); needs the relay of
95
+ cloak-ag/services#262 (#263 on staging).
96
+
97
+ ## [0.2.16]
98
+
99
+ Everything a client needs to run the bridge with the SDK alone, so a partner (for example on Base)
100
+ gets the same flows and rules as the website: deposits from Base, Polygon or Sui into the private
101
+ balance, payouts to Base, Polygon or Sui, and the exits for money that cannot be added. Moved out of
102
+ the website, which now calls these. See `examples/bridge/base-partner.ts`.
103
+
104
+ ### Added
105
+
106
+ * **Exact amounts for any token.** `parseBaseUnits(input, decimals)` turns a typed decimal into base
107
+ units and returns `null` for a sign, an exponent, a comma, a bare point or more fractional digits
108
+ than the token has, instead of truncating. `formatBaseUnits(amount, decimals)` is its exact
109
+ inverse. Neither goes through a float, so 18-decimal amounts keep every digit.
110
+ * **Deposit receiver indices stop where payouts begin.** `BRIDGE_DEPOSIT_INDEX_LIMIT` (8_999) and
111
+ `isBridgeDepositIndex(n)`: the payout refund key and collectors are derived in the same index
112
+ space from 8_999 up, so a deposit index is checked against this limit, not `MAX_RECEIVER_INDEX`.
113
+ * `bridgeDepositKey(deposit)`: `current:<index>` or `legacy:<index>`, since a legacy and a current
114
+ receiver can share an index.
115
+ * **EVM chain ids.** `NetworkEntry.evmChainId`, `evmChainIdHex(networkId)` (`"0x2105"` for Base)
116
+ and `evmNetworkForChainId(id)` (accepts the number or the hex a wallet reports).
117
+ * **Exact Sui coin types.** `NetworkToken.coinType`, `SUI_NATIVE_COIN_TYPE` and
118
+ `SUI_MAINNET_USDC_COIN_TYPE`. A Sui node's types are case-sensitive; a token's `contract` stays
119
+ the lowercase spelling the bridge service quotes with.
120
+ * `defaultDepositToken(networkId)` and `resolveDepositToken(networkId, symbol?)`: only tokens a
121
+ deposit offers, not every token the table lists. `depositNetworks({ liveOnly: true })` and
122
+ `payoutNetworks({ liveOnly: true })` drop planned networks. `depositMinimumHint(networkId, symbol)`
123
+ returns the static hint, a USDC figure, for USDC only.
124
+ * **Who can be paid, in one place.** `classifyRecipient(input)` (Solana by decoding, not by shape;
125
+ Sui; EVM; a `.sol` name; an address on an unpaid network; invalid). `payoutNetworkFor(address,
126
+ chosenNetwork?)`: a Sui address names its own network, an EVM address is a payout only with a
127
+ chosen live EVM network, never a guessed one. `livePayoutNetworksFor(family)` for the picker.
128
+ `payoutMinimum(network)` (3.5 USDC on Sui). `checkPayoutRecipient({ address, network?, token,
129
+ amountBaseUnits? })` returns `{ ok: true, network }` or a reason code: `not_a_payout_address`,
130
+ `network_required`, `network_unavailable`, `token_unsupported`, `below_minimum` with the minimum.
131
+ * **Deposits from Base and Polygon, from any EVM wallet.** Everything takes an EIP-1193 `request`
132
+ function, so a browser wallet, an embedded wallet or a server-side client works the same, with no
133
+ EVM library. `sendEvmDeposit(request, { networkId, token, from, to, amountBaseUnits })` builds the
134
+ transfer (`buildEvmTransfer`: a value transfer for the coin, `transfer(address,uint256)` for
135
+ USDC), switches the wallet to the network's chain and checks it again before sending
136
+ (`ensureEvmChain`), and returns the hash. `watchEvmReceipt` answers confirmed, failed, cancelled
137
+ or unknown (never "failed" for a receipt that did not come). `readEvmBalance` refuses an empty
138
+ token answer rather than reading it as zero. Gas: `readEvmGasReserve`, `nativeGasReserve`,
139
+ `nativeGasFloor` (0.0001 of the coin, for an L2's data fee), `maxSendableEvm`,
140
+ `leavesTooLittleForGas`, `evmCannotPayGas`. Refusals are `EvmOriginError` with a code
141
+ (`EVM_WRONG_CHAIN`, `EVM_REJECTED`, `EVM_CHAIN_NOT_ADDED`, ...), checked with `isEvmOriginError`.
142
+ * **The payout lifecycle, so a caller does not rebuild it.** Stores: `storagePayoutStore(storage,
143
+ key)` over any sync or async key-value storage, with `payoutStoreKey(wallet | { link })` keeping
144
+ the website's existing key format, and `memoryPayoutStore()`. `preparePayoutOrFinish` finishes an
145
+ earlier payout to the same recipient that has money moving instead of paying again.
146
+ `ensureFreshPayout` retires a reservation whose deadline is too close, after checking on chain
147
+ that nothing reached it, and reserves again. `findPayoutBySignature` and `payoutProgress` (the
148
+ tracker's steps, as data). Exact sizing from the pool's live fee: `readPoolFeeConfig(rpc, mint)`,
149
+ `withdrawalNetFor(gross, fee)` and `withdrawalGrossFor(net, fee, legs?)`, the smallest withdrawal
150
+ that delivers what the rail quoted.
151
+ * **Planning a payout across notes.** `planPayoutWithdrawals(notes, netBaseUnits, fee)`: the fewest
152
+ notes, largest first, two per transaction (the fixed fee is charged per transaction), each
153
+ withdrawal sized to what is still owed so the rest stays private as change, and no leg that cannot
154
+ cover its own fee. Returns the legs and `deliveredBaseUnits` to prepare the payout for; throws
155
+ `PayoutPlanError` with `shortBaseUnits` when the notes cannot deliver the amount.
156
+ * **A whole payout in one call.** `payOutFromPrivateBalance(ctx, { id, network, recipient,
157
+ netBaseUnits, notes, withdraw })` refuses what cannot be paid (`PayoutRefused` with the reason),
158
+ plans the notes from the pool's live fee, finishes an earlier unfinished payout to the same
159
+ recipient instead of paying twice, reserves and saves before anything moves, makes each
160
+ withdrawal, and finishes (a collector forwards the exact amount). `payoutWithdrawer(spendOptions)`
161
+ is the `withdraw` to pass: `partialWithdraw` with the Merkle tree carried between legs and every
162
+ result kept for the change notes.
163
+ * **Exits that say how they ended.** `moveToWalletOutcome` runs `moveReceiverFundsToWallet` and
164
+ never throws: `moved`, `nothing`, `cancelled` (declined before signing), `needs_sol`,
165
+ `unconfirmed` (signed; may still land, with the signature when known), or `failed` with a code.
166
+ `moveMayHaveChangedBalance` says when to read again. `moveReasonForDeposit` is the offer rule:
167
+ only for a waiting deposit, once adding failed or it is too small to ever add.
168
+ `moveBridgeDepositToWallet` refuses anything but a waiting deposit and holds the receiver's lock,
169
+ the one adding to the balance holds, so the two never race. Payouts: `isPayoutDeadlinePassed`,
170
+ `isCollectorMovable` and `findPayoutFundsOutside` (the refund key from the keys alone, collectors
171
+ from the records; a failed read throws, never reads as zero).
172
+ * **One transport for every bridge call.** `BridgeTransport` (`get`/`post` of a service path):
173
+ `relayBridgeTransport(relayUrl)` calls Cloak's service directly under the origin lock;
174
+ `bridgeTransportFromFetch(send)` routes through a website's own proxy. `cloakBridgeRail` and the
175
+ paymaster take either a relay URL or a transport, and every check on what comes back (quote
176
+ signature and binding, the paymaster shape check) still runs in the SDK.
177
+ * `BridgeApiError` (`status`, `code`, `retryable`) from the service's error body, with
178
+ `isBridgeApiError(e, code?)`; `readBridgeBody` and `carryBridgeResponse` for custom transports.
179
+ * **Status amounts carry their token.** `status(depositAddress, rail, { originChain, originToken })`
180
+ returns `delivery` (`parseBridgeDelivery`): `amountIn` and `refundedAmount` are origin-token base
181
+ units tagged with that token (an ETH refund is wei, tagged ETH), `amountOut` is Solana USDC, plus
182
+ the pending `stage` and the transaction hashes. Without an origin the token is `null`.
183
+ * `classifyBridgeTerminal(status, { depositSeen, manual })`: `refunded`, `closed-received`,
184
+ `expired-no-deposit` or `closed-unfinished`. A reported `amount_in` counts only when the deposit
185
+ was seen or paid by hand.
186
+ * **A shipped paymaster.** `relayBridgePaymaster(target)` implements `BridgePaymaster`
187
+ (`quoteFee`, `quoteTopUp`, `topUp`). `quotePaymasterTopUp` returns the fee and the dust burn;
188
+ `runPaymasterTopUp(target, receiver, grant, commit?)` funds several destinations at a fee agreed
189
+ beforehand and refuses a `prepare` that charges any other fee, before R signs.
190
+
191
+ * **Receiver indices that are never handed out twice.** `createBridgeOrderLedger(store, ownerKey)`:
192
+ `allocate(deposits)` picks one past discovery, every unsettled reservation and the high-water
193
+ mark, and records it (mark raised, 24 h reservation, `BRIDGE_ORDER_MAX_LIVE_MS`) under a lock
194
+ before the rail is asked for an address; `abandon` / `settle` drop the reservation and never lower
195
+ the mark; `settleFinished(deposits)` closes shielded and moved-out orders; `peekNextIndex` for a
196
+ dry quote. Stores: `memoryBridgeIndexStore()`, `browserBridgeIndexStore(storage?)` (reads the
197
+ high-water key Cloak's website already wrote), or a partner's own `BridgeIndexStore`. Typed
198
+ `BridgeIndexError` (`BRIDGE_INDEX_EXHAUSTED`, `BRIDGE_INDEX_NOT_A_DEPOSIT_INDEX`).
199
+ `nextBridgeReceiverIndex` is the pure rule; `allocateBridgeReceiver` allocates and derives;
200
+ `discoverBridgeDeposits` scans `BRIDGE_DISCOVERY_GAP` past the mark, then settles.
201
+ * `withBridgeLock(name, fn)`: in-process, plus Web Locks across tabs where they exist.
202
+ `bridgeReceiverLockName(receiver)` names the per-receiver lock.
203
+
204
+ * **Quote decisions in the SDK.** `vetBridgeQuoteOption(raw, req, nowMs)` is the per-option check
205
+ `cloakBridgeRail().quote` runs (exported with the wire type `RawBridgeQuoteOption`); refusals carry
206
+ a `BridgeOptionRefusalCode`. `assessBridgeOption` / `assessBridgeOptions` judge vetted options
207
+ (`bridgeViabilitySent` never compares wei with USDC), `pickBestBridgeOption` ranks them,
208
+ `isBridgeSendWindowOpen` (signed deadline, `BRIDGE_SEND_WINDOW_MARGIN_MS`) gates paying an
209
+ allocated address, `bridgeQuoteMatches` binds a quote to the chain, token and amount it was for.
210
+ `bridgeTopUpTotal(heldLamports, { rent?, selfFundedAlt? })` is the receiver grant;
211
+ `checkBridgeReceiverFundable` asks the paymaster a real price for it; `assertRelayServesDeposits`
212
+ is the relay gate (`BridgeUnavailableError`); `bridgeDepositReadiness` is the form's readiness as
213
+ a code.
214
+ * `BridgeQuoteAssessment` gains `reasonCodes` and `sendAtLeast`; `checkPaymasterReady`'s refusal
215
+ gains `code` (`PaymasterNotReadyCode`).
216
+
217
+ * **The prepared shield, in the SDK and with the pool-minimum check.** `prepareBridgeShield(ctx, R,
218
+ noteSpendKey, expected)` proves the deposit while the bridge delivers, holds it up to
219
+ `PREPARED_SHIELD_HOLD_MS` for exactly `expected` to land, then funds R and the deposit's accounts
220
+ in one committed-fee top-up. It lets go before money moves (`outcome` null, `letGo()` says why:
221
+ below the pool minimum, a self-built table needed, no price, dust, another amount, hold expired,
222
+ released, receiver busy) and rejects only once the top-up was sent.
223
+ `finishBridgeDeposit(..., { prepared, order })` awaits it first and falls back by itself; `order`
224
+ settles the ledger on success and on the terminal below-minimum refusal.
225
+ * **One lock per receiver.** `withReceiverLock(receiver, fn, lock?)` refuses at once
226
+ (`BridgeLockBusyError`, `isBridgeLockBusy`) when another operation holds the receiver. The shield
227
+ and the prepared shield take it; the move to the wallet must take it too. `FinishBridgeContext.lock`
228
+ replaces the default for a multi-process partner.
229
+ * **Recovery.** `recoverBridgeDeposits` reports a `status` per deposit (`done`, `dust`,
230
+ `below-minimum`, `busy`, `failed`), skips dust by default (`isBridgeDust`,
231
+ `splitWaitingBridgeDeposits`), takes `stopOnFailure`, `only` and a `ledger`.
232
+ `createBridgeRecovery(ctx, opts)` adds memory (a final result is not retried at the same balance)
233
+ and backoff (`BRIDGE_FINISH_BACKOFF_MS`), with `run` / `stop` / `nextDueInMs` and no timers.
234
+ `assessBridgeFinishFailure` says whether a failed shield is safe to retry from R's balance after
235
+ it, never from hope. `waitForNoteInIndex(sync)` waits for the shield's note in the Note Index.
236
+
237
+ * **The arrival watcher.** `watchBridgeArrival(ctx, order, opts)` reads the receiver every
238
+ `BRIDGE_ONCHAIN_POLL_MS` and the signed rail's status at most every `BRIDGE_STATUS_POLL_MS`, acts
239
+ on a refunded/expired status only after a chain read, reports `onStalled` once after
240
+ `BRIDGE_STALL_AFTER_MS`, and resolves `arrived`, `closed` (with what is held and its
241
+ `classifyBridgeTerminal` kind; an empty close settles the order) or `aborted`. **Arrived means the
242
+ rail's guaranteed minimum landed**; less is `onPartial` and the watch goes on, so stray dust is
243
+ never auto-shielded into a below-minimum refusal. `createArrivalTick` is its timer-free core.
244
+ * **The deposit order.** `nextBridgeOrderState(state, event)` is the lifecycle as a pure reducer
245
+ (`waiting` with its `BridgeSendState`, `arrived`, `funding`, `shielded`, `closed`, `failed` with
246
+ `retryFrom`); an origin revert ends only the order whose own transfer it is. `canSendBridgeOrder`
247
+ (viable, inside the signed window, the order's own amount and token) and `canPrepareBridgeShield`
248
+ (exact quote, sent). `revealBridgeRoute(ctx, input)` allocates an address with every gate before
249
+ it: the quote still matches the input, token and rail offered, relay and paymaster asked again,
250
+ the index recorded before the rail is asked, the allocated quote judged again with the fresh fee;
251
+ a failure before an address abandons the reservation. `runBridgeDeposit(ctx, input, hooks)` is the
252
+ whole deposit in one call, with a `send` callback (e.g. `sendEvmDeposit`) and an optional
253
+ `watchOriginReceipt` (e.g. `watchEvmReceipt`).
254
+
255
+ ### Changed
256
+
257
+ * `BridgeRailStatusResult` gains `delivery` (null when the service sends none).
258
+ * `listBridgeDeposits` stops current receivers at `BRIDGE_DEPOSIT_INDEX_LIMIT` (was
259
+ `MAX_RECEIVER_INDEX + 1`): a deep scan no longer reports the payout refund key or a collector as a
260
+ deposit. Legacy receivers keep their own range.
261
+ * **A bridge deposit quote asks only the network's deposit rails** (`bridgeDepositRails`, the signed,
262
+ refunding rail everywhere today) unless `rails` names others, and a named rail outside them is
263
+ refused before anything is sent (`BridgeQuoteRequestError` `rail_not_offered`); an allocating
264
+ quote must name exactly one. Request refusals are `BridgeQuoteRequestError`s with codes; their
265
+ messages are unchanged.
266
+ * `finishBridgeDeposit` holds the receiver lock and refuses when it is busy; `BridgeRecoveryResult`
267
+ gains `status`, and `recoverBridgeDeposits` no longer attempts dust unless `skipDust: false`.
268
+ * `bridgeTopUpTotal` and the `SELF_FUNDED_ALT_*` constants live in `funder.ts`; the exports are
269
+ unchanged.
270
+ * A bridge quote is asked only for a token the network OFFERS for deposits
271
+ (`resolveDepositToken`), not any token its table lists.
272
+ * Bridge service errors from `cloakBridgeRail` and the paymaster are `BridgeApiError`s; the message
273
+ text is unchanged.
274
+
275
+ ## [0.2.15]
276
+
277
+ ### Added
278
+
279
+ * **Move it to my wallet.** `moveReceiverFundsToWallet({ rpc, receiver, mint, wallet })` moves the
280
+ whole token balance at a one-time receiving address to the connected wallet, in one transaction
281
+ the wallet pays for. It is the way out for money that cannot be shielded: a deposit refused
282
+ because the address also held outside money, an arrival under the pool minimum, and a payout
283
+ refunded to the refund key. It is public and links that address to the wallet; a caller must say
284
+ so first. Works for any receiver signer (current, legacy, the payout refund key), for Token and
285
+ Token-2022 mints. The receiver's token account is left open, so discovery keeps seeing the index
286
+ as used and it is never handed to a new deposit.
287
+ * `readReceiverTokenBalance(rpc, owner, mint, tokenProgram?)`: 0n only when the token account does
288
+ not exist; an RPC failure throws. Pass `tokenProgram` to skip reading the mint.
289
+ * Errors matched by code (`isReceiverMoveError(e, code)`). Before the wallet is asked:
290
+ `RECEIVER_MOVE_NOTHING_TO_MOVE`, and `RECEIVER_MOVE_WALLET_NEEDS_SOL` (the wallet cannot pay the
291
+ fee, plus its token account's rent when it has none; carries `needLamports` / `haveLamports`).
292
+ After: `RECEIVER_MOVE_WALLET_REJECTED` and `RECEIVER_MOVE_SEND_REFUSED` (nothing sent), and
293
+ `RECEIVER_MOVE_UNCONFIRMED` (sent, not seen confirmed; carries `signature`; a retry is safe).
294
+ `isWalletRejection(e)`, `MOVE_FEE_BUDGET_LAMPORTS`.
295
+
296
+ ### Changed
297
+
298
+ * `BridgeDepositState` gains `"moved-out"`: never shielded, emptied by a token transfer out, holds
299
+ nothing now. Its `BridgeDeposit` carries `moveSignature`. `waitingBridgeDeposits` and
300
+ `recoverBridgeDeposits` skip it. Money that lands after a move reports as `"arrived"` again.
301
+
302
+ ### Fixed
303
+
304
+ * **Bridge quotes name the owning wallet.** `BridgeRailQuoteRequest` gains a required
305
+ `solanaOwner` (the wallet that will control the shielded note), sent as `solana_owner`. The
306
+ bridge screens that wallet and answers 400 without it, so every `cloakBridgeRail().quote` failed
307
+ before this. An empty owner is refused before anything is sent.
308
+
309
+ ## [0.2.14]
310
+
311
+ ### Added
312
+
313
+ * **Networks.** `NETWORKS` is the one list of the networks money can come from or go to, with each
314
+ network's tokens, 1Click asset ids, explorers and address shape (`networkById`,
315
+ `depositNetworks`, `payoutNetworks`, `depositTokens`, `oneClickAssetId`, `familyOfAddress`,
316
+ `mustAskNetwork`, `explorerUrl`). An EVM address is valid on every EVM network, so
317
+ `mustAskNetwork("evm")` is true and a caller must ask which one, with no default. Live: Sui,
318
+ Base and Polygon. Ethereum and Arbitrum are listed as `planned` (not offered yet).
319
+ * **Payouts** from the private balance to Sui, Base and Polygon (`PAYOUT_NETWORKS`): a signed
320
+ 1Click quote, checked against the request before any money moves (`verifyPayoutQuote`), then
321
+ `preparePayout`, `settlePayout`, `finishPayout`, `watchPayout` and `fetchPayoutDelivery`.
322
+ `previewPayout` gives the signed arriving amount without reserving anything. A retry before any
323
+ money moved reuses its reservation. Sui falls back to a second route when 1Click cannot quote.
324
+ The caller supplies storage (`PayoutStore`) and may carry the requests through its own proxy
325
+ (`PayoutTransport`).
326
+ * **Deposits from another network** through Cloak's bridge service. `bindDepositQuote` and
327
+ `vetOneClickDepositOption` decide what a signed deposit quote proves and bind it to the request
328
+ (recipient, amounts, assets, refund address, deposit address, slippage, deadline).
329
+ `checkPaymasterReady` asks the fee sponsor for a real price before the user sends anything on
330
+ the other network. `finishBridgeDeposit`, `waitingBridgeDeposits` and `recoverBridgeDeposits`
331
+ shield what arrived, from the receiver key alone. Too little to shield is final
332
+ (`BridgeDepositBelowMinimumError`), never retried. Outside dust of up to `DUST_BURN_CEILING` is
333
+ burned by the sponsor's top-up and never shielded.
334
+ * `depositFromDerivedKey` returns the note it created, and can fund the receiver and its program
335
+ accounts in one caller transaction. `transact` takes `returnMerkleTree`.
336
+
52
337
  ## [0.2.13]
53
338
 
54
339
  ### Fixed
package/README.md CHANGED
@@ -5,15 +5,53 @@ per-mint pool, send privately inside the pool, withdraw to any address, or swap
5
5
  USDC/USDT with the output landing in a public token account. Groth16 proofs are generated
6
6
  client-side (snarkjs) and verified on-chain by the Cloak program.
7
7
 
8
- Version 0.2.14 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
8
+ Version 0.2.20 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
9
9
  `cloak-transaction-0.2.0` circuit bundle. See [Version and compatibility](#version-and-compatibility).
10
10
 
11
11
  ## Installation
12
12
 
13
13
  ```bash
14
- npm install @cloak.dev/sdk@^0.2.14
14
+ npm install @cloak.dev/sdk@^0.2.20
15
15
  ```
16
16
 
17
+ ## One call per action (`createCloak`)
18
+
19
+ ```ts
20
+ import { createCloak } from "@cloak.dev/sdk";
21
+
22
+ const cloak = await createCloak({ wallets: [useWallet(), window.ethereum], rpc: SOLANA_RPC_URL });
23
+
24
+ await cloak.shield({ from: "solana", token: "USDC", amount: "10" });
25
+ await cloak.shield({ from: "base", token: "ETH", amount: "0.002" }); // arrives as USDC
26
+ await cloak.send({ to: "cloak_3x…", token: "USDC", amount: "1" }); // private
27
+ await cloak.send({ to: "0x07f0…", chain: "base", token: "USDC", amount: "5" });
28
+ await cloak.withdraw({ to: "EZcZ…", token: "USDC", amount: "2" }); // exactly 2 arrive
29
+ await cloak.balance(); // { USDC: "…", USDT: "0", SOL: "0", BRS: "0" }
30
+ const { url } = await cloak.createPaymentLink({ token: "USDC", amount: "5" });
31
+ ```
32
+
33
+ - **The account** comes from one wallet signature: the same account the Cloak mobile app shows for
34
+ that wallet. A cloak.ag account opens with `{ cloakKey: "24 words" }`; a business that holds its
35
+ customers' keys passes `{ account: key }`. More wallets go in `wallets: [...]` and are linked to
36
+ the account, so any of them opens it next time.
37
+ - **Any wallet**: `useWallet()` or a wallet-adapter adapter, a Wallet Standard wallet (Phantom,
38
+ Solflare, Backpack, Slush), `window.ethereum` or an EIP-6963 provider (`discoverEvmWallets()`),
39
+ a Privy wallet, a kit signer or `Keypair`, a viem `WalletClient` or an ethers `Signer`, or
40
+ `{ chain, address, signMessage, signTransaction, sendTransaction }`.
41
+ - **Every call names its token.** Solana: SOL, USDC, USDT and BRS each have their own pool. Base
42
+ takes USDC or ETH, Polygon and Sui take USDC, and all arrive as USDC. Out to another chain: USDC.
43
+ - **BRS to and from Base, 1:1 through LayerZero.** `shield({ from: "base", token: "BRS" })` (the Base
44
+ wallet pays LayerZero in ETH, about 0.00145, and needs no SOL) and `send({ to: "0x…", chain:
45
+ "base", token: "BRS" })` (LayerZero's fee, about 0.0154 SOL, comes from the private SOL balance).
46
+ Quotes and receipts report that fee as `networkFee`.
47
+ - **No SOL needed for spends**: relay requests are signed by a key derived from the account.
48
+ - **Business mode**: `storage: encryptedStorage(db, secret)`, `(await cloak.notes()).encryptToSave(secret)`,
49
+ `restoreNotes`, and `ref: "invoice-1042"` on a shield, send or withdrawal so it happens once.
50
+ - **Errors** are `CloakCallError`s with a `code`, `retryable`, and where the money is. A deposit or
51
+ payout that stopped halfway is finished on the next start, or by `cloak.resume()`.
52
+
53
+ The rest of this README documents the functions `createCloak` is built on, for full control.
54
+
17
55
  The SDK is built on [`@solana/kit`](https://github.com/anza-xyz/kit) and re-exports the pieces an
18
56
  integrator needs (`address`, `createCloakRpc`, `generateKeyPairSigner`, `signerFromSecretKey`,
19
57
  `sendInstructions`, …), so `@solana/web3.js` is not required. Token-account derivation for SPL
@@ -267,11 +305,7 @@ await transact(
267
305
  A wallet that cannot sign messages (Ledger, Trezor) passes `signer` instead of `signMessage`: the
268
306
  sender then authenticates by signing a 0-lamport no-op self-transfer that carries the request
269
307
  digest (`auth_mode: "transaction"`). Give a wallet one of the two; when both are present
270
- `signMessage` is used. If the wallet changes that transaction before its device signs it (Phantom
271
- adds compute-budget instructions, Solflare its guards), the SDK sends the message the wallet
272
- actually signed as `auth_tx_message`. Only ComputeBudget and Lighthouse instructions may be added
273
- (`WALLET_ADDED_PROGRAMS`); any other change is refused before anything is sent
274
- (`walletAuthTransactionMessageBinds`).
308
+ `signMessage` is used.
275
309
 
276
310
  `signMessage` must return the raw 64-byte ed25519 detached signature over the bytes it is given;
277
311
  adapters that re-encode or wrap the result are rejected by name. `walletPublicKey` must be the end
@@ -829,7 +863,7 @@ relay endpoint and the localhost-RPC check.
829
863
 
830
864
  ## Version and compatibility
831
865
 
832
- - SDK 0.2.14 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
866
+ - SDK 0.2.15 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
833
867
  (deployed 2026-08-24) and the 0.2.0 circuit bundle — the program and circuit bundle are unchanged
834
868
  since 0.2.0; only the SDK package version has moved. The 0.2.5 flows were exercised on mainnet on
835
869
  2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to USDC and USDT;
@@ -866,12 +900,14 @@ relay endpoint and the localhost-RPC check.
866
900
  - 0.2.13 caps the prover at 8 workers (2 in a 32-bit browser), bounds the circuit download and
867
901
  retries a stalled proof single-threaded; it changes no wire format, hash or signature (see
868
902
  [CHANGELOG.md](CHANGELOG.md)).
869
- - 0.2.14 lets a hardware wallet authenticate through a software wallet that changes the 0 SOL
870
- auth transaction before the device signs it (Phantom adds compute budget, Solflare its guards):
871
- the message the wallet signed is sent as `auth_tx_message` (`tx_message` on
872
- `/viewing-key/register`). The field appears only for such a wallet, so every other request is
873
- byte-identical to 0.2.13; it needs the matching relay release, and an older relay ignores it and
874
- refuses those signatures as before (see [CHANGELOG.md](CHANGELOG.md)).
903
+ - 0.2.14 adds deposits from and payouts to other networks: the network list (`NETWORKS`), the
904
+ payout flow to Sui, Base and Polygon, and signed-quote binding, finishing and recovery for
905
+ deposits through Cloak's bridge service. Every addition is new API; existing calls, wire formats
906
+ and hashes are unchanged (see [CHANGELOG.md](CHANGELOG.md)).
907
+ - 0.2.15 adds the public way out for money a one-time receiving address cannot shield
908
+ (`moveReceiverFundsToWallet`, `readReceiverTokenBalance`) and a `"moved-out"` discovery state.
909
+ `BridgeDepositState` gains that member, so an exhaustive switch over it needs one more case
910
+ (see [CHANGELOG.md](CHANGELOG.md)).
875
911
  - Proofs generated with the 0.1.x circuits are rejected by the mainnet program. SDK 0.1.x builds
876
912
  (which ship the 0.1.0 bundle) are not usable against it; upgrade to 0.2.x.
877
913
  - The note-based `CloakSDK` class is removed in 0.2.0. It targeted the pre-0.2.0 instruction layout
@@ -1,3 +1,12 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+
1
10
  // src/solana/address.ts
2
11
  import {
3
12
  address,
@@ -500,6 +509,10 @@ function selectUtxos(available, targetAmount) {
500
509
  }
501
510
 
502
511
  export {
512
+ __privateGet,
513
+ __privateAdd,
514
+ __privateSet,
515
+ __privateMethod,
503
516
  address,
504
517
  isAddress,
505
518
  SYSTEM_PROGRAM_ADDRESS,