bug(swap): investigate native LUNC to USTR impact and reconcile route costs #1483
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#1483
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 scope
Investigate the remaining high-impact warning on native LUNC → cLUNC → UST1 → USTR after the quote/gas changes in #1481 and #1482. An anonymized mobile report shows approximately 13% impact and a second-click confirmation. This is a reported pricing/clarity concern, not proof that the warning or quote is mathematically wrong.
Post-deployment feedback indicates improvements on CL8Y→USTR, CL8Y→USTC, USTC→USTR, CL8Y→UST1 and UST1→USTR. These are qualitative control observations, not funded execution or complete wallet acceptance. Original pay amount, selected protection, quote generation/time, wallet/app version and frontend artifact are unavailable. Do not infer the original input from the receive or fee display.
Only technical findings and independently selected public test inputs are published here. No conversation, screenshot, reporter name/identifier, wallet balance, actor address or reporter-linked transaction history is included.
Bundle native impact attribution, reference verification, bounded route comparison and consistent retail explanation in this issue. Keep gas-family calibration/device inspection in #1480, independent small-market reference integrity in #1479, and external-DEX integration/design in #1330. This issue does not require adding a third-party DEX or multi-path splitting.
Current codebase
Source reviewed:
d65228c2970a1ec7b11d81000d3f83ceb58132c4. Public backend/health.git_shabefore/after the investigation:0395459971312c31f87d502ef7822733a7250238, the application revision documented by #1482. Backend health is not independent attestation of the reporter's frontend, wallet or contract artifact.indexer/src/api/local_quote.rsevaluates checked, amount-specific net pool/book returns, fees, taxes and hooks from scheduled cached observations. Candidates use independently qualified reference inputs;slippage_percentis symmetric fair-reference deviation:100 × abs(fair − delivered_net) / max(fair, delivered_net). It flags both worse and suspiciously better results. It is neither the selected tolerance nor exclusively AMM size impact.final_responsecompares delivered output with the fair value of authorized gross native input, retaining wrap/unwrap losses. Using a fee-reduced reference to erase wrapper costs would weaken the ≥99% guard.local_wrapper_quote.rsobserves mapping/configuration independently and applies exact integer wrap/unwrap fees, limits and taxes.local_reference_quote.rsbinds asset identities, decimals, provenance and original freshness; scheduled hub prices/economic marks/quorum/census now use one read-only repeatable-read snapshot. Economic total-TVL floor is $10; independent hub priced-leg depth remains $100. Existing economic marks are spot-derived; the lower reporting floor does not certify an independent token oracle.SwapPage.tsxandTradeMarketOrderPanel.tsxprefer route-level deviation.SwapImpactAside.tsxlabels that figure “Price impact”. The same metric drives >5% confirmation, >30% Expert and nonwaivable ≥99% protection. The UI does not give an independently reconciled explanation of wrapper costs, trading fees, size impact and reference/spot divergence.offlineSwapBudget.tsuses generic legacy/v1 family budgets; fee display, Max, native reserve and signing share the plan. A legacy two-hop route plus wrap uses800,000 + 2×2,400,000 + 400,000 + 400,000 = 6,400,000gas; at 28.325 uluna/gas that is 181.28 LUNC. This identifies a current estimate class, not the original signed gas. Network fee is separate from the quoted fair-output deviation and is not a remedy for a price warning.Investigation: public read-only observations
On 2026-10-12 UTC, bounded anonymous GET
/api/v1/route/solveprobes used exact raw amounts,pool_only=truefor native and matching cLUNC controls,max_spread=0.05,protection_policy=quote_relative_v1, and no trader/sender, signing or broadcast. Reference percentages were independently recalculated from published fair/net raw integers; executable shape, original expiry and positive quote-relative floors passed client validation. There were 31 bounded health/quote reads plus one hop-detail quote, paced between cases. Observations are sequential, not an atomic cross-request reserve/reference cohort.For each matched-credit comparison, native and cLUNC quotes returned identical net raw output and 5% minimum receive. Wrapping retained 98% of gross input in this observed configuration. The 4,000 input is a new test case, not a reconstruction of the original reported input. Similar magnitude was observed, not an exact historical reproduction.
A further 4,000-LUNC quote reported 13.0061% with these published hop scalars:
This points to the first pool leg as the dominant observed size-dependent component. These are quote-derived diagnostics, not independent same-cohort reserve/contract attestation. Per-hop percentages have different bases and must not simply be added to the route percentage; wrapper fees, compounded trading costs and reference/spot divergence must reconcile in common units.
Other controls returned validated HTTP200 quotes: CL8Y0.1→USTR (~5.0184%), USTC1→USTR (~5.4898%), CL8Y0.1→UST1 (~3.2769%) and UST1 1→USTR (~1.8048%). CL8Y0.1→native USTC and USTR1/10→native LUNC returned typed
422 unsupported_semanticsin this anonymous scope. Those results do not establish a new regression or reproduce the original successful control contexts. Unsupported native-output capabilities must stay explicit.solve/bestat 1,000/10,000 LUNC returned the same net amounts as the earliersolvesamples. Their percentages differed slightly at different request times; same-generation equivalence was not established, so this is not claimed as an endpoint inconsistency or proof of unrestricted optimality.Why implementation is needed
The remaining gap is actionable attribution and verified route/reference quality. A trader sees a high aggregate “Price impact” figure but cannot distinguish unavoidable wrapper/trading costs, amount-dependent reserve movement, reference/spot divergence or a genuinely inferior selected route. Gas improvements cannot answer that question, and positive qualitative feedback cannot establish it either.
Implement generic, bounded economic attribution and a compact truthful explanation. Correct amount math, reference admission or route selection only if independently pinned evidence proves an error. If the warning is legitimate, preserve it and explain the dominant constraint; any better route must actually be executable and deliver more net output for the same authorized input. Do not manufacture a lower percentage as the acceptance target.
Relevant files
indexer/src/api/local_quote.rs,local_quote/protection.rs,local_quote/diagnostics.rs,local_quote/skeletons.rs,local_quote/reverse.rs: composition, candidate ranking, ceilings/floors, rejection and bounded alternatives.indexer/src/api/local_reference_quote.rs,local_wrapper_quote.rs,local_hook_pricing.rs,route_slippage.rs;indexer/src/indexer/hub_usd.rs,economic_usd.rs,oracle.rs;indexer/src/db/queries/hub_prices.rs: original-time references, source quality and wrapper/economic observations.frontend-dapp/src/pages/SwapPage.tsx,components/swap/SwapImpactAside.tsx,SwapPreSubmitSummary.tsx,components/trade/TradeMarketOrderPanel.tsx;utils/swapRouteSlippage.ts,slippageConstraint.ts,localRouteQuote.ts,swapPayAcquireGuidance.ts: consistent value/copy, review and signing gates.frontend-dapp/src/services/terraclassic/offlineSwapBudget.ts,swapNetworkFee.ts,router.ts,terraBroadcast.ts: preserve reviewed execution plan and separation of gas from price protection.indexer/tests/route_local_quotes_1452.rs,api_route_solve.rs,api_route_exact_output.rs,reference_cohort_1479.rs;frontend-dapp/src/utils/swapRouteSlippage.test.ts, actual Swap/Trade tests;scripts/qa/probe-issue-1473.py,browser-live-trading-quotes-1473.cjs.docs/route-solver.md,docs/frontend.md,docs/indexer-invariants.md,docs/qa/issue-1479,docs/qa/issue-1480; applicableskills/AGENTS_LOCAL_SWAP_QUOTES.md,AGENTS_TRADING_QUOTE_OUTCOMES.md,AGENTS_SMALL_MARKET_REFERENCE.md,AGENTS_OFFLINE_SWAP_BUDGET.md,AGENTS_ORACLE_SAFETY.md,AGENTS_NET_EXECUTION_FLOORS.md.Recommended direction
solve,best, POST and supported receive sizing within existing work limits. Retain amount-specific net-output ranking; do not prioritize a route solely by a smaller displayed percentage. Native paths remain pool-only; compare wrapped hybrid routes separately.Constraints and guardrails
Acceptance criteria
./skills/agent guidance. State remaining protocol, reference, wallet and verification limits; do not equate source tests or a quote HTTP200 with production settlement.Test plan: supported, boundary and failure paths
Test plan: attack, hack and abuse vectors
Investigation verification and implementation verification criteria
Executed source checks during filing: native wrapper/fair-reference ≥99% regression 1/1 passed; route-slippage symmetric/reference arithmetic 3/3 passed; frontend route metric/protection/copy 24/24 passed. An earlier invocation matched only two frontend files (17 tests); it was corrected to the actual
src/utils/swapRouteSlippage.test.tspath before claiming coverage. No code changes, production signing, broadcast, DB mutation or deployment was performed for this report.These checks and public quote-derived hop ratios do not independently prove original reserves, reference provenance, optimality, physical wallet behavior or funded native settlement. The original ~13% report is not independently reproduced because its amount/context/artifact were not available. Private original atomic SQL and full device/contract evidence remain unavailable as documented in #1479/#1480, and no missing credential is bypassed to fabricate acceptance.
Implementation must run
make verify-issue-1452,verify-issue-1473,verify-issue-1479,verify-issue-1480and applicable1464,1453,1391,1398,1381,1390,1396checks with current checksums/source and owned isolated DB/chain fixtures. Add meaningful independent attribution/ranking/actual-entry tests, then fix failures, reset only owned affected fixtures and retest stable final source. Use separate revision/artifact attestation, bounded public probes/browser shards and classified Grafana/Loki/Prometheus evidence where provisioned. Keep initialized 500ms socket / temporary 750ms browser criteria, per-run resource caps and original measurement clocks.Record UTC, exact source/deployment/tool/artifact revisions, scope, counts, p50/p95/p99/max, expected raw economics and failures/skips separately. Complete feasible checks first. Unavailable workflow/device/SQL/deployment tasks may be explicit SKIP but never complete an acceptance box; an executed failure remains FAIL. Human-only wallet/keyring/device actions belong in cl8y-pm, one action/card with at most five taps (reuse the existing fee-review card where applicable). Leave this issue open until every body/comment acceptance criterion has evidence.
PR #1484 merged normally to
db46e30a5011ee4cbd1998c1c97a34d966b07003. Hosted pipelines 427 and 428 genuinely passed every mandatory job; no status fabrication, branch-protection change or forced merge was used. Both Coolify applications finished deploying that revision, with zero fatal build-log matches, and the independent backend/frontend/root attestation passed.Implemented generic signed raw-output attribution and exact 5/30/99 thresholds, plus review-bound confirmation in both entry flows. A pinned regression proved that deeper search discarded a strictly better route below a 0.1% improvement cutoff; 997,000 → 997,498 raw now publishes correctly on the same cohort. Exact-amount cache keys already isolate small and large inputs; executable quotes are never linearly scaled.
Completed verification subsets:
A retail-copy audit found overlapping notices, technical terminology and speculative warning text. A follow-up is consolidating the actual blocker/confirmation into one concise notice, moving ordinary quote details into existing signing details and preserving every execution gate and required risk acknowledgement. Sustained deployed API/UI checks and bounded monitoring receipts follow; no production reserve/book/database state was reset.
The warning follow-up PR #1485 and verification correction PR #1488 are merged and deployed. Final main, frontend and backend revision:
4cb5736574072130e8e14a5ea2e297d3062e8212. Hosted CI 432 and 437 passed their mandatory jobs before normal merges. The worktree and local main include origin/main; existing unrelated local files were preserved.Swap and Trade now say Price difference. Ordinary ≤5% information stays in existing Signing details; larger differences use one short factual notice with the required confirmation. Only the highest-priority current operational blocker is shown, while all independent execution guards remain enforced. Missing advisory breakdowns and disconnected-wallet balance checks no longer generate notices. Inline failures are not repeated in a toast. Exact 5/30/99 thresholds, Expert/risk acknowledgement, original context/expiry, fee review and unknown/included transaction handling remain intact. Unsupported advice to reduce the amount or increase tolerance was removed from price-protection errors.
The original implementation #1484 adds bounded signed raw-output attribution and fixes the deeper search's undocumented 0.1% publication cutoff: the pinned same-cohort 997,000 → 997,498 raw improvement now wins. Exact amount/generation cache keys already isolate small and large inputs; executable quotes are not scaled from a small cached quote. No external DEX, route splitting, new reference-quality class or quote-triggered RPC was introduced.
Completed verification subsets:
make verify-issue-148321 PASS, 0 FAIL, 2 external acceptance SKIPs per round; 286 focused frontend tests each. Full frontend 3,365 tests passed twice. Related required verifiers and owned settlement/rollback subsets are documented in RESULTS.md. Earlier failures are retained with their fixes/retests.wrwkq60kzrrscprdprawvkuqand backendqpdhhugwf0vo8c0lm4eejgkhfinished at the exact final revision. Build-log entries: 59/57; zero fatal-pattern matches. Independent backend/deployment/root attestation passed. Every external root script is covered, including both bootstrap files; the original incomplete checker failure is retained.658a262e90adad54dcedbe9637818e5c679f9fe6ca5cc2d4f7d4d704953a6276../skills/crosslinks updated. The issue body now checks this criterion only.Initialized useful timings, milliseconds (browser nearest-rank quantiles):
Bounded Grafana/Loki monitoring on logs.cl8y.com, 01:41:00–01:46:39 UTC: all 12 frontend error-pattern matches were HTTP200 access entries; no nginx error/404/5xx matches. Eight indexer matches comprise five 503 traces, one 502 response trace and two LCD admission/fee-registry failure entries. No panic/database/integrity matches were observed. The fee-registry health probe subsequently returned configured=true, healthy=true and zero consecutive LCD failures. These observations are retained; passing quote cases do not establish universal provider readiness. Prometheus is SKIP: no datasource provisioned; provider/history follow-up remains in #1464/#1456.
Remaining full acceptance:
bf7eda77-d1e4-4658-ab6e-69d97088669d, in the inbox. Its exact-revision copy-paste preparation command uses scoped OpenBao credentials without printing them; the helper passed read-only preparation at final main. One deliberate submit/no resend remains human work. The API rejected the direct DEX link with HTTP400; the card uses existing PM tracking #143 and includes this DEX issue URL. Existing mobile fee-review cardf2041acd-86a0-4a86-9b90-469196638b90is reused for #1480; no duplicate was created.Issue #1483 remains open. Full device/gas acceptance stays in #1480, independent reference integrity in #1479, and external-DEX design in #1330. No production reserve/book/database reset or automatic transaction resend was performed. Use the agent checklist and RC1483 invariants for follow-up.
New confirmed automatic-ranking regression is tracked in #1489. At the deployed
4cb57365revision, independently selected 10,000 LUNC input returned 63.386134401366040994 USTR automatically, while the existing three-pool-hop quote endpoint returned 84.600140035321497618 USTR through cUSTC on matching generation/reference/observation/expiry and exact gross/credit. This is 33.467896% more net output; normal promotion is intermittent. The existing four-hop cap already permits the route.The follow-up bundles generation dependency scope, deeper-job retry/fairness, bounded path discovery, native progress intent and truthful selected-route copy. Existing #1483 source verification again passed 21 groups with two acceptance skips, but does not cover the live failure under producer churn/contention. The live automatic-ranking counterexample remains FAIL. No source changes, signing or production reset were performed in this investigation; #1483 remains open.
PlasticDigits referenced this issue2026-10-15 05:32:59 +00:00
Closed at the user's request as part of consolidating issues #1449–#1500.
Amount-specific ranking and signed cost attribution are implemented, with the revised separate slippage/fee presentation delivered by #1501. Actual native recovery and protected wrapper rollout move to #1504.
Replacement: #1504
Wallet/device chores and verification-only holds are intentionally excluded. Historical failed receipts remain unchanged; this closure does not claim every old acceptance checkbox passed.
The 2026-10-15 repository reconciliation recovered the remaining local branch history and inspected the stale worktrees/stash. The browser lifecycle and execution-readiness merge commits introduce no new product changes relative to current main; newer policies and issue links are retained. The route-discovery stash is already incorporated by
1536631292and subsequent actor-inventory safety corrections, so the stale snapshot was not reapplied.Four differing historical QA records are preserved separately in docs/qa/merge-reconciliation-2026-10-15/recovered, with provenance/checksums in recovery-manifest.json. Current canonical receipts and artifact checksum lists remain in place. Private ignored configuration/artifacts and original recovery files were saved outside Git before the merged worktrees/branches/stash were removed. No production or shared database was reset, and no deployment/settlement claims are added. This completed implementation issue remains closed; outstanding live implementation work stays in its existing follow-up issues.
Final local verifiers passed: #1489 = 20 PASS / 0 FAIL / 2 explicit acceptance SKIP; #1483 = 21 PASS / 0 FAIL / 2 explicit acceptance SKIP. The first runs retained stale-database PoolTimedOut failures; complete reruns on a fresh owned fixture passed. The fixture was removed afterward. CI was explicitly skipped; details are in docs/qa/merge-reconciliation-2026-10-15/verification.json.