feat(frontend): shielded balances, private swap, note vault backup and unshield UX #1586

Open
opened 2026-10-29 00:34:21 +00:00 by PlasticDigits · 0 comments
Owner

Problem and scope

Give users a complete, accessible, privacy-honest client for the shielded pool (#1583) and private swaps (#1584): shield (deposit), shielded balance and note management, private swap, unshield, note backup and restore. The client must never send the user's wallet address, note key or note data to the indexer, must keep note keys out of plaintext storage, and must make the limits of the privacy model explicit so users do not mistake pooled notes for an anonymity system.

This issue covers:

  • a new shielded area in the dApp with shield, unshield, private swap and note list;
  • an encrypted local note vault (per-deposit keys), backup/export/import and restore-by-scan;
  • quote, risk, tax and fee presentation for shielded flows without reusing wallet-attributed quote paths;
  • transaction construction, signing and optional relayer submission with strict binding;
  • accessibility, mobile/WalletConnect and failure/recovery behaviour;
  • removal of shielded activity from analytics, URLs, logs and third-party requests.

It does not implement the contracts (#1583, #1584), the indexer (#1585) or the security/abuse program (#1587). It consumes their interfaces as specified and must not invent a fallback that weakens them.

Current codebase and investigation

Reviewed checkout: 38c154958; frontend is Vite + React under frontend-dapp/.

  • frontend-dapp/src/pages/SwapPage.tsx (and TradeMarketOrderPanel.tsx) implement the ordinary swap: quote → review → sign, with the connected wallet sent as trader to GET /api/v1/route/solve (src/services/indexer/client.ts lines ~715–760), LOCAL_QUOTE_SIGNING_WINDOW_MS = 30 minutes (src/utils/localQuoteWindow.ts), route display, L9 max spread, positive post-hook min_return, final minimum receive, and the shared risk notices (#1500/#1560).
  • Wallet and transaction plumbing: src/services/terraclassic/wallet.ts, terraBroadcast.ts, terraWalletSignLock.ts, terraWalletSignTxRaw.ts, terraMsgDeadline.ts, terraGas.ts, terraGasRetailInventory.ts; wallet UI in src/components/wallet/; store in src/stores/dex.ts; WalletConnect mobile pairing per skills/AGENTS_FRONTEND_WALLETCONNECT_MOBILE.md.
  • Identity and history surfaces that must not be reused for shielded flows: /portfolio (PortfolioPage.tsx), /trader/:address (TraderPage.tsx), /charts (ChartsPage.tsx), GET /api/v1/traders/... and CSV helpers in src/services/indexer/client.ts (lines ~476–557), and /api/v1/compliance/blacklist-check?wallet=.
  • Security/UX constraints already in force: accessibility policy in docs/design-system.md#accessibility-policy, skills AGENTS_FRONTEND_A11Y_CI.md, AGENTS_FRONTEND_A11Y_FOCUS.md, AGENTS_FRONTEND_COPY_COGNITIVE_LOAD.md; production VITE_DEV_MODE guard (#695); CSP builder frontend-dapp/viteCsp.ts; lazy-chunk recovery (#706); legal clickwrap/footer; Open Graph allowlist (#578); offline swap budget (#1480); local quote window (30 min) and persistent, textual errors.
  • There is no shielded page, route, vault, note store, ed25519 signing, note scanning, relayer client, or privacy notice. No client-side crypto beyond wallet/WebCrypto primitives is present; ed25519 signing must be added with a reviewed dependency (e.g. @noble/ed25519) or WebCrypto where available.
  • The dApp is served with a strict CSP (viteCsp.ts) and connect-src limited to the configured LCD/RPC/indexer/WalletConnect hosts. New endpoints must be added to that list; do not broaden it to https:.
  • Local QA: make dev (Node 24), Playwright, Simulated Wallet, Keplr/LocalTerra (docs/localterra-sdk53.md, skills/AGENTS_E2E_STRICT_CHAIN.md), make verify-issue-<N> conventions and docs/qa/issue-<N>/README.md.

Why a new implementation is needed

The existing swap UX is built around a connected wallet: the wallet address is sent with the quote, the pair records it, the indexer attributes volume/positions, and the wallet appears as the trader. Re-pointing that flow at the pool without changes would leak the wallet in the quote request, the preflight, the analytics and the history views, defeating the purpose of shielded balances.

Notes are also a new custody model for this dApp: the only secret is the note key. A plaintext note list, a browser password manager, or a lost backup means irreversible loss. Users need an explicit, accessible backup/restore flow, a clear warning that no support or contract admin can recover notes, and a UI that never silently reuses a key across deposits.

Finally, a "shielded" label invites overclaiming. The client must present what is actually hidden (the DEX's attribution of the trade) and what is not (amounts, deposit tx, note graph, chain analysis), with no anonymity, mixer or "untraceable" wording.

Relevant files

  • New: frontend-dapp/src/pages/ShieldedPage.tsx (+ tests), components/shielded/* (vault gate, shield form, unshield form, private swap panel, note list, backup/restore, privacy notice), src/services/shielded/{vault,notes,pool,swap,relayer}.ts, src/utils/shielded/* (note encoding, digest display, amount/decimals, status), src/hooks/useShielded*.
  • Routing/navigation: src/App.tsx (or the router entry), header/footer links, SwapPage/PortfolioPage entry points.
  • Indexer client: src/services/indexer/client.ts (new shielded note/quote helpers; no wallet param), src/services/indexer/* parsers.
  • Transactions: src/services/terraclassic/* (CW20 Send builder, spend broadcast, fee/gas, deadline, sign lock), viteCsp.ts, vite.config.ts, .env documentation.
  • Docs: docs/shielded-pool.md (privacy claims), docs/frontend.md, docs/design-system.md, docs/qa/issue-<N>/README.md, skills/AGENTS_FRONTEND_SHIELDED.md.
  • Tests: Vitest units/component tests and Playwright specs in frontend-dapp/; existing wallet/swap test utilities.
  1. Route and entry points. Add /shielded (and a clear link from Swap and Portfolio). The page has three primary actions — Shield, Private swap, Unshield — plus a shielded balance/notes list. Do not add a wizard, a second navigation system, or permanent explanatory walls; follow the existing compact design system and copy rules.

  2. Vault and keys. Generate a fresh note key pair per deposit (ed25519) in the browser; store only the encrypted vault in IndexedDB/localStorage: {version, kdf: PBKDF2-SHA256 (>= 600k iterations, random salt), cipher: AES-GCM (random IV), ciphertext}. The vault contains note keys and note metadata but no wallet address, no seed phrase, no note plaintext on disk outside the ciphertext. Require a passphrase to unlock; lock on tab hide/idle with a generous timeout (never a short reaction window); zero sensitive buffers where feasible. Provide Export encrypted backup and Import; the backup file is encrypted with the same passphrase and carries a version and pool/chain id. There is no server-side recovery, no email reset, no support override; show that before the first deposit and require an explicit acknowledgement. Do not derive the note key from a wallet signature (Ledger/WalletConnect support is inconsistent and it is a phishing-shaped prompt); do not use the wallet key.

  3. Deposit (shield). Build a CW20 Send { contract: pool, amount, msg: { shield_note: { owner_pubkey, blinding } } } from the connected wallet. Use a fresh key and a fresh 32-byte blinding. Preview the exact amount, the token contract address, the pool address, any transfer tax the token will charge (the note is credited post-tax), the caps and the deposit delay. The wallet address is necessarily visible in this transaction; say so in the notice. Do not request a tier discount, do not call per-wallet indexer endpoints, and do not add the wallet to quote requests.

  4. Note status and scanning. After deposit, show pending until the note event is indexed/observed, then available. On import/restore, scan the indexer's range-based shielded note endpoint (#1585) from the deployment leaf, filter locally by the vault's public keys, and verify the commitment locally against the returned fields; never trust an indexer "balance". Reconcile against a direct pool Note/Liability read only where the existing read policy allows it. Handle reorg/re-ingest, duplicate leafs, unknown note versions and notes inserted while offline.

  5. Private swap. Reuse the ordinary quote and risk components but request the quote with the pool as trader (or no trader) and never the connected wallet. Show the reviewed route, the input notes, the expected output note, change, sell/buy/transfer tax, the pair fee, the relayer fee (if any) and the deadline. Build the signed spend digest exactly as #1584 defines it, display a short human-readable summary of what is being signed (token, amount, output, destination for unshield, fee, deadline) and sign with the note key, not the wallet. If the user broadcasts themselves, warn that their wallet appears as the fee payer and the calldata contains the note opening; prefer the relayer for users who need submission privacy. Keep the 30-minute reviewed-quote window and the existing L9/floors; do not introduce a shorter confirmation timer.

  6. Unshield. Sign a spend with destination, amount, fee and deadline bound. Display the destination, fee, the arrival amount and the fact that withdrawing to an address already linked to the deposit source reduces privacy. If a relayer is used, show its fee and that it sees the request; do not auto-select a relayer without consent. Provide a self-broadcast path for users with a funded fresh address and an explicit explanation of the trade-off.

  7. Relayer client. A relayer request contains the fully formed pool message (signed spend) and the user's chosen fee; the relayer may only attach the outer transaction fee/gas and broadcast. The client must verify that the returned/echoed calldata matches what it signed (operations, destination, fee, deadline, nullifier) before showing success, and must handle: refusal, timeout, nonce/gas errors, ambiguous broadcast, duplicate submit and retry. A relayer must never receive the vault passphrase or any other note keys. If no relayer is available, fail closed with a clear self-broadcast option, not a silent fallback that links the wallet.

  8. No leakage in the client. On shielded routes: no analytics/product events with wallet, note key, amount or route (aggregate-only, if any; reference the #1202 privacy-reviewed scope and do not add new identifiers); no wallet address in URLs, Referer, query strings, localStorage keys, error reports or logs; no per-wallet indexer endpoints (/traders/..., blacklist-check?wallet=, tier health) during shielded flows; no third-party scripts, fonts, images or prefetch on the page; CSP connect-src extended only with the exact shielded endpoint(s). Do not cache note payloads in a service worker; clear them on lock. Disable Open Graph sharing for note/destination data.

  9. Privacy notice and copy. A short, persistent, accessible notice states: the deposit transaction is public and links the source address to the shield key; the DEX's own tape/indexer will not attribute the trade to the wallet, but amounts and the note graph are public chain data; the pool is not an anonymity system or mixer; notes are bearer instruments and a lost key/backup is unrecoverable; using the same destination/deposit address or correlated amounts/timing weakens privacy. No "untraceable", "anonymous", "private money" or tax-evasion implications. Localize carefully if translations exist; keep it within the existing legal/risk surfaces.

  10. Accessibility and mobile. Follow docs/design-system.md#accessibility-policy and the A11Y skills: keyboard and screen-reader operation for all three flows; aria-live/role=status for pending/confirmed/failed states; persistent textual errors, never sound/colour only; no short reaction timers; the 30-minute reviewed window applies to the reviewed swap/unshield; 200% root text zoom, 320–430 px widths, both themes, reduced motion; focus management for the vault unlock, backup and relayer dialogs; WalletConnect same-device and extension flows with the existing pairing patterns; no QR-only path.

  11. Failure and recovery. Cover: vault forgotten/locked, corrupted backup, wrong passphrase, missing notes after restore, pending deposit never indexed, note already spent elsewhere, stale quote/expired deadline, pool paused deposits, pair paused, token frozen/blacklisted, launch-guard rejection, insufficient gas for self-broadcast, relayer refusal, reverted transaction, ambiguous broadcast and duplicate submit. Every state must be text, persistent, actionable, and must not suggest retrying a signed spend that could double-spend (nullifier prevents it; explain the outcome instead).

Constraints and guardrails

  • No new wallet attribution: shielded quote requests, preflight, indexer calls and analytics must not contain the connected wallet, sender, tier or blacklist wallet. Do not reuse getRouteSolve unchanged if it would attach trader; add a shielded-specific call with an explicit contract test.
  • Custody: never store note plaintext/keys in plaintext, never send them to a server, never log them, never derive them from a wallet signature, and never reuse a note key across deposits. The vault must be encrypted and exportable; the warning about unrecoverable loss is mandatory before the first deposit.
  • Signing: the wallet signs deposits only; the note key signs spends; no blind transaction signing, no wallet-signed pool spend (the wallet key must not be the note key), no signature over an unparsed blob. Display the fields that are cryptographically bound.
  • Economics: base fee, community-tax transfer/sell/buy tax and treasury commission are displayed and preserved; no fee-tier discount is claimed; no bypass of L9, positive min_return, final minimum receive, deadline, 30% Expert or ≥99% non-waivable guard; no hidden "retry with more slippage".
  • Privacy honesty: the notice and docs must match docs/shielded-pool.md; no anonymity/mixer/tax-evasion language; no claims that the DEX cannot see public chain data.
  • Dependencies and CSP: prefer WebCrypto; if @noble/ed25519 (or equivalent) is added, pin the version, review the licence/supply chain (docs/supply-chain-security.md), and keep it out of the main bundle until the shielded route loads. Do not weaken the CSP or add third-party origins.
  • No dev leakage: production build must reject dev mnemonic/dev mode on shielded routes too (#695); no Simulated Wallet UI on production; no test keys or fixtures with real funds.
  • Compatibility: ordinary Swap/Trade/Pool/Portfolio flows, the 30-minute reviewed local quote window, existing risk notices and the accessibility behaviours must remain unchanged.
  • Backend contract: use the final #1583/#1584 event/message shapes; if they differ, adapt the client and raise the mismatch, do not add a client-side workaround that skips contract checks (e.g. do not compute commitments differently from the contract).

Acceptance criteria

  • AC1: /shielded supports shield, private swap and unshield end-to-end on LocalTerra with cw20-mintable and a community-tax-token; the pool sees no user wallet in swap/unshield calldata, the output and change notes appear in the vault, and the user's wallet is not sent to any shielded indexer request.
  • AC2: A fresh ed25519 key per deposit; the encrypted vault persists across reloads; export/import round-trips on a second browser profile; restore-by-scan finds the deposit and any change notes; a wrong passphrase/corrupted backup fails closed with a clear message.
  • AC3: The first deposit is blocked until the user acknowledges the unrecoverable-loss and privacy-limit notices; the notices match docs/shielded-pool.md and contain no anonymity claim.
  • AC4: Private swap and unshield sign exactly the #1584/#1583 digest, show token/amount/output/destination/fee/deadline, and reject a relayer response that alters any bound field; the wallet is never the note-key signer.
  • AC5: Community-tax transfer tax on deposit, sell/buy tax on swap and the base pair fee are previewed and match the settled amounts; no fee-discount claim is made; L9/floors/deadline and the 30-minute reviewed window are preserved.
  • AC6: Accessible by keyboard and screen reader, with aria-live states, persistent text errors, no short reaction timers, 200% zoom, 320–430 px, both themes and reduced motion; the vault, backup and relayer dialogs manage focus and are dismissible.
  • AC7: No shielded wallet address, note key, opening, amount or route appears in analytics, URLs, Referer, localStorage keys, console/error reports, CSP reports or third-party requests; a request-capture test proves it.
  • AC8: Failure and recovery states are complete and non-destructive: pending deposit, missing indexer note, already-spent note, stale quote, expired deadline, paused pair/pool, frozen/blacklisted token, launch-guard rejection, relayer refusal/timeout/ambiguous broadcast, duplicate submit.
  • AC9: Mobile/WalletConnect and extension flows both work; the CSP contains only the exact shielded endpoint(s); no third-party scripts run on the route; the production build has no dev-mode/mnemonic leakage.
  • AC10: docs/frontend.md, docs/shielded-pool.md (client section), docs/design-system.md (accessibility/privacy note), docs/qa/issue-<N>/README.md and skills/AGENTS_FRONTEND_SHIELDED.md are updated; make verify-issue-<N> exists.

Test plan: functional paths

Path Required checks
Vault Create, unlock, lock on idle/hide, wrong passphrase, re-import, corrupted/truncated/tampered backup, version mismatch, key rotation, many notes, export/import across browsers, no plaintext in storage inspection.
Shield Each allowlisted token (6/9/12/18 dp), min/max/cap, transfer-tax token, paused deposits, delay/confirmation, pending→available, duplicate submit, wallet rejection, tx failure; the key/blinding are fresh per deposit.
Notes List/sort/filter without addresses, spendability, change notes, expired/pending, unindexed note, unknown version, note already spent, restore-by-scan from a leaf range, partial pages, empty result.
Private swap Direct, 2-hop, 3-hop, 4-hop; 1–4 input notes; output/change; tax and fee previews; quote refresh; tolerance/Expert; 30-minute window; min output; deadline; pool/pair paused; frozen/blacklisted token; launch guards; relayer and self-broadcast.
Unshield Full/partial, fee 0/max, destination fresh/reused/blacklisted, self-broadcast, relayer, deadline, pending→confirmed, failed tx, duplicate submit.
Relayer Success, refusal, timeout, malformed/duplicate response, altered destination/fee/amount/route, ambiguous broadcast, retry; assert no bound field can be changed and no double submit.
Wallet/mobile Keplr, WalletConnect same-device, simulated wallet (dev only), network mismatch, chain switch, account switch mid-flow, locked extension, rejected signature; gas/fee display.
A11y Keyboard-only all flows, screen-reader announcements, focus order/restore, dialog dismissal, 200% zoom, 320/390/430 widths, dark/light, reduced motion, long errors, no colour-only state.
Privacy Request capture (no wallet/key/amount in shielded requests), URL/history, Referer, localStorage/IndexedDB inspection, console/network logs, CSP reports, analytics absence, third-party resource absence, Open Graph/sharing disabled.
Build/deploy Production build with CSP, no VITE_DEV_MODE, no dev mnemonic, lazy-loaded shielded chunk, stale-chunk recovery, offline behaviour, no service-worker note cache.

Test plan: attacks, hacks and abuse

  • XSS / note theft: inject HTML/JS via token metadata, notes, relayer responses, indexer errors, URL params or error messages; assert escaping and no vault/key access. A compromised page must not be able to exfiltrate note keys without the user unlocking and signing.
  • Malicious indexer/relayer: forged notes (wrong commitment/leaf/token/amount), replayed pages, out-of-order pages, fake pool address, fake event payload, and a relayer that changes destination/fee/amount/route or withholds the change. The client must verify commitments, bindings and the signed fields; invalid data must not become a balance or a signing prompt.
  • Phishing-shaped prompts: substituting a note pubkey, destination, fee or route at the last step; a fake "restore" flow asking for the passphrase in chat; a malicious backup file; a look-alike token contract; a pool address copied from a hostile source. Show contract addresses, never accept a pubkey from the indexer for a deposit, and verify the backup format/version.
  • Key/backup abuse: brute-force the vault, weak passphrase guidance, passphrase in URL/clipboard, plaintext backups, cloud-sync of a plaintext file, shared device, unattended unlocked vault, screenshot of a key, browser password manager. Enforce KDF/cipher parameters, lock/erase controls and warnings.
  • Replay / double spend: resubmit a signed spend, replay a quote after a route change, replay a vault import across pools/chains, submit the same note via swap and unshield, or race two tabs. The nullifier/contract must reject; the UI must not imply a second success or auto-resend.
  • Privacy attacks: correlate the deposit wallet with the shielded activity through the client (analytics, quote trader, blacklist-check, tier checks, Referer, prefetch, error reports, push notifications, service worker, Open Graph), correlate amounts/timing, reuse a destination, or query note ranges that identify a user. Prove no client-generated link and provide the honest notice.
  • Amount/decimal abuse: 6-vs-18 decimals, huge/negative/zero/NaN/Infinity inputs, scientific notation, locale separators, dust, rounding, min_output at 1 raw unit, and a token whose decimals change. Validate with integer raw units and display human scale per #1259.
  • Build/supply chain: a compromised dependency, a dev-only key shipped in production, a CSP weakened for a new host, a stale lazy chunk serving old code, and a service worker caching note data. Verify pinned deps, production guards, exact connect-src, chunk recovery and no note caching.
  • Device/network: network switch mid-sign, chain mismatch, wallet account switch, tab duplication, lost connectivity, timeout, clock skew (deadline), and a hostile RPC returning false success. Reconcile against the actual tx result, not a client-side assumption.
  • Social/abuse: "support can recover your note" phishing, guaranteed-return or tax-evasion copy, and requests to share a backup key. The UI must not provide such a channel or copy; report abuse paths are separate.

Verification criteria

  • make verify-issue-<N> runs frontend types, lint, Vitest (unit/component), production build, CSP/build guards and doc cross-links; Playwright specs cover the three flows against a stubbed indexer and, with the chain flag, against LocalTerra.
  • A LocalTerra E2E receipt covers shield → private swap → unshield for cw20-mintable and a community-tax token, plus restore-from-backup and relayer failure. Record hashes and assertions in docs/qa/issue-<N>/README.md without wallet-owner identity or personal data.
  • A request-capture and storage-inspection test proves no shielded wallet/key/opening/amount/route left the client in a request, URL, log or persistent store; a11y checks (keyboard, screen reader, zoom, themes) pass on the touched flows.
  • The production build is verified with the CSP, no dev mode/mnemonic, lazy chunk and stale-chunk behaviour; a mobile/WalletConnect smoke test is recorded.
  • docs/qa/issue-<N>/README.md records executed checks and explicit skips (e.g. physical device, funded mainnet) with scope. Executed failures remain FAIL; unavailable checks may be explicit SKIP with PASS WITH SKIPS without claiming deployed acceptance.
  • No conversation, personal data, reporter attribution, wallet-owner identity, note key or mnemonic appears in issue text, docs, fixtures, logs or receipts.

Out of scope / follow-ups

  • Contract/note layer (#1583), private swap execution (#1584), indexer/API (#1585).
  • Threat model, abuse/compliance policy, relayer operations, monitoring and staged rollout (#1587).
  • ZK/encrypted notes, P2P transfers, cross-pool swaps, fiat on-ramp, tax handling beyond display, and any anonymity claim: not in phase 1.
## Problem and scope Give users a complete, accessible, privacy-honest client for the shielded pool (#1583) and private swaps (#1584): shield (deposit), shielded balance and note management, private swap, unshield, note backup and restore. The client must never send the user's wallet address, note key or note data to the indexer, must keep note keys out of plaintext storage, and must make the limits of the privacy model explicit so users do not mistake pooled notes for an anonymity system. This issue covers: - a new shielded area in the dApp with shield, unshield, private swap and note list; - an encrypted local note vault (per-deposit keys), backup/export/import and restore-by-scan; - quote, risk, tax and fee presentation for shielded flows without reusing wallet-attributed quote paths; - transaction construction, signing and optional relayer submission with strict binding; - accessibility, mobile/WalletConnect and failure/recovery behaviour; - removal of shielded activity from analytics, URLs, logs and third-party requests. It does not implement the contracts (#1583, #1584), the indexer (#1585) or the security/abuse program (#1587). It consumes their interfaces as specified and must not invent a fallback that weakens them. ## Current codebase and investigation Reviewed checkout: `38c154958`; frontend is Vite + React under `frontend-dapp/`. - `frontend-dapp/src/pages/SwapPage.tsx` (and `TradeMarketOrderPanel.tsx`) implement the ordinary swap: quote → review → sign, with the connected wallet sent as `trader` to `GET /api/v1/route/solve` (`src/services/indexer/client.ts` lines ~715–760), `LOCAL_QUOTE_SIGNING_WINDOW_MS` = **30 minutes** (`src/utils/localQuoteWindow.ts`), route display, L9 max spread, positive post-hook `min_return`, final minimum receive, and the shared risk notices (#1500/#1560). - Wallet and transaction plumbing: `src/services/terraclassic/wallet.ts`, `terraBroadcast.ts`, `terraWalletSignLock.ts`, `terraWalletSignTxRaw.ts`, `terraMsgDeadline.ts`, `terraGas.ts`, `terraGasRetailInventory.ts`; wallet UI in `src/components/wallet/`; store in `src/stores/dex.ts`; WalletConnect mobile pairing per `skills/AGENTS_FRONTEND_WALLETCONNECT_MOBILE.md`. - Identity and history surfaces that must not be reused for shielded flows: `/portfolio` (`PortfolioPage.tsx`), `/trader/:address` (`TraderPage.tsx`), `/charts` (`ChartsPage.tsx`), `GET /api/v1/traders/...` and CSV helpers in `src/services/indexer/client.ts` (lines ~476–557), and `/api/v1/compliance/blacklist-check?wallet=`. - Security/UX constraints already in force: accessibility policy in `docs/design-system.md#accessibility-policy`, skills `AGENTS_FRONTEND_A11Y_CI.md`, `AGENTS_FRONTEND_A11Y_FOCUS.md`, `AGENTS_FRONTEND_COPY_COGNITIVE_LOAD.md`; production `VITE_DEV_MODE` guard (#695); CSP builder `frontend-dapp/viteCsp.ts`; lazy-chunk recovery (#706); legal clickwrap/footer; Open Graph allowlist (#578); offline swap budget (#1480); local quote window (30 min) and persistent, textual errors. - There is **no** `shielded` page, route, vault, note store, ed25519 signing, note scanning, relayer client, or privacy notice. No client-side crypto beyond wallet/WebCrypto primitives is present; `ed25519` signing must be added with a reviewed dependency (e.g. `@noble/ed25519`) or WebCrypto where available. - The dApp is served with a strict CSP (`viteCsp.ts`) and `connect-src` limited to the configured LCD/RPC/indexer/WalletConnect hosts. New endpoints must be added to that list; do not broaden it to `https:`. - Local QA: `make dev` (Node 24), Playwright, Simulated Wallet, Keplr/LocalTerra (`docs/localterra-sdk53.md`, `skills/AGENTS_E2E_STRICT_CHAIN.md`), `make verify-issue-<N>` conventions and `docs/qa/issue-<N>/README.md`. ## Why a new implementation is needed The existing swap UX is built around a connected wallet: the wallet address is sent with the quote, the pair records it, the indexer attributes volume/positions, and the wallet appears as the trader. Re-pointing that flow at the pool without changes would leak the wallet in the quote request, the preflight, the analytics and the history views, defeating the purpose of shielded balances. Notes are also a new custody model for this dApp: the only secret is the note key. A plaintext note list, a browser password manager, or a lost backup means irreversible loss. Users need an explicit, accessible backup/restore flow, a clear warning that no support or contract admin can recover notes, and a UI that never silently reuses a key across deposits. Finally, a "shielded" label invites overclaiming. The client must present what is actually hidden (the DEX's attribution of the trade) and what is not (amounts, deposit tx, note graph, chain analysis), with no anonymity, mixer or "untraceable" wording. ## Relevant files - New: `frontend-dapp/src/pages/ShieldedPage.tsx` (+ tests), `components/shielded/*` (vault gate, shield form, unshield form, private swap panel, note list, backup/restore, privacy notice), `src/services/shielded/{vault,notes,pool,swap,relayer}.ts`, `src/utils/shielded/*` (note encoding, digest display, amount/decimals, status), `src/hooks/useShielded*`. - Routing/navigation: `src/App.tsx` (or the router entry), header/footer links, `SwapPage`/`PortfolioPage` entry points. - Indexer client: `src/services/indexer/client.ts` (new shielded note/quote helpers; **no** wallet param), `src/services/indexer/*` parsers. - Transactions: `src/services/terraclassic/*` (CW20 `Send` builder, spend broadcast, fee/gas, deadline, sign lock), `viteCsp.ts`, `vite.config.ts`, `.env` documentation. - Docs: `docs/shielded-pool.md` (privacy claims), `docs/frontend.md`, `docs/design-system.md`, `docs/qa/issue-<N>/README.md`, `skills/AGENTS_FRONTEND_SHIELDED.md`. - Tests: Vitest units/component tests and Playwright specs in `frontend-dapp/`; existing wallet/swap test utilities. ## Recommended direction 1. **Route and entry points.** Add `/shielded` (and a clear link from Swap and Portfolio). The page has three primary actions — **Shield**, **Private swap**, **Unshield** — plus a shielded balance/notes list. Do not add a wizard, a second navigation system, or permanent explanatory walls; follow the existing compact design system and copy rules. 2. **Vault and keys.** Generate a fresh note key pair **per deposit** (ed25519) in the browser; store only the encrypted vault in IndexedDB/localStorage: `{version, kdf: PBKDF2-SHA256 (>= 600k iterations, random salt), cipher: AES-GCM (random IV), ciphertext}`. The vault contains note keys and note metadata but **no wallet address, no seed phrase, no note plaintext on disk outside the ciphertext**. Require a passphrase to unlock; lock on tab hide/idle with a generous timeout (never a short reaction window); zero sensitive buffers where feasible. Provide **Export encrypted backup** and **Import**; the backup file is encrypted with the same passphrase and carries a version and pool/chain id. There is no server-side recovery, no email reset, no support override; show that before the first deposit and require an explicit acknowledgement. Do not derive the note key from a wallet signature (Ledger/WalletConnect support is inconsistent and it is a phishing-shaped prompt); do not use the wallet key. 3. **Deposit (shield).** Build a CW20 `Send { contract: pool, amount, msg: { shield_note: { owner_pubkey, blinding } } }` from the connected wallet. Use a fresh key and a fresh 32-byte blinding. Preview the exact amount, the token contract address, the pool address, any transfer tax the token will charge (the note is credited post-tax), the caps and the deposit delay. The wallet address is necessarily visible in this transaction; say so in the notice. Do not request a tier discount, do not call per-wallet indexer endpoints, and do not add the wallet to quote requests. 4. **Note status and scanning.** After deposit, show `pending` until the note event is indexed/observed, then `available`. On import/restore, scan the indexer's **range-based** shielded note endpoint (#1585) from the deployment leaf, filter locally by the vault's public keys, and verify the commitment locally against the returned fields; never trust an indexer "balance". Reconcile against a direct pool `Note`/`Liability` read only where the existing read policy allows it. Handle reorg/re-ingest, duplicate leafs, unknown note versions and notes inserted while offline. 5. **Private swap.** Reuse the ordinary quote and risk components but request the quote with **the pool as trader** (or no trader) and never the connected wallet. Show the reviewed route, the input notes, the expected output note, change, sell/buy/transfer tax, the pair fee, the relayer fee (if any) and the deadline. Build the signed spend digest exactly as #1584 defines it, display a short human-readable summary of what is being signed (token, amount, output, destination for unshield, fee, deadline) and sign with the note key, not the wallet. If the user broadcasts themselves, warn that their wallet appears as the fee payer and the calldata contains the note opening; prefer the relayer for users who need submission privacy. Keep the 30-minute reviewed-quote window and the existing L9/floors; do not introduce a shorter confirmation timer. 6. **Unshield.** Sign a spend with `destination`, amount, fee and deadline bound. Display the destination, fee, the arrival amount and the fact that withdrawing to an address already linked to the deposit source reduces privacy. If a relayer is used, show its fee and that it sees the request; do not auto-select a relayer without consent. Provide a self-broadcast path for users with a funded fresh address and an explicit explanation of the trade-off. 7. **Relayer client.** A relayer request contains the fully formed pool message (signed spend) and the user's chosen fee; the relayer may only attach the outer transaction fee/gas and broadcast. The client must verify that the returned/echoed calldata matches what it signed (operations, destination, fee, deadline, nullifier) before showing success, and must handle: refusal, timeout, nonce/gas errors, ambiguous broadcast, duplicate submit and retry. A relayer must never receive the vault passphrase or any other note keys. If no relayer is available, fail closed with a clear self-broadcast option, not a silent fallback that links the wallet. 8. **No leakage in the client.** On shielded routes: no analytics/product events with wallet, note key, amount or route (aggregate-only, if any; reference the #1202 privacy-reviewed scope and do not add new identifiers); no wallet address in URLs, `Referer`, query strings, `localStorage` keys, error reports or logs; no per-wallet indexer endpoints (`/traders/...`, `blacklist-check?wallet=`, tier health) during shielded flows; no third-party scripts, fonts, images or prefetch on the page; CSP `connect-src` extended only with the exact shielded endpoint(s). Do not cache note payloads in a service worker; clear them on lock. Disable Open Graph sharing for note/destination data. 9. **Privacy notice and copy.** A short, persistent, accessible notice states: the deposit transaction is public and links the source address to the shield key; the DEX's own tape/indexer will not attribute the trade to the wallet, but amounts and the note graph are public chain data; the pool is not an anonymity system or mixer; notes are bearer instruments and a lost key/backup is unrecoverable; using the same destination/deposit address or correlated amounts/timing weakens privacy. No "untraceable", "anonymous", "private money" or tax-evasion implications. Localize carefully if translations exist; keep it within the existing legal/risk surfaces. 10. **Accessibility and mobile.** Follow `docs/design-system.md#accessibility-policy` and the A11Y skills: keyboard and screen-reader operation for all three flows; `aria-live`/`role=status` for pending/confirmed/failed states; persistent textual errors, never sound/colour only; no short reaction timers; the 30-minute reviewed window applies to the reviewed swap/unshield; 200% root text zoom, 320–430 px widths, both themes, reduced motion; focus management for the vault unlock, backup and relayer dialogs; WalletConnect same-device and extension flows with the existing pairing patterns; no QR-only path. 11. **Failure and recovery.** Cover: vault forgotten/locked, corrupted backup, wrong passphrase, missing notes after restore, pending deposit never indexed, note already spent elsewhere, stale quote/expired deadline, pool paused deposits, pair paused, token frozen/blacklisted, launch-guard rejection, insufficient gas for self-broadcast, relayer refusal, reverted transaction, ambiguous broadcast and duplicate submit. Every state must be text, persistent, actionable, and must not suggest retrying a signed spend that could double-spend (nullifier prevents it; explain the outcome instead). ## Constraints and guardrails - **No new wallet attribution:** shielded quote requests, preflight, indexer calls and analytics must not contain the connected wallet, `sender`, tier or blacklist wallet. Do not reuse `getRouteSolve` unchanged if it would attach `trader`; add a shielded-specific call with an explicit contract test. - **Custody:** never store note plaintext/keys in plaintext, never send them to a server, never log them, never derive them from a wallet signature, and never reuse a note key across deposits. The vault must be encrypted and exportable; the warning about unrecoverable loss is mandatory before the first deposit. - **Signing:** the wallet signs deposits only; the note key signs spends; no blind transaction signing, no wallet-signed pool spend (the wallet key must not be the note key), no signature over an unparsed blob. Display the fields that are cryptographically bound. - **Economics:** base fee, community-tax transfer/sell/buy tax and treasury commission are displayed and preserved; no fee-tier discount is claimed; no bypass of L9, positive `min_return`, final minimum receive, deadline, 30% Expert or ≥99% non-waivable guard; no hidden "retry with more slippage". - **Privacy honesty:** the notice and docs must match `docs/shielded-pool.md`; no anonymity/mixer/tax-evasion language; no claims that the DEX cannot see public chain data. - **Dependencies and CSP:** prefer WebCrypto; if `@noble/ed25519` (or equivalent) is added, pin the version, review the licence/supply chain (`docs/supply-chain-security.md`), and keep it out of the main bundle until the shielded route loads. Do not weaken the CSP or add third-party origins. - **No dev leakage:** production build must reject dev mnemonic/dev mode on shielded routes too (#695); no Simulated Wallet UI on production; no test keys or fixtures with real funds. - **Compatibility:** ordinary Swap/Trade/Pool/Portfolio flows, the 30-minute reviewed local quote window, existing risk notices and the accessibility behaviours must remain unchanged. - **Backend contract:** use the final #1583/#1584 event/message shapes; if they differ, adapt the client and raise the mismatch, do not add a client-side workaround that skips contract checks (e.g. do not compute commitments differently from the contract). ## Acceptance criteria - [ ] AC1: `/shielded` supports shield, private swap and unshield end-to-end on LocalTerra with `cw20-mintable` and a community-tax-token; the pool sees no user wallet in swap/unshield calldata, the output and change notes appear in the vault, and the user's wallet is not sent to any shielded indexer request. - [ ] AC2: A fresh ed25519 key per deposit; the encrypted vault persists across reloads; export/import round-trips on a second browser profile; restore-by-scan finds the deposit and any change notes; a wrong passphrase/corrupted backup fails closed with a clear message. - [ ] AC3: The first deposit is blocked until the user acknowledges the unrecoverable-loss and privacy-limit notices; the notices match `docs/shielded-pool.md` and contain no anonymity claim. - [ ] AC4: Private swap and unshield sign exactly the #1584/#1583 digest, show token/amount/output/destination/fee/deadline, and reject a relayer response that alters any bound field; the wallet is never the note-key signer. - [ ] AC5: Community-tax transfer tax on deposit, sell/buy tax on swap and the base pair fee are previewed and match the settled amounts; no fee-discount claim is made; L9/floors/deadline and the 30-minute reviewed window are preserved. - [ ] AC6: Accessible by keyboard and screen reader, with `aria-live` states, persistent text errors, no short reaction timers, 200% zoom, 320–430 px, both themes and reduced motion; the vault, backup and relayer dialogs manage focus and are dismissible. - [ ] AC7: No shielded wallet address, note key, opening, amount or route appears in analytics, URLs, `Referer`, localStorage keys, console/error reports, CSP reports or third-party requests; a request-capture test proves it. - [ ] AC8: Failure and recovery states are complete and non-destructive: pending deposit, missing indexer note, already-spent note, stale quote, expired deadline, paused pair/pool, frozen/blacklisted token, launch-guard rejection, relayer refusal/timeout/ambiguous broadcast, duplicate submit. - [ ] AC9: Mobile/WalletConnect and extension flows both work; the CSP contains only the exact shielded endpoint(s); no third-party scripts run on the route; the production build has no dev-mode/mnemonic leakage. - [ ] AC10: `docs/frontend.md`, `docs/shielded-pool.md` (client section), `docs/design-system.md` (accessibility/privacy note), `docs/qa/issue-<N>/README.md` and `skills/AGENTS_FRONTEND_SHIELDED.md` are updated; `make verify-issue-<N>` exists. ## Test plan: functional paths | Path | Required checks | | --- | --- | | Vault | Create, unlock, lock on idle/hide, wrong passphrase, re-import, corrupted/truncated/tampered backup, version mismatch, key rotation, many notes, export/import across browsers, no plaintext in storage inspection. | | Shield | Each allowlisted token (6/9/12/18 dp), min/max/cap, transfer-tax token, paused deposits, delay/confirmation, pending→available, duplicate submit, wallet rejection, tx failure; the key/blinding are fresh per deposit. | | Notes | List/sort/filter without addresses, spendability, change notes, expired/pending, unindexed note, unknown version, note already spent, restore-by-scan from a leaf range, partial pages, empty result. | | Private swap | Direct, 2-hop, 3-hop, 4-hop; 1–4 input notes; output/change; tax and fee previews; quote refresh; tolerance/Expert; 30-minute window; min output; deadline; pool/pair paused; frozen/blacklisted token; launch guards; relayer and self-broadcast. | | Unshield | Full/partial, fee 0/max, destination fresh/reused/blacklisted, self-broadcast, relayer, deadline, pending→confirmed, failed tx, duplicate submit. | | Relayer | Success, refusal, timeout, malformed/duplicate response, altered destination/fee/amount/route, ambiguous broadcast, retry; assert no bound field can be changed and no double submit. | | Wallet/mobile | Keplr, WalletConnect same-device, simulated wallet (dev only), network mismatch, chain switch, account switch mid-flow, locked extension, rejected signature; gas/fee display. | | A11y | Keyboard-only all flows, screen-reader announcements, focus order/restore, dialog dismissal, 200% zoom, 320/390/430 widths, dark/light, reduced motion, long errors, no colour-only state. | | Privacy | Request capture (no wallet/key/amount in shielded requests), URL/history, `Referer`, localStorage/IndexedDB inspection, console/network logs, CSP reports, analytics absence, third-party resource absence, Open Graph/sharing disabled. | | Build/deploy | Production build with CSP, no `VITE_DEV_MODE`, no dev mnemonic, lazy-loaded shielded chunk, stale-chunk recovery, offline behaviour, no service-worker note cache. | ## Test plan: attacks, hacks and abuse - **XSS / note theft:** inject HTML/JS via token metadata, notes, relayer responses, indexer errors, URL params or error messages; assert escaping and no vault/key access. A compromised page must not be able to exfiltrate note keys without the user unlocking and signing. - **Malicious indexer/relayer:** forged notes (wrong commitment/leaf/token/amount), replayed pages, out-of-order pages, fake pool address, fake event payload, and a relayer that changes destination/fee/amount/route or withholds the change. The client must verify commitments, bindings and the signed fields; invalid data must not become a balance or a signing prompt. - **Phishing-shaped prompts:** substituting a note pubkey, destination, fee or route at the last step; a fake "restore" flow asking for the passphrase in chat; a malicious backup file; a look-alike token contract; a pool address copied from a hostile source. Show contract addresses, never accept a pubkey from the indexer for a deposit, and verify the backup format/version. - **Key/backup abuse:** brute-force the vault, weak passphrase guidance, passphrase in URL/clipboard, plaintext backups, cloud-sync of a plaintext file, shared device, unattended unlocked vault, screenshot of a key, browser password manager. Enforce KDF/cipher parameters, lock/erase controls and warnings. - **Replay / double spend:** resubmit a signed spend, replay a quote after a route change, replay a vault import across pools/chains, submit the same note via swap and unshield, or race two tabs. The nullifier/contract must reject; the UI must not imply a second success or auto-resend. - **Privacy attacks:** correlate the deposit wallet with the shielded activity through the client (analytics, quote `trader`, `blacklist-check`, tier checks, `Referer`, prefetch, error reports, push notifications, service worker, Open Graph), correlate amounts/timing, reuse a destination, or query note ranges that identify a user. Prove no client-generated link and provide the honest notice. - **Amount/decimal abuse:** 6-vs-18 decimals, huge/negative/zero/NaN/Infinity inputs, scientific notation, locale separators, dust, rounding, `min_output` at 1 raw unit, and a token whose decimals change. Validate with integer raw units and display human scale per #1259. - **Build/supply chain:** a compromised dependency, a dev-only key shipped in production, a CSP weakened for a new host, a stale lazy chunk serving old code, and a service worker caching note data. Verify pinned deps, production guards, exact `connect-src`, chunk recovery and no note caching. - **Device/network:** network switch mid-sign, chain mismatch, wallet account switch, tab duplication, lost connectivity, timeout, clock skew (deadline), and a hostile RPC returning false success. Reconcile against the actual tx result, not a client-side assumption. - **Social/abuse:** "support can recover your note" phishing, guaranteed-return or tax-evasion copy, and requests to share a backup key. The UI must not provide such a channel or copy; report abuse paths are separate. ## Verification criteria - [ ] `make verify-issue-<N>` runs frontend types, lint, Vitest (unit/component), production build, CSP/build guards and doc cross-links; Playwright specs cover the three flows against a stubbed indexer and, with the chain flag, against LocalTerra. - [ ] A LocalTerra E2E receipt covers shield → private swap → unshield for `cw20-mintable` and a community-tax token, plus restore-from-backup and relayer failure. Record hashes and assertions in `docs/qa/issue-<N>/README.md` without wallet-owner identity or personal data. - [ ] A request-capture and storage-inspection test proves no shielded wallet/key/opening/amount/route left the client in a request, URL, log or persistent store; a11y checks (keyboard, screen reader, zoom, themes) pass on the touched flows. - [ ] The production build is verified with the CSP, no dev mode/mnemonic, lazy chunk and stale-chunk behaviour; a mobile/WalletConnect smoke test is recorded. - [ ] `docs/qa/issue-<N>/README.md` records executed checks and explicit skips (e.g. physical device, funded mainnet) with scope. Executed failures remain FAIL; unavailable checks may be explicit SKIP with PASS WITH SKIPS without claiming deployed acceptance. - [ ] No conversation, personal data, reporter attribution, wallet-owner identity, note key or mnemonic appears in issue text, docs, fixtures, logs or receipts. ## Out of scope / follow-ups - Contract/note layer (#1583), private swap execution (#1584), indexer/API (#1585). - Threat model, abuse/compliance policy, relayer operations, monitoring and staged rollout (#1587). - ZK/encrypted notes, P2P transfers, cross-pool swaps, fiat on-ramp, tax handling beyond display, and any anonymity claim: 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#1586
No description provided.