fix(swap): explain fair-reference deviation on native wrap routes and suggest wrapped-token alternative #1579
Labels
No labels
agent:fix_bugfix
agent:fix_conflicts
agent:fix_security
agent:gap_analysis
agent:implement
agent:implement
agent:implement
agent:open_issues
agent:ready
agent:research
agent:security_audit
agent:verify
architecture
backend
blocker:hybrid
blocker:launch
blocker:limit-orders
blocker:v2
block:log_only
block:security
bug
ci
contracts
correctness
deploy
dev
devops
docs
documentation
duplicate
e2e
enhancement
epic
feature
frontend
functional-completion
gas
good first issue
governance
help wanted
high-risk
hooks
hybrid
indexer
infra
infrastructure
integrators
invalid
launch-blocker
limit-orders
localnet
localterra
low priority
missing-implementation
needs-design
ops
performance
priority
high
priority
medium
product
qa
QA
question
ready
ready
research
scripts
security
security-hardening
smartcontracts
tech-debt
testing
ux
UX
v2
verification
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
code/cl8y-dex-terraclassic#1579
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary and reported behavior
An anonymized mobile report shows a native-input Swap route:
USTC → cUSTC → cLUNC → LUNCwith:
Slippage <0.01%Fee 1.76%Fair-reference deviation 11.32%noticeSWAPbutton still availableThe reporter asked why the deviation is so high when displayed slippage is near zero. The expected answer is that this figure is not order slippage: it includes independent-reference divergence, wrapping/unwrapping loss, chain tax and trading costs. The current UI shows only the aggregate percentage, so a legitimate route looks broken or deceptive. A second, related product request was to recommend receiving/holding the wrapped asset (for example
cLUNCinstead ofLUNC) when the notice is caused by native wrap/unwrap costs, because wrapped assets let active traders avoid paying chain tax on every swap.This issue bundles the explanation fix and the wrapped-asset advisory. It does not change the risk thresholds or execution policy.
No reporter identity, conversation, screenshot, wallet address, balance or transaction history is included here. The percentages above are the sanitized technical facts needed to reproduce the UI path.
Current codebase
Source reviewed at
38c154958c9eb27a683a27c8dbaa121ccdb83da6(2026-10-28).The explanation is computed, validated, passed — and dropped
frontend-dapp/src/utils/routeEconomicExplanation.tsvalidates the originaleconomic_attributionschema (version,status,method,generation,observed_at_ms,expires_at_ms,fair_amount_out,net_amount_out, exact four signed components, exact dominant cause) and returns a fixed, allowlisted string such asWrapping costs,Trading costs,Selected pool price movement,Independent reference and selected route spot prices differ,Combined costs and pricing, orMatches reference prices.frontend-dapp/src/utils/cw20RouteSolveQuote.ts:116-135and:248-263attach that string aseconomicExplanationto both wrapper-only and general route quotes, alongsideorderCosts,spotAmountOutandrouteSlippagePercent.frontend-dapp/src/pages/SwapPage.tsx:2102-2115passessimData?.economicExplanationintoSwapImpactAsidefor the higher-risk notice, and:2213-2220passes it again for DETAILS.frontend-dapp/src/components/trade/TradeMarketOrderPanel.tsx:952-956and:1125-1133do the same for the shared Trade market notice and DETAILS.frontend-dapp/src/components/swap/SwapImpactAside.tsx:5-25declareseconomicExplanation?: stringbut never destructures, renders or uses it. OnlyrouteSlippagePctandtradingRiskNotice()are rendered.So the documented compact cause explanation is dead data. The prop is accepted and silently ignored.
The documented contract already requires this behavior
docs/route-solver.md:62-67states:That contract was implemented around the route-cost work in #1483, refined by #1500, and narrowed by #1560. The current component no longer renders the cause, and existing tests do not catch the regression.
SwapImpactAside.test.tsxonly covers percentages, thresholds, confirmation and unavailable evidence.The backend attribution is already sufficient for truthful copy
indexer/src/api/local_quote/attribution.rs:55-105computes signedwrapper_loss,trading_cost,market_movementandreference_divergencein common final-output units. They telescope exactly tofair_amount_out - net_amount_out.indexer/src/api/local_quote/order_economics.rs:61-103maps those components intowrapper_costandreference_divergencefor the order-cost breakdown.indexer/src/api/local_quote.rs:1394-1419computes the independent fair output from authorized gross native input and retains wrapper loss once for native wrap/unwrap routes.frontend-dapp/src/components/swap/RouteOrderCostDetails.tsx:16-35already rendersTrading fees,Tax and hook costs,Wrapping costsandReference price differenceinside DETAILS.The backend can legitimately report a large aggregate for a native-wrap route whose selected pool spot differs from the independent reference and whose unwrap loses chain tax. That is a real economic difference, not an arithmetic failure. The defect is that the user-facing notice does not say so.
The client already has enough information for a wrapped-asset advisory
frontend-dapp/src/types/index.ts:988-995exposesgetWrappedEquivalent/getNativeEquivalent.frontend-dapp/src/utils/constants.ts:143-154mapsuluna → cLUNCanduusd → cUSTC, omitting unconfigured addresses.execution_metadata.wrapperalready distinguisheswrap_inputandunwrap_output, andtoken_in/token_outidentify the requested assets.simData.orderCostsalready separates wrapper cost from reference divergence.No new RPC, quote request, route selection or signing path is needed.
Why the new implementation is needed
<0.01%slippage looks like a defect and invites abandonment to another DEX.cLUNC/cUSTCinside the DEX. The current warning does not surface that option, even though the route context already shows native wrap/unwrap.Recommended direction
1. Render the validated cause inside the existing notice/DETAILS
Use the already-computed
economicExplanationonly when the same quote evidence has passed the existing checks:SwapImpactAsidenotice, add one short static cause clause after the required risk sentence, for example:Fair-reference deviation 11.32%. Mostly wrapping and reference-price difference, not slippage.Keep it to one notice and one live-region announcement.RouteOrderCostDetailsraw cost list. Do not duplicate or re-derive amounts.economicExplanationis unavailable or invalid, render nothing extra. The required risk notice and all gates remain.Do not call the aggregate “slippage”. Use “fair-reference deviation” consistently with the current risk policy, and state that network gas is separate.
2. Add a bounded native-wrap advisory
When the selected quote is a supported native route and the validated cost breakdown shows that
wrapper_lossand/orreference_divergencedominate the aggregate, add a concise informational line, for example:Rules:
getWrappedEquivalent/execution_metadata.wrapper.from/toor the exact input; provide no one-click destructive substitution unless separately reviewed. A plain text hint is sufficient for this issue.3. Preserve the existing risk and accessibility contract
evaluateTradingRisk, exact 5/10/30/99 boundaries andassertTradingRiskForSubmitunchanged.4. Update the contract and tests so this cannot silently regress
docs/route-solver.md,skills/AGENTS_ROUTE_COST_ATTRIBUTION.md,skills/AGENTS_TRADING_RISK.md,skills/AGENTS_ORDER_SLIPPAGE.mdand the relevant QA checklist with the “cause + wrapped alternative” presentation and its advisory-only status.Constraints and guardrails
max_spread, floors, funding or signing.order >5% OR total >10%.Relevant files
Frontend:
frontend-dapp/src/components/swap/SwapImpactAside.tsx— deadeconomicExplanationprop; notice/DETAILS rendering.frontend-dapp/src/components/swap/SwapImpactAside.test.tsx— missing cause/advisory coverage.frontend-dapp/src/components/swap/RouteOrderCostDetails.tsx— existing raw cost breakdown.frontend-dapp/src/pages/SwapPage.tsx— notice and DETAILS wiring.frontend-dapp/src/pages/SwapPage.test.tsx— integration coverage.frontend-dapp/src/components/trade/TradeMarketOrderPanel.tsx— shared Trade notice/DETAILS.frontend-dapp/src/components/trade/__tests__/TradeMarketOrderPanel.submitSnapshot.test.tsx— Trade coverage.frontend-dapp/src/utils/cw20RouteSolveQuote.ts— explanation and cost population.frontend-dapp/src/utils/routeEconomicExplanation.ts— fixed allowlisted cause validator/copy.frontend-dapp/src/utils/routeOrderMetrics.ts— validatedorderCosts.frontend-dapp/src/utils/tradingRisk.ts— must remain unchanged behaviorally.frontend-dapp/src/types/index.ts,frontend-dapp/src/utils/constants.ts— wrapped/native equivalents.frontend-dapp/src/utils/nativeWrapRouteSolve.ts— native wrap route context.Backend reference (no behavior change expected unless a pinned fixture proves a defect):
indexer/src/api/local_quote.rsindexer/src/api/local_quote/attribution.rsindexer/src/api/local_quote/order_economics.rsindexer/src/api/local_reference_quote.rsindexer/tests/scenarios/route_cost_attribution_1483.rsDocs/guidance:
docs/route-solver.mdskills/AGENTS_ROUTE_COST_ATTRIBUTION.mdskills/AGENTS_TRADING_RISK.mdskills/AGENTS_ORDER_SLIPPAGE.mddocs/qa/issue-1483/README.md,docs/qa/issue-1500/README.md,docs/qa/issue-1560/README.mdAcceptance criteria
economicExplanationis rendered in the Swap and Trade price notice and/or DETAILS. The dead prop is either used or removed; no path silently discards it again.Test plan — all paths
Unit / component
SwapImpactAside:wrapper_loss→ renders the cause text once.reference_divergence,trading_cost,market_movement,mixed,Matches reference prices→ renders the matching fixed copy.blocked="expert"andblocked="extreme"→ existing copy/CTA preserved; advisory never replaces the blocker.orderCosts/execution_metadataidentity mismatch → no advisory.RouteOrderCostDetailsremains the single numeric breakdown; no duplicate amounts.Integration
SwapPage.test.tsx: native wrap/unwrap fixture with a large fair-reference deviation and available attribution → cause + advisory; same fixture with unavailable attribution → no advisory; direct route → no advisory.TradeMarketOrderPanel.submitSnapshot.test.tsx: shared notice/DETAILS behavior, consent and Expert paths.Accessibility / visual
Regression / policy
order >5 OR total >10unchanged; equality unchanged.validateWrapperOnlyQuote.Test plan — attack, hack and abuse vectors
economicExplanationstring or HTML → rejected by fixed allowlist and schema binding; rendered only as escaped text.orderCosts,spotAmountOut,estimated_amount_outorexecution_metadata.wrapper→ no cause/advisory; risk evaluator remains unavailable or blocks.assertTradingRiskForSubmitremains the final gate.dangerouslySetInnerHTML.Verification criteria
Run the applicable bounded checks from the repository root:
make verify-issue-1560make verify-issue-1500make verify-issue-1483make verify-issue-1498make verify-issue-1452make verify-issue-630(native ticker display, because the advisory namescLUNC/cUSTC)SwapImpactAside.test.tsx,SwapPage.test.tsx,TradeMarketOrderPanel.submitSnapshot.test.tsx,routeEconomicExplanation.test.ts,routeOrderMetrics.test.tsRecord:
Do not close this issue on source-only evidence. Live acceptance requires a served Swap and Trade path with a native wrap/unwrap route, a validated explanation, the wrapped advisory, unchanged risk behavior, and mobile/assistive checks.
Scope boundaries / cross-links