feat(frontend): privacy-reviewed source-to-fee product events (Phase 0 S1) #1202

Open
opened 2026-09-04 03:50:07 +00:00 by PlasticDigits · 10 comments
Owner

Summary and status

Add the Phase 0 S1 first-party client funnel as one bundle: campaign capture, a working product-event opt-out, sanitized event delivery, transaction lifecycle instrumentation, and measured reconciliation coverage. Attribution is descriptive; the indexer remains the fee authority.

Investigated 2026-10-04 against main at 3f9310652ac83818749f5d32c4e32057b08817bc (also the remote main head). Not implemented; keep this issue open. The body consolidates the engineering report and subsequent decisions in the existing comments. Historical draft comments are background; this body is the implementation contract.

Privacy readiness remains on hold. The recorded S1 decision is opt-out required; it is no longer an unanswered decision and needs no replacement decision card. That decision alone does not release the remaining privacy gates. Legal #35 owns the dedicated Notice and footer links. On 2026-10-04, GET https://terms.cl8y.com/privacy returned HTTP 200 with title CL8Y Legal — Terms & Conditions, rather than an identifiable Privacy Notice. A 200, a completed decision card, or T&Cs acceptance is not evidence of the required Notice. Do not mark this issue ready or activate production collection until the gates below are verified.

Current codebase

  • frontend-dapp is a React 19/Vite 7 SPA with TanStack Query, Zustand, and cosmes wallets. main.tsx, App.tsx, package.json, and index.html contain no product-analytics initialization/SDK. There is no campaign/UTM capture, cl8y_intent persistence, S1 opt-out control, analytics endpoint configuration, or #1202 verifier in the checked-in code.
  • SwapPage.tsx and CreatePairPage.tsx replace search parameters with canonical swap/pair keys. Incoming UTMs disappear unless captured before route mount/canonicalization. /swap is an alias that redirects to /; capture must also precede that redirect.
  • useWallet.ts owns explicit connection, reconnect, simulated connection, and disconnect. Existing wallet session persistence and legal clickwrap are not product-event permission.
  • useTerraBroadcastMutation.ts wraps execution through terraBroadcastScope.ts. terraBroadcast.ts reports signing, broadcasting, confirming, and recovering. Split signing and atomic wallet paths differ; a broadcasting callback can occur before a hash exists. Poll/recovery checks the chain response code before returning a successful hash. Nested allowance/economic broadcasts can occur inside one mutation; generic mutation success is insufficient to classify every underlying action.
  • ShareLinkButton.tsx/sharePageLink.ts support Web Share, cancellation, clipboard fallback, and copy failure. Canonical shares drop campaigns; share payloads may contain a trader address or exact swap amount, so do not serialize their text/URL into analytics.
  • Production viteCsp.ts restricts connect-src to self plus configured chain/indexer, WalletConnect, and Legal origins. No analytics-specific destination exists. Development CSP is broader and cannot prove production privacy behavior.
  • protocol_fee_events contains chain-derived fee truth. There are currently seven FeeSource values: swap_amm, book_take, limit_place, wrap, unwrap, ust1_mint, ust1_redeem. #1269 widened uniqueness to (tx_hash, source, pair_id, ordinal) for pair rows and partial (tx_hash, source, ordinal) for NULL-pair rows. One tx can have multiple legitimate fee rows. /api/v1/protocol/fees and /fees/daily expose aggregates, not a client attribution or by-tx receipt service.

Why this implementation is needed

Current landing links cannot survive canonicalization into a joinable client success receipt. Fee aggregates alone cannot describe the acquisition funnel or campaign coverage, and existing wallet/broadcast state has no S1 event transport. Implementing isolated page beacons without opt-out, capture ordering, and confirmed transaction semantics would produce incomplete or misleading attribution.

The marketing S1 specification and operating-system event contract now exist. The earlier comment saying the instrumentation/exclusions files were missing is stale. They describe the campaign taxonomy and coverage target; they do not prove that client collection or a collector has shipped.

Duplicate/implementation check and bundle boundaries

Searches with fj included open and closed issues/PRs for source-to-fee, campaign_id, analytics, telemetry, product events, and opt-out. No second issue owning the S1 client bundle or matching implementation PR was found. Source inspection and repository history confirm the client behavior above is absent.

Related work Relationship; do not duplicate it here
#711 / #713 / #715 Existing query aliases, canonical URL sync, and sharing. Reuse and regression-test; they do not capture campaigns or emit S1 events.
#1209 / #1210 Pair-creation and community invoice fee ingestion. Keep separate; do not promise their fees are already indexed.
#1211 / #1213 Actor/cohort reporting and fee-ledger home. #1211 does not depend on releasing S1. No campaign fields on fee rows.
#1205 (closed) / #1206 (open) / #1204 Chain evidence export, anonymous digest, and HTTP documentation. These are not client acquisition events.
Legal #35 Canonical Notice at https://terms.cl8y.com/privacy and shared footer links. Depend on that work; do not author a second policy here.
Bridge #165 Bridge storage/idle WalletConnect/Coinbase behavior. Do not absorb it or treat S1 refusal as an instruction to disconnect functional wallets.

Keep campaign capture, S1 opt-out, schema/transport, lifecycle hooks, and their tests in this single issue. A marketing warehouse, attribution dashboard, collector deployment, new fee parsers, or wallet-person graph is outside this bundle. A functioning approved first-party receiver is an activation dependency, not a reason to add another service to the DEX indexer.

Constraints and guardrails

  1. Release gates: before readiness/production collection, record the published S1-compatible Notice/version, exact first-party destination, field classification including campaign+txhash linkability, retention/deletion behavior, functional opt-out evidence, and completed privacy/security review. Until then preserve the documented hold. No production S1 capture, persistent touches/IDs, outbound requests, or queued events while disabled. Use synthetic fixtures for preparatory verification.
  2. Opt-out is real: initialize refusal state before capture; offer an accessible control before any live product events. Refusal stops subsequent capture/delivery, cancels pending delivery where possible, clears S1 touches/IDs/queues, and survives reload/navigation/tabs. Preserve only the minimal refusal preference. Re-enabling never replays refused-period events. Storage failure/unknown preference must fail closed for S1 while trading continues. Withdrawal cannot retract an already accepted request; document receiver deletion handling honestly.
  3. First-party only in S1: no GA/PostHog/pixels or third-party S1 hops. The fixed HTTPS receiver is deployment configuration validated against an explicit allowlist; never query/referrer controlled, and never a browser-held secret. Block off-origin redirects and avoid transmitting cookies/full referrers. Do not broaden CSP to */https: for analytics.
  4. Minimize payloads: closed field schema; bucket amounts; omit exact amounts, fees, balances, wallet/user addresses, wallet-derived identifiers, signatures, signed bytes, memos, errors/raw logs, WC URIs, emails/social handles, full URLs/referrers, and share text. Route templates replace dynamic user address segments. Pair/token contract identities may be allowlisted economic metadata; distinguish them from user wallet addresses. A txhash is linkable public-chain data, not anonymity.
  5. Identity/persistence: use a random first-party session/pseudonymous key independent of a wallet. Avoid a persistent cross-session actor unless the reviewed schema requires it. Any wallet-derived keyed pseudonym belongs to separately reviewed first-party infrastructure; never place its key/salt in Vite, Git, or client code. Valid campaign touches expire within 30 days from collection, including invalid/future timestamps and corrupt storage; expire/delete on read/startup without silently extending TTL.
  6. Independent fee authority: client receipts/campaign tags are untrusted descriptive observations. Do not change FeeSource, fee schema/API, transaction economics, or exact-fee calculations. Reconcile privately/offline to existing chain/indexer records; retain multiple fee rows per transaction without multiplying them by duplicate client receipts/touchpoints. No public campaign→tx→wallet endpoint, causal ROI claim, reward, credit, or transaction authorization from client events.
  7. Trading remains available: bounded nonblocking analytics; finite event size/queue/retries/timeouts; no await of delivery on wallet, quote, sign, broadcast, confirmation, or share paths. Analytics exceptions never alter existing callback order, safety gates, or transaction outcome. Dev/LocalTerra/simulated wallets cannot reach a production sink.
  8. Reporting: exclusions are applied privately on the reporting side using the versioned wallet-exclusion method. Do not embed private wallet lists in the SPA. No Telegram/X↔wallet joins or outbound marketing actions. Canonical share URLs remain campaign-free.

Relevant files

Area Existing files to inspect/change
Earliest capture/router/UI frontend-dapp/src/main.tsx, src/App.tsx, src/components/common/Layout.tsx; S1 settings/control integrated with existing UI
Query ordering frontend-dapp/src/pages/SwapPage.tsx, src/pages/CreatePairPage.tsx, src/components/common/SwapAliasRedirect.tsx, src/utils/swapQueryParams.ts
Wallet frontend-dapp/src/hooks/useWallet.ts, src/components/wallet/WalletModal.tsx, src/services/terraclassic/wallet.ts
Transaction lifecycle frontend-dapp/src/hooks/useTerraBroadcastMutation.ts, src/services/terraclassic/terraBroadcast.ts, terraBroadcastScope.ts, terraTxRecoveryPoll.ts
Product surfaces frontend-dapp/src/pages/{SwapPage,TradePage,LimitOrdersPage,WrapPage,Ust1Page,CreateTokenPage,CreatePairPage}.tsx, src/components/trade/{TradeMarketOrderPanel,TradeOrderTicket}.tsx
Quotes/share frontend-dapp/src/services/indexer/client.ts, src/components/ui/ShareLinkButton.tsx, src/utils/sharePageLink.ts
Deployment/privacy integration frontend-dapp/viteCsp.ts, .env.example, src/vite-env.d.ts, index.html, src/components/legal/LegalFooterNotice.tsx (coordinate Notice ownership with Legal #35)
Fee reconciliation, read-only indexer/src/indexer/protocol_fees.rs, indexer/src/api/protocol_fees.rs, indexer/src/db/queries/protocol_fees.rs, indexer/migrations/20260916120001_protocol_fee_events_pair_id.sql
Verification Existing useWallet, useTerraBroadcastMutation, broadcast/recovery, query/share, viteCsp tests; frontend-dapp/e2e/, playwright.config.ts, Makefile, docs/frontend.md, docs/testing.md

Expected new modules: a small typed S1 capture/schema/permission/transport service with focused unit tests, one opt-out UI, a browser integration spec, docs/qa/issue-1202/README.md, and make verify-issue-1202. These paths/target are proposed, not existing implementation.

  1. Finalize the field/event contract and receiver limits with the privacy review. Use utm_campaign as canonical campaign_id; validate the marketing taxonomy/source/medium/intent allowlists, cap all fields, and define handling of duplicate/conflicting parameters. Store only validated first/last touch; do not keep arbitrary query data. Direct navigation must not silently erase a valid prior touch.
  2. Resolve the enable/refusal gate synchronously at bootstrap. Capture an eligible landing before redirects/canonicalization; observe subsequent eligible SPA landings without counting renders as new visits. Clear expired state before use. Snapshot campaign/action/quote context at transaction initiation so a later landing cannot reattribute an in-flight tx; refusal always overrides the snapshot.
  3. Implement a schema-filtered track adapter with a dark-by-default enable flag, fixed approved endpoint, bounded delivery, and explicit finite caps documented with tests. Fail closed on invalid configuration. Quote debounce/re-renders, StrictMode, recovery/retries, and repeated callbacks must not generate duplicate logical successes.
  4. Instrument the following minimum events only where the action applies:
Events Contract
qualified_page_view Route template, coarse referrer/device class, validated campaign/intent and session. No full URL.
quote_requested Action, economic pair/route, route mode, amount bucket, bounded latency/outcome, quote/session IDs. Record attempts, including failures; no keystroke beacon flood.
wallet_connect_started / wallet_connect_succeeded Explicit connect intent and established connection; wallet type/session only. Reconnect is not a new explicit connect funnel.
tx_sign_prompted Actual signing lifecycle, action and applicable quote ID; no fabricated quote for non-quote surfaces.
tx_broadcast / tx_succeeded Canonical validated txhash, action/economic metadata and first/last campaign snapshot. Broadcast means an acknowledged submission with a hash; recovering alone does not prove success. Success requires confirmed chain code 0.
tx_failed Action, normalized stage/reason; omit unknown hashes. Treat ambiguous confirmation/recovery as pending/unknown until resolved, not final failure or success.
share_started / share_completed Object type and known channel only; completion means Web Share resolved or clipboard copy succeeded. Cancellation/copy failure is not completion.
  1. Give nested broadcasts/allowance steps explicit identity; auxiliary approval success cannot stand for a swap. Deduplicate logical receipts with stable IDs plus canonical chain+txhash/action as appropriate. Preserve all distinct economic transactions and existing broadcast recovery semantics.
  2. Produce a private reconciliation receipt and reproducible coverage calculation. Normalize txhash case and chain identity, deduplicate economic transactions before joining the existing fee rows, and preserve event-time USD/null pricing. Missing or zero-fee/pending-ingest cases are labeled, never invented as $0 or fake fee receipts. Collector/warehouse construction remains outside this issue.

Acceptance criteria

  • AC1 — readiness: all privacy gates have factual evidence; the published Notice describes S1, destinations and retention. Opt-out-required is implemented. Until gates pass, disabled production S1 performs zero capture/persistence/delivery; refusal preference alone is permitted.
  • AC2 — capture: valid first/last campaigns survive /, /swap, /create canonicalization, navigation, permitted reload, connect and transaction completion; expiry is ≤30d. Invalid/absent campaigns have documented behavior.
  • AC3 — events: the minimum schema above covers Swap, Trade market, limit placement/cancel/edit/claim where supported, Wrap/Unwrap, UST1 mint/redeem, Create Token and Create Pair. Quote/share events are omitted on surfaces without that UI. No dummy identifiers or new unrelated LP event scope.
  • AC4 — outcomes: split/atomic/recovery paths yield confirmed success only after code 0, with the correct economic action/hash and frozen campaign context; no duplicate logical success or allowance-as-swap success.
  • AC5 — refusal: accessible desktop/mobile control stops collection and clears pending/local S1 data across navigation/reload/tabs, including refusal during an in-flight transaction; the transaction still completes normally. Re-enable does not replay suppressed events.
  • AC6 — boundary: golden/network payloads obey the closed schema; no wallet, secret, raw error, exact amount/fee, full referrer, or share content leaks. Only the reviewed first-party HTTPS receiver is reachable; no dev/simulated traffic reaches production.
  • AC7 — resilience: documented caps for field/payload/queue/rate/retries/timeouts are enforced. Disabled, blocked, offline, slow or failed analytics never block/modify trading or safety gates. Production CSP remains restrictive and canonical shares unchanged.
  • AC8 — reconciliation: at least one actual controlled staging/LocalTerra economic transaction with an isolated test receiver has tx_succeeded.txhash matching the indexer's canonical success and positive-fee row(s), without duplicate USD attribution. Stubbed hashes alone cannot satisfy this criterion; mainnet spending is not required.
  • AC9 — measured coverage: retain the ≥80% target. Report distinct eligible successful economic trades with a joinable S1 success receipt / independently verified eligible successful economic trades on instrumented surfaces, with numerator, denominator, window, surface/chain, exclusion version, ingest lag, and suppression/missing-receipt counts. Establish the 14-day dual-logging baseline described by the S1 plan after permitted activation. Never derive the denominator solely from received client events, count fee rows as trades, include auxiliary approvals, or silently drop missing events. Explicitly report opted-out traffic as unobserved/excluded; no claim of global retail coverage. Zero denominator is N/A, not 100%; pending baseline/receiver evidence keeps this AC open.
  • AC10 — maintenance: schema/gates/limits, test matrix, reconciliation method and exact results are documented; focused #1202 verifier and applicable frontend regression/build checks pass. Indexer fee contracts and independent related issues remain unchanged.

Test plan — functional and failure paths

ID Paths Required assertions
T1 Land on /, /swap, /create, and each other scoped route with valid params; alias/direct/SPA/reload/back navigation Capture precedes canonicalization/redirect; first touch stable, last touch updates only for qualifying campaigns; no render duplicates. Canonical shares do not gain UTMs.
T2 No campaign; partial/conflicting/duplicate keys; second campaign; direct return; expiry boundary/future timestamp; corrupt/denied/quota storage Defined validation/direct-touch behavior; expired/invalid data discarded; no exception or indefinitely refreshed TTL.
T3 Dark flag, invalid/unconfigured endpoint, unresolved Notice gate, initial/refreshed/cross-tab opt-out, opt-out mid-sign/confirmation/delivery, re-enable Zero forbidden collection/delivery; S1 state cleared; refusal persists; no refused-period replay; transaction and wallet behavior unaffected.
T4 Wallet explicit connect success, rejection/error/cancel, reconnect, switch/disconnect, simulated wallet Correct event pair only on appropriate explicit intent; no raw address; no production dev delivery.
T5 Quote success/no route/error, pool/hybrid/multihop, native wrap route, exact pay/receive, stale/canceled/debounced request Bounded attempt events with bucketed values and honest outcome/latency; no keypress/render flood or stale tx context.
T6 Every scoped economic action: Swap, Trade, limit place/cancel/edit/claim, Wrap/Unwrap, UST1 mint/redeem, token/pair create; available share controls Correct action and lifecycle; no fake nonapplicable events. Exercise nested allowance+send and multi-transaction actions separately.
T7 Split and atomic signing; sign rejection/stall, definite CheckTx rejection, sequence retry, ambiguous RPC failure, recovery success/timeout, nonzero chain code Hash only when available; no broadcast claim before acknowledgment; no success on ambiguity/nonzero code; confirmed recovered success once; no double counting on retries.
T8 Web Share success/abort/unsupported; clipboard fallback success/failure Completion only on actual success, canonical URL unchanged, no serialized share URL/text.
T9 Receiver offline/slow/429/4xx/5xx, CSP-blocked/redirected response, page unload, full queue, repeated render/tab callbacks Finite caps/retries, dedup, no UI/transaction delay or uncaught exceptions; withdrawal prevents later pending sends.
T10 Production build with gate unset/set; dev/simulated configuration; approved vs arbitrary destinations Dark default, restrictive production CSP, no vendor SDK/secret, dev receiver isolation; storage/opt-out failure fails closed.
T11 Actual controlled chain tx plus isolated receiver/indexer; multi-hop with multiple fees, repeated receipts, missing/unpriced/zero-fee rows Correct private chain+hash join, one-to-many fees preserved, no receipt-induced fee duplication; unmatched cases explicit.
T12 Coverage fixtures above/below/exactly 80%; duplicate/auxiliary receipts, omitted successes, exclusions/opt-out, ingest lag, zero denominator Independent denominator; correct counts/rate; missing data visible; N/A for zero denominator. Actual baseline recorded separately from synthetic tests.

Test plan — attack, hack and abuse vectors

ID Vector Expected result
A1 XSS/HTML/control characters, oversized/duplicate/encoded UTMs, wallet strings hidden in campaign fields; extra/prototype keys Reject/drop outside the closed schema and taxonomy; bounded size; no query injection into DOM/logs/storage/payload.
A2 Arbitrary wallet props, trader-address route, malicious token metadata, WC URI/signature/raw error/memo, exact amount in share URL Golden payload tests distinguish permitted contract metadata from user identity; no forbidden field/value forwarding.
A3 Spoofed/poisoned localStorage preference/timestamps/actor/touches; future clock; missing storage Fail closed for S1 or discard invalid touch; no bypass of refusal, unlimited TTL, privilege change, or effect on wallet storage.
A4 Query-driven sink, HTTPS lookalike/userinfo/port, HTTP/data/javascript URL, off-origin redirect, permissive CSP Reject unapproved destination; no credentials/referrer forwarding or redirect leak; production allowlist remains exact.
A5 Fabricated success, invalid/wrong-chain/case-varied hash, replay, copied existing victim txhash, conflicting campaign receipts Reject invalid shapes; private reconcile/dedup on canonical chain+hash; chain match validates economics only, not claimed campaign ownership. Conflicts flagged, no replacement of established receipt or financial credit.
A6 Wallet-derived hash as “anonymous”; campaign+txhash export; raw IP/UA as stable key; browser analytics token No wallet-derived client identity/secret or public attribution graph; linkability included in review and receiver retention/access controls.
A7 Bot beacon flood, quote loop, multi-tab/reload replay, enormous queue, endless retry/429 Enforced client caps, documented receiver size/rate/dedup contract and staging evidence; bounded memory/network; no economic side effects. Client controls alone do not make a public receiver abuse-proof.
A8 Opt-out during pending send/tx; stale callback or another tab re-enables tracking; clear refusal on touch expiry Recheck permission at capture/enqueue/delivery; purge pending state, synchronize refusal, no late suppressed receipt, no reset of refusal by touch TTL.
A9 Third-party SDK/vendor added as convenience; piggyback S1 on WC/Legal; global interception of fetch/errors No vendor S1 path or unrelated telemetry interception; closed first-party adapter only; bundle/network tests detect violations.
A10 Duplicate receipt×multiple fee rows/touches inflates USD; unknown price becomes $0; only received successes form denominator Preserve indexer truth and null pricing; transaction dedup before fee join; independent coverage denominator; attribution never becomes causal ROI.

Verification criteria

  1. Add executable focused tests for T1–T12/A1–A10 and a proposed make verify-issue-1202 entrypoint with explicit prerequisite failures. No existing verifier currently proves S1. The issue/PR must map each AC to actual evidence, not just source text checks.
  2. Run make lint-frontend, make test-frontend, make build-frontend, and regressions make verify-issue-711, make verify-issue-713, make verify-issue-715, make verify-issue-695. Extend existing wallet/broadcast/recovery/share/CSP tests where the hooks change. Use the repo Node 24 wrapper.
  3. Browser tests intercept an isolated first-party test receiver: capture-before-rewrite, every scoped surface/event, accessible opt-out (desktop/mobile), refusal races/tabs, sanitized payloads, lifecycle outcomes, and production CSP. Stubs prove UI/schema behavior only.
  4. For AC8, provision the actual local chain/indexer when needed (make has-localterra; make setup-cloud-localterra if absent), start Vite with make dev, and use the controlled wallet/test receiver. Do not report “no chain in agent VM” without provisioning. Record matching actual confirmed hash/fee-row counts and sanitized receipts privately; do not publish campaign-linked wallet histories in issue evidence.
  5. Record readiness review and real Notice/receiver evidence, then the measured coverage window/baseline for AC9. A reachable T&Cs fallback, old draft review, synthetic 100% result, or skipped live check is insufficient. Unexecuted items remain unchecked with their precise dependency.
  6. Document result date/commit, test commands, PASS/FAIL/unexecuted distinctions, retention and deletion behavior, caps, and activation/disable procedure in docs/qa/issue-1202/README.md. Verify the diff introduces no fee-source/API/schema changes, no canonical-share regression, and no production analytics activation while gates are unresolved. Close this issue only when all applicable acceptance evidence is complete.
## Summary and status Add the Phase 0 S1 **first-party client funnel** as one bundle: campaign capture, a working product-event opt-out, sanitized event delivery, transaction lifecycle instrumentation, and measured reconciliation coverage. Attribution is descriptive; the indexer remains the fee authority. **Investigated 2026-10-04 against `main` at `3f9310652ac83818749f5d32c4e32057b08817bc` (also the remote main head). Not implemented; keep this issue open.** The body consolidates the engineering report and subsequent decisions in the existing comments. Historical draft comments are background; this body is the implementation contract. **Privacy readiness remains on hold.** The [recorded S1 decision](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1202#issuecomment-48604) is **opt-out required**; it is no longer an unanswered decision and needs no replacement decision card. That decision alone does not release the remaining privacy gates. [Legal #35](https://git.cl8y.com/code/cl8y-ecosystem-legal/issues/35) owns the dedicated Notice and footer links. On 2026-10-04, `GET https://terms.cl8y.com/privacy` returned HTTP 200 with title `CL8Y Legal — Terms & Conditions`, rather than an identifiable Privacy Notice. A 200, a completed decision card, or T&Cs acceptance is not evidence of the required Notice. Do not mark this issue ready or activate production collection until the gates below are verified. ## Current codebase - `frontend-dapp` is a React 19/Vite 7 SPA with TanStack Query, Zustand, and cosmes wallets. `main.tsx`, `App.tsx`, `package.json`, and `index.html` contain no product-analytics initialization/SDK. There is no campaign/UTM capture, `cl8y_intent` persistence, S1 opt-out control, analytics endpoint configuration, or #1202 verifier in the checked-in code. - `SwapPage.tsx` and `CreatePairPage.tsx` replace search parameters with canonical swap/pair keys. Incoming UTMs disappear unless captured **before route mount/canonicalization**. `/swap` is an alias that redirects to `/`; capture must also precede that redirect. - `useWallet.ts` owns explicit connection, reconnect, simulated connection, and disconnect. Existing wallet session persistence and legal clickwrap are not product-event permission. - `useTerraBroadcastMutation.ts` wraps execution through `terraBroadcastScope.ts`. `terraBroadcast.ts` reports `signing`, `broadcasting`, `confirming`, and `recovering`. Split signing and atomic wallet paths differ; a `broadcasting` callback can occur **before a hash exists**. Poll/recovery checks the chain response code before returning a successful hash. Nested allowance/economic broadcasts can occur inside one mutation; generic mutation success is insufficient to classify every underlying action. - `ShareLinkButton.tsx`/`sharePageLink.ts` support Web Share, cancellation, clipboard fallback, and copy failure. Canonical shares drop campaigns; share payloads may contain a trader address or exact swap amount, so do not serialize their text/URL into analytics. - Production `viteCsp.ts` restricts `connect-src` to self plus configured chain/indexer, WalletConnect, and Legal origins. No analytics-specific destination exists. Development CSP is broader and cannot prove production privacy behavior. - `protocol_fee_events` contains chain-derived fee truth. There are currently seven `FeeSource` values: `swap_amm`, `book_take`, `limit_place`, `wrap`, `unwrap`, `ust1_mint`, `ust1_redeem`. #1269 widened uniqueness to `(tx_hash, source, pair_id, ordinal)` for pair rows and partial `(tx_hash, source, ordinal)` for NULL-pair rows. **One tx can have multiple legitimate fee rows.** `/api/v1/protocol/fees` and `/fees/daily` expose aggregates, not a client attribution or by-tx receipt service. ## Why this implementation is needed Current landing links cannot survive canonicalization into a joinable client success receipt. Fee aggregates alone cannot describe the acquisition funnel or campaign coverage, and existing wallet/broadcast state has no S1 event transport. Implementing isolated page beacons without opt-out, capture ordering, and confirmed transaction semantics would produce incomplete or misleading attribution. The [marketing S1 specification](https://git.cl8y.com/PlasticDigits/cl8y-marketing/src/branch/main/strategy/source-to-fee-instrumentation.md) and [operating-system event contract](https://git.cl8y.com/PlasticDigits/cl8y-marketing/src/branch/main/strategy/operating-system.md) now exist. The earlier comment saying the instrumentation/exclusions files were missing is stale. They describe the campaign taxonomy and coverage target; they do not prove that client collection or a collector has shipped. ## Duplicate/implementation check and bundle boundaries Searches with `fj` included open and closed issues/PRs for `source-to-fee`, `campaign_id`, analytics, telemetry, product events, and opt-out. No second issue owning the S1 client bundle or matching implementation PR was found. Source inspection and repository history confirm the client behavior above is absent. | Related work | Relationship; do not duplicate it here | | --- | --- | | #711 / #713 / #715 | Existing query aliases, canonical URL sync, and sharing. Reuse and regression-test; they do not capture campaigns or emit S1 events. | | #1209 / #1210 | Pair-creation and community invoice fee ingestion. Keep separate; do not promise their fees are already indexed. | | #1211 / #1213 | Actor/cohort reporting and fee-ledger home. #1211 does not depend on releasing S1. No campaign fields on fee rows. | | #1205 (closed) / #1206 (open) / #1204 | Chain evidence export, anonymous digest, and HTTP documentation. These are not client acquisition events. | | [Legal #35](https://git.cl8y.com/code/cl8y-ecosystem-legal/issues/35) | Canonical Notice at `https://terms.cl8y.com/privacy` and shared footer links. Depend on that work; do not author a second policy here. | | [Bridge #165](https://git.cl8y.com/code/cl8y-bridge-monorepo/issues/165) | Bridge storage/idle WalletConnect/Coinbase behavior. Do not absorb it or treat S1 refusal as an instruction to disconnect functional wallets. | Keep campaign capture, S1 opt-out, schema/transport, lifecycle hooks, and their tests in **this single issue**. A marketing warehouse, attribution dashboard, collector deployment, new fee parsers, or wallet-person graph is outside this bundle. A functioning approved first-party receiver is an activation dependency, not a reason to add another service to the DEX indexer. ## Constraints and guardrails 1. **Release gates:** before readiness/production collection, record the published S1-compatible Notice/version, exact first-party destination, field classification including campaign+txhash linkability, retention/deletion behavior, functional opt-out evidence, and completed privacy/security review. Until then preserve the documented hold. No production S1 capture, persistent touches/IDs, outbound requests, or queued events while disabled. Use synthetic fixtures for preparatory verification. 2. **Opt-out is real:** initialize refusal state before capture; offer an accessible control before any live product events. Refusal stops subsequent capture/delivery, cancels pending delivery where possible, clears S1 touches/IDs/queues, and survives reload/navigation/tabs. Preserve only the minimal refusal preference. Re-enabling never replays refused-period events. Storage failure/unknown preference must fail closed for S1 while trading continues. Withdrawal cannot retract an already accepted request; document receiver deletion handling honestly. 3. **First-party only in S1:** no GA/PostHog/pixels or third-party S1 hops. The fixed HTTPS receiver is deployment configuration validated against an explicit allowlist; never query/referrer controlled, and never a browser-held secret. Block off-origin redirects and avoid transmitting cookies/full referrers. Do not broaden CSP to `*`/`https:` for analytics. 4. **Minimize payloads:** closed field schema; bucket amounts; omit exact amounts, fees, balances, wallet/user addresses, wallet-derived identifiers, signatures, signed bytes, memos, errors/raw logs, WC URIs, emails/social handles, full URLs/referrers, and share text. Route templates replace dynamic user address segments. Pair/token **contract** identities may be allowlisted economic metadata; distinguish them from user wallet addresses. A txhash is linkable public-chain data, not anonymity. 5. **Identity/persistence:** use a random first-party session/pseudonymous key independent of a wallet. Avoid a persistent cross-session actor unless the reviewed schema requires it. Any wallet-derived keyed pseudonym belongs to separately reviewed first-party infrastructure; never place its key/salt in Vite, Git, or client code. Valid campaign touches expire within **30 days from collection**, including invalid/future timestamps and corrupt storage; expire/delete on read/startup without silently extending TTL. 6. **Independent fee authority:** client receipts/campaign tags are untrusted descriptive observations. Do not change `FeeSource`, fee schema/API, transaction economics, or exact-fee calculations. Reconcile privately/offline to existing chain/indexer records; retain multiple fee rows per transaction without multiplying them by duplicate client receipts/touchpoints. No public campaign→tx→wallet endpoint, causal ROI claim, reward, credit, or transaction authorization from client events. 7. **Trading remains available:** bounded nonblocking analytics; finite event size/queue/retries/timeouts; no await of delivery on wallet, quote, sign, broadcast, confirmation, or share paths. Analytics exceptions never alter existing callback order, safety gates, or transaction outcome. Dev/LocalTerra/simulated wallets cannot reach a production sink. 8. **Reporting:** exclusions are applied privately on the reporting side using the versioned [wallet-exclusion method](https://git.cl8y.com/PlasticDigits/cl8y-marketing/src/branch/main/strategy/wallet-exclusions.md). Do not embed private wallet lists in the SPA. No Telegram/X↔wallet joins or outbound marketing actions. Canonical share URLs remain campaign-free. ## Relevant files | Area | Existing files to inspect/change | | --- | --- | | Earliest capture/router/UI | `frontend-dapp/src/main.tsx`, `src/App.tsx`, `src/components/common/Layout.tsx`; S1 settings/control integrated with existing UI | | Query ordering | `frontend-dapp/src/pages/SwapPage.tsx`, `src/pages/CreatePairPage.tsx`, `src/components/common/SwapAliasRedirect.tsx`, `src/utils/swapQueryParams.ts` | | Wallet | `frontend-dapp/src/hooks/useWallet.ts`, `src/components/wallet/WalletModal.tsx`, `src/services/terraclassic/wallet.ts` | | Transaction lifecycle | `frontend-dapp/src/hooks/useTerraBroadcastMutation.ts`, `src/services/terraclassic/terraBroadcast.ts`, `terraBroadcastScope.ts`, `terraTxRecoveryPoll.ts` | | Product surfaces | `frontend-dapp/src/pages/{SwapPage,TradePage,LimitOrdersPage,WrapPage,Ust1Page,CreateTokenPage,CreatePairPage}.tsx`, `src/components/trade/{TradeMarketOrderPanel,TradeOrderTicket}.tsx` | | Quotes/share | `frontend-dapp/src/services/indexer/client.ts`, `src/components/ui/ShareLinkButton.tsx`, `src/utils/sharePageLink.ts` | | Deployment/privacy integration | `frontend-dapp/viteCsp.ts`, `.env.example`, `src/vite-env.d.ts`, `index.html`, `src/components/legal/LegalFooterNotice.tsx` (coordinate Notice ownership with Legal #35) | | Fee reconciliation, read-only | `indexer/src/indexer/protocol_fees.rs`, `indexer/src/api/protocol_fees.rs`, `indexer/src/db/queries/protocol_fees.rs`, `indexer/migrations/20260916120001_protocol_fee_events_pair_id.sql` | | Verification | Existing `useWallet`, `useTerraBroadcastMutation`, broadcast/recovery, query/share, `viteCsp` tests; `frontend-dapp/e2e/`, `playwright.config.ts`, `Makefile`, `docs/frontend.md`, `docs/testing.md` | Expected new modules: a small typed S1 capture/schema/permission/transport service with focused unit tests, one opt-out UI, a browser integration spec, `docs/qa/issue-1202/README.md`, and `make verify-issue-1202`. These paths/target are **proposed**, not existing implementation. ## Recommended solution direction 1. Finalize the field/event contract and receiver limits with the privacy review. Use `utm_campaign` as canonical `campaign_id`; validate the marketing taxonomy/source/medium/intent allowlists, cap all fields, and define handling of duplicate/conflicting parameters. Store only validated first/last touch; do not keep arbitrary query data. Direct navigation must not silently erase a valid prior touch. 2. Resolve the enable/refusal gate synchronously at bootstrap. Capture an eligible landing before redirects/canonicalization; observe subsequent eligible SPA landings without counting renders as new visits. Clear expired state before use. Snapshot campaign/action/quote context at transaction initiation so a later landing cannot reattribute an in-flight tx; refusal always overrides the snapshot. 3. Implement a schema-filtered `track` adapter with a dark-by-default enable flag, fixed approved endpoint, bounded delivery, and explicit finite caps documented with tests. Fail closed on invalid configuration. Quote debounce/re-renders, StrictMode, recovery/retries, and repeated callbacks must not generate duplicate logical successes. 4. Instrument the following minimum events only where the action applies: | Events | Contract | | --- | --- | | `qualified_page_view` | Route template, coarse referrer/device class, validated campaign/intent and session. No full URL. | | `quote_requested` | Action, economic pair/route, route mode, amount bucket, bounded latency/outcome, quote/session IDs. Record attempts, including failures; no keystroke beacon flood. | | `wallet_connect_started` / `wallet_connect_succeeded` | Explicit connect intent and established connection; wallet type/session only. Reconnect is not a new explicit connect funnel. | | `tx_sign_prompted` | Actual signing lifecycle, action and applicable quote ID; no fabricated quote for non-quote surfaces. | | `tx_broadcast` / `tx_succeeded` | Canonical validated txhash, action/economic metadata and first/last campaign snapshot. Broadcast means an acknowledged submission with a hash; `recovering` alone does not prove success. Success requires confirmed chain code 0. | | `tx_failed` | Action, normalized stage/reason; omit unknown hashes. Treat ambiguous confirmation/recovery as pending/unknown until resolved, not final failure or success. | | `share_started` / `share_completed` | Object type and known channel only; completion means Web Share resolved or clipboard copy succeeded. Cancellation/copy failure is not completion. | 5. Give nested broadcasts/allowance steps explicit identity; auxiliary approval success cannot stand for a swap. Deduplicate logical receipts with stable IDs plus canonical chain+txhash/action as appropriate. Preserve all distinct economic transactions and existing broadcast recovery semantics. 6. Produce a private reconciliation receipt and reproducible coverage calculation. Normalize txhash case and chain identity, deduplicate economic transactions before joining the existing fee rows, and preserve event-time USD/null pricing. Missing or zero-fee/pending-ingest cases are labeled, never invented as `$0` or fake fee receipts. Collector/warehouse construction remains outside this issue. ## Acceptance criteria - [ ] **AC1 — readiness:** all privacy gates have factual evidence; the published Notice describes S1, destinations and retention. Opt-out-required is implemented. Until gates pass, disabled production S1 performs zero capture/persistence/delivery; refusal preference alone is permitted. - [ ] **AC2 — capture:** valid first/last campaigns survive `/`, `/swap`, `/create` canonicalization, navigation, permitted reload, connect and transaction completion; expiry is ≤30d. Invalid/absent campaigns have documented behavior. - [ ] **AC3 — events:** the minimum schema above covers Swap, Trade market, limit placement/cancel/edit/claim where supported, Wrap/Unwrap, UST1 mint/redeem, Create Token and Create Pair. Quote/share events are omitted on surfaces without that UI. No dummy identifiers or new unrelated LP event scope. - [ ] **AC4 — outcomes:** split/atomic/recovery paths yield confirmed success only after code 0, with the correct economic action/hash and frozen campaign context; no duplicate logical success or allowance-as-swap success. - [ ] **AC5 — refusal:** accessible desktop/mobile control stops collection and clears pending/local S1 data across navigation/reload/tabs, including refusal during an in-flight transaction; the transaction still completes normally. Re-enable does not replay suppressed events. - [ ] **AC6 — boundary:** golden/network payloads obey the closed schema; no wallet, secret, raw error, exact amount/fee, full referrer, or share content leaks. Only the reviewed first-party HTTPS receiver is reachable; no dev/simulated traffic reaches production. - [ ] **AC7 — resilience:** documented caps for field/payload/queue/rate/retries/timeouts are enforced. Disabled, blocked, offline, slow or failed analytics never block/modify trading or safety gates. Production CSP remains restrictive and canonical shares unchanged. - [ ] **AC8 — reconciliation:** at least one actual controlled staging/LocalTerra economic transaction with an isolated test receiver has `tx_succeeded.txhash` matching the indexer's canonical success and positive-fee row(s), without duplicate USD attribution. Stubbed hashes alone cannot satisfy this criterion; mainnet spending is not required. - [ ] **AC9 — measured coverage:** retain the [≥80% target](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1202#issuecomment-43879). Report `distinct eligible successful economic trades with a joinable S1 success receipt / independently verified eligible successful economic trades on instrumented surfaces`, with numerator, denominator, window, surface/chain, exclusion version, ingest lag, and suppression/missing-receipt counts. Establish the 14-day dual-logging baseline described by the S1 plan after permitted activation. Never derive the denominator solely from received client events, count fee rows as trades, include auxiliary approvals, or silently drop missing events. Explicitly report opted-out traffic as unobserved/excluded; no claim of global retail coverage. Zero denominator is N/A, not 100%; pending baseline/receiver evidence keeps this AC open. - [ ] **AC10 — maintenance:** schema/gates/limits, test matrix, reconciliation method and exact results are documented; focused #1202 verifier and applicable frontend regression/build checks pass. Indexer fee contracts and independent related issues remain unchanged. ## Test plan — functional and failure paths | ID | Paths | Required assertions | | --- | --- | --- | | T1 | Land on `/`, `/swap`, `/create`, and each other scoped route with valid params; alias/direct/SPA/reload/back navigation | Capture precedes canonicalization/redirect; first touch stable, last touch updates only for qualifying campaigns; no render duplicates. Canonical shares do not gain UTMs. | | T2 | No campaign; partial/conflicting/duplicate keys; second campaign; direct return; expiry boundary/future timestamp; corrupt/denied/quota storage | Defined validation/direct-touch behavior; expired/invalid data discarded; no exception or indefinitely refreshed TTL. | | T3 | Dark flag, invalid/unconfigured endpoint, unresolved Notice gate, initial/refreshed/cross-tab opt-out, opt-out mid-sign/confirmation/delivery, re-enable | Zero forbidden collection/delivery; S1 state cleared; refusal persists; no refused-period replay; transaction and wallet behavior unaffected. | | T4 | Wallet explicit connect success, rejection/error/cancel, reconnect, switch/disconnect, simulated wallet | Correct event pair only on appropriate explicit intent; no raw address; no production dev delivery. | | T5 | Quote success/no route/error, pool/hybrid/multihop, native wrap route, exact pay/receive, stale/canceled/debounced request | Bounded attempt events with bucketed values and honest outcome/latency; no keypress/render flood or stale tx context. | | T6 | Every scoped economic action: Swap, Trade, limit place/cancel/edit/claim, Wrap/Unwrap, UST1 mint/redeem, token/pair create; available share controls | Correct action and lifecycle; no fake nonapplicable events. Exercise nested allowance+send and multi-transaction actions separately. | | T7 | Split and atomic signing; sign rejection/stall, definite CheckTx rejection, sequence retry, ambiguous RPC failure, recovery success/timeout, nonzero chain code | Hash only when available; no broadcast claim before acknowledgment; no success on ambiguity/nonzero code; confirmed recovered success once; no double counting on retries. | | T8 | Web Share success/abort/unsupported; clipboard fallback success/failure | Completion only on actual success, canonical URL unchanged, no serialized share URL/text. | | T9 | Receiver offline/slow/429/4xx/5xx, CSP-blocked/redirected response, page unload, full queue, repeated render/tab callbacks | Finite caps/retries, dedup, no UI/transaction delay or uncaught exceptions; withdrawal prevents later pending sends. | | T10 | Production build with gate unset/set; dev/simulated configuration; approved vs arbitrary destinations | Dark default, restrictive production CSP, no vendor SDK/secret, dev receiver isolation; storage/opt-out failure fails closed. | | T11 | Actual controlled chain tx plus isolated receiver/indexer; multi-hop with multiple fees, repeated receipts, missing/unpriced/zero-fee rows | Correct private chain+hash join, one-to-many fees preserved, no receipt-induced fee duplication; unmatched cases explicit. | | T12 | Coverage fixtures above/below/exactly 80%; duplicate/auxiliary receipts, omitted successes, exclusions/opt-out, ingest lag, zero denominator | Independent denominator; correct counts/rate; missing data visible; N/A for zero denominator. Actual baseline recorded separately from synthetic tests. | ## Test plan — attack, hack and abuse vectors | ID | Vector | Expected result | | --- | --- | --- | | A1 | XSS/HTML/control characters, oversized/duplicate/encoded UTMs, wallet strings hidden in campaign fields; extra/prototype keys | Reject/drop outside the closed schema and taxonomy; bounded size; no query injection into DOM/logs/storage/payload. | | A2 | Arbitrary wallet props, trader-address route, malicious token metadata, WC URI/signature/raw error/memo, exact amount in share URL | Golden payload tests distinguish permitted contract metadata from user identity; no forbidden field/value forwarding. | | A3 | Spoofed/poisoned localStorage preference/timestamps/actor/touches; future clock; missing storage | Fail closed for S1 or discard invalid touch; no bypass of refusal, unlimited TTL, privilege change, or effect on wallet storage. | | A4 | Query-driven sink, HTTPS lookalike/userinfo/port, HTTP/data/javascript URL, off-origin redirect, permissive CSP | Reject unapproved destination; no credentials/referrer forwarding or redirect leak; production allowlist remains exact. | | A5 | Fabricated success, invalid/wrong-chain/case-varied hash, replay, copied existing victim txhash, conflicting campaign receipts | Reject invalid shapes; private reconcile/dedup on canonical chain+hash; chain match validates economics only, not claimed campaign ownership. Conflicts flagged, no replacement of established receipt or financial credit. | | A6 | Wallet-derived hash as “anonymous”; campaign+txhash export; raw IP/UA as stable key; browser analytics token | No wallet-derived client identity/secret or public attribution graph; linkability included in review and receiver retention/access controls. | | A7 | Bot beacon flood, quote loop, multi-tab/reload replay, enormous queue, endless retry/429 | Enforced client caps, documented receiver size/rate/dedup contract and staging evidence; bounded memory/network; no economic side effects. Client controls alone do not make a public receiver abuse-proof. | | A8 | Opt-out during pending send/tx; stale callback or another tab re-enables tracking; clear refusal on touch expiry | Recheck permission at capture/enqueue/delivery; purge pending state, synchronize refusal, no late suppressed receipt, no reset of refusal by touch TTL. | | A9 | Third-party SDK/vendor added as convenience; piggyback S1 on WC/Legal; global interception of fetch/errors | No vendor S1 path or unrelated telemetry interception; closed first-party adapter only; bundle/network tests detect violations. | | A10 | Duplicate receipt×multiple fee rows/touches inflates USD; unknown price becomes `$0`; only received successes form denominator | Preserve indexer truth and null pricing; transaction dedup before fee join; independent coverage denominator; attribution never becomes causal ROI. | ## Verification criteria 1. Add executable focused tests for T1–T12/A1–A10 and a proposed `make verify-issue-1202` entrypoint with explicit prerequisite failures. No existing verifier currently proves S1. The issue/PR must map each AC to actual evidence, not just source text checks. 2. Run `make lint-frontend`, `make test-frontend`, `make build-frontend`, and regressions `make verify-issue-711`, `make verify-issue-713`, `make verify-issue-715`, `make verify-issue-695`. Extend existing wallet/broadcast/recovery/share/CSP tests where the hooks change. Use the repo Node 24 wrapper. 3. Browser tests intercept an **isolated** first-party test receiver: capture-before-rewrite, every scoped surface/event, accessible opt-out (desktop/mobile), refusal races/tabs, sanitized payloads, lifecycle outcomes, and production CSP. Stubs prove UI/schema behavior only. 4. For AC8, provision the actual local chain/indexer when needed (`make has-localterra`; `make setup-cloud-localterra` if absent), start Vite with `make dev`, and use the controlled wallet/test receiver. Do not report “no chain in agent VM” without provisioning. Record matching actual confirmed hash/fee-row counts and sanitized receipts privately; do not publish campaign-linked wallet histories in issue evidence. 5. Record readiness review and real Notice/receiver evidence, then the measured coverage window/baseline for AC9. A reachable T&Cs fallback, old draft review, synthetic 100% result, or skipped live check is insufficient. Unexecuted items remain unchecked with their precise dependency. 6. Document result date/commit, test commands, PASS/FAIL/unexecuted distinctions, retention and deletion behavior, caps, and activation/disable procedure in `docs/qa/issue-1202/README.md`. Verify the diff introduces no fee-source/API/schema changes, no canonical-share regression, and no production analytics activation while gates are unresolved. Close this issue only when all applicable acceptance evidence is complete.
Author
Owner

Summary

Marketing cannot measure source → fee. The DEX SPA (frontend-dapp on dex.cl8y.com) has no PostHog, gtag, Plausible, or other product-analytics SDK. There is no UTM / campaign_id / cl8y_intent persistence. Swap and Create Pair replace the query string with a canonical set after land, so inbound campaign params are wiped unless captured first.

Add privacy-reviewed first-party product events so a campaign_id can survive from landing through tx_succeeded, joinable to indexer fee rows via txhash. Attribution is descriptive only — not causal ROI. The indexer remains the sole economic authority for fees. Do not change FeeSource. Pair-creation fee indexing stays a separate ticket.

Related spec lives in PlasticDigits/cl8y-marketing (strategy/operating-system.md product event contract; Phase 0 item 6 in strategy/90-day-plan.md). There is no strategy/source-to-fee-instrumentation.md or wallet-exclusions.md in-tree yet.


Current codebase

Architecture

Browser SPA (Vite/React) ──LCD/RPC──▶ Terra Classic
        │                    │
        │ quotes/charts      │ txs (sign → broadcast → poll)
        ▼                    ▼
   Indexer API          On-chain events
   (Axum/Postgres) ──▶ protocol_fee_events (fee truth)
  • Client: frontend-dapp — React 19 + Vite 7 + TanStack Query + Zustand + cosmes wallets.
  • Indexer: indexer — Rust Axum/SQLx; economic authority for fees.
  • No analytics module, feature-flag service, or third-party pixels in deps or index.html.
  • Production CSP connect-src is allowlisted (LCD/RPC/indexer/WalletConnect/Legal). Third-party analytics hosts are blocked unless CSP is updated (viteCsp.ts).

Surfaces in scope

Surface Route Page
Trade (swap) / (/swap alias) SwapPage.tsx
Limit / book /trade, /trade/:pairAddr, /limits TradePage.tsx, LimitOrdersPage.tsx
Wrap /wrap WrapPage.tsx
UST1 /ust1 Ust1Page.tsx
Create token /token/create CreateTokenPage.tsx
Create pair /create CreatePairPage.tsx

Wrap / UST1 / create-token nav items appear when the corresponding env addresses are set.

UTM / campaign

Grep finds no utm_, campaign_id, or cl8y_intent. SwapPage and CreatePairPage call setSearchParams(..., { replace: true }) with canonical keys only (from/to/amount or pair tokens). Inbound UTMs are stripped after first sync unless captured on land first.

Wallet, quotes, txs, share

  • Wallet: WalletModal → useWalletStore.connect → connectTerraWallet. Persistence keys cl8y_wallet_connection, cl8y_dev_sim.
  • Quotes: hybrid LCD + indexer route/solve on Swap — natural quote_requested hook.
  • Tx: terraBroadcast.ts phases signing → broadcasting → confirming (+ recovering). useTerraBroadcastMutation exposes phase + pendingTxHash; success data is typically the tx hash string. Maps to tx_sign_prompted / tx_broadcast / tx_succeeded / tx_failed.
  • Share: ShareLinkButton + shareOrCopyPageLink (Web Share → clipboard) on Swap, Trader, Portfolio. Shared URLs are canonical and campaign-free today.

Indexer join key (do not change FeeSource)

protocol_fee_events.tx_hash with UNIQUE (tx_hash, source, ordinal). Sources today: swap_amm, book_take, limit_place, wrap, unwrap, ust1_mint, ust1_redeem. Public API is aggregate (GET /api/v1/protocol/fees); there is no by-txhash HTTP API. Reconciliation is offline/SQL or a future marketing-core ingest.

Feature flags

No LaunchDarkly/Unleash. Behavior is VITE_*. There is no VITE_ANALYTICS_ENDPOINT or analytics kill-switch yet. Simulated Wallet exists only in VITE_DEV_MODE and must not hit a production sink.


Why a new implementation is needed

Phase 0 marketing cannot claim what acquires fee-paying flow. Without client events + durable campaign params, landing traffic cannot be joined to protocol_fee_events on txhash. Indexer aggregates cannot answer “which campaign”. Third-party pixels are the wrong default: production CSP blocks them, and raw wallets must not leave the first party.

Capture must run before Swap/Create Pair URL canonicalization, or campaign params are lost on the primary trade landing path.


Constraints and guardrails

  1. Indexer remains the sole fee economic authority. Client events are funnel/touch only. Do not extend FeeSource or put exact fees in analytics.
  2. Amounts in analytics are bucketed. Exact fees stay in the indexer.
  3. No raw wallet addresses in third-party payloads. Prefer omit wallet from all analytics payloads. Optional local actor_key with offline salt.
  4. First-party HTTPS sink preferred (future cl8y-marketing-core or a minimal Coolify collector). A vendor is allowed only if already privacy-reviewed and CSP/script allowlisted. None is in-tree today.
  5. Out of scope: indexer FeeSource / pair_creation (separate ticket), marketing Postgres schema in this repo, incrementality experiments, Telegram/X ↔ wallet joins, paid media pixels.
  6. Document ≤30d TTL and privacy basis for stored UTMs / cl8y_intent.
  7. wallet-exclusions applies on the reporting side, not in the client. Do not invent exclusion lists in the SPA.
  8. Simulated Wallet / VITE_DEV_MODE must not emit to the production sink.
  9. Share links stay canonical unless product later opts into explicit campaign share URLs. Attribution uses stored first/last touch, not rewritten share URLs.
  10. Do not treat first-touch or last-touch as causal lift.

Relevant files

Area Files
App bootstrap / routes frontend-dapp/src/main.tsx, App.tsx, components/common/navItems.ts
CSP / env frontend-dapp/viteCsp.ts, index.html, .env.example, package.json
URL strip risk frontend-dapp/src/pages/SwapPage.tsx, utils/swapQueryParams.ts, pages/CreatePairPage.tsx
Wallet frontend-dapp/src/hooks/useWallet.ts, components/wallet/WalletModal.tsx
Tx funnel frontend-dapp/src/hooks/useTerraBroadcastMutation.ts, services/terraclassic/terraBroadcast.ts
Quotes frontend-dapp/src/services/indexer/client.ts, Swap quote effects
Share frontend-dapp/src/components/ui/ShareLinkButton.tsx, utils/sharePageLink.ts
Other surfaces pages/TradePage.tsx, WrapPage.tsx, Ust1Page.tsx, CreateTokenPage.tsx, components/trade/TradeMarketOrderPanel.tsx, TradeOrderTicket.tsx
Fee join (read-only) indexer/src/indexer/protocol_fees.rs, indexer/migrations/20260821120000_protocol_fees.sql, indexer/src/api/protocol_fees.rs
Marketing spec cl8y-marketing/strategy/operating-system.md, 90-day-plan.md, fee-growth-model.md, technical-architecture.md, founder-decisions.md

  1. Capture-on-land first (synchronously, before Swap/Create Pair setSearchParams): parse utm_* + cl8y_intent (+ agreed campaign taxonomy keys); persist first-touch and last-touch in localStorage with ≤30d TTL.
  2. Thin first-party track(event, props) module, gated by env (VITE_ANALYTICS_ENDPOINT or equivalent kill-switch) so it can ship dark.
  3. Wire:
    • Layout/router → qualified_page_view
    • Quote effects → quote_requested (bucketed amounts)
    • Wallet modal/store → wallet_connect_started / wallet_connect_succeeded
    • useTerraBroadcastMutation / phase callbacks → tx_sign_prompted / tx_broadcast / tx_succeeded / tx_failed with txhash, action, pair/route, first+last campaign_id
    • ShareLinkButton → share_started / share_completed (if share UI exists on that surface; else defer that event only)
  4. Sink: first-party HTTPS endpoint. Add it to CSP connect-src. Do not add gtag/PostHog unless separately approved.
  5. Identity: random actor_key in local storage; never send raw wallet to third parties.
  6. Reconcile offline: marketing joins events → protocol_fee_events on txhash.
  7. Short DEX docs or PR note linking the marketing event contract. Author source-to-fee-instrumentation.md in marketing if still missing; do not block the client on that filename.

Acceptance criteria

  • Campaign params persist across wallet connect → sign → broadcast on the happy path (first + last touch available on tx_succeeded).
  • Capture runs before Swap/Create Pair URL canonicalization; UTMs are not lost on / or /create.
  • Minimum events from the marketing product event contract are emitted on in-scope surfaces: qualified_page_view, quote_requested, wallet_connect_started / wallet_connect_succeeded, tx_sign_prompted, tx_broadcast / tx_succeeded / tx_failed, and share events where share UI exists.
  • tx_broadcast / tx_succeeded include txhash, action, pair/route, first+last campaign_id.
  • Amounts in analytics are bucketed; exact fees are not sent.
  • ≥1 staging/mainnet test tx shows client tx_succeeded.txhash matching an indexer protocol_fee_events.tx_hash (or equivalent success/fee row).
  • Network log / schema: no raw wallets in third-party payloads (prefer no wallet in first-party payloads either).
  • Feature flag or env gate: can ship dark then enable. VITE_DEV_MODE / Simulated Wallet does not hit prod sink.
  • CSP allowlists only the approved first-party sink (or reviewed vendor).
  • Short note in DEX docs or PR linking the marketing spec.
  • Indexer FeeSource unchanged.

Test plan: all paths

  1. Land with UTMs + cl8y_intent on /: first-touch stored; Swap canonical URL rewrite does not drop stored campaign; qualified_page_view fires once per qualified land.
  2. Land with no params: events still fire; campaign ids empty/absent per spec; no throw.
  3. Last-touch update: second land with a different campaign updates last-touch only; first-touch unchanged until TTL.
  4. TTL: stored touches expire at ≤30d; documented.
  5. Quote: quote_requested on swap quote (success, empty route, LCD error) with bucketed amount.
  6. Wallet: started / succeeded / cancelled / failed connect; no address in payload.
  7. Tx happy path on swap, limit/book, wrap, UST1, create-token, create-pair (if in dApp): sign → broadcast → success with matching txhash.
  8. Tx fail paths: user reject sign, broadcast error, confirm timeout/fail — tx_failed with normalized stage; no fake success.
  9. Share: started/completed and cancel/failure; shared URL remains canonical (no forced UTM pollution).
  10. Dark flag: env unset ⇒ zero network beacons.
  11. Dev/sim wallet: no prod sink.
  12. CSP: production build connect-src includes the sink and still blocks arbitrary analytics hosts.
  13. Join: one real or captured txhash exists in protocol_fee_events.
  14. Surfaces without quote/share: events that do not apply are omitted, not stubbed with dummy pair ids.

Test plan: attack, hack, and abuse vectors

Vector Expected result
Hostile campaign_id / UTM (XSS, huge strings, unknown keys) Sanitize length/charset; drop unknown keys; never echo raw query into DOM or logs
Campaign spoofing / last-touch hijack Treated as descriptive only; server allowlist/taxonomy if sink exists; first-touch preferred for “source of land”
Fake tx_succeeded without chain confirm Emit only after confirmed phase / successful mutation; marketing join still requires indexer row
Wallet leakage in props, share text, or WC logs Redact; tests fail if terra1/0x address appears in analytics payload
Bot / self-traffic / Simulated Wallet Dev gate; reporting-side exclusions later; client must not special-case production wallets
Analytics sink SSRF / open beacon Fixed allowlisted URL from env; no user-controlled sink host
CSP / supply-chain (adding gtag/PostHog) Default is first-party beacon only; vendor requires explicit review
localStorage tampering Corrupt JSON ignored; no throw; no privilege gain
Share amplification of organic links Do not claim last-touch from canonical shares without campaign

Verification criteria

  • Unit tests for capture-before-canonicalize, TTL, sanitization, and payload schema (no wallet, bucketed amounts, txhash present on success).
  • Hook tests for wallet and useTerraBroadcastMutation phase mapping.
  • Playwright or equivalent: land with UTMs → connect (sim or stub) → swap (stub broadcast) → tx_succeeded payload still has first-touch campaign id after URL rewrite.
  • Production CSP snapshot includes only the approved sink.
  • Manual: one staging/mainnet txhash equals an indexer fee/success row.
  • Docs/PR links the marketing event contract and states indexer is fee truth.
  • make / existing frontend verify targets still pass; indexer tests untouched.
## Summary Marketing cannot measure source → fee. The DEX SPA (`frontend-dapp` on dex.cl8y.com) has no PostHog, gtag, Plausible, or other product-analytics SDK. There is no UTM / `campaign_id` / `cl8y_intent` persistence. Swap and Create Pair **replace** the query string with a canonical set after land, so inbound campaign params are wiped unless captured first. Add privacy-reviewed first-party product events so a `campaign_id` can survive from landing through `tx_succeeded`, joinable to indexer fee rows via `txhash`. Attribution is descriptive only — not causal ROI. The indexer remains the sole economic authority for fees. Do not change `FeeSource`. Pair-creation fee indexing stays a separate ticket. Related spec lives in `PlasticDigits/cl8y-marketing` (`strategy/operating-system.md` product event contract; Phase 0 item 6 in `strategy/90-day-plan.md`). There is no `strategy/source-to-fee-instrumentation.md` or `wallet-exclusions.md` in-tree yet. --- ## Current codebase ### Architecture ```text Browser SPA (Vite/React) ──LCD/RPC──▶ Terra Classic │ │ │ quotes/charts │ txs (sign → broadcast → poll) ▼ ▼ Indexer API On-chain events (Axum/Postgres) ──▶ protocol_fee_events (fee truth) ``` - **Client:** `frontend-dapp` — React 19 + Vite 7 + TanStack Query + Zustand + cosmes wallets. - **Indexer:** `indexer` — Rust Axum/SQLx; economic authority for fees. - **No analytics module, feature-flag service, or third-party pixels** in deps or `index.html`. - Production CSP `connect-src` is allowlisted (LCD/RPC/indexer/WalletConnect/Legal). Third-party analytics hosts are blocked unless CSP is updated (`viteCsp.ts`). ### Surfaces in scope | Surface | Route | Page | |---|---|---| | Trade (swap) | `/` (`/swap` alias) | `SwapPage.tsx` | | Limit / book | `/trade`, `/trade/:pairAddr`, `/limits` | `TradePage.tsx`, `LimitOrdersPage.tsx` | | Wrap | `/wrap` | `WrapPage.tsx` | | UST1 | `/ust1` | `Ust1Page.tsx` | | Create token | `/token/create` | `CreateTokenPage.tsx` | | Create pair | `/create` | `CreatePairPage.tsx` | Wrap / UST1 / create-token nav items appear when the corresponding env addresses are set. ### UTM / campaign Grep finds no `utm_`, `campaign_id`, or `cl8y_intent`. `SwapPage` and `CreatePairPage` call `setSearchParams(..., { replace: true })` with canonical keys only (`from`/`to`/amount or pair tokens). **Inbound UTMs are stripped after first sync** unless captured on land first. ### Wallet, quotes, txs, share - Wallet: `WalletModal` → `useWalletStore.connect` → `connectTerraWallet`. Persistence keys `cl8y_wallet_connection`, `cl8y_dev_sim`. - Quotes: hybrid LCD + indexer `route/solve` on Swap — natural `quote_requested` hook. - Tx: `terraBroadcast.ts` phases `signing` → `broadcasting` → `confirming` (+ `recovering`). `useTerraBroadcastMutation` exposes `phase` + `pendingTxHash`; success data is typically the tx hash string. Maps to `tx_sign_prompted` / `tx_broadcast` / `tx_succeeded` / `tx_failed`. - Share: `ShareLinkButton` + `shareOrCopyPageLink` (Web Share → clipboard) on Swap, Trader, Portfolio. Shared URLs are canonical and campaign-free today. ### Indexer join key (do not change FeeSource) `protocol_fee_events.tx_hash` with `UNIQUE (tx_hash, source, ordinal)`. Sources today: `swap_amm`, `book_take`, `limit_place`, `wrap`, `unwrap`, `ust1_mint`, `ust1_redeem`. Public API is aggregate (`GET /api/v1/protocol/fees`); there is no by-txhash HTTP API. Reconciliation is offline/SQL or a future marketing-core ingest. ### Feature flags No LaunchDarkly/Unleash. Behavior is `VITE_*`. There is no `VITE_ANALYTICS_ENDPOINT` or analytics kill-switch yet. Simulated Wallet exists only in `VITE_DEV_MODE` and must not hit a production sink. --- ## Why a new implementation is needed Phase 0 marketing cannot claim what acquires fee-paying flow. Without client events + durable campaign params, landing traffic cannot be joined to `protocol_fee_events` on `txhash`. Indexer aggregates cannot answer “which campaign”. Third-party pixels are the wrong default: production CSP blocks them, and raw wallets must not leave the first party. Capture must run **before** Swap/Create Pair URL canonicalization, or campaign params are lost on the primary trade landing path. --- ## Constraints and guardrails 1. Indexer remains the **sole fee economic authority**. Client events are funnel/touch only. Do not extend `FeeSource` or put exact fees in analytics. 2. Amounts in analytics are **bucketed**. Exact fees stay in the indexer. 3. **No raw wallet addresses** in third-party payloads. Prefer omit wallet from all analytics payloads. Optional local `actor_key` with offline salt. 4. First-party HTTPS sink preferred (future `cl8y-marketing-core` or a minimal Coolify collector). A vendor is allowed only if already privacy-reviewed **and** CSP/script allowlisted. None is in-tree today. 5. Out of scope: indexer `FeeSource` / pair_creation (separate ticket), marketing Postgres schema in this repo, incrementality experiments, Telegram/X ↔ wallet joins, paid media pixels. 6. Document ≤30d TTL and privacy basis for stored UTMs / `cl8y_intent`. 7. `wallet-exclusions` applies on the **reporting** side, not in the client. Do not invent exclusion lists in the SPA. 8. Simulated Wallet / `VITE_DEV_MODE` must not emit to the production sink. 9. Share links stay canonical unless product later opts into explicit campaign share URLs. Attribution uses stored first/last touch, not rewritten share URLs. 10. Do not treat first-touch or last-touch as causal lift. --- ## Relevant files | Area | Files | |---|---| | App bootstrap / routes | `frontend-dapp/src/main.tsx`, `App.tsx`, `components/common/navItems.ts` | | CSP / env | `frontend-dapp/viteCsp.ts`, `index.html`, `.env.example`, `package.json` | | URL strip risk | `frontend-dapp/src/pages/SwapPage.tsx`, `utils/swapQueryParams.ts`, `pages/CreatePairPage.tsx` | | Wallet | `frontend-dapp/src/hooks/useWallet.ts`, `components/wallet/WalletModal.tsx` | | Tx funnel | `frontend-dapp/src/hooks/useTerraBroadcastMutation.ts`, `services/terraclassic/terraBroadcast.ts` | | Quotes | `frontend-dapp/src/services/indexer/client.ts`, Swap quote effects | | Share | `frontend-dapp/src/components/ui/ShareLinkButton.tsx`, `utils/sharePageLink.ts` | | Other surfaces | `pages/TradePage.tsx`, `WrapPage.tsx`, `Ust1Page.tsx`, `CreateTokenPage.tsx`, `components/trade/TradeMarketOrderPanel.tsx`, `TradeOrderTicket.tsx` | | Fee join (read-only) | `indexer/src/indexer/protocol_fees.rs`, `indexer/migrations/20260821120000_protocol_fees.sql`, `indexer/src/api/protocol_fees.rs` | | Marketing spec | `cl8y-marketing/strategy/operating-system.md`, `90-day-plan.md`, `fee-growth-model.md`, `technical-architecture.md`, `founder-decisions.md` | --- ## Recommended direction 1. **Capture-on-land first** (synchronously, before Swap/Create Pair `setSearchParams`): parse `utm_*` + `cl8y_intent` (+ agreed campaign taxonomy keys); persist first-touch and last-touch in `localStorage` with **≤30d TTL**. 2. **Thin first-party `track(event, props)` module**, gated by env (`VITE_ANALYTICS_ENDPOINT` or equivalent kill-switch) so it can ship dark. 3. Wire: - Layout/router → `qualified_page_view` - Quote effects → `quote_requested` (bucketed amounts) - Wallet modal/store → `wallet_connect_started` / `wallet_connect_succeeded` - `useTerraBroadcastMutation` / phase callbacks → `tx_sign_prompted` / `tx_broadcast` / `tx_succeeded` / `tx_failed` with `txhash`, action, pair/route, first+last `campaign_id` - `ShareLinkButton` → `share_started` / `share_completed` (if share UI exists on that surface; else defer that event only) 4. **Sink:** first-party HTTPS endpoint. Add it to CSP `connect-src`. Do not add gtag/PostHog unless separately approved. 5. Identity: random `actor_key` in local storage; never send raw wallet to third parties. 6. Reconcile offline: marketing joins events → `protocol_fee_events` on `txhash`. 7. Short DEX docs or PR note linking the marketing event contract. Author `source-to-fee-instrumentation.md` in marketing if still missing; do not block the client on that filename. --- ## Acceptance criteria - [ ] Campaign params persist across wallet connect → sign → broadcast on the happy path (first + last touch available on `tx_succeeded`). - [ ] Capture runs before Swap/Create Pair URL canonicalization; UTMs are not lost on `/` or `/create`. - [ ] Minimum events from the marketing product event contract are emitted on in-scope surfaces: `qualified_page_view`, `quote_requested`, `wallet_connect_started` / `wallet_connect_succeeded`, `tx_sign_prompted`, `tx_broadcast` / `tx_succeeded` / `tx_failed`, and share events where share UI exists. - [ ] `tx_broadcast` / `tx_succeeded` include `txhash`, action, pair/route, first+last `campaign_id`. - [ ] Amounts in analytics are bucketed; exact fees are not sent. - [ ] ≥1 staging/mainnet test tx shows client `tx_succeeded.txhash` matching an indexer `protocol_fee_events.tx_hash` (or equivalent success/fee row). - [ ] Network log / schema: no raw wallets in third-party payloads (prefer no wallet in first-party payloads either). - [ ] Feature flag or env gate: can ship dark then enable. `VITE_DEV_MODE` / Simulated Wallet does not hit prod sink. - [ ] CSP allowlists only the approved first-party sink (or reviewed vendor). - [ ] Short note in DEX docs or PR linking the marketing spec. - [ ] Indexer `FeeSource` unchanged. --- ## Test plan: all paths 1. **Land with UTMs + `cl8y_intent` on `/`:** first-touch stored; Swap canonical URL rewrite does not drop stored campaign; `qualified_page_view` fires once per qualified land. 2. **Land with no params:** events still fire; campaign ids empty/absent per spec; no throw. 3. **Last-touch update:** second land with a different campaign updates last-touch only; first-touch unchanged until TTL. 4. **TTL:** stored touches expire at ≤30d; documented. 5. **Quote:** `quote_requested` on swap quote (success, empty route, LCD error) with bucketed amount. 6. **Wallet:** started / succeeded / cancelled / failed connect; no address in payload. 7. **Tx happy path** on swap, limit/book, wrap, UST1, create-token, create-pair (if in dApp): sign → broadcast → success with matching `txhash`. 8. **Tx fail paths:** user reject sign, broadcast error, confirm timeout/fail — `tx_failed` with normalized stage; no fake success. 9. **Share:** started/completed and cancel/failure; shared URL remains canonical (no forced UTM pollution). 10. **Dark flag:** env unset ⇒ zero network beacons. 11. **Dev/sim wallet:** no prod sink. 12. **CSP:** production build connect-src includes the sink and still blocks arbitrary analytics hosts. 13. **Join:** one real or captured txhash exists in `protocol_fee_events`. 14. **Surfaces without quote/share:** events that do not apply are omitted, not stubbed with dummy pair ids. --- ## Test plan: attack, hack, and abuse vectors | Vector | Expected result | |---|---| | Hostile `campaign_id` / UTM (XSS, huge strings, unknown keys) | Sanitize length/charset; drop unknown keys; never echo raw query into DOM or logs | | Campaign spoofing / last-touch hijack | Treated as descriptive only; server allowlist/taxonomy if sink exists; first-touch preferred for “source of land” | | Fake `tx_succeeded` without chain confirm | Emit only after confirmed phase / successful mutation; marketing join still requires indexer row | | Wallet leakage in props, share text, or WC logs | Redact; tests fail if `terra1`/`0x` address appears in analytics payload | | Bot / self-traffic / Simulated Wallet | Dev gate; reporting-side exclusions later; client must not special-case production wallets | | Analytics sink SSRF / open beacon | Fixed allowlisted URL from env; no user-controlled sink host | | CSP / supply-chain (adding gtag/PostHog) | Default is first-party beacon only; vendor requires explicit review | | localStorage tampering | Corrupt JSON ignored; no throw; no privilege gain | | Share amplification of organic links | Do not claim last-touch from canonical shares without campaign | --- ## Verification criteria - Unit tests for capture-before-canonicalize, TTL, sanitization, and payload schema (no wallet, bucketed amounts, txhash present on success). - Hook tests for wallet and `useTerraBroadcastMutation` phase mapping. - Playwright or equivalent: land with UTMs → connect (sim or stub) → swap (stub broadcast) → `tx_succeeded` payload still has first-touch campaign id after URL rewrite. - Production CSP snapshot includes only the approved sink. - Manual: one staging/mainnet txhash equals an indexer fee/success row. - Docs/PR links the marketing event contract and states indexer is fee truth. - `make` / existing frontend verify targets still pass; indexer tests untouched.
PlasticDigits changed title from Intake request — DEX client source-to-fee instrumentation (Phase 0 S1) From: Ma to feat(frontend): privacy-reviewed source-to-fee product events (Phase 0 S1) 2026-09-04 04:03:51 +00:00
Author
Owner

+1; S1 also requires ≥80% coverage of non-excluded successful trades on instrumented surfaces (join tx_succeeded.txhash to indexer fee rows).

+1; S1 also requires ≥80% coverage of non-excluded successful trades on instrumented surfaces (join tx_succeeded.txhash to indexer fee rows).

Privacy DoR (enqueue / ship hold) — Privacy policy alignment

Not legal advice. Gap IDs: G1 (block), G3 (high). Forwarded via Market sensor to Ops Sensor as enqueue hold.

Must be true before enqueue claims “ready” / before ship:

  1. Privacy Notice published (or a founder/counsel-approved interim notice linked from dex) that names S1 client-event collection, purposes, retention, and destinations. T&Cs-only is not enough (G1).
  2. Event schema written (names, fields, PII/pseudonym classes) with explicit no raw wallets to third-party vendors (product rule).
  3. Destinations listed: first-party only vs any third party; if any 3P, disclose in notice and get founder/counsel sign-off before enqueue.
  4. Opt-out / refuse decision recorded by founder: required or not; if UI offers refuse, processing must actually stop or down-scope (consent ≠ decoration).
  5. Founder “no analytics on dex today” remains true until (1)+(4) land — do not ship measurement IDs / SDKs ahead of notice.
  6. Redaction test plan: sample payloads show wallets absent or irreversibly redacted before any vendor hop.

Nice-to-have (not ship-blockers alone): align with bridge storage-consent schema (cl8y-bridge-monorepo#165) if S1 shares the same consent record; document retention/deletion owner.

Not blocked on PlasticDigits/cl8y-agent-control#65 (that issue is work-queue ranking research, not privacy).

## Privacy DoR (enqueue / ship hold) — Privacy policy alignment Not legal advice. Gap IDs: **G1** (block), **G3** (high). Forwarded via Market sensor to Ops Sensor as enqueue hold. **Must be true before enqueue claims “ready” / before ship:** 1. **Privacy Notice published** (or a founder/counsel-approved interim notice linked from dex) that names S1 client-event collection, purposes, retention, and destinations. T&Cs-only is not enough (G1). 2. **Event schema written** (names, fields, PII/pseudonym classes) with explicit **no raw wallets to third-party vendors** (product rule). 3. **Destinations listed:** first-party only vs any third party; if any 3P, disclose in notice and get founder/counsel sign-off before enqueue. 4. **Opt-out / refuse decision recorded** by founder: required or not; if UI offers refuse, processing must actually stop or down-scope (consent ≠ decoration). 5. **Founder “no analytics on dex today” remains true** until (1)+(4) land — do not ship measurement IDs / SDKs ahead of notice. 6. **Redaction test plan:** sample payloads show wallets absent or irreversibly redacted before any vendor hop. **Nice-to-have (not ship-blockers alone):** align with bridge storage-consent schema (cl8y-bridge-monorepo#165) if S1 shares the same consent record; document retention/deletion owner. **Not blocked on** PlasticDigits/cl8y-agent-control#65 (that issue is work-queue ranking research, not privacy).

DRAFT — DoR items 2 / 3 / 6 (schema · destinations · redaction)

Status: DRAFT — not ship approval / not legal advice. For founder/counsel + eng review. Full stub kept by Privacy policy alignment; Market sensor may send event-name deltas after field inventory.

2 — Event schema (field classes)

Aligned with source-to-fee-instrumentation (names provisional until eng finalizes):

Event Allowed Never to 3P
qualified_page_view route, referrer_class, campaign_id, cl8y_intent, device_class, session_id raw wallet, email, X handle, IP-as-stable-id
wallet_connect_started / succeeded wallet_type, actor_key_pseudo, session_id raw wallet address to vendors
tx_broadcast / tx_succeeded / tx_failed campaign_id (+ first/last touch), txhash, session_id, outcome raw wallet to vendors

actor_key_pseudo = first-party irreversible / session key — not the on-chain address in cleartext to third parties. Campaign persistence: first-party ≤30d TTL (plan rec); disclose when Privacy Notice (G1) ships.

3 — Destinations

Destination Class Rule
Coolify / marketing Postgres / marketing API (when built) 1P Preferred for S1 receipts
Indexer 1P fee authority Join via txhash; not a marketing vendor
PostHog / GA / etc. 3P — not approved today Founder: no analytics SDK on dex; do not add without Notice + counsel
WalletConnect / Coinbase CCA 3P product stack Separate from S1; do not piggyback wallets onto these

Any proposed 3P hop for S1 payloads → stop for founder/counsel + Notice update before enqueue.

6 — Redaction tests (sketches)

  1. No analytics SDK / measurement IDs in dex bundle.
  2. Network: no S1 POSTs off allowlisted 1P hosts.
  3. Golden payloads: no cleartext wallets toward 3P; actor_key_pseudo ≠ raw address.
  4. tx_succeeded carries campaign_id + txhash for indexer join without wallet on marketing hop.
  5. If founder requires refuse: must stop/down-scope S1 (pair with bridge#165 consent record if shared).

Still founder-gated: G1 Privacy Notice; DoR 4 opt-out decision.

## DRAFT — DoR items 2 / 3 / 6 (schema · destinations · redaction) **Status: DRAFT — not ship approval / not legal advice.** For founder/counsel + eng review. Full stub kept by Privacy policy alignment; Market sensor may send event-name deltas after field inventory. ### 2 — Event schema (field classes) Aligned with `source-to-fee-instrumentation` (names provisional until eng finalizes): | Event | Allowed | Never to 3P | |---|---|---| | `qualified_page_view` | route, referrer_class, campaign_id, cl8y_intent, device_class, session_id | raw wallet, email, X handle, IP-as-stable-id | | `wallet_connect_started` / `succeeded` | wallet_type, actor_key_pseudo, session_id | raw wallet address to vendors | | `tx_broadcast` / `tx_succeeded` / `tx_failed` | campaign_id (+ first/last touch), txhash, session_id, outcome | raw wallet to vendors | `actor_key_pseudo` = first-party irreversible / session key — **not** the on-chain address in cleartext to third parties. Campaign persistence: first-party ≤30d TTL (plan rec); disclose when Privacy Notice (G1) ships. ### 3 — Destinations | Destination | Class | Rule | |---|---|---| | Coolify / marketing Postgres / marketing API (when built) | **1P** | Preferred for S1 receipts | | Indexer | **1P fee authority** | Join via txhash; not a marketing vendor | | PostHog / GA / etc. | **3P — not approved today** | Founder: no analytics SDK on dex; do not add without Notice + counsel | | WalletConnect / Coinbase CCA | **3P product stack** | Separate from S1; do not piggyback wallets onto these | Any proposed **3P** hop for S1 payloads → stop for founder/counsel + Notice update before enqueue. ### 6 — Redaction tests (sketches) 1. No analytics SDK / measurement IDs in dex bundle. 2. Network: no S1 POSTs off allowlisted 1P hosts. 3. Golden payloads: no cleartext wallets toward 3P; `actor_key_pseudo` ≠ raw address. 4. `tx_succeeded` carries campaign_id + txhash for indexer join without wallet on marketing hop. 5. If founder requires refuse: must stop/down-scope S1 (pair with bridge#165 consent record if shared). **Still founder-gated:** G1 Privacy Notice; DoR 4 opt-out decision.

DRAFT delta — DoR 2 fuller S1 table (Market sensor inventory)

Status: DRAFT — not ship approval / not legal advice. Eng may trim event names. Supersedes the shorter event list in the prior DoR 2/3/6 draft comment for schema rows only; destinations + redaction sketches still apply.

Events (source-to-fee + OS; don’t invent beyond this)

Event Fields
qualified_page_view route, referrer_class, campaign_id, cl8y_intent, device_class + session_id
quote_requested action, pair_or_route, route_mode, amount_bucket, latency_ms, outcome + session_id, quote_id
wallet_connect_started wallet_type + session_id
wallet_connect_succeeded wallet_type, actor_key_pseudo + session_id
tx_sign_prompted action, pair_or_route, quote_id + session_id
tx_broadcast / tx_succeeded action, pair_or_route, txhash, first/last campaign_id + txhash join
tx_failed action, stage, reason_normalized + session_id
share_started / share_completed object_type, channel_if_known + session_id

Cross-cut: utm_*, cl8y_intent, campaign_id ≤30d, session_id, actor_key_pseudo. Amounts bucketed. No raw wallets to third parties.

Destination preference: first-party VITE_ANALYTICS_ENDPOINT / Coolify Postgres; indexer is fee-truth join only.

DoR 4 (opt-out): still OPEN — founder skipped opt-out widget; do not assume an answer.

## DRAFT delta — DoR 2 fuller S1 table (Market sensor inventory) **Status: DRAFT — not ship approval / not legal advice.** Eng may trim event names. Supersedes the shorter event list in the prior DoR 2/3/6 draft comment for **schema rows only**; destinations + redaction sketches still apply. ### Events (source-to-fee + OS; don’t invent beyond this) | Event | Fields | |---|---| | `qualified_page_view` | route, referrer_class, campaign_id, cl8y_intent, device_class + session_id | | `quote_requested` | action, pair_or_route, route_mode, amount_bucket, latency_ms, outcome + session_id, quote_id | | `wallet_connect_started` | wallet_type + session_id | | `wallet_connect_succeeded` | wallet_type, actor_key_pseudo + session_id | | `tx_sign_prompted` | action, pair_or_route, quote_id + session_id | | `tx_broadcast` / `tx_succeeded` | action, pair_or_route, txhash, first/last campaign_id + txhash join | | `tx_failed` | action, stage, reason_normalized + session_id | | `share_started` / `share_completed` | object_type, channel_if_known + session_id | **Cross-cut:** `utm_*`, `cl8y_intent`, `campaign_id` ≤30d, `session_id`, `actor_key_pseudo`. Amounts **bucketed**. **No raw wallets to third parties.** **Destination preference:** first-party `VITE_ANALYTICS_ENDPOINT` / Coolify Postgres; indexer is fee-truth join only. **DoR 4 (opt-out):** still **OPEN** — founder skipped opt-out widget; do not assume an answer.

DRAFT delta — fuller S1 event set (Market sensor)

Status: DRAFT — complements comment 44486; not ship approval. Canonical: PlasticDigits/cl8y-marketing/strategy/source-to-fee-instrumentation.md.

Also include (provisional until eng finalizes):

Event Required (class) Join
quote_requested action, pair_or_route, route_mode, amount_bucket, latency_ms, outcome session_id, quote_id
tx_sign_prompted action, pair_or_route, quote_id session_id
share_started / share_completed object_type, channel_if_known session_id

Same rules as 44486: amounts bucketed; no raw wallets to 3P; actor_key_pseudo first-party only; 1P sink preferred; indexer = txhash fee-truth join only.

Still open: G1 Privacy Notice; DoR 4 opt-out (founder skipped widget — no assumed answer).

## DRAFT delta — fuller S1 event set (Market sensor) **Status: DRAFT** — complements comment 44486; not ship approval. Canonical: `PlasticDigits/cl8y-marketing/strategy/source-to-fee-instrumentation.md`. Also include (provisional until eng finalizes): | Event | Required (class) | Join | |---|---|---| | `quote_requested` | action, pair_or_route, route_mode, amount_bucket, latency_ms, outcome | session_id, quote_id | | `tx_sign_prompted` | action, pair_or_route, quote_id | session_id | | `share_started` / `share_completed` | object_type, channel_if_known | session_id | Same rules as 44486: amounts bucketed; no raw wallets to 3P; `actor_key_pseudo` first-party only; 1P sink preferred; indexer = txhash fee-truth join only. **Still open:** G1 Privacy Notice; DoR 4 opt-out (founder skipped widget — no assumed answer).
Member

HOLD: privacy DoR / legal#35 — Market+ops overnight hold

HOLD: privacy DoR / legal#35 — Market+ops overnight hold
Member

Overnight privacy/#1202 security note (2026-09-06)

Private dual-pass audit filed under ops-worker/cl8y-security-audits → 2026-09-06/cl8y-dex-terraclassic-privacy-1202/ (ops-sensor mirror of kimi-k3-max + grok-4.6-high).

HOLD respected — no implement, no ready. Top process High: do not ship client product events until destinations + redaction DoR signed (campaign_id/txhash linkability, sink allowlist, no secrets in payloads). Formal kimi security pass when HOLD lifts.

## Overnight privacy/#1202 security note (2026-09-06) Private dual-pass audit filed under `ops-worker/cl8y-security-audits` → `2026-09-06/cl8y-dex-terraclassic-privacy-1202/` (ops-sensor mirror of kimi-k3-max + grok-4.6-high). **HOLD respected** — no implement, no `ready`. Top process High: do not ship client product events until destinations + redaction DoR signed (campaign_id/txhash linkability, sink allowlist, no secrets in payloads). Formal kimi security pass when HOLD lifts.
Author
Owner

S1 opt-out operator card on cl8y-pm /inbox was failed (“Could not understand the issue”). That was this engineering ticket, not a missing DEX AC.

A replacement phone card is queued: pick required (opt-out before product events go live) or not_required (events may go live without an opt-out widget). Completing that card is the unlock; it is not implement work on this issue.

S1 opt-out operator card on cl8y-pm `/inbox` was failed (“Could not understand the issue”). That was this engineering ticket, not a missing DEX AC. A replacement phone card is queued: pick **required** (opt-out before product events go live) or **not_required** (events may go live without an opt-out widget). Completing that card is the unlock; it is not implement work on this issue.
Author
Owner

Operator S1 decision on cl8y-pm /inbox: required. Ship an opt-out control before DEX product events go live. This is the unlock, not implement work on this ticket.

Operator S1 decision on cl8y-pm /inbox: **required**. Ship an opt-out control before DEX product events go live. This is the unlock, not implement work on this ticket.
Sign in to join this conversation.
No milestone
No project
No assignees
4 participants
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#1202
No description provided.