fix(indexer): quote swaps under 250 ms from cached liquidity with zero request-triggered RPC #1452
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#1452
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem and scope
Fix the swap route-solver regression reported on USTR routes as one implementation: liquidity-aware executable candidate selection, a useful initial quote in strictly less than 250 ms, bounded deeper search, effective caching, and consistent refreshes.
An anonymized report describes CL8Y→USTR and LUNC→USTR being blocked even for small offers. The displayed route used CL8Y→cLUNC→UST1→USTR and showed approximately 67.41% expected slippage alongside the existing 5% protection error. A related report describes small USTC→USTR quotes periodically changing from low slippage to approximately 8% without an amount edit. Slow quotes are also reported. These are related solver symptoms; no conversation, screenshot, identity, wallet, or private transaction history is published here.
Users should get a good route automatically and quickly. They must not have to select intermediates, diagnose pools, or increase protection settings to compensate for the solver.
Architecture requirement: initial quotes, deeper search, refreshes, reference pricing, route preflight and preparation of the reviewed route must use locally cached data. No request-triggered RPC/LCD calls or network validation at any stage. A separately scheduled, bounded indexer ingestion worker maintains reserves, books, configuration and prices; requests must not start extra chain polling. On-chain execution enforces signed floors against actual settlement.
Current codebase and investigation
Reviewed revision:
b26b762c4a870251d780715eac6eea4e2db5c14e. Read-only public production probes: 2026-10-09 UTC.route_paths.rsenumerates simple paths by hop count, then lexicographic pair address.best_execution.rsenumerates at most 32 structural paths and evaluates the first five usable candidates. Its cheap admission filter principally removes zero-output, implausible, and near-full-drain paths; it does not prioritize useful amount-specific depth. LCD mode takes the first five structural candidates. Final selection maximizes executable net output within that restricted set.enrich_route_slippageagain. Reference prices solve one whole token into a quote token using best execution. Quote output, graph, references, tax configuration and wallet validation can represent different observations. An enrichment failure returns early and can leave fields absent or retain fields carried by a cached body; this needs explicit consistency coverage.spot_amount_out, then indexer slippage. Per-hop market-spread preflight is a separate check. Funded high-impact guidance currently suggests pay/10 without proving the resulting trade is executable.Public API observations:
100000000000000000raw, 18 decimals) selected CL8Y→cLUNC→UST1→USTR, returning approximately 9.509154182294578288 USTR. The request took 21.10 s, reported five candidates,global_v6_funded, and passed fidelity on a repeated observation.1000000000000000000raw) selected CL8Y→cUSTC→UST1→USTR, returning approximately 97.707786127357668350 USTR in 9.73 s.spot_amount_outandslippage_percent. They reproduce the thin-route selection and latency concern, but do not reproduce the exact reported 67.41% or 8% figures.Why a new implementation is needed
Waiting 10–30 seconds for a potentially unexecutable thin route is incompatible with retail swapping. A hop-count shortlist can omit deeper routes; output-only selection without execution constraints can choose a route the wallet subsequently blocks. Independently refreshed references and quote caches can cause apparent slippage changes unrelated to the typed amount. Existing caching and fidelity tests do not establish the requested latency or correct constrained route selection.
A good initial result is sufficient; global optimality is not required. Deeper optimization must improve a usable baseline without holding the initial response hostage.
Relevant files
indexer/src/api/route_paths.rs,route_graph.rs,best_execution.rs: enumeration, shortlist, concurrency, validation and winner selection.indexer/src/api/db_orderbook_sim.rs,hybrid_route_opt.rs: reserve/book mirrors, cheap scoring, hybrid plan and execution parity.indexer/src/api/route_solver.rs,route_slippage.rs,route_solve_progress.rs,route_exact_output.rs: response/cache identity, reference calculations, progress and receive sizing.indexer/src/api/community_tax_rank.rs: tax-aware executable net ranking.frontend-dapp/src/services/indexer/client.ts,utils/cw20RouteSolveQuote.ts,utils/directHybridQuote.ts,services/terraclassic/swapRoutePreflight.ts: request constraints and authoritative validation.frontend-dapp/src/pages/SwapPage.tsx,components/trade/TradeMarketOrderPanel.tsx,utils/swapRouteSlippage.ts,utils/swapPayAcquireGuidance.ts: refresh/signing consistency and existing misleading size guidance.docs/route-solver.md,docs/swap-max-spread-ux.md,docs/frontend.md; relevant tests alongside these modules.Recommended direction
Constraints and guardrails
min_return, finalminimum_receive, stale-submit checks, 30% Expert behavior and the non-waivable ≥99% guard. This issue does not authorize weakening economic protections.Acceptance criteria
make verify-issue-<this issue>with performance, selection, caching, refresh and abuse regressions; update current optimality/budget docs and agent guidance.Test plan: functional paths
Use deterministic Rust/DB fixtures and mocked clocks/providers first; run browser integration with controlled network latency and a read-only production reproduction separately. Include a meaningful >5-path quality benchmark and unchanged-snapshot refresh fixture, rather than tests that merely mirror sorting code.
Test plan: attack, hack and abuse
Verification criteria and investigation results
Record revision, UTC timestamp, exact command, meaningful test counts, request/quote generations, cache counters, snapshot identity and latency distributions. Performance evidence must include initial useful output and later improvement timings, not just asynchronous acknowledgement latency. Source checks do not establish deployment.
Completed before filing:
make verify-issue-1398: PASS, 7 verification groups, 0 failures/skips; focused retest, full contract workspace, frontend quote/signing and formatting/docs checks.cargo test --manifest-path indexer/Cargo.toml --lib api::route_paths -- --test-threads=1: 13 passed.api::route_slippage: 3 passed; withapi::best_execution: 9 passed.make verify-issue-1257: FAIL, 3 groups passed/3 failed. Its frontend token-registry test encountered the local CL8Y env override; a correct mainnetVITE_CL8Y_TOKEN_ADDRESSretest of its five frontend suites passed 122/122. The verifier's source grep and route-solver optimality documentation checks still fail; do not report the aggregate verifier green.Unavailable investigation checks do not hold issue creation: direct public LCD smart queries returned HTTP 403, so independent on-chain reserve/path comparison and the exact historical percentages remain unverified. No production signing/device acceptance was attempted. Implementing this issue must add the missing deterministic quality, refresh and <250 ms regressions, then verify the deployed frontend/indexer on the same route corpus. Keep unresolved executed failures visible.
fix(indexer): return cached USTR routes under 250 ms and improve executable route selectionto fix(indexer): quote swaps under 250 ms from cached liquidity with zero request-triggered RPCMerge consolidation in progress at the user's explicit request, including WIP PR #1455. CI is intentionally skipped; unavailable review/status/verification holds are overridden without publishing fabricated PASS statuses.
Integration with #1454 exposed conflicts in
Makefileandindexer/src/lcd/mod.rs. The resolution retains both verifier targets, provider admission/failover and background quote-ingestion pacing/body bounds, with both test modules. Inspection also found that the new local mirror loader still selected independent pool reserves when reading books: a newer pool height could erase a usable compatible book. The combined implementation now retains the separately committed hybrid generation at its original age, and uses current pool-only observations when that hybrid is stale/missing. A disposable-DB regression covers independent pool advancement and original hybrid age.Full focused local verifiers for #1452 and #1453 are running against the combined source. Final counts, revision and remaining implementation scope will follow. This comment does not claim deployment or complete acceptance of the documented unsupported tax/hook/manual-split/wrap modes.
Combined-source sanity results before the explicitly requested WIP merge:
make verify-issue-1452: 13 PASS / 1 FAIL / 0 SKIP. Its first controlled browser passes; the second records one 3,866.9 ms desktop Swap outlier (all cases have zero provider calls and zero page errors). An independent browser retest passes all 40 quotes with a maximum of 100.5 ms. Preserve the failed timing receipt; this retest is not a claim that every run meets the budget.npm run test:unit: 2,948 PASS / 137 FAIL across 357 files (11 failing files). These failures include fixtures still loading the factory instead ofgetAllPairsPaged, expecting LCD/direct-pair quoting/execution or removed acquisition copy.TokenSearchSelectpassed an isolated retest; the acquisition-copy assertion remains failed. The broad suite remains FAIL, not SKIP.make verify-issue-1453: 10 PASS / 2 FAIL / 2 SKIP. Provider/book/valuation/discovery library groups, 73 dedicated liquidity/feed DB tests per pass, 97 frontend tests per pass and four browser checks pass. Both failed groups are the legacyapi_route_solve_db_hybridsuite: 2 PASS / 8 FAIL per pass because its uninitialized old request-time solver fixtures now receive explicit 503 instead of live-fidelity answers. That fixture migration and current local corpus belong here.api_healthassertion: a malformed query withouttoken_inexpects an attestation-driven 503, but the local request parser returns 400 before any RPC. The optional authenticated runtime fixture initially failed because our newly provisioned disposable cluster also granted the runtime access to its application DB; revoking that exact synthetic grant makes both retests pass. No shared/production DB was changed.The user explicitly requested merging WIP and overriding CI/review/verification holds. Executed failures remain recorded as FAIL. This issue remains open for substantive implementation, not verification alone: community-tax forwards, deducting-hook inverse, explicit manual split, zero-hop wrap/unwrap, incremental admission of large configuration populations and complete authoritative actor-inventory recovery remain unfinished. Also migrate the existing route/page/health regression fixtures to the current contract while retaining meaningful URL, decimals, tax, abuse and signing assertions; classify actual product regressions separately rather than deleting tests or relaxing protections.
Deployment/live latency/provider recovery/history reconstruction is tracked in #1456. Existing #1449 continues DeFiLlama deployment/reconciliation. Full source and scoped receipts will be committed under
docs/qa/merge-2026-10-09/.Both #1454 and WIP #1455 are now merged. Local main contains every original local/remote branch head and the resolved integration source; its fingerprint exactly matches the tested source. No stashed work exists. Other workers' three clean worktrees/branches remain intact.
Final source-level problems remain as recorded above; they are not converted to PASS or SKIP. Database isolation verifier ended at 24 PASS / 4 FAIL / 2 SKIP (two obsolete health-fixture failures and two interrupted unavailable published-bridge waits). Separate network retests pass internal bridge TCP/external rejection/host IPv4 confinement with explicit bridge-host/IPv6 skips, and the authenticated runtime-login fixture passes twice after correcting only our synthetic database grant.
#1453 is closed for its merged implementation; migration/deployment/live latency/provider/history work is tracked in #1456. This issue remains open because substantial tax/hook/manual-split/wrap/admission/inventory functionality is unfinished, plus current-contract fixture migration. The final audit-only direct push to protected main was rejected; #1457 publishes that receipt through the normal PR path with the user-authorized merge override. See the complete sanity and cleanup report.
Merge/sanity review of PR #1458 at
53853c9fb5(2026-10-10 UTC): Forgejo reports mergeable and successful ci/woodpecker/pr/woodpecker. No source merge conflict is present.The first broad frontend run executed all 3,097 tests: 3,095 passed and two failed. PairSearchSelect.issue350 pressed Enter after any getPairs call rather than waiting for the JADE search result; SwapPage.extraDebitSell asserted the token-balance message while the initial network-fee blocker was still displayed. Both passed on a focused one-worker retry (5/5 tests). These executed failures are retained; the integration will tighten the asynchronous test waits and rerun the full suite rather than treating them as skips.
The first bao-exec request failed because the cached workstation session had expired. The documented no-print certificate login restored access. fj now consumes the OpenBao PAT through stdin in a temporary private configuration removed after each command; no fetched credential is published.
Issue #1452 is already closed. Remaining unsupported execution semantics from this PR now have engineering follow-up #1459; they are not claimed complete or converted into verification skips. Deployment, live/reference-network/device acceptance and historical/provider reconciliation remain #1456 (DeFiLlama #1449). Per the explicit merge instruction, unavailable workflow holds will not block merging reviewed code; runtime floor, funding, blacklist, expiry and unsupported-model protections remain enforced. Final results and merge revision will follow.
Additional merge sanity finding: strict verification of the existing local smartcontracts/artifacts/build-provenance.json with scripts/ci/build-provenance.py failed (provenance mismatch: source_commit). Its historical revision is
3ba788949a, while review source is #1458 at53853c9f.Independent byte comparisons found all 170 recorded contract source inputs unchanged. Three external build-recipe inputs differ (docker/frontend/Dockerfile, docker/indexer/Dockerfile, scripts/ci/build-indexer-release.sh), and the existing pair/token wasm output hashes differ from this old receipt. Their current hashes do match the tracked checksums.txt. This is insufficient to claim a valid current release provenance receipt; the failed strict check is retained and not converted to PASS. The PR itself changes no contract source.
Before deployment, regenerate/review release artifacts and exact provenance for the final consolidated revision through the normal reproducible build, retaining the historical receipt rather than relabeling it. Track this with the existing build/policy/deployment work in #1456. Local synthetic chain checks can establish behavior of the exact tested checksums separately; source merging does not establish release artifact provenance or production deployment.
Timestamp correction: the earlier merge review comment used the Seoul calendar date (2026-10-10) and incorrectly labelled it UTC. The actual make verify-issue-1452 receipt starts at 2026-10-09T23:12:25Z; canonical verifier/browser/Git receipts use their recorded UTC timestamps. Test outcomes and revisions are unchanged. The final consolidation report will include the exact UTC window.
Merge work complete: #1458 merged normally as
c8b29eb0f7. Three asynchronous frontend assertions were corrected inc923aab0; all 3,097 frontend tests and 999 contract tests pass. The quote verifier passed 14/0/0; all related local verifiers completed with zero failed groups and explicit unavailable skips. Hosted Woodpecker pipeline 377 passed all six required steps for exact headc923aab015.Final consolidation audit retains exact commands, revisions, UTC timestamps, latency samples, historical failed frontend attempts and current skip/failure scope. The interrupted Compose published-loopback probe is retained; its final full verifier passed 28/0/2 using the documented host-bridge/IPv6 skips, while authenticated roles, internal TCP, confinement and ACL checks passed.
The old local optimized-wasm provenance receipt still fails strict verification; regenerate/review release artifacts before deployment under #1456. Current source testing and hosted CI do not erase that failure or establish deployed acceptance. Remaining wrapper-floor, stateful cooldown/AutoLP, uncensused tax-wallet and composed inverse implementation is tracked in #1459. Original #1452/#1453/#1354 were already closed; no issue is held open solely for verification.
Origin rejected direct protected-main publication of the documentation audit. Audit PR #1460 then hit fj HTTP 405 for its pending fresh CI context. The explicitly authorized single-PR force_merge override published these documentation-only receipts; no branch-protection setting changed and no new CI pass is claimed for the audit commit. Product source exactly matches the tested #1458 head.
Local main now matches origin at
736be44410. Both remotes were fetched/pruned; every local/remote branch head is included, with no active stashes or uncommitted work. Four existing worker worktrees/branches are preserved. The owned temporary audit branch and temporary chain/probe resources were removed.PlasticDigits referenced this issue2026-10-10 11:10:08 +00:00