feat(shielded): atomic private swaps from shielded notes via the official router #1584
Labels
No labels
agent:fix_bugfix
agent:fix_conflicts
agent:fix_security
agent:gap_analysis
agent:implement
agent:implement
agent:implement
agent:open_issues
agent:ready
agent:research
agent:security_audit
agent:verify
architecture
backend
blocker:hybrid
blocker:launch
blocker:limit-orders
blocker:v2
block:log_only
block:security
bug
ci
contracts
correctness
deploy
dev
devops
docs
documentation
duplicate
e2e
enhancement
epic
feature
frontend
functional-completion
gas
good first issue
governance
help wanted
high-risk
hooks
hybrid
indexer
infra
infrastructure
integrators
invalid
launch-blocker
limit-orders
localnet
localterra
low priority
missing-implementation
needs-design
ops
performance
priority
high
priority
medium
product
qa
QA
question
ready
ready
research
scripts
security
security-hardening
smartcontracts
tech-debt
testing
ux
UX
v2
verification
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
code/cl8y-dex-terraclassic#1584
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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:
PrivateSwapexecution path and its signed authorisation digest;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.smartcontracts/contracts/pair/src/contract.rsexecute_receiveacceptsCw20HookMsg::Swap { belief_price, max_spread, min_return, to, deadline, trader, hybrid, greedy }, gates trading blacklist, factory whitelist and asset code-id pins, thenexecute_swapsends the ask token to the receiver withCw20ExecuteMsg::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.smartcontracts/contracts/router/src/msg.rsExecuteRouteSwapOperations { funding_version: 1, operations, max_spread, minimum_receive, to, deadline, unwrap_output }andExecuteSwapOperations; the router holds the gross input, pays each hop withCw20ExecuteMsg::Send, and the final payout usesroute_tax::transfer(smartcontracts/contracts/router/src/route_tax.rs) which callsRouteTransfer { slot, recipient, amount }for route-tax-capable tokens andcw20::Cw20ExecuteMsg::Transferotherwise.tois a plain address; there is no output hook.community-tax-tokenclassifies route sells through the official router and requires an authenticatedRouteTaxContextwithtrader,pair,offer_token,economic,gross(smartcontracts/contracts/community-tax-token/src/tax.rsapply_transfer,preview,hop_trader_addr).is_route_traderrejects the router and protocol-exempt addresses. Sell tax is charged on the gross and the pair receivesamount; buy tax is charged on router→recipient. Manager/directory exemptions follow the authenticated trader.max_walletand cooldown launch guards usefrom/toand the hop trader.pair/src/discount_cache.rskeys a 300-second cache by(trader, sender)and the registry (smartcontracts/contracts/fee-discount) reads the trader's live CL8Y balance. The indexer'sroute/solveacceptstrader/senderand caches discount by the pair (indexer/src/api/route_solver.rsaround lines 46, 92–124). The dApp always sends the connected wallet astrader(frontend-dapp/src/services/indexer/client.tslines 715–760).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.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 positivemin_return(#1398), route-local tax funding v1 (#1381), launch guards (#608) and the token code-id freeze (#585/#582).LIABILITY,Unshield, the canonical spend digest and aCommitSwapOutputsettlement hook callable only by the stored router with a pending id. No swap execution exists yet.Known facts that constrain the design:
ctx.gross >= economic + sell_tax(trader). If the pool forwards a user-suppliedtraderfield, a user could claim another wallet's manager exemption, so the pool must always set the trader to the pool.community-tax-tokenwith active launch guards will treat the pool as the trader/recipient:max_walletwould 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.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/andpair/src/discount_cache.rs(read-only; no pool registration)indexer/src/api/{route_solver,best_execution,hybrid_route_opt}.rsandfrontend-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.mdscripts/qa/verify-issue-<N>.sh,MakefileRecommended direction
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 exactSwapOperationvector (includingmin_return,hybrid/greedyfields if used) and the requiredmin_output.Router output hook (primary) — additive only. Add
output_hook: Option<Binary>toExecuteRouteSwapOperations(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 existingRouteTransferfirst and let the token deliver toto, or require the hook path to be used only for tokens whoseRouteTransfersupports a hook. Simpler and safer: requireoutput_hookonly withto = pool, and make the router reject a hook whentois not a contract that accepts it, whenunwrap_outputis set, or when the final leg is native. Keep the field optional and defaultNone, 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 inreplyreads 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 belowmin_output.PrivateSwapexecute 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. Requiresum(inputs) >= gross_input + relayer_fee, withgross_inputbound in the signature; change =sum(inputs) − gross_input − feein 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 withExecuteRouteSwapOperations { 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).Trader identity and taxes. The router's
RouteTaxContext.tradermust be the pool: the pool sends the CW20Senditself, so the router sees the pool as the sender. Never accept atraderfield in the pool's message. Require the pool to be non-exempt on every routed tax token (noPROTOCOL_EXEMPT, noMANAGER_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, requireRouteTaxPreview/RouteTaxContextsuccess; 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.Launch-guard and fee policy. Shielded swaps are disabled for a token when
trading_enabled == false,cooldown_blocks > 0, ormax_walletwould 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/solvemust be called with the pool as trader (or without a trader), and the dApp must not imply a tier discount. Document the trade-off indocs/shielded-pool.md.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 derivemin_outputfrom the reviewed quote with the same rules as the ordinary Swap UI (L9 max spread, positive post-hookmin_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.Settlement and liability.
CommitSwapOutput(from #1583) must verifyinfo.sender == router,pending_idexists 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 thanmin_output, the hook reverts and the whole swap reverts. If the router sends the output with a plainTransfer(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 thatReconcileshows the discrepancy until governance-free recovery (there is none: the tx must revert).Reentrancy and ordering. The pool must be reentrancy-safe: no state mutation before validation; a
PENDING_SETTLEMENTkeyed 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 CW20Sendhook that the router/pair executes (the pair's output is a plain transfer). The router must not call an arbitrary hook on atothat is not the pool, and the pool must rejectCommitSwapOutputwheninfo.sender != stored router.Constraints and guardrails
IncreaseAllowancefor the pair/router; it uses CW20Sendof its own balance and router funding v1. NoTransferFrompath, no approval to an arbitrary contract.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_tax::validate_asset_path); no foreign DEX, no manual split, no native output, nounwrap_output, no limit order/book leg in phase 1.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.funding_version; do not re-use the new hook field for non-shielded flows.Acceptance criteria
PrivateSwapspends 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.max_spread,min_output, deadline, input/output tokens, gross, owner key and relayer fee. A relayer that substitutes a pair, adds a hop, raisesmax_spread, lowersmin_output, changes the owner key or redirects the destination causes a revert.RouteTaxContext.gross >= economic + sell_tax(pool)and the output note equal to the post-tax net.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.Reconcilestays consistent.unwrap_output, and anytoother than the intended contract.docs/shielded-pool.md,docs/route-solver.md(shielded quote note),docs/contracts-security-audit.md,docs/qa/issue-<N>/README.mdandskills/AGENTS_SHIELDED_SWAP.mdare updated;make verify-issue-<N>exists.Test plan: functional paths
min_output; output note amount; change note; liability delta; event fields.cw20-mintable, tax capability query failure,RouteTaxContextmismatch; gross/tax/net reconciliation with the note.trading_enabled=false, cooldown, max_wallet), deadline now/past,max_spreadboundary, insufficient liquidity, zero output, hook-requiredmin_return.Test plan: attacks, hacks and abuse
max_spread, lowersmin_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.PROTOCOL_EXEMPT/MANAGER_EXEMPT/directory, a user-suppliedtraderclaiming another wallet's exemption, a route that classifies the pool as a transfer instead of a sell, a pool-sideSendFromallowance, 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.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.CommitSwapOutputwith the same pending id, a third party sending the output token directly to the pool, a router that transfers totowithout 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.Send; two swaps nest; a hook calls back intoPrivateSwap; 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.trading_enabledflips mid-tx; every check must be read at execution time, not cached from the quote.gross + fee > inputs,min_outputat 1 raw unit,max_spreadat the boundary, large reserves and overflow; no output note may exceed the actual credit.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.VERIFY_ISSUE_<N>_CHAIN=1, opt-in): shield → private swap on a direct route → private swap on a 2-hop route → unshield, usingcw20-mintableand a community-tax-token with sell tax; assertReconcile, no residual unaccounted balance, no nullifier reuse, and the expected tax/commission receipts.docs/qa/issue-<N>/README.md; a route above the documented envelope is FAIL, not a skip.docs/qa/issue-<N>/README.mdrecords explicit skips and evidence; executed failures remain FAIL. No conversation, personal data or wallet-owner identity is stored.Out of scope / follow-ups