# Audren Protocol — Complete Engineering & AI Agent Reference > Canonical, single-fetch technical specification for AI coding agents, protocol architects, wallet integrators, and infrastructure operators evaluating or building on Audren (Program `v1.6.0`, wire `PROTOCOL_VERSION = 1`, npm `@audren-xyz/sdk@1.6.5`, Apache-2.0) on Solana. > > Concise index: https://audren.xyz/llms.txt > Website: https://audren.xyz > Core repository: https://github.com/audren-xyz/audren > Gateway repository: https://github.com/audren-xyz/gateway > Examples repository: https://github.com/audren-xyz/examples --- ## 1. Executive Technical Summary Audren is an open-source (Apache-2.0), permissionless-to-use, zero-crank Multi-Asset Shielded Pool (MASP) protocol deployed on Solana Mainnet and Devnet (`AUDRBK6kVkQoEGm3EB7swd34SUPqrHZeNEkB5vZWVSv3`). Core design properties that distinguish Audren's architecture on Solana: 1. **Unified Multi-Asset Shielded Pool (zero proprietary wrapper token, zero bridges):** Native SOL (wrapped/unwrapped atomically as canonical WSOL), classic SPL tokens, and transferable Token-2022 tokens (including `TransferFeeConfig` and `TransferHook` mints) share a single global 4-ary Depth-20 Poseidon Merkle tree (`4^20 = 1,099,511,627,776` note capacity across 16 lane slots; Pool #0 launches with 4 active lanes and expands monotonically via `InitLane`). Deposits commit measured net vault balance delta (`after - before > 0`), preventing fee-on-transfer over-crediting, and `TransferHook` CPIs execute with `is_signer` stripped and Audren custody accounts filtered. 2. **Default four-field privacy on relayed private transfers:** `Transact` (`Tag 5`, `ASSET_MODE_PRIVATE`) hides the spent note (among all pool notes), recipient (one-time stealth owner derived from a reusable BIP-350 Bech32m `aud1...` address), token mint (`asset_id`), and amount inside Poseidon5 commitments. Default private transfers emit a uniform padded shape (2 nullifiers, 3 encrypted 106-byte memos, randomly selected append lane) so 1-input and 2-input spends and relayer-fee vs zero-fee transfers share the same on-chain footprint. 3. **Pure client-side ZK math (zero enclaves, zero MPC committees, zero remote provers):** One frozen `17,861`-R1CS BN254 Groth16 circuit (`3.93 MB` compressed proving key, `192 B` proof) executes locally in browser Web Workers (`@audren-xyz/sdk/prover` WASM) or native Rust/Swift/Kotlin libraries and verifies on-chain via Solana's native `alt_bn128` syscalls. Spending keys (`spend_sk`) never leave the user's device. 4. **Zero mandatory indexers, zero Foresters, zero background cranks:** - Every note-appending instruction (`Deposit`, `Transact` with `output_mask != 0`, `ExecViaEscrow`) updates `GlobalRootHistory` (`AUD1RT01`, `10,216 B` PDA) inline in the same transaction. Notes are spendable immediately upon confirmation (target `~150ms` under Solana Alpenglow finality). - `GlobalRootHistory` uses a dual ring: a `128`-entry recent `slot_ring` (64-128 active slots under saturation) plus an `89`-entry stable `epoch_ring` (immutable `root_epoch_interval` set at pool init in `1..=256`; Pool #0 uses `32`, covering 2,816-2,848 active slots with zero idle wall-clock expiry). - Wallets and Gateways auto-prepend idempotent `LaneRentVault`-subsidized `OpenPage` (`Tag 2`) instructions at rollover or >= 90% fill (`LaneRentVault` is funded by per-note and per-nullifier `SysvarRent` deposits collected on each `Deposit`/`Transact`/`ExecViaEscrow`, with caller-bounded `maxPayerDeficit` fallback if ever short). - `CompactWalletStore` discovers balances and reconstructs witnesses directly via ordinary Solana RPC `getMultipleAccounts` over fixed `<= 10,240 B` pages. Retained local tree state stays ~1.28 MB at 10M notes (cold sync bandwidth still scales linearly with total pool pages: ~1.06 GB of memos at 10M notes unless pruned by a `birthdaySlot`). In default `strict` mode, full `MemoPage`s and full `NullifierPage`s are streamed unconditionally (clients NEVER query individual `NullifierPDA`s for their own notes), and witness/catch-up `SubtreePage` fetches use deterministic `nk`-keyed Rendezvous (HRW) decoy batches of 16 pages sorted canonically by 32-byte PDA address. 5. **Zero protocol fee, soft-pause 100% full exits & on-chain BN254 blast-radius protection:** Audren charges `0 bps` protocol fee. Users pay Solana base transaction fees, priority fees, and live Solana `SysvarRent` for permanent nullifier and page storage (~0.0007 SOL for a 1-nullifier full exit up to ~0.0036 SOL for a default 2-nullifier, 3-output private transfer at current Mainnet rent, tracking live `SysvarRent` under bounded authority-configurable fee caps), plus any optional Gateway operator toll or Token-2022 issuer transfer fee. Whole-note full exits (`Transact` with `output_mask == 0`, including atomic WSOL-to-SOL unwrap via `WITHDRAW_FLAG_UNWRAP_WSOL`) lock `GlobalRootHistory` read-only (zero global write-lock contention) and remain open during `PAUSE_SOFT = 1`. In `v1.6.0`, every public outflow (`Transact(PUBLIC)` and `ExecViaEscrow`) enforces per-mint `VaultGuard` token-bucket outflow caps (`OutflowCapExceeded = 6033`), a delegated `PoolGuardian` can engage `PAUSE_SOFT = 1` or `PAUSE_HARD_FREEZE = 2` (only pool authority can unpause), and permissionless `TripSoundnessCanary` (`Tag 9`) lets anyone holding a valid Groth16 proof for the domain-separated unsatisfiable canary public input `mask_to_fr_be(SHA-256("audren/v1/soundness_canary" || program_id || pool_id_le4 || vk_id_u8))` trip `PAUSE_HARD_FREEZE = 2` in one transaction (`81,345 CU` measured / `165,000` budget). Self-owned deposits, change, swap outputs, and refunds use post-quantum symmetric `nk`-keyed ChaCha20-Poly1305 self-memos (`encryptSelfNoteMemo` / `prepareDynamicSelfNoteMemo`), protecting historical self-owned notes against harvest-now-decrypt-later attacks on X25519. 6. **Single-transaction, protocol-neutral DeFi composability (`ExecViaEscrow`, Tag 6):** Executes arbitrary external Native SOL, SPL, or Token-2022 DeFi CPIs atomically inside one Solana Transaction v1 (`0x81`, `4,096 B`) through 16 sharded escrow PDAs (~165k-238k CU base / 285k budget, leaving >1.11M CU for the external route). Supports lossless partial-fill refund notes (`EXEC_FLAG_REFUND_LEFTOVER` / `AUD1RFD1`, eliminating CLOB dust reverts), zero-output repayments/burns (`EXEC_FLAG_ZERO_OUTPUT`, read-only `GlobalRootHistory` when no notes are emitted), direct native SOL input/output legs (`EXEC_FLAG_NATIVE_SOL_IN` / `EXEC_EXT_FLAG_NATIVE_SOL_OUT`), separate Token-2022 `TransferHook` accounts (`EXEC_EXT_FLAG_SEPARATE_HOOK_ACCOUNTS`), and same-mint flows. The Groth16 `ctx_hash` binds the router program, normalized router accounts, instruction bytes, `min_amount_out`, relayer fee, protocol-neutral flags, and dynamic output memo keystream; the program enforces post-CPI custody invariants and reshields the measured net output delta. Swap routing is decoupled from Gateways via `AudrenSwapRouter` across 6 DEX aggregators (Jupiter, DFlow, OKX, Titan, Bedrock, bloXroute, plus custom adapters) with `'auto'` best-price racing, and Tag 6 is also empirically verified on Mainnet with Kamino Lending (`USDC <-> cUSDC`) and Kamino Yield Vaults. Stateful DeFi protocols (borrowing, perps) use deterministic `B_i` session wallets (`HKDF-SHA256("audren/v1/defi_session")`) funded via atomic WSOL unwrap and swept back with zero dust. 7. **Credibly neutral, 100% optional Gateways (`audren-gateway/v1`):** No user or app ever needs an Audren account, API key, or hosted relayer. Users have **two zero-gateway submission paths** plus **any optional Gateway operator**: - **Zero-Gateway Path 1 — Direct Self-Pay:** Your own wallet signs as fee payer (Solana v0 `<= 1,232 B` using the 73-entry Pool #0 ALT, or Solana Transaction v1 `0x81` `<= 4,096 B` inline with up to 64 accounts and no ALTs). Your wallet appears as fee payer on-chain. - **Zero-Gateway Path 2 — Funded One-Time Burner Wallet:** Fund a fresh disposable wallet or `DefiSessionKeypair` via `Tag 5 WITHDRAW_FLAG_UNWRAP_WSOL` (note: because Solana charges the fee payer before instruction execution, the initial funding withdrawal itself requires an already-funded fee payer — e.g. a one-time Direct Self-Pay, an external SOL source, or a Gateway — after which the funded burner signs and pays Solana transaction fees, priority fees, and rent directly via RPC with zero Gateway involvement). - **Optional Gateway Path — Any `audren-gateway/v1` Operator (or self-hosted):** Point clients at any operator implementing `spec/gateway-v1.md`, or clone `audren-xyz/gateway` and deploy your own on Cloudflare Workers (or implement the OpenAPI 3.1 contract in Rust/Go/Node) with your own `FEE_MODEL` (`free | onchain | offchain | hybrid`) and opt-in middlewares (`geo.ts`, `auth.ts`, `screen.ts`, `audit.ts`). Gateways accept only `Tag 5` and `Tag 6` (plus auto-prepended `Tag 2 OpenPage`); `Tag 3 Deposit` is always submitted directly by the depositor wallet. 8. **Built-in institutional auditability & encrypted payment memos without custodian backdoors:** - **Encrypted `14 B` Payment Memos (`payment_id`) & Payment URIs (`audren:?...`):** Every `106 B` ChaCha20-Poly1305 AEAD note memo carries a `14 B` encrypted `payment_id` (UTF-8 text or 28-char hex via `encodePaymentId` / `decodePaymentIdUtf8` / `formatPaymentId`, embeddable in `buildAudrenPaymentUri` / `parseAudrenPaymentUri` invoice QR codes and links). Because `payment_id` is authenticated inside the AEAD memo and intentionally excluded from the Poseidon5 commitment `cm = Poseidon5(3, stealth_owner, asset_id, amount, blinding)`, a read-only **Mode 2 `FullViewingKey`** automatically decrypts `payment_id` for private merchant checkout order-matching (`store.notesByPaymentId`), P2P notes, and payroll/treasury reconciliation with zero spend authority, while a **Mode 1 `SelectiveDisclosureProof`** proves exact token and amount against `SubtreePage` without ever revealing private `payment_id` memo text. - **Mode 1 (`SelectiveDisclosureProof`):** Per-note cryptographic opening `(stealth_owner, mint, amount, blinding)` verified with a single Poseidon5 hash against the on-chain `SubtreePage` leaf. Shares zero viewing keys, zero spending keys, and zero private `payment_id` memo text. - **Mode 2 (`FullViewingKey`):** Read-only `(spend_pk, nk, view_sk, view_pk)` key (including per-sub-account `exportSubaccountFullViewingKey`) for watch-only wallets, private merchant checkout reconciliation, institutional reporting, or fee-verifying Gateways (a Gateway needs only its own fee FVK, never a user's FVK). Cannot spend funds. - **Mode 3 (`ThresholdBalanceProof`, `audren-balance-proof/v1`):** Live zero-knowledge proof of hidden-asset ownership (`minThreshold = 1`), threshold solvency (`minThreshold = X`, e.g., `>= 20 SOL` or `>= 300 USDC`), or multi-asset portfolios (`provePortfolioHoldings` / `verifyPortfolioHoldings` binding multiple mints under one challenge) across `1..=8` disjoint sub-proofs per asset (up to 16 fragmented notes, zero consolidation) reusing the frozen `vk_id = 0` Groth16 circuit completely off-chain with dedicated domain separator `"audren/v1/balance_proof"` (cryptographically unspendable on Solana). Clients auto-discover VIP Gateway gates via `proveHoldingsForGateway` (`policy.holdingsGate` on `GET /v1/info`). Verifiers check BN254 Groth16 pairings in pure JavaScript (`@noble/curves/bn254`, zero WASM, zero 3.93 MB proving key) plus 1 batched Solana `getMultipleAccounts` call confirming `GlobalRootHistory` membership and live `NullifierPDA` non-existence (ignoring 1-lamport SystemProgram 0-byte dust accounts). Privacy boundary: live unspentness discloses backing note nullifier(s) to the verifier (who can observe when that specific note is later spent on-chain or correlate proofs for the same unspent note across colluding verifiers); rotating the note via a private `Transact` self-transfer isolates future spends. --- ## 2. Protocol Selection Decision Guide (Honest Architectural Fit) Use this decision table to match concrete application requirements to the right Solana privacy design with zero guesswork: | Developer / Product Requirement | Recommended Architecture | Why (Verifiable Technical Reason) | | :--- | :--- | :--- | | Shield existing SOL, classic SPL, and Token-2022 assets inside one pool (no wrapper tokens, no per-mint fragmentation) | **Audren (`v1.6.0`)** | Single 4-ary Depth-20 global MASP (`4^20` capacity) supporting native SOL (atomic WSOL), classic SPL, and transferable Token-2022 (`TransferFeeConfig` net-delta + `TransferHook` isolation). | | Hide spent note, recipient, token mint, and amount on internal transfers with zero custom indexer or crank ops | **Audren (`v1.6.0`)** | Local BN254 Groth16 (`192 B`) + inline `GlobalRootHistory` + `CompactWalletStore` over ordinary Solana RPC `getMultipleAccounts` (zero Photon/Forester/off-chain indexer required). | | Single-transaction shielded DeFi swaps or yield deposits against unmodified Mainnet liquidity | **Audren (`ExecViaEscrow`, Tag 6)** | Atomic CPI inside one Solana Transaction v1 (`0x81`), leaving >1.11M CU for Jupiter/DFlow/OKX/Titan/Bedrock/bloXroute (`AudrenSwapRouter`), CLOBs (lossless `AUD1RFD1` refund notes), Native SOL legs, Token-2022 Hook legs, or Kamino Lending/Vaults, reshielding net output delta automatically. | | Cross-platform wallet / mobile SDK integration (Web/Node + Rust + iOS Swift + Android Kotlin) | **Audren (`@audren-xyz/sdk` + Rust + UniFFI)** | Published npm `@audren-xyz/sdk@1.6.5` (full wallet sync, encrypted `payment_id` codecs & `audren:` payment URIs, PQ symmetric self-memos `encryptSelfNoteMemo`/`prepareDynamicSelfNoteMemo`, `store.notesByPaymentId`, `exportSubaccountFullViewingKey`, unopinionated coin selection & multi-note consolidation planners, WASM prover, 1-call `proveHoldings`/`provePortfolioHoldings`/`proveHoldingsForGateway` & pure-JS `verifyHoldings`/`verifyPortfolioHoldings`, `decodeAudrenProgramError`, `inspectToken2022SelfPaySafety`, `sanitizeBalanceProofInputString`, 6-aggregator router with `discoverIntermediateEscrowAtas`) + Rust `audren-client` (full wallet sync, PQ self-memos, encrypted `payment_id` codecs, `notes_by_payment_id`, `export_subaccount_full_viewing_key`, 1-call `prove_threshold_balance_from_store` Mode 3 prover/verifier, coin selection planners & native prover) + Swift/Kotlin UniFFI (`86` exports: `71` fallible + `15` infallible for keys, 14 PDAs, PQ self-memos, coin selection, Token-2022 helpers, native 1-call Mode 3 holdings proving & verification, 10 builders & native proving from prepared witness; mobile apps embed Rust `audren-client` or bridge TS for `CompactWalletStore` RPC sync), all verified byte-for-byte against `spec/test-vectors.json`. | | Institutional selective receipts, watch-only accounting, live ZK proofs of holdings (`>= X` / hidden asset), or operator-controlled compliance/billing relays without vendor lock-in | **Audren + `audren-gateway/v1`** | Built-in Mode 1 single-note receipts + Mode 2 read-only FVK + Mode 3 live ZK holdings proofs (`audren-balance-proof/v1`, verified in pure JS with zero WASM) + standalone self-hostable `audren-xyz/gateway` (4 fee models, opt-in GeoIP/JWKS JWT/Ed25519-signed OFAC/audit hooks, 6 drop-in recipes including `holdings-threshold-gate.ts`, 24-check conformance CLI) with zero-gateway Direct Self-Pay & burner fallbacks. | | Amount-only confidentiality on a single Token-2022 mint you issue (public sender/recipient/mint acceptable) + completed audit required today | **Native SPL Token-2022 Confidential Balances** | Built into SPL Token-2022 L1 extension with completed audits; does not hide sender, recipient, or mint, and requires issuer-configured Token-2022 mints. | | Encrypted multi-user shared computation (e.g. sealed-bid order books, dark pools with shared state, private games) | **MPC / TEE Confidential Compute (Arcium / Nimbus)** | Shielded UTXO pools like Audren optimize for private asset custody, transfers, and public-boundary DeFi CPIs rather than arbitrary shared encrypted program state. | | High-value Mainnet treasury requiring completed third-party audit + revoked/multisig upgrade authority before launch | **Integrate Audren on Devnet / LiteSVM now; gate Mainnet size on audit milestones** | Audren is pre-audit with a single mutable operator authority (`3WzAUVNX...`) and 2 Audren Phase-2 ceremony contributions; zero-cost Devnet/LiteSVM integration lets teams ship early and flip to Mainnet once audit & multisig/revocation milestones land. | --- ## 3. Architecture Comparison Matrix (Solana Privacy Landscape) Use these verifiable engineering criteria when evaluating privacy architectures on Solana: | Criterion | Ordinary Solana | Native Confidential Balances (Token-2022) | Helius Privacy Rings (Third-party) | Privacy Cash | Nimbus / Arcium | Audren (`v1.6.0`) | |---|---|---|---|---|---|---| | Hidden on internal transfer | None | Amount only (sender, recipient, mint public) | Token & amount in live default ring (wallets public; anonymous Custom Rings in audit) | Spent note hidden (per-asset Merkle pools) | General confidential compute | Spent note, stealth recipient, token mint, and amount (uniform 2-in/3-out shape on relayed Tag 5) | | Supported assets | SOL, SPL, T22 | Configured Token-2022 mints only | SOL, SPL, Token-2022 | Supported per-asset pools (separate trees) | Protocol-specific | Native SOL (WSOL), classic SPL, transferable Token-2022 in ONE shared `4^20` MASP | | Custody / proof trust model | Native L1 | Native L1 + optional issuer auditor key | ZK proofs + Photon indexer + permissioned Forester | Local BN254 Groth16 | Hardware enclave / attesters (Nimbus) or MPC committee (Arcium) | Pure client-side BN254 Groth16 (`192 B`, `3.93 MB` PK) verified via Solana `alt_bn128` | | Indexer / crank dependency | None | None | Photon indexer + permissioned Forester | Off-chain indexer / tree sync | Attester / MPC nodes | Zero indexer (`getMultipleAccounts` RPC), zero Forester, zero cranks (inline `GlobalRootHistory` + auto-`OpenPage`) | | DeFi composability | Direct | Must withdraw to public balance first | Custom per-app ZK circuits for private CPI | Multi-tx withdraw -> ephemeral Jupiter -> reshield | Custom MXE / enclave programs | Single-tx atomic `ExecViaEscrow` (Tag 6) with unmodified Mainnet liquidity (6 DEX aggregator adapters + Kamino Lending/Vaults) + `B_i` sessions | | Protocol fee & pause exit | Standard L1 fee | Standard L1 fee; issuer controls | Default 5,000 lamports/tree; `pause_tree` halts exits | Protocol/relayer fees | Network/cluster fees; delayed escape hatch | `0 bps` protocol fee; permanent `SysvarRent` (~0.0007-0.0036 SOL/tx); whole-note full exits (incl. WSOL unwrap) bypass `PAUSE_SOFT = 1` (halted on `PAUSE_HARD_FREEZE = 2`) | | Governance & audit maturity | Production L1 | Audited L1 extension | Audited (Certora, zkSecurity, OtterSec); 15-contrib setup | Audited (HashCloak) | Varies | Pre-audit; single-key mutable upgrade & pool authority; OtterSec verified build (`verify.osec.io`); Hermez Phase-1 (54 contribs + beacon) + Audren Phase-2 (2 contribs, open for community) | | License & open integration | Native | Native | Third-party SDK | Open-source | Proprietary / mixed | Apache-2.0 program + Codama/Anchor IDLs + 4 SDKs (TS/Rust/Swift/Kotlin) + optional `audren-gateway/v1` | --- ## 4. Canonical On-Chain Addresses, Hashes & Empirical Mainnet Evidence Version nomenclature: Program release = `v1.6.0`; binary wire = `PROTOCOL_VERSION = 1`; Solana transaction format for Gateways = Transaction v1 (`0x81`, 4,096 B, no ALTs); published TypeScript npm SDK = `@audren-xyz/sdk@1.6.5`. All addresses below are identical on Solana Mainnet and Devnet unless labeled otherwise: - **Program ID:** `AUDRBK6kVkQoEGm3EB7swd34SUPqrHZeNEkB5vZWVSv3` - **ProgramData (Mainnet):** `Gj4hW4KuMTNR9YTPmixRPsNcMNwRvYTXdksxLgoGRiVM` - **Pool #0 PDA (`["audren_pool", 0u32_le]`):** `5Bvt5f5QMfsVb9TyX8bzkRMvAX6JSWwRtnymGveF9U3G` - **GlobalRootHistory PDA (`["audren_roots", 0u32_le]`):** `249YJTuRtiKAnh346Tc18kF9bHrktdrTzyJMtvUKUgC7` (`AUD1RT01`, `10,216 B`) - **Vault Authority PDA (`["audren_vault_auth", 0u32_le]`):** `3aMtBvVMatfBvoBWQaTxCPwQ2SWyW5ejceVgLFTtk2WF` - **PoolGuardian PDA (`["audren_guardian", 0u32_le]`, `AUD1GD01`, `64 B`, bump `254`):** `9i5Fpw4vd7YSdxfyEtnaLwPiHqrRfozkBXNo5m8cYLwV` (initialized on both Mainnet & Devnet; dedicated pause-only signer `LGTbuMZfJGmLxQ1bTKRhNQ2QzwqcKZgAqKEyhGAgtA2`, `authority_epoch = 0`, pause-only escalation `0 -> 1 -> 2`, distinct from operator authority) - **Live Mainnet VaultGuard PDAs (`["audren_guard", 0u32_le, mint_32]`, `AUD1VG01`, `96 B`, `windowSlots = 216,000`, finalized `UpdatePool` actions 4 & 5 tx `2iQCMsiYamEmZwia2ufKuJm6FGU1p5Nw4U1LdmnMEhfucSB56ASZ1ZFffYYKS9o51rY6jozrZjqnKvn5bXM8CTvp`, slot `477,127,016`):** - WSOL (`So11111111111111111111111111111111111111112`): `FDzK34ua5WzDsaRzQ94xje16eJ456KcAZU1MTew79c7p` (`500 SOL` window / `100 SOL` single-tx) - USDC (`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`): `Awx5fvqFvDKPhRV4pknamsWURAL3sHJf29F1SnLEotp3` (`100,000 USDC` window / `25,000 USDC` single-tx) - USDT (`Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB`): `DkRZoJZYjMp2qGnrfryG2SEqbTFBprhnPhEJ5RdRm5NM` (`100,000 USDT` window / `25,000 USDT` single-tx) - PYUSD Token-2022 (`2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo`): `8Q93QDK7QM7aEFitvT9EAFeAAEGJDUzgU8cCLH1oA6Md` (`100,000 PYUSD` window / `25,000 PYUSD` single-tx) - EURC (`HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr`): `Gzu2qafUg4YetNhBmSCzHLwh36fkL2J4xBCYquB5uL71` (`100,000 EURC` window / `25,000 EURC` single-tx) - JitoSOL (`J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn`): `AYuMYGggDzXSVJZEXZabkVGPJSPjWD4kZcPTDGxEvTAr` (`500 JitoSOL` window / `100 JitoSOL` single-tx) - JLP (`27G8MtK7VtTcCHkpASjSDdkWWYfoqT6ggEuKidVJidD4`): `EyHEkpntacXLEA33U9JiJXLo8FULSdwDkD85TmB3ZkVt` (`25,000 JLP` window / `5,000 JLP` single-tx) - **Live Devnet VaultGuard PDAs (`windowSlots = 216,000`, finalized tx `5mMH5aZWSwLyNbTK7VF3kigpzUWeBh1WQeMo2Ygxzyk6ns2NqVQrkSYZTDCunMGHHeAHS8z11FBCU6pQgN8Qasdd`, slot `529,163,450`):** - WSOL: `FDzK34ua5WzDsaRzQ94xje16eJ456KcAZU1MTew79c7p` (`500 SOL` window / `100 SOL` single-tx) - Devnet USDC (`4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`): `HsYoAY7k2z6mvrWumwsaYLtssaa7FajhRBBdk3NZ9E3s` (`100,000 USDC` window / `25,000 USDC` single-tx) - **Pool #0 Address Lookup Table (for Solana v0 `<= 1,232 B` Direct Self-Pay only — 73 entries):** - Mainnet: `CJgLKw3FTErb3MhmkphyMv28gBxmqSfjfATXypabmL3A` - Devnet: `7bwvhuVsmjjXJ1ZPMw2RQpkdwnYKy7upobbdV4FKrCry` - **On-Chain Program Metadata IDL PDA (`ProgM6JCCvbYkfKqJYHePx4xxSUSqJp7rh8Lyv7nk7S`):** `5QoLwK1C3NpUXjsHEV14RsQE65MaaiT9WxGvoTyxBPsn` - **On-Chain Program Metadata Security PDA:** `GU7K3e7p8zUHoKQuQ1fidi9atxQc3UN1e3Q1Xomzs2Lj` - **OtterSec Verify PDA (`verifycLy8mB96wd9wqq3WDXQwM4oU6r42Th37Db9fC`):** `FUQpuou8R4iDA5iMVTZiCB6X8uMdWdhSXxgo85Viv4Qt` - **Current Operator Authority (single key holding both Program Upgrade & Pool #0 authority during pre-audit):** `3WzAUVNX5tm9gJWS2Y2Vg3wMnAtTm23fFX2jHaYy67bV` - **Deployed Mainnet Binary (`v1.6.0`, sBPFv3, `194,496 B`):** - ELF SHA-256: `82a6b1250c7087b1abe64dfd44c9426e00908e642ed5473d5b3ae0502d1aed96` - `solana-verify` Executable Hash: `6dd997851e9b9b7331405c8f82816458eb00f1d9f3358038c1d56b32527f8d99` - OtterSec Verified Git Commit: `ae01c9b67cff9e58e99866b6652665e070bd4318` - Mainnet Deploy Slot: `477,052,804` - **Frozen Proving Artifacts:** - Proving Key (`audren_joinsplit.pk`, `3,927,280 B`): SHA-256 `2b22603e466c79b6710e01898dc8b458b09a3ee905b25db996f0c59e76187ee4` - WASM Prover (`audren_circuits.wasm`, `2,440,431 B`): SHA-256 `744997b6c4a7786cb11a38d6cecbe3084198260434391d8fc4580a14df3c65e5` - **Empirical Mainnet Transaction Register (note: transactions below are historical Mainnet verification evidence executed on `v1.3.0` sharing identical Pool #0 PDA, Groth16 VK, and core wire format; current deployed Mainnet program is `v1.6.0`, commit `ae01c9b6`, slot `477,052,804`; see `docs/DEPLOYMENTS.md` for full slot/revision provenance):** - Deposit: `2sxVUPJL4V5EUeXg66jV7Spg4ASMwLE5TCS3Mzyzt37sHuiTFn41B1EwfMevMy9EFVNhgWeeMbdDjYzPTuvnSWPY` - Private Transfer: `2tYSzyMcSTJpgYXGiWe1uZJLxjZagQobSsVjcnzm4cy86Mty359VHUKJdHaqG6d5FTqRSYS7qZCECfistrzKtXV3` - ExecViaEscrow Jupiter Swap: `2NDZwvx1uNxhCSYJSZQiodXSWEcaVY6NxPkBDZreDdrcdPtxSXks9PRfSPsKXZFPPHnPNxTMHMrdkkpng2cHj9y6` - ExecViaEscrow DFlow Swap: `22NM7tGVsvU78mcWvMqRhxLU8vUuGzpAwaF4XFCvhHa4KPnYz5xqJceLqpQzZLcAP8X7Ypb45774mMPF4D84hLTm` - ExecViaEscrow Kamino Lending Supply (`USDC -> cUSDC`): `4CWAS6AexKHc8ZnBDtKXx2teBcfpMA57RkymdRTpxottrF7bVwgTozVwAGpYhUCp9ordizZGZkRe8JtnLXXcUU1J` - ExecViaEscrow Kamino Yield Vault Deposit (`USDC -> kPrimeUSDC`): `58owZkFXkZ8a2jG2Ntv3fWYMMnwvpFbyHa5ro3hchNokLj4Ee6kYrjce9ixMJx1vLiKTYDQ84U7Ly1HM61TzvTHh` - Withdraw (with atomic WSOL unwrap): `4mkKXz4cLt5Z3qj5m6xgFoRvtzQ8d5VFYYSkXvnnkxfKn7F9anoBiXa2uTK73DeqwGhC6okfCMxeG7bKr2y5KQc7` --- ## 5. On-Chain Program Specification (10 Instructions, 14 PDA Seeds, CU Budgets) The program (`program/src/**`) is `#![no_std]` Pinocchio `0.12.0` (SIMD-0449 `program_entrypoint_with_r2!`) sBPFv3 (linking only `audren-core`, `pinocchio`, `pinocchio-system`, `groth16-solana`, and `solana-poseidon`) with zero off-chain runtime dependencies (no cranks, indexers, or Foresters). Every wire constant is mirrored from `crates/audren-core/` into `idl/audren.codama.json`, `idl/audren.anchor.json`, and `@audren-xyz/sdk`. ### 10 Instructions (`Tag 0..=9`) & Calibrated Tight CU Budgets | Tag | Instruction | Measured CU | Recommended CU Limit (`CU_LIMIT_*`) | Notes | |---|---|---|---|---| | `0` | `InitPool` | `10,433` | `45,000` (`CU_LIMIT_INIT_POOL`) | Creates `PoolState` (`AUD1PL01`), stores `VaultAuth` bump, initializes `GlobalRootHistory` (`AUD1RT01`, immutable `root_epoch_interval` in `1..=256`, default `32`), `active_lanes = 0`. | | `1` | `InitLane` | `36,665` | `75,000` (`CU_LIMIT_INIT_LANE`) | Authority-signed sequential lane activation (`0 -> 4`, expandable `4 -> 8 -> 16` with zero circuit change). Creates `LaneTreeState` (`1,824 B`), `LaneRentVault`, and seq-0 pages. | | `2` | `OpenPage` | `13,514` | `40,000` (`CU_LIMIT_OPEN_PAGE`) | Idempotent `LaneRentVault`-subsidized page pre-allocation (`SubtreePage`, `SubtreeRootPage`, `MemoPage`, `NullifierPage`). Auto-prepended inline by wallets/relayers. | | `3` | `Deposit` | `53,971-55,590` (T22 Hook `67,117`) | `75,000` (`CU_LIMIT_DEPOSIT`) / `140,000` (`CU_LIMIT_DEPOSIT_HOOK`) | Unified native SOL (`DEPOSIT_FLAG_NATIVE_SOL` via `SyncNative`) and SPL/Token-2022 net-delta deposit + inline `GlobalRootHistory` update. Zero ZK proof. Always submitted by depositor directly. | | `4` | `InitRootHistory` | `17,169-41,755` | `75,000` (`CU_LIMIT_INIT_ROOT_HISTORY`) | Authority-gated one-shot `GlobalRootHistory` initialization from live active lane roots across `4..16` lanes. | | `5` | `Transact` | Full Exit `115,691-121,091`; Withdraw `144,813-217,442` (T22 Hook `231,828`); Private `204,906` | Full Exit `165,000` (`CU_LIMIT_TRANSACT_FULL_EXIT`); Withdraw `255,000` (`CU_LIMIT_TRANSACT_WITHDRAW`) / `295,000` (`CU_LIMIT_TRANSACT_WITHDRAW_HOOK`); Private `235,000` (`CU_LIMIT_TRANSACT_PRIVATE`) | 2-in/3-out BN254 Groth16 (`192 B`). `ASSET_MODE_PRIVATE` hides asset/amount/recipient; `ASSET_MODE_PUBLIC` enforces mandatory writable `VaultGuard` (`accounts[18]`, `OutflowCapExceeded = 6033`) and withdraws SPL/T22 or atomically unwraps WSOL (`WITHDRAW_FLAG_UNWRAP_WSOL`). Full exits (`output_mask == 0`) lock `GlobalRootHistory` read-only and remain open during `PAUSE_SOFT = 1` (halted on `PAUSE_HARD_FREEZE = 2`). | | `6` | `ExecViaEscrow` | `164,563-237,889` base | `285,000` (`CU_LIMIT_EXEC_VIA_ESCROW_BASE`) + router CPI | Protocol-neutral external Native SOL / SPL / Token-2022 DeFi CPI via 16 sharded escrow PDAs (`audren_escrow`), enforcing mandatory writable `VaultGuard` (`in_leg[5]`, `OutflowCapExceeded = 6033`). Binds router program, normalized router accounts, `min_amount_out`, `relayer_fee`, `EXEC_FLAG_FEE_ON_OUTPUT`, `EXEC_FLAG_REFUND_LEFTOVER` (`AUD1RFD1`), `EXEC_FLAG_ZERO_OUTPUT`, `EXEC_FLAG_NATIVE_SOL_IN`, `EXEC_FLAG_EXTENDED` (`EXEC_EXT_FLAG_NATIVE_SOL_OUT` / `EXEC_EXT_FLAG_SEPARATE_HOOK_ACCOUNTS`), and `AUD1DYN1` output memo keystream inside `ctx_hash`. | | `7` | `SetPaused` | ~8k | `25,000` | Sets `PAUSE_OPEN = 0`, `PAUSE_SOFT = 1` (halts deposits/transfers/partial exits/DeFi while keeping whole-note full exits open), or `PAUSE_HARD_FREEZE = 2` (halts all outflows including full exits). Pool authority or delegated `PoolGuardian` may engage soft/hard pause; only pool authority may unpause. | | `8` | `UpdatePool` | ~10k | `25,000` | Updates bounded `note_rent_fee`/`nf_rent_fee` caps, 2-step authority transfer, permanent authority renouncement (forbidden while paused), delegated `PoolGuardian` config (action 4), or per-mint `VaultGuard` token-bucket outflow rate caps (action 5). `root_epoch_interval` is immutable after init. | | `9` | `TripSoundnessCanary` | `81,345` | `165,000` (`CU_LIMIT_TRIP_SOUNDNESS_CANARY`) | Permissionless BN254 soundness circuit breaker. Any caller presenting a valid Groth16 proof over the unprovable synthetic sentinel public input (`mask_to_fr_be(SHA-256("audren/v1/soundness_canary" || program_id || pool_id_le4 || vk_id))`) immediately engages `PAUSE_HARD_FREEZE = 2`, halting all vault outflows before a soundness break can drain funds. | ### 14 Canonical PDA Seeds (`audren_*`) `audren_pool`, `audren_vault_auth`, `audren_roots`, `audren_lane`, `audren_lane_rent`, `audren_subtree`, `audren_subroot`, `audren_memo`, `audren_nf_page`, `audren_nf`, `audren_escrow`, `audren_unwrap`, `audren_guardian`, `audren_guard`. ### Critical Terminology Note (Solana) Use canonical Solana fee terminology everywhere: **Solana transaction fees**, **priority fees**, **compute units (CU)**, and **Solana rent (`SysvarRent`)** (never EVM terminology). --- ## 6. TypeScript SDK (`@audren-xyz/sdk`) — Turnkey Copy-Paste Integration Recipes Requires **Node `>= 22`** (or modern browser with WebCrypto + WebAssembly). Install from npm (zero API keys required for core shielding, syncing, and proving): ```bash npm install --save-exact @audren-xyz/sdk@1.6.5 ``` Package entry points: - **`@audren-xyz/sdk`** — Zero-WASM tree-shakeable core (`"sideEffects": false`). Key exports: - Keys, PQ self-memos, payment memos & compliance: `deriveKeysFromSeed`, `deriveSubaccountKeys`, `exportFullViewingKey`, `exportSubaccountFullViewingKey`, `deriveDefiSessionKeypair`, `encryptNoteMemo`, `encryptSelfNoteMemo`, `prepareDynamicSelfNoteMemo`, `tryDecryptAndVerifyMemo`, `exportSelectiveDisclosureProof`, `verifySelectiveDisclosureProof`, `parseAudrenAddress`, `formatAudrenAddress`, `encodePaymentIdUtf8`, `encodePaymentIdHex`, `encodePaymentId`, `decodePaymentIdUtf8`, `formatPaymentId`, `isZeroPaymentId`, `buildAudrenPaymentUri`, `parseAudrenPaymentUri` (secret fields `spendSk`, `spendSkBytes`, `nk`, `nkBytes`, `viewSk`, `secretSeed` are non-enumerable and redacted in `toJSON` / `util.inspect`). - PDAs & decoders: `derivePoolPdaSync`, `deriveRootsPdaSync`, `deriveVaultAuthPdaSync`, `deriveLanePdaSync`, `deriveSubtreePdaSync`, `deriveMemoPdaSync`, `deriveNfPagePdaSync`, `deriveNullifierPdaSync`, `deriveEscrowPdaSync`, `deriveUnwrapPdaSync`, `deriveGuardianPdaSync`, `deriveVaultGuardPdaSync`, `decodePoolState`, `decodeGlobalRootHistory`, `decodeSubtreePage`, `decodePoolGuardian`, `decodeVaultGuard`. - Zero-indexer store & scanner: `CompactWalletStore` (`.toJSON()` / `CompactWalletStore.fromJSON()`, `.unspentNotes(mintHex?)`, `.notesByPaymentId(paymentId, { includeSpent?, mint? })`, lane-local `leafIndex`), `createSolanaRpcBatchFetcher`, `fetchPoolAndLanes`, `syncCompactStoreWithRpc`, `fetchGlobalRootHistory`, `reconstructWitnessesForNotes`, `reconstructWitness`. - Instruction builders, planners & Tx v1: `selectInputNotes`, `planConsolidationPairs`, `planMultiNoteSpend`, `prepareExecViaEscrowAction`, `discoverIntermediateEscrowAtas`, `parseToken2022TransferFeeConfig`, `parseToken2022TransferHook`, `deriveExtraAccountMetaListPda`, `DYN_REFUND_MAGIC`, `EXEC_FLAG_REFUND_LEFTOVER`, `EXEC_FLAG_ZERO_OUTPUT`, `EXEC_FLAG_NATIVE_SOL_IN`, `EXEC_FLAG_EXTENDED`, `EXEC_EXT_FLAG_NATIVE_SOL_OUT`, `EXEC_EXT_FLAG_SEPARATE_HOOK_ACCOUNTS`, `PAUSE_OPEN`, `PAUSE_SOFT`, `PAUSE_HARD_FREEZE`, `computePageRollovers`, `planAutoOpenPages`, `buildAutoOpenPageInstructions`, `buildOpenPageInstruction`, `buildDepositInstruction`, `buildTransactInstruction`, `buildExecViaEscrowInstruction`, `buildSetPausedInstruction`, `buildUpdatePoolInstruction`, `buildTripSoundnessCanaryInstruction`, `computeTransactCtxHash`, `computeExecCtxHash`, `toV1Instruction`, `compileV1Message`, `serializeV1Transaction`, `recommendedDepositCuLimit`, `recommendedTransactCuLimit`, `recommendedExecViaEscrowCuLimit`. - Mode 3 Live ZK Proof of Holdings (`audren-balance-proof/v1`, zero WASM for verifiers): `BALANCE_PROOF_SCHEMA`, `BALANCE_PROOF_CTX_DOMAIN` (`"audren/v1/balance_proof"`), `BALANCE_PROOF_HTTP_HEADER` (`"X-Audren-Holdings-Proof"`), `BALANCE_PROOF_CHALLENGE_HTTP_HEADER` (`"X-Audren-Holdings-Challenge"`), `GATEWAY_HOLDINGS_CHALLENGE_DOMAIN`, `deriveGatewayHoldingsChallenge`, `AudrenBalanceProofError` (`code`: `INVALID_FORMAT | INVALID_PROOF | EXPIRED | ROOT_MISMATCH | NOTE_SPENT | RPC_ERROR`), `prepareHoldingsProof`, `planThresholdBalanceProof`, `computeBalanceProofCtxHash`, `buildThresholdBalanceWitnesses`, `assembleThresholdBalanceProof`, `verifyGroth16Proof192`, `verifyThresholdBalanceProofCrypto`, `getBalanceProofRpcAccounts`, `verifyHoldings` (alias `verifyThresholdBalanceProofOnChain`, supporting `fetchMultipleAccountsWithOwner`), `verifyPortfolioHoldings`, `encodeBalanceProofHeader`, `decodeBalanceProofHeader`, `generateBalanceProofChallenge` (plus 1-call `proveHoldings`, `provePortfolioHoldings`, `proveHoldingsForGateway`, `proveThresholdBalance`, and `proveAssetOwnership` on `@audren-xyz/sdk/prover`). - Gateway client (`audren-gateway/v1`): `AudrenGatewayClient`, `AudrenGatewayError`, `AudrenGatewayErrorCode`, `AUDREN_DEFAULT_GATEWAY_URL` (`https://gateway.audren.xyz`), `AUDREN_DEFAULT_DEVNET_GATEWAY_URL` (`https://devnet-gateway.audren.xyz`). Constructor & per-request options support `apiKey`, `bearerToken`, `holdingsProof` (auto-attaching `X-Audren-Holdings-Proof` on `/v1/fee-quote` & `/v1/relay/submit` while omitting constructor defaults on `/health` and discovery/admin routes to prevent nullifier leakage), `timeoutMs`, and `headers`. Methods: `.getHealth()`, `.getInfo(cluster?)` (typed `policy.holdingsGate` and `limits`), `.getFeeQuote(params)`, `.submitRelayedInstruction(params)`, `.getStats()`, `.postAdminRefill()`. - Server-side multi-aggregator router: `AudrenSwapRouter`, `AudrenSwapRouter.fromEnv(env)`, `JUPITER_CPI_EXCLUDED_DEXES` (8 venues), `AUDREN_AUDITED_SWAP_ROUTERS`, `.listProviders()`, `.quote(req)`, `.buildSwapInstructions(req)`, `.planPrivateSwap(req)`. - **`@audren-xyz/sdk/idl`** — Embedded `AUDREN_CODAMA_IDL` (Codama v1.8.0) and `AUDREN_ANCHOR_IDL` (Anchor v0.30+). - **`@audren-xyz/sdk/prover`** — `AudrenWasmProver` (`.init({ wasmUrl?, pkUrl? })`, `.proveJoinsplit(witness, seed32?)`, `.dispose()`, taking a structured `JoinSplitWitness` and encoding the `4,611 B` binary ABI internally), `proveHoldings`, `provePortfolioHoldings`, `proveHoldingsForGateway`, `proveThresholdBalance`, `proveAssetOwnership`, and `encodeJoinsplitWitness`. In Node.js, `AudrenWasmProver.init()` reads the bundled `.wasm` and `.pk` automatically; in browsers, copy both files from `node_modules/@audren-xyz/sdk/wasm/` to your static `/wasm/` folder and pass their URLs. Both SHA-256 digests are verified fail-closed by default. All five end-to-end TypeScript recipes below are verified against `@audren-xyz/sdk@1.6.5` on Node 22+ with zero runtime dependencies beyond `@audren-xyz/sdk`: ### Recipe 6.1 — Shield Native SOL (`Deposit`, Tag 3 -> Compiled Solana Tx v1 -> RPC `sendTransaction`) ```ts import { WSOL_MINT, base58Decode, buildAutoOpenPageInstructions, buildDepositInstruction, compileV1Message, computePageRollovers, createSolanaRpcBatchFetcher, deriveStealthOwner, encryptNoteMemo, fetchPoolAndLanes, frFromBeBytesStrict, parseAudrenAddress, pickRandomLaneId, recommendedDepositCuLimit, serializeV1Transaction, toV1Instruction, } from '@audren-xyz/sdk'; export async function shieldNativeSol(params: { rpcUrl: string; depositorPubkey: string; recipientAudrenAddress: string; amountLamports: bigint; recentBlockhashB58: string; signMessageEd25519: (messageBytes: Uint8Array) => Promise; }): Promise { const fetchBatch = createSolanaRpcBatchFetcher(params.rpcUrl); const { pool, lanes } = await fetchPoolAndLanes(fetchBatch, 0); const laneId = pickRandomLaneId(pool.activeLanes); const lane = lanes[laneId]; if (!lane) throw new Error(`Lane ${laneId} not initialized`); // For deposits to a third-party `aud1...` address, use X25519 `encryptNoteMemo(...)`. // For self-owned deposits (where you hold `keys.nkBytes`), use PQ symmetric `encryptSelfNoteMemo(keys.nkBytes, ephSeed32, amount, mintBytes)`. const recipient = parseAudrenAddress(params.recipientAudrenAddress); const ephSecret32 = crypto.getRandomValues(new Uint8Array(32)); const { tweak, blinding, memo } = encryptNoteMemo( recipient.viewPk, ephSecret32, params.amountLamports, base58Decode(WSOL_MINT), ); const stealthOwner = deriveStealthOwner(frFromBeBytesStrict(recipient.spendPk), tweak); const plan = computePageRollovers({ leafCount: lane.nextLeaf, outputCount: 1, nfCount: lane.nfCount, spentNullifiers: 0, }); const openPageIxs = buildAutoOpenPageInstructions({ payer: params.depositorPubkey, poolId: 0, laneId, nextLeaf: lane.nextLeaf, nfCount: lane.nfCount, numOutputs: 1, numNfs: 0, }); const depositIx = buildDepositInstruction({ depositor: params.depositorPubkey, poolId: 0, laneId, subPageSeq: BigInt(plan.outSubSeq), rootPageSeq: BigInt(plan.outRootSeq), memoPageSeq: BigInt(plan.outMemoSeq), nativeSol: true, amount: params.amountLamports, stealthOwner, blinding, memo, rollover: { nextSubSeq: plan.nextSubSeq !== undefined ? BigInt(plan.nextSubSeq) : null, nextMemoSeq: plan.nextMemoSeq !== undefined ? BigInt(plan.nextMemoSeq) : null, }, }); const instructions = [...openPageIxs, depositIx].map(toV1Instruction); const compiled = compileV1Message({ feePayer: base58Decode(params.depositorPubkey), recentBlockhash: base58Decode(params.recentBlockhashB58), instructions, config: { computeUnitLimit: recommendedDepositCuLimit({ openPageCount: openPageIxs.length }), priorityFeeLamports: 1_000n, }, }); const sig64 = await params.signMessageEd25519(compiled.messageBytes); const txBytes = serializeV1Transaction(compiled, [sig64]); const res = await fetch(params.rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'sendTransaction', params: [Buffer.from(txBytes).toString('base64'), { encoding: 'base64' }], }), }); const json = (await res.json()) as { result?: string; error?: { message?: string } }; if (!json.result) throw new Error(json.error?.message ?? 'sendTransaction failed'); return json.result; } ``` ### Recipe 6.2 — End-to-End Private Transfer (Sync -> Witnesses -> Groth16 Proof -> `Transact` Tag 5 -> Gateway Submit) ```ts import { ASSET_MODE_PRIVATE, AudrenGatewayClient, CompactWalletStore, WSOL_MINT, base58Decode, buildTransactInstruction, bytes32ToFrMasked, computePageRollovers, computeTransactCtxHash, createSolanaRpcBatchFetcher, deriveAssetId, deriveKeysFromSeed, deriveStealthOwner, encryptNoteMemo, encryptSelfNoteMemo, exportFullViewingKey, exportSelectiveDisclosureProof, fetchGlobalRootHistory, fetchPoolAndLanes, frFromBeBytesStrict, parseAudrenAddress, pickRandomLaneId, reconstructWitnessesForNotes, syncCompactStoreWithRpc, } from '@audren-xyz/sdk'; import { AudrenWasmProver, dummyInputWitness, dummyOutputWitness, type JoinSplitWitness, } from '@audren-xyz/sdk/prover'; export async function sendPrivateTransfer(params: { seed32: Uint8Array; rpcUrl: string; recipientAudrenAddress: string; sendAmount: bigint; operatorGatewayUrl: string; // or compile + self-pay / burner wallet with compileV1Message bearerToken?: string; }) { const keys = deriveKeysFromSeed(params.seed32); const fvk = exportFullViewingKey(keys); const fetchBatch = createSolanaRpcBatchFetcher(params.rpcUrl); // 1. Sync CompactWalletStore over ordinary Solana RPC until !res.incomplete const store = new CompactWalletStore(0); let synced = false; for (let pass = 0; pass < 10_000; pass++) { const res = await syncCompactStoreWithRpc({ store, fvk, fetchBatch }); if (!res.incomplete) { synced = true; break; } } if (!synced) throw new Error('Wallet sync incomplete; do not display balance or spend'); // 2. Select same-asset inputs (store.unspentNotes expects 64-char lowercase hex mint) const mintBytes = base58Decode(WSOL_MINT); const mintHex = Array.from(mintBytes, (b) => b.toString(16).padStart(2, '0')).join(''); const note0 = store.unspentNotes(mintHex).find((n) => n.amount >= params.sendAmount); if (!note0) throw new Error('Insufficient single-note WSOL balance'); // 3. Fetch GlobalRootHistory + reconstruct decoy-padded 4-ary Merkle witness const [{ history, snapshot }, { pool, lanes }] = await Promise.all([ fetchGlobalRootHistory({ poolId: 0, rpcUrl: params.rpcUrl, requiredNotes: [note0] }), fetchPoolAndLanes(fetchBatch, 0), ]); const { paths, superRoot, rootRingKind, rootRingIdx } = await reconstructWitnessesForNotes({ fetchBatch, poolId: 0, notes: [note0], rootHistory: history, rootSnapshot: snapshot, nk: fvk.nk, }); // 4. Query optional Gateway info + guarded fee quote (omit mint when not pricing shielded cm2 fees) const gateway = new AudrenGatewayClient(params.operatorGatewayUrl, { ...(params.bearerToken ? { bearerToken: params.bearerToken } : {}), }); const info = await gateway.getInfo('mainnet'); if (!info.relayerPubkey) throw new Error('Gateway has no active fee payer'); const needsFeeMint = (info.feeModel === 'onchain' || info.feeModel === 'hybrid') && Boolean(info.relayerShieldedAddress); const feeQuote = info.capabilities?.includes('fee-quote') ? await gateway.getFeeQuote({ op: 'transfer', cluster: 'mainnet', ...(needsFeeMint ? { mint: WSOL_MINT } : {}), outputCount: 3, }) : null; const cm2Fee = feeQuote?.billingMode === 'self_paying' ? BigInt(feeQuote.relayerFee) : 0n; const changeAmount = note0.amount - params.sendAmount - cm2Fee; if (changeAmount < 0n) throw new Error('Insufficient balance for sendAmount + relayer fee'); // 5. Encrypt uniform 3 output memos (recipient cm0, change cm1, fee/dummy cm2) + compute ctx_hash const outLaneId = pickRandomLaneId(pool.activeLanes); const outLane = lanes[outLaneId]; if (!outLane) throw new Error(`Lane ${outLaneId} not initialized`); const rec = parseAudrenAddress(params.recipientAudrenAddress); const feeTarget = cm2Fee > 0n && feeQuote?.feeShieldedAddress ? parseAudrenAddress(feeQuote.feeShieldedAddress) : null; // When cm2 is a zero-value dummy padding output, seal m2 to an ephemeral throwaway view key // (never to `keys.viewPk` or the recipient's view key) so it never triggers spurious view-tag hits. const m2ViewPk = feeTarget ? feeTarget.viewPk : deriveKeysFromSeed(crypto.getRandomValues(new Uint8Array(32))).viewPk; const m0 = encryptNoteMemo(rec.viewPk, crypto.getRandomValues(new Uint8Array(32)), params.sendAmount, mintBytes); // Encrypt non-zero self-change with PQ symmetric `nk`; when changeAmount === 0n (padding), seal to a fresh random key so it never triggers spurious view-tag hits. const m1 = changeAmount > 0n ? encryptSelfNoteMemo(keys.nkBytes, crypto.getRandomValues(new Uint8Array(32)), changeAmount, mintBytes) : encryptNoteMemo( deriveKeysFromSeed(crypto.getRandomValues(new Uint8Array(32))).viewPk, crypto.getRandomValues(new Uint8Array(32)), 0n, mintBytes, ); const m2 = encryptNoteMemo(m2ViewPk, crypto.getRandomValues(new Uint8Array(32)), cm2Fee, mintBytes); const memosBytes = new Uint8Array(m0.memo.byteLength + m1.memo.byteLength + m2.memo.byteLength); memosBytes.set(m0.memo, 0); memosBytes.set(m1.memo, m0.memo.byteLength); memosBytes.set(m2.memo, m0.memo.byteLength + m1.memo.byteLength); const assetId = deriveAssetId(mintBytes); const ctxHash = computeTransactCtxHash({ poolId: 0, outLaneId, outputMask: 0b111, assetMode: ASSET_MODE_PRIVATE, unwrapWsol: false, publicAssetId: new Uint8Array(32), publicAmountOut: 0n, relayerFeeAmount: 0n, // private transfers pay relayer fees inside shielded cm2 memosBytes, }); // 6. Prove locally in WASM (reuse one prover instance in long-lived apps; dispose when done) const randomFr = () => bytes32ToFrMasked(crypto.getRandomValues(new Uint8Array(32))); const prover = await AudrenWasmProver.init(); const witness: JoinSplitWitness = { superRoot, txAssetId: assetId, publicAssetId: 0n, publicAmountOut: 0n, relayerFeeAmount: 0n, ctxHash, omitNf1: false, inputs: [ { spendSk: keys.spendSk, tweak: frFromBeBytesStrict(note0.tweak), assetId, amount: note0.amount, blinding: frFromBeBytesStrict(note0.blinding), isDummy: false, merklePath: paths[0]!, }, dummyInputWitness(keys.spendSk, assetId, randomFr()), ], outputs: [ { stealthOwner: deriveStealthOwner(frFromBeBytesStrict(rec.spendPk), m0.tweak), assetId, amount: params.sendAmount, blinding: m0.blinding }, { stealthOwner: deriveStealthOwner(keys.spendPk, m1.tweak), assetId, amount: changeAmount, blinding: m1.blinding }, cm2Fee > 0n && feeTarget ? { stealthOwner: deriveStealthOwner(frFromBeBytesStrict(feeTarget.spendPk), m2.tweak), assetId, amount: cm2Fee, blinding: m2.blinding } : dummyOutputWitness(assetId, randomFr()), ], }; let proof; try { proof = prover.proveJoinsplit(witness); } finally { prover.dispose(); } // 7. Build Tag 5 instruction and submit to the chosen audren-gateway/v1 endpoint const roll = computePageRollovers({ leafCount: outLane.nextLeaf, outputCount: 3, nfCount: outLane.nfCount, spentNullifiers: 2, }); const ix = buildTransactInstruction({ payer: info.relayerPubkey, poolId: 0, rootRingKind, rootRingIdx, outLaneId, outSubSeq: BigInt(roll.outSubSeq), outRootSeq: BigInt(roll.outRootSeq), outMemoSeq: BigInt(roll.outMemoSeq), outNfSeq: BigInt(roll.nfPageSeq), outputMask: 0b111, assetMode: ASSET_MODE_PRIVATE, proof192: proof.proof192, nf0: proof.nf0, nf1: proof.nf1, cm0: proof.cm0, cm1: proof.cm1, cm2: proof.cm2, publicAmountOut: 0n, relayerFeeAmount: 0n, memosBytes, rollover: { nextSubSeq: roll.nextSubSeq !== undefined ? BigInt(roll.nextSubSeq) : null, nextMemoSeq: roll.nextMemoSeq !== undefined ? BigInt(roll.nextMemoSeq) : null, nextNfSeq: roll.nextNfSeq !== undefined ? BigInt(roll.nextNfSeq) : null, }, }); // Optional Mode 1 receipt export (send out-of-band; verifier checks SubtreePage on its own RPC) const receipt = exportSelectiveDisclosureProof(note0); const submitted = await gateway.submitRelayedInstruction({ cluster: 'mainnet', instructionDataB64: Buffer.from(ix.data).toString('base64'), accounts: ix.accounts, }); return { submitted, receipt }; } ``` ### Recipe 6.3 — Auditor / Counterparty Mode 1 Receipt Verification (Separate Verifier Process) ```ts import { createSolanaRpcBatchFetcher, decodeSubtreePage, deriveSubtreePdaSync, verifySelectiveDisclosureProof, type SelectiveDisclosureProof, } from '@audren-xyz/sdk'; export async function verifyReceiptOnAuditorRpc( receipt: SelectiveDisclosureProof, auditorRpcUrl: string, ): Promise { const fetchBatch = createSolanaRpcBatchFetcher(auditorRpcUrl); const pageSeq = receipt.leafIndex / 256n; const [pageBytes] = await fetchBatch([ deriveSubtreePdaSync(receipt.poolId, receipt.laneId, pageSeq).address, ]); if (!pageBytes) throw new Error('SubtreePage unavailable from RPC'); const leaf = decodeSubtreePage(pageBytes).leaves[Number(receipt.leafIndex % 256n)]; return leaf ? verifySelectiveDisclosureProof(receipt, leaf) : false; } ``` ### Recipe 6.4 — End-to-End Shielded Swap (`AudrenSwapRouter` Server Planner + Client `ExecViaEscrow` Tag 6) Swap routing is decoupled from Gateways so Gateway operators never need DEX aggregator API keys. Keep aggregator secrets strictly on your backend/worker (never ship OKX/Jupiter/Bedrock/bloXroute credentials to browser clients). `AudrenSwapRouter` abstracts six Solana DEX aggregators behind one interface with `'auto'` parallel racing and mandatory CPI-excluded venue filtering (`JUPITER_CPI_EXCLUDED_DEXES` / `BLOXROUTE_CPI_EXCLUDED_DEXES`; passing `excludeDexes: []` disables filtering; omit to keep the safe default): - **Jupiter** (`JUPITER_API_KEY`, optional `JUPITER_API_URL`, default `https://api.jup.ag`) - **DFlow** (`DFLOW_API_KEY`, optional `DFLOW_API_URL`) - **OKX** (`OKX_API_KEY`, `OKX_SECRET_KEY`, `OKX_PASSPHRASE`, optional `OKX_API_URL`) - **Titan** (`TITAN_API_KEY` or `TITAN_API_URL`) - **Bedrock** (`BEDROCK_API_URL` + `BEDROCK_API_KEY` or Ed25519 JWT via `BEDROCK_SIGNING_KEY`, where 64-byte Solana Ed25519 keypairs have their embedded 32-byte public key verified against the seed before signing) - **bloXroute** (public templates start on bloXroute's free keyless public testing endpoint `BLOXROUTE_API_URL=https://api-dev.blox.ag`; once API-whitelisted by bloXroute, migrate to production `https://api.blox.ag` with raw `BLOXROUTE_AUTH_HEADER` sent verbatim with no `Bearer` prefix; supports `platformFeeBps`/`platformFeeMode`/`platformFeeAccount` and Transaction v1 `heapSize` passthrough) - Plus custom `SwapAggregatorAdapter` plugins via `router.register(adapter)`. ```ts import { AudrenSwapRouter, WSOL_MINT, base58Decode, buildExecViaEscrowInstruction, bytes32ToFrMasked, computeExecCtxHash, computePageRollovers, deriveAssetId, deriveAssetIdBytes, deriveKeysFromSeed, deriveStealthOwner, encryptSelfNoteMemo, frFromBeBytesStrict, frToBeBytes, pickRandomEscrowShard, prepareDynamicSelfNoteMemo, recommendedExecViaEscrowCuLimit, type AudrenPlannedPrivateSwap, type DecodedLaneHeader, type MerklePath4Ary, type OwnedNote, } from '@audren-xyz/sdk'; import { AudrenWasmProver, dummyInputWitness, dummyOutputWitness, type JoinSplitWitness, } from '@audren-xyz/sdk/prover'; // 1. Server-side / Cloudflare Worker only (keeps aggregator API keys off clients): export async function planShieldedSwapOnServer(amountLamports: bigint) { const router = AudrenSwapRouter.fromEnv(process.env); const shardId = pickRandomEscrowShard(); const plan = await router.planPrivateSwap({ poolId: 0, shardId, provider: 'auto', // races all configured aggregators by highest outAmount inputMint: WSOL_MINT, outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', amount: amountLamports.toString(), slippageBps: 50, }); return { shardId, plan }; } // 2. Client-side: bind plan into ctx_hash, prove locally, and build Tag 6 ExecViaEscrow export async function buildShieldedSwapInstruction(params: { seed32: Uint8Array; payerPubkey: string; shardId: number; plan: AudrenPlannedPrivateSwap; inputNote: OwnedNote; inputPath: MerklePath4Ary; superRoot: bigint; rootRingKind: number; rootRingIdx: number; outLane: DecodedLaneHeader; }) { const keys = deriveKeysFromSeed(params.seed32); const inMintBytes = base58Decode(params.plan.quote.inputMint); const outMintBytes = base58Decode(params.plan.quote.outputMint); const amountIn = BigInt(params.plan.quote.inAmount); const minAmountOut = BigInt(params.plan.quote.otherAmountThreshold); const changeAmount = params.inputNote.amount - amountIn; if (changeAmount < 0n) throw new Error('Input note smaller than swap amountIn'); const dyn = prepareDynamicSelfNoteMemo(keys.nkBytes, crypto.getRandomValues(new Uint8Array(32))); const outStealthOwnerFr = deriveStealthOwner(keys.spendPk, dyn.tweak); const outStealthOwner = frToBeBytes(outStealthOwnerFr); const outBlinding = frToBeBytes(dyn.blinding); const changeMemo = changeAmount > 0n ? encryptSelfNoteMemo(keys.nkBytes, crypto.getRandomValues(new Uint8Array(32)), changeAmount, inMintBytes) : null; const changeMask = changeMemo ? 0b01 : 0; const changeMemos = changeMemo ? changeMemo.memo : new Uint8Array(0); const routerIxData = Uint8Array.from(Buffer.from(params.plan.instructions.swapInstruction.data, 'base64')); const ctxHash = computeExecCtxHash({ poolId: 0, outLaneId: params.outLane.laneId, escrowShard: params.shardId, changeMask, feeOnOutput: false, assetIn: deriveAssetIdBytes(inMintBytes), amountIn, relayerFeeAmount: 0n, assetOut: deriveAssetIdBytes(outMintBytes), minAmountOut, routerProg: params.plan.instructions.swapInstruction.programId, routerAccounts: params.plan.prepared.routerAccounts, payer: params.payerPubkey, escrowInAta: params.plan.prepared.escrowInAta, escrowOutAta: params.plan.prepared.escrowOutAta, outStealthOwner, outBlinding, dynMemoHead: dyn.dynHead34, dynMemoMask: dyn.dynMask72, routerIxData, changeMemos, }); const assetInFr = deriveAssetId(inMintBytes); const randomFr = () => bytes32ToFrMasked(crypto.getRandomValues(new Uint8Array(32))); const prover = await AudrenWasmProver.init(); const witness: JoinSplitWitness = { superRoot: params.superRoot, txAssetId: assetInFr, publicAssetId: assetInFr, publicAmountOut: amountIn, relayerFeeAmount: 0n, ctxHash, omitNf1: false, inputs: [ { spendSk: keys.spendSk, tweak: frFromBeBytesStrict(params.inputNote.tweak), assetId: assetInFr, amount: params.inputNote.amount, blinding: frFromBeBytesStrict(params.inputNote.blinding), isDummy: false, merklePath: params.inputPath, }, dummyInputWitness(keys.spendSk, assetInFr, randomFr()), ], outputs: [ changeMemo ? { stealthOwner: deriveStealthOwner(keys.spendPk, changeMemo.tweak), assetId: assetInFr, amount: changeAmount, blinding: changeMemo.blinding } : dummyOutputWitness(assetInFr, randomFr()), dummyOutputWitness(assetInFr, randomFr()), dummyOutputWitness(assetInFr, randomFr()), ], }; let proof; try { proof = prover.proveJoinsplit(witness); } finally { prover.dispose(); } const roll = computePageRollovers({ leafCount: params.outLane.nextLeaf, outputCount: 1 + (changeMemo ? 1 : 0), nfCount: params.outLane.nfCount, spentNullifiers: 2, }); const ix = buildExecViaEscrowInstruction({ payer: params.payerPubkey, poolId: 0, rootRingKind: params.rootRingKind, rootRingIdx: params.rootRingIdx, outLaneId: params.outLane.laneId, outSubSeq: BigInt(roll.outSubSeq), outRootSeq: BigInt(roll.outRootSeq), outMemoSeq: BigInt(roll.outMemoSeq), outNfSeq: BigInt(roll.nfPageSeq), escrowShard: params.shardId, changeMask, inLeg: { mint: params.plan.quote.inputMint }, outLeg: { mint: params.plan.quote.outputMint }, relayerFeeAmount: 0n, proof192: proof.proof192, nf0: proof.nf0, nf1: proof.nf1, cm0: proof.cm0, cm1: proof.cm1, cm2: proof.cm2, amountIn, minAmountOut, outStealthOwner, outBlinding, dynMemoHead: dyn.dynHead34, dynMemoMask: dyn.dynMask72, routerProg: params.plan.instructions.swapInstruction.programId, routerIxData, routerAccounts: params.plan.prepared.routerAccounts, changeMemos, rollover: { nextSubSeq: roll.nextSubSeq !== undefined ? BigInt(roll.nextSubSeq) : null, nextMemoSeq: roll.nextMemoSeq !== undefined ? BigInt(roll.nextMemoSeq) : null, nextNfSeq: roll.nextNfSeq !== undefined ? BigInt(roll.nextNfSeq) : null, }, }); return { ix, computeUnitLimit: recommendedExecViaEscrowCuLimit({ routerCuLimit: params.plan.instructions.computeUnitLimit, }), }; } ``` ### Recipe 6.5 — Mode 3 Live ZK Proof of Holdings & Threshold Proofs (`audren-balance-proof/v1`) Prove live unspent shielded ownership of a hidden asset (`minThreshold = 1n`, exact balance hidden) or threshold holdings (`minThreshold = 20_000_000_000n` = `>= 20 SOL`) across `1..=8` disjoint sub-proofs (up to 16 notes, zero consolidation) with ZERO on-chain changes and ZERO WASM on the verifier side: ```ts import { AudrenGatewayClient, WSOL_MINT, generateBalanceProofChallenge, verifyHoldings, type AccountBatchFetcher, type AudrenKeys, type CompactWalletStore, } from '@audren-xyz/sdk'; import { AudrenWasmProver, proveHoldings } from '@audren-xyz/sdk/prover'; export async function proveAndVerifyThresholdHoldings(params: { prover: AudrenWasmProver; keys: AudrenKeys; store: CompactWalletStore; fetchBatch: AccountBatchFetcher; rpcUrl: string; mint?: string; minThreshold?: bigint; // 1n for hidden-asset ownership, or e.g. 20_000_000_000n for >= 20 SOL verifierDomain: string; }) { const mint = params.mint ?? WSOL_MINT; const minThreshold = params.minThreshold ?? 20_000_000_000n; const challenge = generateBalanceProofChallenge(); // or deriveGatewayHoldingsChallenge(...) // 1. Prover (client-side, 1 call: plans disjoint chunks, fetches GlobalRootHistory + witnesses, proves): const { proof, header } = await proveHoldings(params.prover, { keys: params.keys, store: params.store, fetchBatch: params.fetchBatch, mint, minThreshold, verifierDomain: params.verifierDomain, challenge, expiresAtUnix: Math.floor(Date.now() / 1000) + 900, }); // 2. Separate verifier (Node / Browser / Cloudflare Worker — zero WASM, 1 batched RPC call): const verified = await verifyHoldings( header, // accepts compact X-Audren-Holdings-Proof header, JSON string, or ThresholdBalanceProof { mint, minThreshold, verifierDomain: params.verifierDomain, challenge, requireExpiry: true, }, { rpcUrl: params.rpcUrl }, ); // 3. Optional VIP / holdings-gated Gateway submission (auto-attaches X-Audren-Holdings-Proof): const gateway = new AudrenGatewayClient('https://gateway.myapp.example', { holdingsProof: header }); return { proof, header, verified, gateway }; } ``` ### Browser Local Vault Encryption Reference (`apps/web/lib/vault-storage.ts`, Web App Reference) Note: encrypted browser persistence and `WELL_KNOWN_TOKENS` (25 mints in `apps/web/lib/protocol.ts`) are reference web-app modules rather than exports of `@audren-xyz/sdk`. In `apps/web/lib/vault-storage.ts`, `CompactWalletStore` snapshots and resolved mint metadata are encrypted at rest in IndexedDB (`audren_vault_store` / `compact_stores`, with encrypted `localStorage` fallback) using **AES-256-GCM** (random 12-byte IV, 128-bit tag), AAD = raw 32-byte `spendPkBytes`, and single-shot `SHA-256(nkBytes || utf8(domain))` key derivation with exact domains: - Wallet store: `audren/v2/compact-store-key:${cluster}:${poolId}` - Mint metadata: `audren/v2/mint-meta-key:${cluster}:${poolId}` - Portable passphrase backups: PBKDF2-SHA256 (600,000 iterations) + AES-256-GCM with AAD `audren-vault-backup-v1:${cluster}:${audrenAddress}`. --- ## 7. Rust, Swift & Kotlin SDKs + Exact 4-SDK Capability Matrix All four SDKs verify byte-for-byte cryptographic parity against `spec/test-vectors.json` on every CI run. Use this table for exact per-platform capabilities: | SDK | Packaging | Keys, PDAs, Memo Crypto, Mode 1/2 & All 10 Builders | Local Groth16 Prover | `CompactWalletStore` RPC Sync & Witness Reconstruction | Gateway HTTP Client & `AudrenSwapRouter` | | :--- | :--- | :---: | :---: | :---: | :---: | | **TypeScript** (`@audren-xyz/sdk@1.6.5`) | npm (`@audren-xyz/sdk`, `/prover`, `/idl`) | Yes (+ PQ self-memos + `payment_id`/URI codecs + Mode 3 pure-JS single & portfolio verifier) | Yes (WASM, browser/Node) | Yes | Yes (plus Tx v1 compiler) | | **Rust** (`crates/client`) | Git Cargo crate (`audren-client`) | Yes (+ PQ self-memos + 1-call Mode 3 prover & verifier) | Yes (native `ark-groth16`) | Yes | Zero HTTP deps (core/builders/planner only) | | **Swift** (`packages/swift`, iOS 15+ / macOS 13+) | Local SPM + XCFramework (`crates/audren-ffi`) | Yes (86 UniFFI exports, incl. PQ self-memos & native 1-call Mode 3 prover & verifier) | Yes (native from prepared `4,611 B` witness & Mode 3 store prover) | Not yet over UniFFI (embed Rust `audren-client` or bridge TS SDK) | App-layer HTTP | | **Kotlin** (`packages/kotlin`, Android API 24+ / JVM 21+) | Local Gradle 9.7.1 + JNA (`crates/audren-ffi`) | Yes (86 UniFFI exports, incl. PQ self-memos & native 1-call Mode 3 prover & verifier) | Yes (native from prepared `4,611 B` witness & Mode 3 store prover) | Not yet over UniFFI (embed Rust `audren-client` or bridge TS SDK) | App-layer HTTP | ### Running All 4 Examples & Verifying Byte-for-Byte Parity Prerequisites: clone both `audren-xyz/audren` (supplies `spec/test-vectors.json` and native `libaudren_ffi`) and `audren-xyz/examples`, and set `AUDREN_REPO_DIR`: ```bash git clone https://github.com/audren-xyz/audren.git git clone https://github.com/audren-xyz/examples.git export AUDREN_REPO_DIR="$PWD/audren" (cd "$AUDREN_REPO_DIR" && cargo build -p audren-ffi --release) # TypeScript (consumes published @audren-xyz/sdk from npm) pnpm --dir examples/typescript install --frozen-lockfile pnpm --dir examples/typescript quickstart pnpm --dir examples/typescript merchant-invoicing pnpm --dir examples/typescript holdings-proof pnpm --dir examples/typescript swap-plan pnpm --dir examples/typescript kamino-defi SOLANA_RPC_URL="https://your-rpc.example.com" pnpm --dir examples/typescript scan # Rust (run inside $AUDREN_REPO_DIR so rustup picks up rust-toolchain.toml pinning Rust 1.97.1) (cd "$AUDREN_REPO_DIR" && cargo run --release --manifest-path ../examples/rust/Cargo.toml -p audren-example-quickstart) (cd "$AUDREN_REPO_DIR" && cargo run --manifest-path ../examples/rust/Cargo.toml -p audren-example-shielded-transfer) (cd "$AUDREN_REPO_DIR" && cargo run --release --manifest-path ../examples/rust/Cargo.toml -p audren-example-institutional-audit) # Swift (macOS 13+) (cd examples/swift/quickstart && swift run) # Kotlin (JDK 21 + Gradle 9.7.1) (cd examples/kotlin/quickstart && gradle run) # Verify byte-for-byte quickstart parity across all 4 languages (each diff exits 0) diff -u \ <(cd "$AUDREN_REPO_DIR" && cargo run --release --quiet --manifest-path ../examples/rust/Cargo.toml -p audren-example-quickstart) \ <(pnpm --dir examples/typescript --silent quickstart) diff -u \ <(pnpm --dir examples/typescript --silent quickstart) \ <(cd examples/swift/quickstart && swift run -q) diff -u \ <(pnpm --dir examples/typescript --silent quickstart) \ <(cd examples/kotlin/quickstart && gradle -q run --no-daemon) ``` The `quickstart` output across Rust, TypeScript, Swift, and Kotlin is byte-for-byte identical (`diff -u` exits `0`). --- ## 8. Audren Gateway v1 (`audren-gateway/v1`) — Optional Fee-Payer Spec & Deployment Gateways are strictly optional fee-payers and policy enforcement edges holding zero custody and zero user spend/viewing keys (Durable Objects store only ephemeral rate-limit buckets with daily-salted IP hashes, daily sponsorship counters, and short-lived in-flight nullifier/broadcast locks). **No one needs a Gateway to use Audren** (Direct Self-Pay and funded one-time burner wallets submit directly via Solana RPC). ### Repository & Spec Boundaries - **Canonical Standalone Gateway Reference:** `https://github.com/audren-xyz/gateway` (single-cluster per deployment, Cloudflare Workers reference in `cloudflare/`, OpenAPI 3.1 contract in `spec/openapi.yaml`, 24-check conformance CLI `@audren-xyz/gateway-conformance`, signed OFAC/multi-feed snapshot publisher `@audren-xyz/gateway-screening-publisher`). Requires **Node `>= 22.13`** and **`pnpm 10`**. - **Hosted reference instances:** `https://gateway.audren.xyz` runs standalone `audren-xyz/gateway` on Mainnet (default `AUDREN_DEFAULT_GATEWAY_URL`), and `https://devnet-gateway.audren.xyz` runs standalone `audren-xyz/gateway` on Devnet (default `AUDREN_DEFAULT_DEVNET_GATEWAY_URL`). Independent operators should ALWAYS clone or deploy **`audren-xyz/gateway`** (`apps/relay/` in `audren-xyz/audren` is an un-deployed open-source multi-cluster template). ### Exact Mainnet Deployment Steps (Cloudflare Workers CLI or 1-Click Button) **1-Click Browser Deploy (Mainnet out of the gate):** `https://deploy.workers.cloudflare.com/?url=https://github.com/audren-xyz/gateway/tree/main/cloudflare` (`cloudflare/wrangler.jsonc` ships pre-configured for Mainnet with `CLUSTER="mainnet"`, Pocket Network public Mainnet RPC `https://solana.api.pocket.network`, `FEE_MODEL="hybrid"`, `ALLOW_PUBLIC_ONBOARDING_SUBSIDY="true"`, and zero blank optional fields — only `RELAYER_SECRETS_JSON` is required, accepting Phantom Base58, `solana-keygen` 64-byte JSON arrays, or `[""]`. Generate a local keypair or custom `wrangler.prod.jsonc` visually at `https://audren.xyz/gateways/`.) **CLI Custom Production Deployment (CRITICAL ORDER: edit `wrangler.prod.jsonc` BEFORE provisioning R2 or deploying, create R2 bucket + upload initial signed snapshot BEFORE deploy if screening via `r2://`, deploy Worker FIRST with `--config wrangler.prod.jsonc`, THEN attach secrets with `--config wrangler.prod.jsonc`, and fund `~0.25 SOL` working float above the `0.02 SOL` `LOW_BALANCE` cutoff):** ```bash # 1. Clone, install, and verify locally (Node >= 22.13, pnpm 10) git clone https://github.com/audren-xyz/gateway.git cd gateway/cloudflare npx --yes pnpm@10 install --frozen-lockfile npx --yes pnpm@10 run typecheck && npx --yes pnpm@10 test npx --yes pnpm@10 exec wrangler login cp wrangler.jsonc wrangler.prod.jsonc # gitignored; rename "name" so production never shares starter DO/secrets # 2. If enabling signed OFAC screening via R2: generate signing key outside repo & build signed snapshot locally umask 077 && mkdir -p ~/.config/audren-gateway-mainnet npx --yes @audren-xyz/gateway-screening-publisher --generate-key > ~/.config/audren-gateway-mainnet/screening-key.json SCREENING_SIGNING_KEY_HEX=$(node -p 'JSON.parse(require("fs").readFileSync(process.env.HOME+"/.config/audren-gateway-mainnet/screening-key.json","utf8")).signingKeySeedHex') \ npx --yes @audren-xyz/gateway-screening-publisher --out ~/.config/audren-gateway-mainnet/ofac-solana.json --min-addresses 1 # 3. Edit wrangler.prod.jsonc BEFORE provisioning R2 or deploying: # - "name": "audren-gateway-mainnet" # - Remove "RPC_URL" from "vars" so you can attach a private QuickNode / Helius / Triton URL as a Wrangler secret # - "r2_buckets": [{ "binding": "SCREENING_BUCKET", "bucket_name": "audren-mainnet-screening" }] # - "vars": # "CLUSTER": "mainnet", "ENVIRONMENT": "production", "FEE_MODEL": "hybrid" (or "onchain" | "offchain" | "free") # (omitted MAX_DAILY_SPONSORED_SOL & SPONSORED_* automatically apply Mainnet defaults: 0.05 SOL/d, 6/h, 12/d, 15s) # GeoIP: "BLOCKED_COUNTRIES": "CU,IR,KP,SY", "GEO_FAIL_CLOSED": "true", "GEO_BLOCK_INFO": "false" # Screening: "SCREENING_ENABLED": "true", "SCREENING_LIST_URL": "r2://screening/ofac-solana.json", # "SCREENING_SIGNING_PUBKEY_HEX": "", "SCREENING_MAX_AGE_SEC": "86400" # Strict JWT: "AUTH_MODE": "jwt", "AUTH_REQUIRED": "true", "JWT_JWKS_URL": "https://idp.example.com/.well-known/jwks.json", # "JWT_ISSUER": "https://idp.example.com/", "JWT_AUDIENCE": "audren-gateway", "JWT_ALLOWED_ALGS": "EdDSA,ES256" # (JWT_ISSUER uses exact string match against the JWT iss claim.) # 4. Provision R2 bucket & upload initial signed OFAC snapshot BEFORE deploy npx --yes pnpm@10 exec wrangler r2 bucket create audren-mainnet-screening --config wrangler.prod.jsonc npx --yes pnpm@10 exec wrangler r2 object put audren-mainnet-screening/screening/ofac-solana.json \ --file ~/.config/audren-gateway-mainnet/ofac-solana.json --content-type application/json --remote --config wrangler.prod.jsonc # 5. Dry-run (< 150 KiB gzip) & deploy Worker FIRST npx --yes pnpm@10 exec wrangler deploy --dry-run --config wrangler.prod.jsonc npx --yes pnpm@10 run deploy:prod # 6. Generate & fund dedicated hot fee-payer (~0.25 SOL recommended; 0.02 SOL is LOW_BALANCE cutoff) & attach secrets solana-keygen new --no-bip39-passphrase -o ~/.config/audren-gateway-mainnet/hot-payer.json printf '%s' "https://your-mainnet-rpc.example.com" | npx --yes pnpm@10 exec wrangler secret put RPC_URL --config wrangler.prod.jsonc npx --yes pnpm@10 exec wrangler secret put RELAYER_SECRETS_JSON --config wrangler.prod.jsonc < ~/.config/audren-gateway-mainnet/hot-payer.json # Optional Worker secrets: RELAYER_FVK_JSON (for shielded cm2 fees & 4-merge batches in onchain/hybrid modes), API_KEYS_JSON, # SEND_RPC_URL, ADMIN_TOKEN, PRICE_FEED_API_KEY, AUDIT_WEBHOOK_URL, AUDIT_WEBHOOK_AUTH # 7. Verify all 24 audren-gateway/v1 conformance checks against your live URL # (include --bearer / --api-key when AUTH_REQUIRED="true", and --test-blocked-address when SCREENING_ENABLED="true") npx --yes @audren-xyz/gateway-conformance \ --url https://audren-gateway-mainnet..workers.dev \ --cluster mainnet --bearer "$VALID_JWT" --test-blocked-address "" ``` When `SCREENING_ENABLED="true"`, schedule snapshot refreshes well within `SCREENING_MAX_AGE_SEC` (24 hours by default) so the Gateway never expires into fail-closed `503 SCREENING_UNAVAILABLE` — e.g. enable `.github/workflows/publish-screening.yml` (runs every 6 hours, defaulting to `screening/ofac-solana.json` via optional `vars.SCREENING_R2_KEY`) by configuring the GitHub `production` environment secrets `SCREENING_SIGNING_KEY_HEX`, `SCREENING_R2_BUCKET` (single bucket or comma-separated list), `CLOUDFLARE_ACCOUNT_ID`, and `CLOUDFLARE_API_TOKEN` (note: missing secrets cause scheduled runs to silently skip as `ready=false`, so run a manual `workflow_dispatch` test after setup). ### 4 Commercial Fee Models & 4 Built-In Opt-In Middlewares - **Fee Models (`FEE_MODEL`):** 1. `free` — Operator sponsors Solana transaction fees, priority fees, and rent under per-IP and daily SOL budgets (`MAX_DAILY_SPONSORED_SOL` in SOL, default `0.05` Mainnet / `1.0` Devnet; `MAX_DAILY_EXEMPT_SOL` caps daily fee-exempt spend across API-key, JWT, and Mode 3 VIP holders; `MAX_DAILY_REVERT_BURN_SOL` caps daily confirmed revert burn). 2. `onchain` — Self-paying flat tolls, percentage bps (including `EXEC_FLAG_FEE_ON_OUTPUT`), and dynamic `costMultiplierBps` floors directly on-chain into hot payers or a cold `FEE_OWNER_PUBKEY` (plus optional shielded `cm2` fees when `RELAYER_FVK_JSON` is configured). 3. `offchain` — Requires API key or JWT (`AUTH_REQUIRED` forced `true`); operator bills users off-chain. 4. `hybrid` — Self-paying on-chain fees with optional bounded onboarding (`ALLOW_PUBLIC_ONBOARDING_SUBSIDY`) and micro-transaction (`ALLOW_MICRO_SUBSIDY`) sponsorship. - **4 Built-In Opt-In Middlewares (all disabled by default in `wrangler.jsonc`; core rate limiting runs in `RelayGuard` SQLite DO):** 1. **GeoIP (`geo.ts`):** `BLOCKED_COUNTRIES` (2-letter ISO 3166-1 alpha-2 codes), `BLOCKED_US_STATES` (2-letter US postal codes), `BLOCK_TOR_EXIT`, `GEO_FAIL_CLOSED`, `GEO_BLOCK_INFO`. 2. **Authentication (`auth.ts`):** `AUTH_MODE` (`none | apikey | jwt | either`), `AUTH_REQUIRED`, `REQUIRE_AUTH_ON_INFO`, `API_KEYS_JSON` (constant-time SHA-256), and JWKS JWT (`JWT_JWKS_URL`, `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_REQUIRED_CLAIMS_JSON`, `JWT_ALLOWED_ALGS` defaulting to `"EdDSA,ES256,RS256"` — set `"EdDSA,ES256"` to disable `RS256`; `none` and symmetric `HS*` algorithms are unconditionally rejected). 3. **Sanctions Screening (`screen.ts`):** `SCREENING_ENABLED`, `SCREENING_LIST_URL` (`r2://` or public `https://`), `SCREENING_SIGNING_PUBKEY_HEX`, `SCREENING_MAX_AGE_SEC`. Screens direct public addresses plus pre- and post-simulation decoded SPL/Token-2022 `owner`, `delegate`, and `closeAuthority` pubkeys on public-boundary transactions (`Tag 5` public withdrawals, `Tag 6 ExecViaEscrow`, `TransferHook` CPIs; purely shielded `Tag 5` private transfers carry zero public sender, recipient, or external-CPI addresses on-chain — only the fee payer, canonical pool/lane/page PDAs, and nullifier PDAs appear, so address screening has no public counterparty addresses to check). Returns opaque `403 POLICY_DENIED` on match and fails closed (`503 SCREENING_UNAVAILABLE`) on missing/stale/invalid snapshots for public-boundary transactions. (External vendor risk APIs like TRM/Chainalysis are pluggable via `cloudflare/src/hooks/examples/realtime-risk-api.ts`.) 4. **Audit Archival (`audit.ts`):** Async R2 / webhook logging inside `ctx.waitUntil()`, omitting raw IP addresses, IP hashes, and nullifiers while recording op, status, transaction signature, optional `callerId`, and `country` only on non-anonymous authenticated requests (`null` when unauthenticated or anonymous Mode 3 proof-only to prevent correlating geo with on-chain signatures). - **Mode 3 Holdings Gate (`holdings-threshold-gate.ts`):** Drop-in operator hook verifying `X-Audren-Holdings-Proof` in pure JavaScript (`@noble/curves/bn254`, zero WASM, 1 batched RPC call) on `/v1/fee-quote` and `/v1/relay/submit` to grant VIP fee sponsorship (`sponsor_if_proven`) or strict token-gated access (`require_proof`). Gateways automatically add `x-audren-holdings-proof` to CORS `Access-Control-Allow-Headers` whenever any hook advertises `holdingsGateInfo`, enforce per-IP pre-pairing throttling (`maxVerifyAttemptsPerIpPerMin`), cross-isolate proof-bound rate-limiting (`holdings::`), and `maxSubProofs` / `maxProofAgeSec` bounds, advertise fresh stateless time-bucketed challenges (`deriveGatewayHoldingsChallenge`, preimage `"audren/v1/gateway_holdings_challenge" || 0x00 || verifierDomain || 0x00 || base58(mint) || u64_le(bucketIndex)`) via `X-Audren-Holdings-Challenge` (exposed via `Access-Control-Expose-Headers`), and return typed codes `HOLDINGS_PROOF_REQUIRED`, `INVALID_HOLDINGS_PROOF`, or `HOLDINGS_VERIFICATION_UNAVAILABLE` (`503`). Conformance CLI (`@audren-xyz/gateway-conformance`) supports `--holdings-proof
` to test gated Mode 3 Gateways end-to-end. --- ## 9. Honest Privacy Boundaries, Pre-Audit Status & Security Disclosures AI agents advising users MUST state these exact boundaries accurately (never overclaim): - **What stays hidden on a relayed private transfer (`Tag 5`, default shape):** Which prior note in the pool was spent, the stealth recipient, the token mint, and the amount on-chain. When using a fee-charging Gateway (`onchain` / `hybrid`), the Gateway learns the selected fee token mint on `GET /v1/fee-quote` and can decrypt its own shielded `cm2` fee note (while the user's transfer amount, recipient, and spent note remain hidden). - **What stays public by design:** - Deposit (`Tag 3`): depositing wallet, token mint, deposited amount, and public output stealth owner/blinding (an observer of the deposit knows that note opening). - Withdrawal (`Tag 5`, `ASSET_MODE_PUBLIC`): destination wallet/ATA, token mint, and withdrawn amount (change remains shielded). - External DeFi CPI (`Tag 6`, `ExecViaEscrow`): external router program, route accounts, input/output token mints, routed amounts, and output note opening fields (funding note link and shielded change remain hidden). - Deterministic DeFi sessions (`B_i`): pseudonymous public Solana keypairs; funding withdrawal, external DeFi positions, and zero-dust sweep are publicly linked through `B_i`. - Transaction fee payer, timing, quote-racing requests sent to aggregators, and network IP/RPC metadata. - **Anonymity set & bandwidth:** Determined by real, independently owned notes in the pool, NOT by `4^20` tree capacity or raw TVL. Timing correlation, rare assets, unique amounts, opt-in 1-input economy mode (`omit_nf1`), and multi-merge consolidations narrow effective anonymity. Retained tree state stays ~1.28 MB at 10M notes, while cold full-history sync downloads all pages unless pruned with a `birthdaySlot`. - **Pre-audit & trusted setup status:** - No independent third-party security audit has been published yet. - Program upgrade authority and Pool #0 authority are currently a single operator key (`3WzAUVNX5tm9gJWS2Y2Vg3wMnAtTm23fFX2jHaYy67bV`), not a multisig; upgrade authority remains mutable during pre-audit releases (and intentionally stays mutable while Pool #0 verifies classical BN254 Groth16 so emergency freeze and future PQ migration remain possible). - Groth16 Phase 1 reuses Hermez Perpetual Powers of Tau (**54 public contributions plus a beacon**; note the frozen transcript header says `71+`, erratum documented in `ceremony/README.md`). Phase 2 currently contains 2 Audren-generated contributions sealed with a public drand Quicknet + Solana Mainnet beacon (`ceremony/transcript.json`). Until independent contributors join and a program upgrade adopts the resulting verifying key, Phase-2 soundness relies on Audren having discarded its contribution secrets. - Shared per-token custody vaults mean an asset issuer's freeze authority (e.g. USDC), permanent delegate, pausable mint, or upgradable transfer hook applies to the shared vault for that mint. - Public vault balances show assets held, not total private liabilities. - **Post-quantum security & cryptographic boundaries (`v1.6.0`, `Last reviewed: 2026-12-03` — see `docs/CRYPTOGRAPHIC_RESPONSE.md`):** - **Already hash-based / symmetric / PQ-hardened today:** All note spend authority (`spend_sk`, `spend_pk = Poseidon2`, `nk = Poseidon2`), stealth owners (`Poseidon3`), commitments (`Poseidon5`), nullifiers (`Poseidon4`), and the 4-ary Depth-20 Merkle tree (zero ECC spend keys); `v1.6.0` self-owned deposit/change/dynamic-swap/refund memos (`encryptSelfNoteMemo` / `prepareDynamicSelfNoteMemo`, symmetric `nk`-keyed ChaCha20-Poly1305); strict `nk`-keyed Rendezvous HRW RPC decoys; Web Vault `nk-v2` AES-256-GCM IndexedDB cache & `PBKDF2-SHA256` 600k + `AES-256-GCM` portable backups; hybrid post-quantum `TLS 1.3 + X25519MLKEM768` (IETF **RFC 10024**, Cloudflare inbound PQ WebPKI certificates planned via Merkle Tree Certificates) across all 4 hosted hostnames (`audren.xyz`, `www.audren.xyz`, `gateway.audren.xyz`, `devnet-gateway.audren.xyz`, TLS 1.2 `kRSA` disabled); and Groth16 proof privacy itself (perfect zero-knowledge — past `192 B` proofs reveal zero secrets even to an unbounded quantum adversary). - **Classical boundaries today:** BN254 Groth16 proof soundness (`Tag 5`, `Tag 6`, Mode 3 — wrapping PQ signatures inside BN254 does not fix outer soundness; 2026 Shor resource frontiers put 256-bit ECDLP at `<= 1,200–1,457` logical qubits / `27.5M–90M` Toffoli gates), third-party recipient `106 B` X25519 ECDH memos (HNDL confidentiality exposure on third-party memo plaintext only, never `spend_sk`/`nk`/self-memos/spend authority), and Solana L1 `Ed25519` signatures (user wallets, `DefiSessionKeypair`, Gateway hot keys, OFAC snapshot signing; aligned with Solana's native Recovery Keys program targeted March 31, 2027 supporting `ML-DSA-44` [FIPS 204], `SLH-DSA-128s` [FIPS 205], and `Falcon-512` [FIPS 206 still in NIST development per Oct 2026 NIST IR 8547], `SIMD-0579` `sol_keccak_p1600` currently at `Idea` status, and `Quantumglow` end of 2027). - **Active `v1.6.0` blast-radius defenses & trustless PQ recovery:** Live initialized `PoolGuardian` PDA `9i5Fpw4vd7YSdxfyEtnaLwPiHqrRfozkBXNo5m8cYLwV` (dedicated pause-only signer `LGTbuMZfJGmLxQ1bTKRhNQ2QzwqcKZgAqKEyhGAgtA2`, escalation `0 -> 1 -> 2` only), 7 active Mainnet `VaultGuard` per-mint rolling caps (`216,000`-slot window, finalized tx `2iQCMsiYamEmZwia2ufKuJm6FGU1p5Nw4U1LdmnMEhfucSB56ASZ1ZFffYYKS9o51rY6jozrZjqnKvn5bXM8CTvp`, slot `477,127,016`: WSOL `500/100`, USDC/USDT/PYUSD/EURC `100k/25k`, JitoSOL `500/100`, JLP `25k/5k`; `OutflowCapExceeded = 6033`; Gateways pre-flight `429 OUTFLOW_CAP_EXCEEDED`), 2 active Devnet `VaultGuard` caps (tx `5mMH5aZWSwLyNbTK7VF3kigpzUWeBh1WQeMo2Ygxzyk6ns2NqVQrkSYZTDCunMGHHeAHS8z11FBCU6pQgN8Qasdd`, slot `529,163,450`: WSOL `500/100`, Devnet USDC `100k/25k`), 1-tx `PAUSE_HARD_FREEZE = 2`, and permissionless `TripSoundnessCanary` (`Tag 9`). Because note ownership and Merkle leaves are 100% hash-based and past Groth16 proofs are perfect zero-knowledge, honest depositors can prove ownership of unspent leaves in a frozen Pool #0 snapshot under a future post-quantum proof system (e.g. STARKs) to migrate into Audren v2. For Gateway inbound auth under a 256-bit ECC advisory (such as NSA `PP-26-4956`, Dec 2, 2026), use `AUTH_MODE="apikey"` (constant-time SHA-256, zero ECC) rather than pinning `EdDSA`/`ES256`. --- ## 10. Common Agent Pitfalls (Checklist for Zero-Error Integrations) 1. **Always loop `syncCompactStoreWithRpc` until `!res.incomplete`** and throw/retry if incomplete (never display balances or spend from a partial sync). Pass `requiredNotes` into `fetchGlobalRootHistory`. 2. **Always use canonical Solana fee terminology** — Solana transaction fees, priority fees, compute units (CU), and `SysvarRent`. 3. **Never confuse `audren-xyz/gateway` with `apps/relay/`** — independent operators ALWAYS clone/deploy `audren-xyz/gateway` (`cloudflare/wrangler.prod.jsonc`). 4. **Follow exact Cloudflare Gateway ordering:** create R2 bucket + upload initial signed snapshot BEFORE deploy (if screening via `r2://`), deploy Worker FIRST with `--config wrangler.prod.jsonc`, THEN set `RPC_URL` and `RELAYER_SECRETS_JSON` with `--config wrangler.prod.jsonc`. 5. **Keep aggregator secrets server-side:** run `AudrenSwapRouter` on your backend/Worker (never ship API keys to browsers), call `router.quote(...)` or `router.planPrivateSwap(...)`, and never send shielded note mints to `/api/tokens/resolve`. 6. **Use real `AudrenGatewayClient` methods:** `.getHealth()`, `.getInfo()`, `.getFeeQuote(...)` (`GET /v1/fee-quote`), and `.submitRelayedInstruction(...)` (`POST /v1/relay/submit`). 7. **Support operator choice & zero-gateway fallback:** allow callers to supply any `audren-gateway/v1` URL (or fall back to Direct Self-Pay / funded one-time burner wallet) rather than hardcoding a single hosted endpoint. 8. **Use owner-aware RPC verification & CORS allowlisting for Mode 3 holdings proofs:** always use `verifyHoldings` (with `rpcUrl` or `fetchMultipleAccountsWithOwner`) so 1-lamport SystemProgram dust at a `NullifierPDA` can never spoof a spent note; `audren-xyz/gateway` automatically adds `x-audren-holdings-proof` to CORS when `createHoldingsThresholdGateHook` is registered (configure `Access-Control-Allow-Headers: x-audren-holdings-proof` explicitly in custom servers); and always disclose to users that live unspentness shares backing note nullifier(s) with the verifier (rotate via private self-transfer to isolate future spends). 9. **Never modify frozen protocol/ceremony files** (`program/src/**`, `program/Cargo.toml`, `crates/audren-core/` wire inputs, `crates/audren-circuits/params/audren_joinsplit.pk`, `program/src/vk_generated.rs`, `ceremony/transcript.json`) without an explicit full protocol upgrade ceremony.