# Cloak Documentation - LLM Full Export This file is a single-document context pack for AI coding agents. It complements: - `/llms.txt` (index) - `/sdk/llms.txt` (full TypeScript SDK contract map) - `/sdk/rust/llms.txt` (full Rust SDK contract map) Use this file when an agent asks for "all docs in one place". --- ## 1) Product snapshot Cloak is a privacy-focused Solana stack with: - an app/client integration layer - `@cloak.dev/sdk` (TypeScript) for transaction orchestration - `cloak-sdk` (Rust crate) for server-side / CLI / program-client orchestration - on-chain shield-pool program logic - proof circuits Both SDKs target the same on-chain protocol and produce identical wire payloads. Primary integration path is the SDK UTXO API in whichever language matches the host app. --- ## 2) AI read order For TypeScript integrations: 1. `/llms.txt` 2. `/llms-full.txt` 3. `/sdk/llms.txt` 4. `/sdk/quickstart` 5. `/sdk/utxo-transactions` 6. `/sdk/wallet-integration` For Rust integrations: 1. `/llms.txt` 2. `/llms-full.txt` 3. `/sdk/rust/llms.txt` 4. `/sdk/rust/quickstart` 5. `/sdk/rust/core-concepts` 6. `/sdk/rust/api-reference` --- ## 3) Route map with intent ### Getting Started - `/platform/overview` - Purpose: high-level architecture across SDK, programs, and circuits. - `/sdk/introduction` - Purpose: language picker — TypeScript vs Rust. ### Platform - `/platform/components` - Purpose: subsystem boundaries and responsibilities. - `/platform/transaction-flows` - Purpose: lifecycle details for deposit, transfer, withdraw, swap. - `/architecture/viewing-keys-compliance` - Purpose: viewing-key lifecycle, registration requirements, compliance history behavior. ### TypeScript SDK (`@cloak.dev/sdk`) - `/sdk/quickstart` - Purpose: smallest end-to-end example for deposit plus send/withdraw. - `/sdk/examples` - Purpose: concise examples for send, swap, payroll-like flows, compliance history. - `/sdk/kit-integration` - Purpose: integrate Cloak with codebases standardized on `@solana/kit`. - `/sdk/core-concepts` - Purpose: UTXO primitives, fee model, root freshness, operational defaults. - `/sdk/utxo-transactions` - Purpose: production transaction APIs and runtime semantics. - `/sdk/wallet-integration` - Purpose: wallet-adapter patterns and signing behavior. - `/sdk/error-handling` - Purpose: error categories, retries, and troubleshooting guidance. - `/sdk/api-reference` - Purpose: public SDK exports. - `/sdk/llms.txt` - Purpose: exhaustive TypeScript SDK contract and symbol map for AI tools. ### Rust SDK (`cloak-sdk`) - `/sdk/rust/introduction` - Purpose: scope, install from git, minimal `TransactOptions` setup, TS→Rust mental model. - `/sdk/rust/quickstart` - Purpose: first SOL deposit end-to-end with retry-loop walkthrough. - `/sdk/rust/core-concepts` - Purpose: Rust types mapped to protocol primitives (`FlowKind`, `Utxo`, retry classification). - `/sdk/rust/api-reference` - Purpose: `TransactOptions`, `TransactResult`, `SwapOptions`, `RpcProvider`, `Relay`, instruction builders. - `/sdk/rust/error-handling` - Purpose: `Error` variants, inner/outer retry loops, common failure modes, `RUST_LOG` tracing. - `/sdk/rust/llms.txt` - Purpose: exhaustive Rust SDK contract map and symbol reference for AI tools. ### Protocol / Runtime - `/protocol/architecture` - Purpose: end-to-end data flow from client to chain. - `/protocol/shield-pool` - Purpose: on-chain behavior that integrators must align with. - `/protocol/fee-model` - Purpose: on-chain fee constants, formula, and per-flow breakdown. - `/packages/circuits` - Purpose: circuit build and consumption pipeline. - `/operations/security` - Purpose: trust boundaries and security controls. ### AI tools - `/ai-tools/ai-integration` - Purpose: canonical llms files and one-shot prompts. - `/ai-tools/claude-code` - Purpose: Claude Code prompt playbook. - `/ai-tools/cursor` - Purpose: Cursor rules and prompts. - `/ai-tools/windsurf` - Purpose: Windsurf rules and prompts. ### User Guide (plain-language, non-developer) Use these when answering end-user questions (custody, fees, recovery, compliance) rather than integration questions. They are authoritative for user-facing wording. - `/guide/what-is-cloak` - Purpose: plain-language positioning and live capability list. - `/guide/how-it-works` - Purpose: the four user flows (shield, private send, private swap, unshield) without protocol internals. - `/guide/private-balance` - Purpose: canonical custody model — private balance, UTXOs, backup file, loss/recovery semantics. - `/guide/fees` - Purpose: user-facing who-pays fee table (free shielding; SOL 0.005 + 0.3%; SPL 0.3% on the way out). - `/guide/payment-links` - Purpose: single-use bearer payment links — send without a recipient address / receive without revealing one; fragment-carried secret, claim mechanics, fee timing. - `/guide/security` - Purpose: audit status, named threat model, "what Cloak cannot do", governance honesty. - `/guide/compliance` - Purpose: viewing-key selective disclosure, compliance reports, Range screening. - `/guide/verified-addresses` - Purpose: canonical program ID + official domains (anti-scam reference). - `/guide/faq` - Purpose: honest user FAQ (trust, custody, recovery, fees, privacy depth). - `/guide/glossary` - Purpose: plain-language term definitions matching app vocabulary. - `/guide/wallets-and-tokens` - Purpose: supported wallets and tokens-per-action tables. - `/learn/wallet-public-diary`, `/learn/zero-knowledge-without-the-math`, `/learn/privacy-is-not-anonymity`, `/learn/prove-your-funds-privately` - Purpose: conceptual explainers (problem-first privacy, plain ZK, accountable privacy, proof of funds). --- ## 4) High-signal runtime contracts These are intentionally repeated here because agents often miss them. They apply to both SDKs. 1. Prefer UTXO APIs for new integrations. 2. Keep all transaction amount math in `bigint` (TS) or `u64` / `i64` (Rust) — no float math. 3. `externalAmount` / `external_amount` semantics in UTXO flows: - positive = deposit - negative = withdraw or swap - zero = shield-to-shield transfer 4. Treat stale-root and root-not-found issues as retryable (SDK transaction paths already retry by default; Rust uses typed `Error::RootNotFound` / `Error::StaleProofState` variants). 5. Never log secrets (private keys, viewing keys (`nk`), seed material, raw note payloads, blindings, UTXO private keys). 6. Transaction signatures are public and can be logged for support/debugging. 7. Viewing-key registration affects scanner/compliance readability. 8. Rust-specific: swaps (`opts.swap = Some(...)`) and direct SPL withdraw require `opts.relay_url` — `submit_direct` rejects them with `Error::Config`. For full signature-level details, use `/sdk/llms.txt` (TypeScript) or `/sdk/rust/llms.txt` (Rust). --- ## 5) One-shot implementation spec: simple SOL send flow This is the recommended minimal flow for AI-generated integrations. ### Goal Send SOL privately through Cloak by: - depositing SOL into shielded state - then performing a full withdrawal to a public recipient wallet ### Required API path (TypeScript) - `transact(...)` for deposit - `fullWithdraw(...)` for send - optional `partialWithdraw(...)` for keep-change behavior ### Required API path (Rust) - `cloak_sdk::core::transact::transact(opts)` with `opts.external_amount > 0` for deposit - `cloak_sdk::core::transact::transact(opts)` with `opts.external_amount < 0` + `opts.recipient` for withdraw - Thread `cached_merkle_tree` + `address_lookup_table_accounts` from the deposit result into the withdraw `TransactOptions` ### Reference snippet (TypeScript) ```typescript import { CLOAK_PROGRAM_ID, NATIVE_SOL_MINT, createUtxo, createZeroUtxo, fullWithdraw, generateUtxoKeypair, transact, } from "@cloak.dev/sdk"; import { Connection, Keypair } from "@solana/web3.js"; const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed"); const signer = Keypair.fromSecretKey(/* Uint8Array secret key */); const amount = 1_000_000_000n; // 1 SOL const owner = await generateUtxoKeypair(); const output = await createUtxo(amount, owner, NATIVE_SOL_MINT); const deposited = await transact( { inputUtxos: [await createZeroUtxo(NATIVE_SOL_MINT)], outputUtxos: [output], externalAmount: amount, depositor: signer.publicKey, }, { connection, programId: CLOAK_PROGRAM_ID, depositorKeypair: signer, walletPublicKey: signer.publicKey, }, ); const recipient = Keypair.generate().publicKey; await fullWithdraw(deposited.outputUtxos, recipient, { connection, programId: CLOAK_PROGRAM_ID, depositorKeypair: signer, walletPublicKey: signer.publicKey, cachedMerkleTree: deposited.merkleTree, }); ``` ### Reference snippet (Rust) ```rust use std::sync::Arc; use cloak_sdk::{ constants::{MIN_DEPOSIT_LAMPORTS, NATIVE_SOL_MINT}, core::{transact::{transact, TransactOptions}, utxo::{Utxo, UtxoKeypair}}, rpc::SolanaRpc, }; use solana_keypair::Keypair; use solana_pubkey::Pubkey; #[tokio::main] async fn main() -> anyhow::Result<()> { let rpc = Arc::new(SolanaRpc::new(std::env::var("SOLANA_RPC_URL")?)); let payer = Arc::new(load_keypair_from_path(&std::env::var("KEYPAIR_PATH")?)?); let amount = MIN_DEPOSIT_LAMPORTS; // Deposit. let owner = UtxoKeypair::generate()?; let output = Utxo::new(amount, owner, NATIVE_SOL_MINT)?; let deposit = transact(TransactOptions { inputs: vec![], outputs: vec![output], external_amount: amount as i64, rpc: Some(rpc.clone()), payer: Some(payer.clone()), relay_url: Some("https://api.cloak.ag".into()), ..Default::default() }).await?; // Withdraw (full). let mut input = deposit.output_commitments; // actual `Utxo` — saved with its keypair let recipient: Pubkey = args_recipient()?; let withdraw = transact(TransactOptions { inputs: vec![/* the Utxo from deposit, with index populated */], outputs: vec![ Utxo::zero(Some(NATIVE_SOL_MINT), None)?, Utxo::zero(Some(NATIVE_SOL_MINT), None)?, ], external_amount: -(amount as i64), recipient: Some(recipient), rpc: Some(rpc), payer: Some(payer), relay_url: Some("https://api.cloak.ag".into()), cached_merkle_tree: deposit.cached_merkle_tree, address_lookup_table_accounts: deposit.address_lookup_table_accounts, ..Default::default() }).await?; println!("{}", withdraw.signature); Ok(()) } ``` ### Validation checklist for agents (TypeScript) - uses UTXO API (not legacy note API) - uses `bigint` for transaction amounts - no secret logging - includes progress and user-facing error states - uses `KEYPAIR_PATH` + ` ` for minimal CLI scripts - does not use `SENDER_PRIVATE_KEY` or `AMOUNT_SOL` + `parseFloat(...)` - does not use `RECIPIENT_ADDRESS` / `SEND_LAMPORTS` env input for one-file CLI scripts - exits explicitly with `process.exit(0)` on success and `process.exit(1)` on failure ### Validation checklist for agents (Rust) - uses `cloak_sdk::core::transact::transact(opts)` as the entrypoint - amounts are `u64` / `i64` — no float math - saves the `UtxoKeypair` durably (required to spend the note later) - threads `cached_merkle_tree` + `address_lookup_table_accounts` between transacts - no secret logging; enables `RUST_LOG=cloak_sdk=debug` for troubleshooting only - uses SDK defaults for program/relay/circuits (no user-facing config) - does not add custom retry loops — the SDK retries RootNotFound/BlockhashExpired/StaleProofState - loads signer from `KEYPAIR_PATH` (Solana JSON keypair file); does not accept raw secret bytes via env --- ## 6) Recommended one-shot prompt template Copy this prompt into your coding assistant: "Implement a minimal Cloak SOL send integration with `@cloak.dev/sdk`. Before coding, read `/llms.txt`, `/llms-full.txt`, `/sdk/llms.txt`, `/sdk/quickstart`, and `/sdk/utxo-transactions`. Use UTXO APIs with bigint-safe logic and implement deposit plus full-withdraw send flow. For script tasks, generate one keypair-only file with CLI shape `npx tsx send-sol-private.ts `. Use env vars `SOLANA_RPC_URL` and `KEYPAIR_PATH` only. Do not generate `SENDER_PRIVATE_KEY` or `AMOUNT_SOL` float parsing. Do not use `RECIPIENT_ADDRESS` or `SEND_LAMPORTS` env inputs for one-file CLI scripts. Use SDK defaults for program, relay, and circuits. Do not log secrets. Add progress + error UX. Rely on SDK stale-root retries for standard flows. Terminate script entrypoints explicitly with `process.exit(0)` on success and `process.exit(1)` on failure. Return a capability matrix, file patches, commands run, and verification summary." --- ## 7) Sources of truth in this repository When docs and code differ, validate against implementation: - TypeScript SDK exports: `sdk/src/index.ts` - TypeScript SDK runtime: `sdk/src/core/*`, `sdk/src/utils/*` - Rust SDK public API: `rustsdk/src/lib.rs` - Rust SDK orchestrator: `rustsdk/src/core/transact.rs`, `rustsdk/src/core/transact/*.rs` - Rust SDK relay + RPC: `rustsdk/src/services/relay.rs`, `rustsdk/src/rpc.rs` - Program behavior: `programs/shield-pool/src/*` - Relay routes/payloads: `services/relay/src/main.rs`, `services/relay/src/api/*` - Relay sync behavior: `services/relay/src/commitment_sync.rs` - Circuits/build flow: `packages/circuits/*`, `packages/justfile`, `packages/scripts/*` --- ## 8) Related files - `/llms.txt` - `/.well-known/llms.txt` - `/sdk/llms.txt` (TypeScript) - `/sdk/rust/llms.txt` (Rust) - `/ai-tools/ai-integration`