feat(shielded): atomic private swaps from shielded notes via the official router #1584

Open
opened 2026-10-29 00:32:55 +00:00 by PlasticDigits · 0 comments
Owner

Problem and scope

Add atomic private swaps to the shielded pool from #1583: a note owner authorises a spend and an exact route through the official router in one transaction; the pool becomes the on-chain trader, the router settles into the pool, and the pool credits the net output as a new note (plus change) before the transaction commits. No user wallet address appears in the swap; no funds can be redirected, partially credited or left in the pool unaccounted.

This issue covers:

  • the pool's PrivateSwap execution path and its signed authorisation digest;
  • the minimal additive router change needed to return swap output into a contract hook so the output note is created atomically;
  • tax/guard/code-id/fee behaviour when the trader is the pool;
  • the quote contract for shielded swaps (the solver keeps working; the request must not carry the user's wallet);
  • tests for route substitution, tax evasion, partial settlement and reentrancy.

It does not cover deposits/withdrawals (see #1583), indexer attribution/API (#1585), the dApp (#1586), or the security/abuse program (#1587). Limit orders, greedy book-first execution, native-asset routes, hybrid splits inside the pool (beyond a declared router plan), P2P notes, and cross-pool swaps are out of scope.

Current codebase and investigation

Reviewed checkout: 38c154958.

  • Pair: smartcontracts/contracts/pair/src/contract.rs execute_receive accepts Cw20HookMsg::Swap { belief_price, max_spread, min_return, to, deadline, trader, hybrid, greedy }, gates trading blacklist, factory whitelist and asset code-id pins, then execute_swap sends the ask token to the receiver with Cw20ExecuteMsg::Transfer (around lines 1400–1425 and 2300). There is no CW20 receive hook on the pair's output transfer, so a contract that wants an atomic output callback cannot get one from a direct pair swap.
  • Router: smartcontracts/contracts/router/src/msg.rs ExecuteRouteSwapOperations { funding_version: 1, operations, max_spread, minimum_receive, to, deadline, unwrap_output } and ExecuteSwapOperations; the router holds the gross input, pays each hop with Cw20ExecuteMsg::Send, and the final payout uses route_tax::transfer (smartcontracts/contracts/router/src/route_tax.rs) which calls RouteTransfer { slot, recipient, amount } for route-tax-capable tokens and cw20::Cw20ExecuteMsg::Transfer otherwise. to is a plain address; there is no output hook.
  • Tax: community-tax-token classifies route sells through the official router and requires an authenticated RouteTaxContext with trader, pair, offer_token, economic, gross (smartcontracts/contracts/community-tax-token/src/tax.rs apply_transfer, preview, hop_trader_addr). is_route_trader rejects the router and protocol-exempt addresses. Sell tax is charged on the gross and the pair receives amount; buy tax is charged on router→recipient. Manager/directory exemptions follow the authenticated trader. max_wallet and cooldown launch guards use from/to and the hop trader.
  • Fee discount: pair/src/discount_cache.rs keys a 300-second cache by (trader, sender) and the registry (smartcontracts/contracts/fee-discount) reads the trader's live CL8Y balance. The indexer's route/solve accepts trader/sender and caches discount by the pair (indexer/src/api/route_solver.rs around lines 46, 92–124). The dApp always sends the connected wallet as trader (frontend-dapp/src/services/indexer/client.ts lines 715–760).
  • Route solving: indexer/src/api/route_solver.rs, best_execution.rs, hybrid_route_opt.rs, route_paths.rs; quotes are local-only and must never trigger RPC (AGENTS.md, #1452). docs/route-solver.md, docs/swap-max-spread-ux.md.
  • Guards: pair pause, factory trading blacklist (pair/src/blacklist_guard.rs, router/src/blacklist_guard.rs), asset code-id pin + factory whitelist (pair/src/asset_code_id_guard.rs), hooks with positive min_return (#1398), route-local tax funding v1 (#1381), launch guards (#608) and the token code-id freeze (#585/#582).
  • Pool: #1583 defines the note tree, LIABILITY, Unshield, the canonical spend digest and a CommitSwapOutput settlement hook callable only by the stored router with a pending id. No swap execution exists yet.

Known facts that constrain the design:

  1. The router receives the pool's gross input and needs an authenticated trader; the token requires ctx.gross >= economic + sell_tax(trader). If the pool forwards a user-supplied trader field, a user could claim another wallet's manager exemption, so the pool must always set the trader to the pool.
  2. Direct pair swaps cannot deliver an output hook, and a plain transfer would leave the output sitting in the pool with no note, breaking liability accounting. The router therefore needs either an optional output hook or a reply-based settlement in the pool.
  3. A community-tax-token with active launch guards will treat the pool as the trader/recipient: max_wallet would reject any output above the cap because the pool's balance is large, and cooldown would throttle the whole pool to one swap per window. Shielded swaps for such tokens must fail closed until guards are lifted; do not disable guards and do not exempt the pool.
  4. Fee discounts are per-wallet CL8Y balances; the pool is not a wallet tier holder. Silent discount claims would be incorrect and would invite abuse by registering the pool. Phase 1 therefore pays the base fee and the quote must use the pool as trader, not the user's wallet.

Why a new implementation is needed

Shielded balances without a swap path are custody, not a product: users would have to unshield to trade, exposing the very address the feature is meant to keep out of the DEX's data. A swap executed by the user's wallet is attributable by the pair, the indexer, the trader leaderboard and the portfolio; a pool-executed swap is not.

Atomicity is also a safety requirement. A swap that sends the input and only later credits an output note gives a relayer or a griefer a window to strand funds, double-credit, or leave unaccounted output in the pool. The spend authorisation must bind the exact route, the minimum output, the deadline, the owner key and the change destination, and the output note must be created in the same transaction or the whole swap must revert.

Relevant files

  • smartcontracts/contracts/shielded-pool/src/{contract,spend,settle,msg,state,error}.rs (new; from #1583)
  • smartcontracts/contracts/router/src/{msg,contract,route_tax}.rs (additive output-hook field and tests)
  • smartcontracts/packages/dex-common/src/ (shared hook/settlement types if needed)
  • smartcontracts/contracts/pair/src/contract.rs (read-only; no behaviour change)
  • smartcontracts/contracts/community-tax-token/src/{contract,tax}.rs (read-only; tax and guard behaviour)
  • smartcontracts/contracts/fee-discount/src/ and pair/src/discount_cache.rs (read-only; no pool registration)
  • indexer/src/api/{route_solver,best_execution,hybrid_route_opt}.rs and frontend-dapp/src/services/indexer/client.ts (quote parameters; wallet must not be sent)
  • docs/shielded-pool.md, docs/route-solver.md, docs/contracts-security-audit.md, docs/qa/issue-<N>/README.md, skills/AGENTS_SHIELDED_SWAP.md
  • scripts/qa/verify-issue-<N>.sh, Makefile
  1. One signed swap authorisation. Extend the #1583 canonical digest with a swap context:
    context_hash = SHA256("cl8y-shielded-swap-v1" || router || len(operations_json) || operations_json || max_spread || min_output || deadline || gross_input || max_relayer_fee || owner_pubkey || output_token),
    and sign SHA256(domain || chain_id || pool || version || input_token || gross_input || nullifier_set_hash || relayer_fee || output_owner_pubkey || context_hash). Use a deterministic serialisation of the router operations (canonical field order, no maps, fixed decimal/uint encoding) and hash it; the pool reconstructs the operations and compares the digest, never trusts a route supplied outside the signature. Bind the exact SwapOperation vector (including min_return, hybrid/greedy fields if used) and the required min_output.

  2. Router output hook (primary) — additive only. Add output_hook: Option<Binary> to ExecuteRouteSwapOperations (and the CW20 hook variant) and apply it only on the final payout: if present, Cw20ExecuteMsg::Send { contract: to, amount: final_net, msg: output_hook } instead of a plain transfer; for tax-capable tokens use the existing RouteTransfer first and let the token deliver to to, or require the hook path to be used only for tokens whose RouteTransfer supports a hook. Simpler and safer: require output_hook only with to = pool, and make the router reject a hook when to is not a contract that accepts it, when unwrap_output is set, or when the final leg is native. Keep the field optional and default None, preserve the existing byte-for-byte behaviour for non-shielded users, and cap the hook payload size (e.g. 8–16 KiB) to bound gas. Add an ADR if the router interface changes (the repo already uses ADRs for interface-level decisions).

    Do not add a hook to the pair's output transfer in this issue: keep the pair unchanged and let the router deliver the hook. If the router change is rejected in review, fall back to a submessage reply: the pool calls the router, records PENDING_SETTLEMENT { token, min_output, owner_pubkey, baseline_balance, nonce }, and in reply reads its own post-swap CW20 balance, computes the delta against the recorded baseline, and inserts the note. The fallback must prove per-tx isolation (two swaps in one tx; a donation to the pool during the same tx) and must revert if the delta is below min_output.

  3. PrivateSwap execute path. Accept up to four input notes in the same token, all owned by the same ed25519 key (or an explicit set of keys, each with its own signature), plus route, max_spread, min_output, deadline, relayer_fee, output_owner_pubkey. Verify every note (commitment, root, signature, nullifier, deadline) before any state change. Require sum(inputs) >= gross_input + relayer_fee, with gross_input bound in the signature; change = sum(inputs) − gross_input − fee in the input token; output note = the post-tax net received in the output token. Mark nullifiers, decrement liability by the inputs, send the gross to the router with ExecuteRouteSwapOperations { funding_version: 1, operations, max_spread, minimum_receive, to: pool, output_hook: CommitSwapOutput { pending_id, min_output, output_token, owner_pubkey, relayer_fee } }, and let the settlement hook credit the output and insert change in one atomic sequence. If the hook is absent or not called, the transaction must fail (the pending entry alone is not a settlement).

  4. Trader identity and taxes. The router's RouteTaxContext.trader must be the pool: the pool sends the CW20 Send itself, so the router sees the pool as the sender. Never accept a trader field in the pool's message. Require the pool to be non-exempt on every routed tax token (no PROTOCOL_EXEMPT, no MANAGER_EXEMPT, no directory entry) and test that a governance attempt to add it is rejected by the token (the token already rejects protocol addresses). Compute the gross from the note, not from a user-declared economic amount. For a tax-capable token, require RouteTaxPreview/RouteTaxContext success; if the capability query fails, fail closed rather than routing with an unknown tax. The user-facing quote must preview sell tax (and buy tax on the output) and the note's net result. If the output token also has a buy tax, the output note is the net after that tax.

  5. Launch-guard and fee policy. Shielded swaps are disabled for a token when trading_enabled == false, cooldown_blocks > 0, or max_wallet would apply to the pool (which it will when set), unless governance explicitly records a decision and the pool-level throttle is documented and accepted. Do not add the pool to exemption maps. Phase 1 pays the base pair fee: the pool is not registered in the fee-discount registry, route/solve must be called with the pool as trader (or without a trader), and the dApp must not imply a tier discount. Document the trade-off in docs/shielded-pool.md.

  6. Quote and route contract. Shielded quotes use the existing solver with trader = pool (a stable public address, not the user) or no trader, and never include the user's wallet, sender, tier or blacklist-check wallet. The quote must carry the same fields the pool will bind (operations, max_spread, min_output, gross, deadline) and the client must derive min_output from the reviewed quote with the same rules as the ordinary Swap UI (L9 max spread, positive post-hook min_return, final minimum receive). The pool re-checks the signed route; the indexer remains a hint. No request-time RPC/LCD, no new solver work on the request path; the existing cache and progress rules apply.

  7. Settlement and liability. CommitSwapOutput (from #1583) must verify info.sender == router, pending_id exists in the current tx, token matches, amount >= min_output, and the pending entry has not been consumed. It computes the output note from the actual credit, credits the change note (input token) in the same tx, clears the pending entry, updates liability and emits both notes. If the router or token credits less than min_output, the hook reverts and the whole swap reverts. If the router sends the output with a plain Transfer (hook missing), the pool must not accept the unattributed balance; add a test that the pending entry cannot be settled by a later token transfer and that Reconcile shows the discrepancy until governance-free recovery (there is none: the tx must revert).

  8. Reentrancy and ordering. The pool must be reentrancy-safe: no state mutation before validation; a PENDING_SETTLEMENT keyed by (tx scope, pending_id); a guard that rejects a second settlement in the same tx with the same pending id; no callback into the pool from the input token except the CW20 Send hook that the router/pair executes (the pair's output is a plain transfer). The router must not call an arbitrary hook on a to that is not the pool, and the pool must reject CommitSwapOutput when info.sender != stored router.

Constraints and guardrails

  • No standing allowances: the pool never calls IncreaseAllowance for the pair/router; it uses CW20 Send of its own balance and router funding v1. No TransferFrom path, no approval to an arbitrary contract.
  • Exact binding: operations digest, max_spread, min_output, deadline, input token, gross, output token, owner key, relayer fee and destination are all covered by the signed digest; any mismatch reverts. The relayer cannot choose the route, reduce the output, redirect the change, or skim more than the signed fee.
  • Route limits: the router's existing hop, asset-path and repeated-taxable-asset rules remain (route_tax::validate_asset_path); no foreign DEX, no manual split, no native output, no unwrap_output, no limit order/book leg in phase 1.
  • Fees/taxes preserved: pair commission, treasury destination, protocol fee events, community-tax sell/buy/transfer tax and route-local funding v1 are unchanged. Shielded swaps must not create a tax-exempt path, a fee-discount path or a treasury bypass. Do not modify token tax code.
  • Guards preserved: factory blacklist, token freeze, pair pause, launch guards, code-id pins and deadline checks remain enforced on every call. The pool is not exempt from any of them; a blacklisted pool address stops all shielded swaps (expected and documented).
  • Gas: a shielded swap must fit the documented retail envelope (measure on LocalTerra; docs/adr/0004-terraclassic-retail-gas-census.md). If ed25519 verification plus Merkle + router execution exceeds it, reduce the number of input notes or stop and revise; do not silently raise the wallet gas cap. The router hook must not add unbounded work.
  • No request-time chain calls: quotes stay local to the indexer cache; the frontend must not add LCD simulations for shielded swaps beyond the existing preflight policy, and must never include the user's wallet in a shielded quote.
  • Backward compatibility: the router field is optional; all existing swap paths, quote shapes and pair behaviour are unchanged. Do not change funding_version; do not re-use the new hook field for non-shielded flows.
  • Data hygiene: no wallet address, note key, user conversation or private report in calldata examples, tests, docs or issue text.

Acceptance criteria

  • AC1: A signed PrivateSwap spends 1–4 notes atomically, sends the gross input to the official router, and credits the output note plus change in the same transaction; if any step fails, no nullifier is consumed, no liability changes, and no token leaves the pool.
  • AC2: The route digest binds the exact operations vector, max_spread, min_output, deadline, input/output tokens, gross, owner key and relayer fee. A relayer that substitutes a pair, adds a hop, raises max_spread, lowers min_output, changes the owner key or redirects the destination causes a revert.
  • AC3: The pool is the router trader; the pool is not exempt, not manager-exempt and not in the fee-discount registry; sell and buy tax are charged exactly as for a normal routed wallet swap, with RouteTaxContext.gross >= economic + sell_tax(pool) and the output note equal to the post-tax net.
  • AC4: Shielded swaps fail closed for tokens with active launch guards (trading_enabled=false, cooldown, max_wallet), for a paused pair, for a frozen/blacklisted token or pair, for a code-id drift and for an unknown tax capability. No guard is disabled or bypassed.
  • AC5: No fee-tier discount is claimed or implied for shielded swaps; the quote uses the pool (or no trader) and never the user's wallet; the base fee and treasury commission match the ordinary swap for the same route and amount.
  • AC6: The output is exactly-once and cannot be stranded: a missing hook, a plain-token transfer, a duplicate settlement, a wrong router, a below-min output or a third-party donation cannot settle a pending swap; Reconcile stays consistent.
  • AC7: The router change is optional and additive; every existing router/pair test and non-shielded swap path is unchanged, and the new field is rejected for native output, unwrap_output, and any to other than the intended contract.
  • AC8: Gas for deposit/withdraw/private swap is measured and documented; the shielded swap fits the documented envelope or the issue is reported FAIL with the measured numbers.
  • AC9: docs/shielded-pool.md, docs/route-solver.md (shielded quote note), docs/contracts-security-audit.md, docs/qa/issue-<N>/README.md and skills/AGENTS_SHIELDED_SWAP.md are updated; make verify-issue-<N> exists.
  • AC10: The privacy claim stays accurate: the pair/indexer see the pool as the trader, but the input and output amounts and the note graph remain public chain data; the docs and UI copy do not claim hidden amounts or anonymity.

Test plan: functional paths

Path Required checks
Single-note swap Direct pair route, 2/3/4-hop route, native-wrapped hops only as supported by the router, 6/9/12/18-decimal tokens, 1 raw unit, dust, large amounts; exact min_output; output note amount; change note; liability delta; event fields.
Multi-note swap 2–4 notes, same key and mixed leaf ages, different deposits; one invalid note fails all; sum/change arithmetic; nullifier set; gas at 4 notes.
Tax paths Community-tax sell (tax >0), buy tax on output, tax >0 and close-to-zero, tax on an intermediate hop, no-tax cw20-mintable, tax capability query failure, RouteTaxContext mismatch; gross/tax/net reconciliation with the note.
Output settlement Router hook path; reply fallback if implemented; output > min, output == min, output < min; output token mismatch; two swaps in one tx; hook payload size at the cap; settlement after a failed router call.
Guards Pair paused, token frozen, factory-blacklisted wallet/pool/token/pair, code-id drift, launch guards (trading_enabled=false, cooldown, max_wallet), deadline now/past, max_spread boundary, insufficient liquidity, zero output, hook-required min_return.
Quotes Quote with pool trader and no trader produce the same execution binding; quote must not include the user's wallet; stale quote/deadline; solver timeout/404; no request-triggered RPC; frontend preflight parity; Expert/tolerance change.
Failure/recovery Router reverts, token transfer fails, settlement hook reverts, ambiguous broadcast, duplicate submit, retry after failure; no duplicate nullifier spend and no lost change.
Compatibility All existing pair/router/factory/community-tax tests; non-shielded swap routes and quotes byte-identical in shape; router schema additive; old clients omit the new field.

Test plan: attacks, hacks and abuse

  • Route substitution / MEV: relayer swaps a pair, inserts an extra hop, changes the offer/ask token, inflates max_spread, lowers min_output, extends the deadline or replays a quote on a new state. The digest must reject every mutation. A sandwicher cannot change the signed destination; a delayed relayer hits the deadline.
  • Tax evasion: pool added to PROTOCOL_EXEMPT/MANAGER_EXEMPT/directory, a user-supplied trader claiming another wallet's exemption, a route that classifies the pool as a transfer instead of a sell, a pool-side SendFrom allowance, or a swap through a non-official router. All must fail or be rejected by governance/token tests; verify the token's tax context is the pool and the amount matches.
  • Fee abuse: register the pool in the fee-discount registry or feed trader=<user> to the pair, claim a tier without a CL8Y balance, or use the discount cache keyed by (trader, sender) to inherit another wallet's discount. No discount path may apply; the pair fee must equal the non-discounted base.
  • Theft / partial settlement: output note credited to the relayer's key, change note to the relayer, relayer fee above the cap, a second CommitSwapOutput with the same pending id, a third party sending the output token directly to the pool, a router that transfers to to without the hook, and a swap that leaves the output in the router. Only the signed owner may receive the output and change; unattributed balances must revert or be visible, never credited.
  • Reentrancy / ordering: a malicious allowed token re-enters the pool during Send; two swaps nest; a hook calls back into PrivateSwap; the router calls the hook twice; the pool is called with a pending id from another tx. Reentrancy guard, per-tx pending scoping and exactly-once must hold.
  • Double spend / replay: same notes spent in swap and withdraw in one tx or across txs; cross-chain/cross-pool signature replay; signature reuse with a different route/owner/destination; nullifier front-run by a party that knows the public opening (must not authorize a spend).
  • Guard bypass: paused pair, frozen token, blacklisted wallet/pair, launch guard state changed between quote and execution, a token whose trading_enabled flips mid-tx; every check must be read at execution time, not cached from the quote.
  • Numerics: 6-vs-18-decimal scale, tax rounding, change dust, gross + fee > inputs, min_output at 1 raw unit, max_spread at the boundary, large reserves and overflow; no output note may exceed the actual credit.
  • DoS / resources: max notes, max hops, max hook size, huge route vectors, deep book/hybrid data, repeated failing swaps, and indexer quote floods. Bound loops, payloads and gas; no unbounded routing inside the pool.
  • Privacy leakage: the pool must not emit the submitter as owner, must not include the relayer in a "trader" field, and must not forward the user's wallet to the router/indexer. The quote request and indexer cache keys must be free of the user's address.

Verification criteria

  • make verify-issue-<N> runs workspace fmt/clippy/build, the new pool and router tests, all existing pair/router/community-tax/fee-discount tests, schema checks and doc cross-links.
  • LocalTerra E2E (VERIFY_ISSUE_<N>_CHAIN=1, opt-in): shield → private swap on a direct route → private swap on a 2-hop route → unshield, using cw20-mintable and a community-tax-token with sell tax; assert Reconcile, no residual unaccounted balance, no nullifier reuse, and the expected tax/commission receipts.
  • A router compatibility test proves the optional field is ignored when absent and that all existing non-shielded swap tests still pass unchanged.
  • Gas receipts (deposit, 1-note swap, 4-note swap, withdraw) are recorded in docs/qa/issue-<N>/README.md; a route above the documented envelope is FAIL, not a skip.
  • docs/qa/issue-<N>/README.md records explicit skips and evidence; executed failures remain FAIL. No conversation, personal data or wallet-owner identity is stored.
  • The final revision is reviewed by an independent agent for tax evasion, route binding, settlement atomicity and guard bypass before the sibling dApp issue consumes the interface.

Out of scope / follow-ups

  • Indexer classification, non-attribution, note discovery (#1585).
  • dApp vault, quotes, shield/unshield and private swap UX (#1586).
  • Threat model, abuse/compliance policy, relayer operations and staged rollout (#1587).
  • ZK notes, encrypted payloads, P2P transfers, cross-pool routes, native-asset shielding, limit-order/book execution, and fee-tier claims for shielded notes: not in phase 1.
## Problem and scope Add **atomic private swaps** to the shielded pool from #1583: a note owner authorises a spend and an exact route through the official router in one transaction; the pool becomes the on-chain trader, the router settles into the pool, and the pool credits the net output as a new note (plus change) before the transaction commits. No user wallet address appears in the swap; no funds can be redirected, partially credited or left in the pool unaccounted. This issue covers: - the pool's `PrivateSwap` execution path and its signed authorisation digest; - the **minimal additive** router change needed to return swap output into a contract hook so the output note is created atomically; - tax/guard/code-id/fee behaviour when the trader is the pool; - the quote contract for shielded swaps (the solver keeps working; the request must not carry the user's wallet); - tests for route substitution, tax evasion, partial settlement and reentrancy. It does **not** cover deposits/withdrawals (see #1583), indexer attribution/API (#1585), the dApp (#1586), or the security/abuse program (#1587). Limit orders, greedy book-first execution, native-asset routes, hybrid splits inside the pool (beyond a declared router plan), P2P notes, and cross-pool swaps are out of scope. ## Current codebase and investigation Reviewed checkout: `38c154958`. - **Pair:** `smartcontracts/contracts/pair/src/contract.rs` `execute_receive` accepts `Cw20HookMsg::Swap { belief_price, max_spread, min_return, to, deadline, trader, hybrid, greedy }`, gates trading blacklist, factory whitelist and asset code-id pins, then `execute_swap` sends the ask token to the receiver with `Cw20ExecuteMsg::Transfer` (around lines 1400–1425 and 2300). There is **no CW20 receive hook on the pair's output transfer**, so a contract that wants an atomic output callback cannot get one from a direct pair swap. - **Router:** `smartcontracts/contracts/router/src/msg.rs` `ExecuteRouteSwapOperations { funding_version: 1, operations, max_spread, minimum_receive, to, deadline, unwrap_output }` and `ExecuteSwapOperations`; the router holds the gross input, pays each hop with `Cw20ExecuteMsg::Send`, and the final payout uses `route_tax::transfer` (`smartcontracts/contracts/router/src/route_tax.rs`) which calls `RouteTransfer { slot, recipient, amount }` for route-tax-capable tokens and `cw20::Cw20ExecuteMsg::Transfer` otherwise. `to` is a plain address; there is no output hook. - **Tax:** `community-tax-token` classifies route sells through the official router and requires an authenticated `RouteTaxContext` with `trader`, `pair`, `offer_token`, `economic`, `gross` (`smartcontracts/contracts/community-tax-token/src/tax.rs` `apply_transfer`, `preview`, `hop_trader_addr`). `is_route_trader` rejects the router and protocol-exempt addresses. Sell tax is charged on the gross and the pair receives `amount`; buy tax is charged on router→recipient. Manager/directory exemptions follow the authenticated trader. `max_wallet` and cooldown launch guards use `from`/`to` and the hop trader. - **Fee discount:** `pair/src/discount_cache.rs` keys a 300-second cache by `(trader, sender)` and the registry (`smartcontracts/contracts/fee-discount`) reads the trader's live CL8Y balance. The indexer's `route/solve` accepts `trader`/`sender` and caches discount by the pair (`indexer/src/api/route_solver.rs` around lines 46, 92–124). The dApp always sends the connected wallet as `trader` (`frontend-dapp/src/services/indexer/client.ts` lines 715–760). - **Route solving:** `indexer/src/api/route_solver.rs`, `best_execution.rs`, `hybrid_route_opt.rs`, `route_paths.rs`; quotes are local-only and must never trigger RPC (`AGENTS.md`, #1452). `docs/route-solver.md`, `docs/swap-max-spread-ux.md`. - **Guards:** pair pause, factory trading blacklist (`pair/src/blacklist_guard.rs`, `router/src/blacklist_guard.rs`), asset code-id pin + factory whitelist (`pair/src/asset_code_id_guard.rs`), hooks with positive `min_return` (#1398), route-local tax funding v1 (#1381), launch guards (#608) and the token code-id freeze (#585/#582). - **Pool:** #1583 defines the note tree, `LIABILITY`, `Unshield`, the canonical spend digest and a `CommitSwapOutput` settlement hook callable only by the stored router with a pending id. No swap execution exists yet. Known facts that constrain the design: 1. The router receives the pool's gross input and needs an authenticated trader; the token requires `ctx.gross >= economic + sell_tax(trader)`. If the pool forwards a user-supplied `trader` field, a user could claim another wallet's manager exemption, so the pool must always set the trader to the pool. 2. Direct pair swaps cannot deliver an output hook, and a plain transfer would leave the output sitting in the pool with no note, breaking liability accounting. The router therefore needs either an optional output hook or a reply-based settlement in the pool. 3. A `community-tax-token` with active launch guards will treat the **pool** as the trader/recipient: `max_wallet` would reject any output above the cap because the pool's balance is large, and cooldown would throttle the whole pool to one swap per window. Shielded swaps for such tokens must fail closed until guards are lifted; do not disable guards and do not exempt the pool. 4. Fee discounts are per-wallet CL8Y balances; the pool is not a wallet tier holder. Silent discount claims would be incorrect and would invite abuse by registering the pool. Phase 1 therefore pays the base fee and the quote must use the pool as trader, not the user's wallet. ## Why a new implementation is needed Shielded balances without a swap path are custody, not a product: users would have to unshield to trade, exposing the very address the feature is meant to keep out of the DEX's data. A swap executed by the user's wallet is attributable by the pair, the indexer, the trader leaderboard and the portfolio; a pool-executed swap is not. Atomicity is also a safety requirement. A swap that sends the input and only later credits an output note gives a relayer or a griefer a window to strand funds, double-credit, or leave unaccounted output in the pool. The spend authorisation must bind the exact route, the minimum output, the deadline, the owner key and the change destination, and the output note must be created in the same transaction or the whole swap must revert. ## Relevant files - `smartcontracts/contracts/shielded-pool/src/{contract,spend,settle,msg,state,error}.rs` (new; from #1583) - `smartcontracts/contracts/router/src/{msg,contract,route_tax}.rs` (additive output-hook field and tests) - `smartcontracts/packages/dex-common/src/` (shared hook/settlement types if needed) - `smartcontracts/contracts/pair/src/contract.rs` (read-only; no behaviour change) - `smartcontracts/contracts/community-tax-token/src/{contract,tax}.rs` (read-only; tax and guard behaviour) - `smartcontracts/contracts/fee-discount/src/` and `pair/src/discount_cache.rs` (read-only; no pool registration) - `indexer/src/api/{route_solver,best_execution,hybrid_route_opt}.rs` and `frontend-dapp/src/services/indexer/client.ts` (quote parameters; wallet must not be sent) - `docs/shielded-pool.md`, `docs/route-solver.md`, `docs/contracts-security-audit.md`, `docs/qa/issue-<N>/README.md`, `skills/AGENTS_SHIELDED_SWAP.md` - `scripts/qa/verify-issue-<N>.sh`, `Makefile` ## Recommended direction 1. **One signed swap authorisation.** Extend the #1583 canonical digest with a swap context: `context_hash = SHA256("cl8y-shielded-swap-v1" || router || len(operations_json) || operations_json || max_spread || min_output || deadline || gross_input || max_relayer_fee || owner_pubkey || output_token)`, and sign `SHA256(domain || chain_id || pool || version || input_token || gross_input || nullifier_set_hash || relayer_fee || output_owner_pubkey || context_hash)`. Use a deterministic serialisation of the router operations (canonical field order, no maps, fixed decimal/uint encoding) and hash it; the pool reconstructs the operations and compares the digest, never trusts a route supplied outside the signature. Bind the **exact** `SwapOperation` vector (including `min_return`, `hybrid`/`greedy` fields if used) and the required `min_output`. 2. **Router output hook (primary) — additive only.** Add `output_hook: Option<Binary>` to `ExecuteRouteSwapOperations` (and the CW20 hook variant) and apply it only on the final payout: if present, `Cw20ExecuteMsg::Send { contract: to, amount: final_net, msg: output_hook }` instead of a plain transfer; for tax-capable tokens use the existing `RouteTransfer` first and let the token deliver to `to`, or require the hook path to be used only for tokens whose `RouteTransfer` supports a hook. Simpler and safer: require `output_hook` only with `to = pool`, and make the router reject a hook when `to` is not a contract that accepts it, when `unwrap_output` is set, or when the final leg is native. Keep the field optional and default `None`, preserve the existing byte-for-byte behaviour for non-shielded users, and cap the hook payload size (e.g. 8–16 KiB) to bound gas. Add an ADR if the router interface changes (the repo already uses ADRs for interface-level decisions). Do **not** add a hook to the pair's output transfer in this issue: keep the pair unchanged and let the router deliver the hook. If the router change is rejected in review, fall back to a submessage reply: the pool calls the router, records `PENDING_SETTLEMENT { token, min_output, owner_pubkey, baseline_balance, nonce }`, and in `reply` reads its own post-swap CW20 balance, computes the delta against the recorded baseline, and inserts the note. The fallback must prove per-tx isolation (two swaps in one tx; a donation to the pool during the same tx) and must revert if the delta is below `min_output`. 3. **`PrivateSwap` execute path.** Accept up to **four** input notes in the same token, all owned by the same ed25519 key (or an explicit set of keys, each with its own signature), plus route, `max_spread`, `min_output`, `deadline`, `relayer_fee`, `output_owner_pubkey`. Verify every note (commitment, root, signature, nullifier, deadline) **before** any state change. Require `sum(inputs) >= gross_input + relayer_fee`, with `gross_input` bound in the signature; change = `sum(inputs) − gross_input − fee` in the input token; output note = the post-tax net received in the output token. Mark nullifiers, decrement liability by the inputs, send the gross to the router with `ExecuteRouteSwapOperations { funding_version: 1, operations, max_spread, minimum_receive, to: pool, output_hook: CommitSwapOutput { pending_id, min_output, output_token, owner_pubkey, relayer_fee } }`, and let the settlement hook credit the output and insert change in one atomic sequence. If the hook is absent or not called, the transaction must fail (the pending entry alone is not a settlement). 4. **Trader identity and taxes.** The router's `RouteTaxContext.trader` must be the pool: the pool sends the CW20 `Send` itself, so the router sees the pool as the sender. Never accept a `trader` field in the pool's message. Require the pool to be **non-exempt** on every routed tax token (no `PROTOCOL_EXEMPT`, no `MANAGER_EXEMPT`, no directory entry) and test that a governance attempt to add it is rejected by the token (the token already rejects protocol addresses). Compute the gross from the note, not from a user-declared economic amount. For a tax-capable token, require `RouteTaxPreview`/`RouteTaxContext` success; if the capability query fails, fail closed rather than routing with an unknown tax. The user-facing quote must preview sell tax (and buy tax on the output) and the note's net result. If the output token also has a buy tax, the output note is the net after that tax. 5. **Launch-guard and fee policy.** Shielded swaps are **disabled** for a token when `trading_enabled == false`, `cooldown_blocks > 0`, or `max_wallet` would apply to the pool (which it will when set), unless governance explicitly records a decision and the pool-level throttle is documented and accepted. Do not add the pool to exemption maps. Phase 1 pays the base pair fee: the pool is not registered in the fee-discount registry, `route/solve` must be called with the pool as trader (or without a trader), and the dApp must not imply a tier discount. Document the trade-off in `docs/shielded-pool.md`. 6. **Quote and route contract.** Shielded quotes use the existing solver with `trader = pool` (a stable public address, not the user) or no trader, and never include the user's wallet, `sender`, tier or blacklist-check wallet. The quote must carry the same fields the pool will bind (operations, max_spread, min_output, gross, deadline) and the client must derive `min_output` from the reviewed quote with the same rules as the ordinary Swap UI (L9 max spread, positive post-hook `min_return`, final minimum receive). The pool re-checks the signed route; the indexer remains a hint. No request-time RPC/LCD, no new solver work on the request path; the existing cache and progress rules apply. 7. **Settlement and liability.** `CommitSwapOutput` (from #1583) must verify `info.sender == router`, `pending_id` exists in the current tx, token matches, amount `>= min_output`, and the pending entry has not been consumed. It computes the output note from the actual credit, credits the change note (input token) in the same tx, clears the pending entry, updates liability and emits both notes. If the router or token credits less than `min_output`, the hook reverts and the whole swap reverts. If the router sends the output with a plain `Transfer` (hook missing), the pool must not accept the unattributed balance; add a test that the pending entry cannot be settled by a later token transfer and that `Reconcile` shows the discrepancy until governance-free recovery (there is none: the tx must revert). 8. **Reentrancy and ordering.** The pool must be reentrancy-safe: no state mutation before validation; a `PENDING_SETTLEMENT` keyed by `(tx scope, pending_id)`; a guard that rejects a second settlement in the same tx with the same pending id; no callback into the pool from the input token except the CW20 `Send` hook that the router/pair executes (the pair's output is a plain transfer). The router must not call an arbitrary hook on a `to` that is not the pool, and the pool must reject `CommitSwapOutput` when `info.sender != stored router`. ## Constraints and guardrails - **No standing allowances:** the pool never calls `IncreaseAllowance` for the pair/router; it uses CW20 `Send` of its own balance and router funding v1. No `TransferFrom` path, no approval to an arbitrary contract. - **Exact binding:** operations digest, `max_spread`, `min_output`, deadline, input token, gross, output token, owner key, relayer fee and destination are all covered by the signed digest; any mismatch reverts. The relayer cannot choose the route, reduce the output, redirect the change, or skim more than the signed fee. - **Route limits:** the router's existing hop, asset-path and repeated-taxable-asset rules remain (`route_tax::validate_asset_path`); no foreign DEX, no manual split, no native output, no `unwrap_output`, no limit order/book leg in phase 1. - **Fees/taxes preserved:** pair commission, treasury destination, protocol fee events, community-tax sell/buy/transfer tax and route-local funding v1 are unchanged. Shielded swaps must not create a tax-exempt path, a fee-discount path or a treasury bypass. Do not modify token tax code. - **Guards preserved:** factory blacklist, token freeze, pair pause, launch guards, code-id pins and deadline checks remain enforced on every call. The pool is not exempt from any of them; a blacklisted pool address stops all shielded swaps (expected and documented). - **Gas:** a shielded swap must fit the documented retail envelope (measure on LocalTerra; `docs/adr/0004-terraclassic-retail-gas-census.md`). If ed25519 verification plus Merkle + router execution exceeds it, reduce the number of input notes or stop and revise; do not silently raise the wallet gas cap. The router hook must not add unbounded work. - **No request-time chain calls:** quotes stay local to the indexer cache; the frontend must not add LCD simulations for shielded swaps beyond the existing preflight policy, and must never include the user's wallet in a shielded quote. - **Backward compatibility:** the router field is optional; all existing swap paths, quote shapes and pair behaviour are unchanged. Do not change `funding_version`; do not re-use the new hook field for non-shielded flows. - **Data hygiene:** no wallet address, note key, user conversation or private report in calldata examples, tests, docs or issue text. ## Acceptance criteria - [ ] AC1: A signed `PrivateSwap` spends 1–4 notes atomically, sends the gross input to the official router, and credits the output note plus change in the same transaction; if any step fails, no nullifier is consumed, no liability changes, and no token leaves the pool. - [ ] AC2: The route digest binds the exact operations vector, `max_spread`, `min_output`, deadline, input/output tokens, gross, owner key and relayer fee. A relayer that substitutes a pair, adds a hop, raises `max_spread`, lowers `min_output`, changes the owner key or redirects the destination causes a revert. - [ ] AC3: The pool is the router trader; the pool is not exempt, not manager-exempt and not in the fee-discount registry; sell and buy tax are charged exactly as for a normal routed wallet swap, with `RouteTaxContext.gross >= economic + sell_tax(pool)` and the output note equal to the post-tax net. - [ ] AC4: Shielded swaps fail closed for tokens with active launch guards (`trading_enabled=false`, cooldown, `max_wallet`), for a paused pair, for a frozen/blacklisted token or pair, for a code-id drift and for an unknown tax capability. No guard is disabled or bypassed. - [ ] AC5: No fee-tier discount is claimed or implied for shielded swaps; the quote uses the pool (or no trader) and never the user's wallet; the base fee and treasury commission match the ordinary swap for the same route and amount. - [ ] AC6: The output is exactly-once and cannot be stranded: a missing hook, a plain-token transfer, a duplicate settlement, a wrong router, a below-min output or a third-party donation cannot settle a pending swap; `Reconcile` stays consistent. - [ ] AC7: The router change is optional and additive; every existing router/pair test and non-shielded swap path is unchanged, and the new field is rejected for native output, `unwrap_output`, and any `to` other than the intended contract. - [ ] AC8: Gas for deposit/withdraw/private swap is measured and documented; the shielded swap fits the documented envelope or the issue is reported FAIL with the measured numbers. - [ ] AC9: `docs/shielded-pool.md`, `docs/route-solver.md` (shielded quote note), `docs/contracts-security-audit.md`, `docs/qa/issue-<N>/README.md` and `skills/AGENTS_SHIELDED_SWAP.md` are updated; `make verify-issue-<N>` exists. - [ ] AC10: The privacy claim stays accurate: the pair/indexer see the pool as the trader, but the input and output amounts and the note graph remain public chain data; the docs and UI copy do not claim hidden amounts or anonymity. ## Test plan: functional paths | Path | Required checks | | --- | --- | | Single-note swap | Direct pair route, 2/3/4-hop route, native-wrapped hops only as supported by the router, 6/9/12/18-decimal tokens, 1 raw unit, dust, large amounts; exact `min_output`; output note amount; change note; liability delta; event fields. | | Multi-note swap | 2–4 notes, same key and mixed leaf ages, different deposits; one invalid note fails all; sum/change arithmetic; nullifier set; gas at 4 notes. | | Tax paths | Community-tax sell (tax >0), buy tax on output, tax >0 and close-to-zero, tax on an intermediate hop, no-tax `cw20-mintable`, tax capability query failure, `RouteTaxContext` mismatch; gross/tax/net reconciliation with the note. | | Output settlement | Router hook path; reply fallback if implemented; output > min, output == min, output < min; output token mismatch; two swaps in one tx; hook payload size at the cap; settlement after a failed router call. | | Guards | Pair paused, token frozen, factory-blacklisted wallet/pool/token/pair, code-id drift, launch guards (`trading_enabled=false`, cooldown, max_wallet), deadline now/past, `max_spread` boundary, insufficient liquidity, zero output, hook-required `min_return`. | | Quotes | Quote with pool trader and no trader produce the same execution binding; quote must not include the user's wallet; stale quote/deadline; solver timeout/404; no request-triggered RPC; frontend preflight parity; Expert/tolerance change. | | Failure/recovery | Router reverts, token transfer fails, settlement hook reverts, ambiguous broadcast, duplicate submit, retry after failure; no duplicate nullifier spend and no lost change. | | Compatibility | All existing pair/router/factory/community-tax tests; non-shielded swap routes and quotes byte-identical in shape; router schema additive; old clients omit the new field. | ## Test plan: attacks, hacks and abuse - **Route substitution / MEV:** relayer swaps a pair, inserts an extra hop, changes the offer/ask token, inflates `max_spread`, lowers `min_output`, extends the deadline or replays a quote on a new state. The digest must reject every mutation. A sandwicher cannot change the signed destination; a delayed relayer hits the deadline. - **Tax evasion:** pool added to `PROTOCOL_EXEMPT`/`MANAGER_EXEMPT`/directory, a user-supplied `trader` claiming another wallet's exemption, a route that classifies the pool as a transfer instead of a sell, a pool-side `SendFrom` allowance, or a swap through a non-official router. All must fail or be rejected by governance/token tests; verify the token's tax context is the pool and the amount matches. - **Fee abuse:** register the pool in the fee-discount registry or feed `trader=<user>` to the pair, claim a tier without a CL8Y balance, or use the discount cache keyed by `(trader, sender)` to inherit another wallet's discount. No discount path may apply; the pair fee must equal the non-discounted base. - **Theft / partial settlement:** output note credited to the relayer's key, change note to the relayer, relayer fee above the cap, a second `CommitSwapOutput` with the same pending id, a third party sending the output token directly to the pool, a router that transfers to `to` without the hook, and a swap that leaves the output in the router. Only the signed owner may receive the output and change; unattributed balances must revert or be visible, never credited. - **Reentrancy / ordering:** a malicious allowed token re-enters the pool during `Send`; two swaps nest; a hook calls back into `PrivateSwap`; the router calls the hook twice; the pool is called with a pending id from another tx. Reentrancy guard, per-tx pending scoping and exactly-once must hold. - **Double spend / replay:** same notes spent in swap and withdraw in one tx or across txs; cross-chain/cross-pool signature replay; signature reuse with a different route/owner/destination; nullifier front-run by a party that knows the public opening (must not authorize a spend). - **Guard bypass:** paused pair, frozen token, blacklisted wallet/pair, launch guard state changed between quote and execution, a token whose `trading_enabled` flips mid-tx; every check must be read at execution time, not cached from the quote. - **Numerics:** 6-vs-18-decimal scale, tax rounding, change dust, `gross + fee > inputs`, `min_output` at 1 raw unit, `max_spread` at the boundary, large reserves and overflow; no output note may exceed the actual credit. - **DoS / resources:** max notes, max hops, max hook size, huge route vectors, deep book/hybrid data, repeated failing swaps, and indexer quote floods. Bound loops, payloads and gas; no unbounded routing inside the pool. - **Privacy leakage:** the pool must not emit the submitter as owner, must not include the relayer in a "trader" field, and must not forward the user's wallet to the router/indexer. The quote request and indexer cache keys must be free of the user's address. ## Verification criteria - [ ] `make verify-issue-<N>` runs workspace fmt/clippy/build, the new pool and router tests, all existing pair/router/community-tax/fee-discount tests, schema checks and doc cross-links. - [ ] LocalTerra E2E (`VERIFY_ISSUE_<N>_CHAIN=1`, opt-in): shield → private swap on a direct route → private swap on a 2-hop route → unshield, using `cw20-mintable` and a community-tax-token with sell tax; assert `Reconcile`, no residual unaccounted balance, no nullifier reuse, and the expected tax/commission receipts. - [ ] A router compatibility test proves the optional field is ignored when absent and that all existing non-shielded swap tests still pass unchanged. - [ ] Gas receipts (deposit, 1-note swap, 4-note swap, withdraw) are recorded in `docs/qa/issue-<N>/README.md`; a route above the documented envelope is FAIL, not a skip. - [ ] `docs/qa/issue-<N>/README.md` records explicit skips and evidence; executed failures remain FAIL. No conversation, personal data or wallet-owner identity is stored. - [ ] The final revision is reviewed by an independent agent for tax evasion, route binding, settlement atomicity and guard bypass before the sibling dApp issue consumes the interface. ## Out of scope / follow-ups - Indexer classification, non-attribution, note discovery (#1585). - dApp vault, quotes, shield/unshield and private swap UX (#1586). - Threat model, abuse/compliance policy, relayer operations and staged rollout (#1587). - ZK notes, encrypted payloads, P2P transfers, cross-pool routes, native-asset shielding, limit-order/book execution, and fee-tier claims for shielded notes: not in phase 1.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
code/cl8y-dex-terraclassic#1584
No description provided.