feat(shielded): note-based shielded balance pool for CL8Y-controlled CW20 code ids #1583
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#1583
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
Build the custody and note layer for shielded balances of CL8Y-controlled CW20 assets: a new
shielded-poolcontract that (a) accepts deposits of allowlisted, code-id-pinned CW20s, (b) represents each deposit as a note commitment in an append-only Merkle tree, (c) authorises spending by a note key signature plus a nullifier (no wallet address in the spend path), and (d) pays out to a caller-chosen destination with an optional relayer fee.This issue delivers the primitive only: deposit (
Shield), withdraw (Unshield), change notes, note queries, liability accounting, caps, migration, and the internal settlement hook that the sibling swap issue consumes. Atomic private swaps, indexer work and dApp work are separate issues and must not be started as a partial substitute for this layer.The scope is deliberately not a general mixer and not an anonymity system:
Current codebase and investigation
Reviewed checkout:
/home/answorld/repos/cl8y-dex-terraclassicat38c154958. No shielded, nullifier, commitment or note code exists in the repository: the only matches forshieldedare unrelated comments inindexer/tests/api_evidence_daily.rs.smartcontracts/Cargo.tomlis a CosmWasm 1.5.11 workspace (cosmwasm-std = 1.5.11) with singleton-style contracts undersmartcontracts/contracts/(factory, pair, router, fee-discount, faucet, hooks, community-tax-token, community-tax-autolp, community-token-launcher, bridge-debt-token, bridge-debt). Shared types live insmartcontracts/packages/dex-common.ed25519_verify/secp256k1_verifyare unused). There is no Merkle tree, nullifier set, commitment scheme or note store. Any note design must prove on-chain verification and gas cost on columbus-5; do not assume a precompile.bridge-debt-token(receipt token),community-tax-autolp, and thecommunity-tax-tokenAdoptpath.bridge-debt/bridge-debt-tokencurrently lackensure_from_older_versioninmigrate(internal audit BD-3); do not repeat that mistake.Sendhook does not necessarily deliver the declared transfer amount.community-tax-tokenexecute_sendcallstax::execute_send_hook(&to, &sender, credit, msg)with the post-tax credit, so a deposit hook must use the hook'samount/credit and never a user-declared amount.community-tax-tokenSendFromextra-debits the owner (preview.debit = amount + taxfor a pair-direct sell) and requires allowance.cw20-mintable10184;community-tax-tokeninstances 11611 / 11619 / 11626 / 11630 (refresh per the #611 program); CL8Y token instance;bridge-debt-tokeninstance. Current factory whitelist is[6036, 8266, 10184, 11611, 11619, 11630]per the deploy traces; 6036 (TerraSwap legacy) and 8266 (third-party template) are not CL8Y-controlled and must not be admitted by this feature. Thecw20-codeid-auditscatalogue documents known-bad fee-on-transfer/ALPHA 8654.smartcontracts/contracts/pair/src/asset_code_id_guard.rs: pin the liveContractInfo.code_idat instantiate/refresh, re-check it on every write, and require the factoryIsCodeIdWhitelistedquery. Errors fail closed (AssetCodeIdGuardUnavailable). The pool must mirror this rather than trusting a stored address alone.docs/runbooks/wasm-admin-migration.md, code-id audit procedurecw20-codeid-audits/PROCEDURE.md, TVL/security ladder indocs/security-posture.md, retail gas census ADRdocs/adr/0004-terraclassic-retail-gas-census.md, evidence/privacy precedent indocs/qa/issue-1397/README.md.docs/qa/issue-<N>/README.md,scripts/qa/verify-issue-<N>.shorscripts/verify-issue-<N>.sh, and amake verify-issue-<N>target. LocalTerra patterns are indocs/localterra-sdk53.md,scripts/setup-cloud-agent-localterra.sh, anddocs/runbooks/.Why a new implementation is needed
All CL8Y-controlled balances and swaps are currently attributable to a wallet address:
pairemitssender/receiver,community-tax-tokenrecords exemptions and guard state per address, and the indexer publishesswap_events.sender,/api/v1/pairs/{addr}/trades,/api/v1/traders/{addr},trader_positionsand leaderboards. Users who hold or trade CL8Y, community-tax tokens orcw20-mintableassets have no supported path that keeps their position and trading out of the DEX's own data products, and no way to hold a pooled balance that is spendable by a key rather than by a wallet account.A note-based custody contract is the minimal on-chain primitive that makes a private swap path possible: it aggregates balances at one address, authorises spends without exposing the wallet, and gives the swap issue an atomic settlement point. Without it, any "private" frontend would merely be a wallet-address rotation, which provides no DEX-level non-attribution and no atomic swap output.
Relevant files
New work:
smartcontracts/contracts/shielded-pool/Cargo.tomlsmartcontracts/contracts/shielded-pool/src/{lib,contract,msg,state,error,note,tree,spend,query,tests,multitest}.rssmartcontracts/Cargo.toml(workspace member)smartcontracts/packages/dex-common/src/(only if shared types are required by the sibling router/swap issue)scripts/qa/verify-issue-<N>.sh,Makefiledocs/shielded-pool.md,docs/qa/issue-<N>/README.md,skills/AGENTS_SHIELDED_POOL.mddocs/security-model.md,docs/security-posture.md,docs/contracts-security-audit.md,docs/runbooks/wasm-admin-migration.md,docs/runbooks/cw20-whitelist-policy.mdReference implementations to read before coding:
smartcontracts/contracts/pair/src/asset_code_id_guard.rs,smartcontracts/contracts/community-tax-token/src/{contract,tax}.rs,smartcontracts/contracts/bridge-debt-token/src/contract.rs,smartcontracts/contracts/factory/src/contract.rs(WHITELISTED_CODE_IDS),docs/adr/0004-terraclassic-retail-gas-census.md.Recommended direction
New crate, no changes to existing contracts in this issue. Instantiate with
{ factory, governance, router, allowed_tokens, limits }.routeris stored for the sibling swap issue; the pool must not call it yet.Note model (versioned). A note opening is
{ version: u8, token: Addr, amount: Uint128, owner_pubkey: Binary (32-byte ed25519 public key), blinding: Binary (32 bytes), leaf_index: u32 }.commitment = SHA256("cl8y-shielded-note-v1" || chain_id || pool_addr || token || amount || owner_pubkey || blinding).Compute commitments inside the contract from the opening; never accept an externally supplied commitment as authoritative. Bind
chain_idand the pool address so proofs and signatures cannot be replayed across chains or pools. Keepversionin the preimage so a future encrypted/ZK note version can coexist.Tree and nullifier state. Append-only Merkle tree of depth 32 with SHA256 pair hashing and a zero-subtree optimisation. Persist only the nodes/frontier needed for insertion and proofs; store a bounded history of recent roots (at least 64, configurable) so a note inserted while a spend is prepared remains spendable.
NULLIFIERS: Map<[u8;32], NullifierRecord { height, tx_index }>; a nullifier isSHA256("cl8y-shielded-nullifier-v1" || commitment)— deterministic, single-use, and not secret. Do not reuse a nullifier domain across note versions.Deposit (
Receive(Cw20ReceiveMsg)). Accept onlyCw20HookMsg::ShieldNote { owner_pubkey, blinding }from an allowlisted token contract. Validate: token is allowlisted and its livecode_idequals the pin and is factory-whitelisted (mirrorasset_code_id_guard);amount > 0; decimals 6–18 (decimals are display-only; do not do unit conversion on-chain); per-note min/max; per-token TVL cap; per-block and per-address deposit caps; note key is a valid 32-byte ed25519 key and is not the pool/factory/router address; deposit delay config. Use the hook'samount(post-tax credit), not a declared amount. Insert the note, increase per-tokenLIABILITY, emitaction=shield_notewith the commitment, token, amount, owner pubkey, leaf index and the new root. Because public CW20 transfers and public openings are phase-1 policy, the deposit event may carry the opening; the note's safety must not depend on keeping the opening secret — authorisation is the owner key signature, not knowledge of the opening.Withdraw (
Unshield). Input a single note opening plus its Merkle path against a stored root (any root in history), anullifier,destination,relayer_fee,deadline, and an ed25519 signature. Verify in this order: deadline → note is well formed and token allowlisted/pinned → commitment matches → path matches a stored root → note key is the signer → nullifier unused → fee ≤ configured cap and ≤ amount → destination validates and is not blacklisted (factoryBlacklistCheck) → mark the nullifier, decrease liability, transferamount - feetodestinationandfeetoinfo.senderif non-zero. Emit a spend event with the nullifier and leaf index but no wallet address. A failed transfer must revert the whole call (no partial state).Change notes and output notes. The pool creates output notes itself with a fresh blinding (
SHA256(pool || nullifier || leaf_index || output_counter)is acceptable because openings are public in phase 1) and the owner pubkey bound in the signed digest. Change = input note amount − withdrawn amount − relayer fee. Never accept a user-supplied output blinding in phase 1; that only creates a theft surface with no safety benefit. Insert output notes in the same call and emit them.Canonical spend digest. Define one documented digest used by
Unshieldand by the sibling swap issue:SHA256(domain || chain_id || pool || version || token || amount || leaf_index || commitment || nullifier || relayer_fee || len(destination) || destination || output_owner_pubkey || deadline || context_hash),where
context_hashisSHA256("unshield")or the swap-route digest supplied by the sibling issue. Verify withcosmwasm_std::ed25519_verify; record the measured gas and wasmvm support on columbus-5. If ed25519 verification is not available or is outside the retail gas envelope, fall back tosecp256k1_verifyand document the change; do not ship a hand-rolled curve implementation.Swap settlement primitive (defined here, used later). Expose an internal
CommitSwapOutput { pending_id, token, min_output, owner_pubkey, relayer_fee? , deadline }hook that is callable only by the storedrouter, only while aPENDING_SETTLEMENTentry with thatpending_idexists in the current tx, and only for an allowlisted token. It computes the output note from the actual received credit, checks>= min_output, inserts the note, updates liability, clears the pending entry, and must be exactly-once.Unshieldand the siblingPrivateSwapshare the same note/liability code. If the router cannot deliver a hook, the recommended fallback is a submessage reply that reads the pool's post-swap CW20 balance delta under a per-tx pending record; both options need tests proving no cross-credit between two swaps in one tx.Queries.
Config,AllowedToken { token },Root,RootHistory,NoteCount,Note { leaf_index }(commitment + token/amount metadata only),Nullifier { nullifier },Liability { token },Reconcile {}(on-chain CW20 balance vs liability per allowlisted token),PendingSettlement. Do not add a qeury that filters notes by owner pubkey; note discovery is the indexer issue's range-based endpoint.Admin surface.
UpdateConfig(governance) may add/remove tokens, change caps, deposit delay, relayer fee cap and root-history length;PauseDepositsblocks new deposits only. There must be no admin message that moves pool funds, spends a note, burns a nullifier, or blocks a withdrawal. Governance can rotate the router only while no settlement is pending. Migration must preserve the tree, nullifier set, liability and pending state, and must reject a version downgrade/unknown version (ensure_from_older_versionpattern, see BD-3).Privacy statement. Write
docs/shielded-pool.mdwith an explicit claim matrix: what is hidden (the DEX's own attribution; the swap sender is the pool), what is public (amounts, deposit tx, note graph, timings), what is not provided (anonymity, amount privacy, sanction-resistant mixing), and what the user must do (fresh, unlinked deposit source; one key per deposit; no destination reuse). Any "anonymity"/"mixer" wording is forbidden. The dApp notice is the frontend issue's responsibility, but the contract-level docs must be correct first.Constraints and guardrails
code_idis pinned and factory-whitelisted, and whose initial set is limited tocw20-mintable10184, the currentcommunity-tax-tokeninstance ids,bridge-debt-token, and the CL8Y token instance. Exclude 6036, 8266, 8654 and every third-party/rebase/fee-on-transfer token. Adding a code id is a governance action with a written review; a code-id drift or failed factory query fails closed.LIABILITYmust equal the sum of unspent note amounts plus pending settlement inputs. The pool's CW20 balance must be>= LIABILITY. Any discrepancy is a bug: fail the write that would increase it and exposeReconcile; do not add an admin "fix" path.community-tax-tokenmay incur the configured transfer tax (the hook amount is the net credit) and a swap by the pool may incur sell/buy tax (sibling issue). The pool must never be registered as protocol-exempt or manager-exempt, and must never use another wallet's exemption. Do not add the pool toPROTOCOL_EXEMPT,MANAGER_EXEMPTor the fee-discount registry.make build-optimizedand record checksums. Measure deposit, withdraw, change-note and no-op gas on LocalTerra; document the envelope and the ed25519 verify cost indocs/shielded-pool.md. If verification exceeds the retail envelope, stop and revise the design rather than shipping an unusable contract.sha2and thecosmwasm-stdcrypto API. Any new curve/cipher dependency needs a written justification, licence/supply-chain review (docs/supply-chain-security.md), and acw20-codeid-audits-style decompile of the built wasm. Do not vendor crypto code.pair,router,factory,community-tax-tokenorcw20-mintablebehaviour in this issue. The settlement hook may be unreachable until the sibling issue lands; tests may exercise it with a stub router.Acceptance criteria
shielded-poolcontract builds with the optimized optimizer, is schema-exported, has a cw2 identity, a versioned migrate that preserves tree/nullifiers/liability/pending state, and rejects unknown or older versions.Unshieldverifies deadline, membership against a historical root, key signature, nullifier freshness and destination; paysamount - feeto the destination andfeeto the submitter; consumes the nullifier exactly once; never leaves partial state on a failed CW20 transfer.Reconcile/liability accounting matches the contract's CW20 balances across deposit, withdraw, change, settlement, tax-affected deposits and failed calls;Reconcileis exposed and tested.PauseDepositsdoes not blockUnshield; migration preserves pending settlements or refuses to migrate while one exists.docs/shielded-pool.mdcontains the claim matrix, failure modes, gas envelope, key/backup model and the explicit "not an anonymity system / not a mixer" statement; security docs and invariant matrix are updated;make verify-issue-<N>anddocs/qa/issue-<N>/README.mdexist.min_output, and cannot be satisfied by a third party sending tokens to the pool.Test plan: functional paths
CommitSwapOutput; wrong router; missing pending id; wrong token; below min; duplicate same tx; pending expiry/deadline; third-party token donation without a pending id; migration while pending.Config,Root,RootHistory,Note,Nullifier,Liability,Reconcile,PendingSettlement;UpdateConfigauth; token add/remove auth; router rotation while pending rejected;PauseDepositsauth and effect; unknown message/version rejected.Test plan: attacks, hacks and abuse
0xffsignatures, wrong key type, public key not 32 bytes, digest length tricks, signature malleability, and a note whose commitment is recomputed with a different blinding. No path may accept a signature from any key other than the note's.MsgMigrateContract(code-id drift must fail); a token that re-entersreceive; a token whose transfer returns without transferring; decimals >18 or 0; a token that burns on transfer; community-taxSendFromallowance weirdness. No deposit may inflate liability above the actual credit.Reconcile; never silently mint a note.UpdateConfig/pause/router rotation; governance attempts to add a token that is not pinned/whitelisted; adding the pool to a token's exemption map (out of contract, but test the token side does not let the pool evade tax); wasm migration with malformed/old state; a rogue token address that self-reports an allowed code id.Verification criteria
make verify-issue-<N>runscargo fmt --check,cargo clippy -D warnings, unit + multitest tests for the new crate, schema export check, the workspace build, and the documentation cross-link check.cw20-mintableanalogue, the realcommunity-tax-tokencrate (including tax >0 andSendFromextra-debit) and a bridge-debt-token analogue; the fee-on-transfer/ALPHA mutant is rejected.VERIFY_ISSUE_<N>_CHAIN=1): store + instantiate the optimized pool, deposit viacw20-mintable, withdraw to a fresh address, deposit viacommunity-tax-token, verify the tax affects the note and the pool balance matchesReconcile. Capture transaction receipts without any personal or wallet data.docs/qa/issue-<N>/README.md, including ed25519 verification and a comparison to the retail envelope; a failure to stay within the envelope is reported as FAIL, not skipped.docs/shielded-pool.md,docs/security-model.md,docs/security-posture.md,docs/contracts-security-audit.md,docs/runbooks/wasm-admin-migration.mdand the new agent skill are updated and cross-linked.docs/qa/issue-<N>/README.mdrecords the agent checklist, explicit skip policy and evidence. Unavailable live/device checks may be explicit SKIP with overall PASS WITH SKIPS; executed failures remain FAIL.Out of scope / follow-ups