fix(swap): fund token taxes at route swap points without intermediate wallet debits #1381
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#1381
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
Token identity correction: the taxed intermediate is ALPHA (
terra1x6e64es6yhauhvs3prvpdg2gkqdtfru840wgnhs935x8axr7zxkqzysuxz). Canonical cLUNC is a different contract (terra1437qslye72t7qmmahn4t5chz50r8a62g45phwkquwpyu2l62u6ksqssgdg). The earlier intermediate label was incorrect; the quote, code 11666, tax configuration, and synthetic preview evidence concern ALPHA.CL8Y→USTR can receive a quote for a route that requires extra ALPHA already held in the trader's wallet. The live solver selects CL8Y→ALPHA→UST1→USTR, labels it
tax_kind=none, and reports zero sell tax, while the ALPHA middle-hop contract actually charges a 1% sell extra-debit to the authenticated trader. Tokens acquired by the preceding hop sit on the router, so they do not fund that separate wallet debit. A trader with no ALPHA reserve can therefore hit the existing sell-tax error despite holding enough CL8Y. Reducing CL8Y or tapping CL8Y Max cannot solve a zero balance of the required intermediate asset.This issue bundles contract/router tax funding at swap points, route capability discovery, quote/execute parity, frontend preflight, and recovery messaging for this failure. Permanent acceptance requires supported taxed intermediate routes to work without an intermediate balance in the trader wallet; route exclusion alone is containment. Related closed work: #615, #1267, #1285. Their security checks remain relevant, but their router-hop funding and exclusion expectations must be revised where they conflict with the required behavior below.
Required behavior and scope
Collect configured tax at the affected swap points from this route's own token amounts. Do not debit the trader's separate wallet balance for a routed hop's tax. The trader still bears the economic cost through the quoted exchange result, but needs only the explicitly authorized initial offer and network fees. No pre-existing ALPHA, UST1, or any other intermediate balance is required.
This intentionally replaces the wallet-funded router-hop rule in T592-13 / R607-1 / R607-4 / R607-7, the old R615 middle-hop exclusion as a permanent solution, and the previous blanket H-01 prohibition on router tax sizing to the extent needed for correct local tax funding. Keep the security purpose of 1:1 declared pair credit: the pair must receive exactly the economic amount its swap hook declares. Any change to how gross routed funds are split into pair input and tax requires an explicit, tested protocol/API revision; an inconsistent CW20 credit/hook amount is unacceptable.
A temporary exclusion of genuinely unsupported legacy-tax routes is allowed during rollout. It does not satisfy the permanent fix for migrated, supported community-tax tokens such as ALPHA.
Anonymized report and investigation evidence
The reported symptom is a CL8Y→USTR attempt displaying the application's sell-tax balance error. No reporter identity, wallet address, screenshot, chat quotation, or conversation is published here. The failed transaction hash, input amount, selected route, and deployed bundle version for that attempt are unavailable; the exact reported transaction is not claimed reproduced.
Investigation on 2026-10-04 against current
main3f9310652a, matching the remote main head:Read-only live
GET https://indexer.dex.cl8y.com/api/v1/route/solvewith canonical CL8Y/USTR contract IDs, syntheticamount_in=1000000000000000000(1 CL8Y), andmax_hops=3returned CL8Y→ALPHA→UST1→USTR. It returnedsell_tax_bps=0,buy_tax_bps=0,router_hops_tax=false,tax_kind=none, andfidelity_check=passed. Repeating with an explicit deterministic synthetic trader still returned the ALPHA middle hop,tax_kind=none, zero sell tax, and passed fidelity; a read-only LCD balance query confirmed that synthetic trader held zero ALPHA. These requests did not use a reporter wallet or broadcast anything.LCD contract/config queries identify canonical CL8Y as code 10184, with
get_configrejected as an unsupported query bycw20_mintable. CL8Y itself is not established as a community-tax sell token by this evidence. The selected ALPHA intermediate is code 11666, withsell_bps=100andbuy_bps=450.Execute-aligned read-only ALPHA
TaxPreviewfrom its configured official router to the selected ALPHA/UST1 pair, with a deterministic synthetic non-exempt trader andSwap.trader, returned:These are synthetic raw units.
debitdescribes the router leg; the additionalhop_trader_debitis charged to the trader. Contractapply_transfercallssub_balance(trader, tax)for this case.Live
/api/v1/community-tokensreported catalog code 11630, total 1, containing KENA. ALPHA code 11666 was absent. Catalog attestation requires the configured code ID and launcher/admin provenance; routing currently relies on that catalog for tax discovery.make verify-issue-1285passed, including its 35-test frontend run and the nestedmake verify-issue-126788-test run.cargo test --manifest-path indexer/Cargo.toml --lib community_tax_rank -- --test-threads=1passed all 14 tests, including the catalogued middle-hop exclusion. Passing these tests does not cover a live taxed intermediate absent from the catalog.Three temporary synthetic frontend probes confirmed current behavior: a successful taxed config followed by a failed 503 refetch changes detection to
honest; disabled Create Token configuration prevents swap tax discovery; andextraDebitSubmitGatewith an unknown wallet balance returnsblockSubmit=falseeven with a known positive tax debit. The probes asserted existing behavior and were removed after execution; they are evidence of gaps, not tests proving a fix.A follow-up live identity census queried
token_infoand tax configuration for all 20 distinct CW20 contracts in the indexed asset inventory plus the published token list. ALPHA reportsname=ALPHA Lunc Universe,symbol=ALPHA, code 11666, sell 1%, buy 4.5%. Canonical cLUNC reportsname=Wrapped LUNC,symbol=cLUNC, code 10184 (cw20_mintable), with no community sell tax. Among assets in the current indexed DEX pools, ALPHA is the only positive community-tax sell configuration found; KENA has zero buy/sell/transfer bps. USTRIX and DO, present in the published token list but with no indexed DEX pools, expose different legacy APIs: USTRIXtax_maphas conditional 5% Send tax, and DOtax_infohas address-conditioned default 1.5% Send/Transfer tax plus a sender-specific 20% Send override. An unsupportedget_configalone must not classify every legacy token as tax-free; inspect its actual supported tax API/capability. This census concerns token-level taxes, separately from pool fees and native wrap/unwrap costs.Read-only previews and quote simulations establish the route hazard; they do not establish execution success. No live funds, signatures, migrations, or deployments were used.
Current codebase and why a new implementation is needed
best_execution.rsloads tax metadata for candidate hop assets and appliespath_sells_middle_tax_hop. That predicate only recognizes entries inTaxRankSnapshot.by_addrand an option-2 code/hash policy. Missing rows are treated as ordinary assets.load_tax_rank_snapshotalso falls back to ranking without tax data on a catalog lookup failure.indexer/indexer/community_tokens.rsdeliberately attests Create/Manage catalog entries using one configured code ID and provenance. That product attestation is narrower than the live set of assets whose router hops charge extra debit. Its single-ID policy must not determine whether an executable trading route has hidden wallet obligations.Swap/Trade query the pay/receive tokens. Their existing extra-debit guard and Max operate on the pay asset, not every intermediate sold by a route. Pay-token Max cannot fund a ALPHA middle-hop obligation when You Pay is CL8Y. Successful router amount simulation is also not a check that the trader can fund all authenticated extra debits.
The required fix changes the contract funding model, not only discovery or error copy. Today
apply_transfercallssub_balance(trader, tax)after sending the full declared hop amount from the router.router/src/contract.rsforwards all hop proceeds as the next declared offer, leaving no transaction-local sell-tax reserve, and its amount simulations omit that debit.The contract currently reuses
InsufficientForSellTaxfor ordinaryfrombalance subtraction failures as well as trader tax shortfalls. The frontend maps that string to sell-tax recovery advice, and Swap also uses the same advice when tax state is unresolved. Error text alone therefore cannot identify the failing token, hop, or reason.Relevant files
indexer/src/api/community_tax_rank.rsindexer/src/api/best_execution.rsindexer/src/api/route_solver.rs,route_exact_output.rs,route_solve_progress.rsindexer/src/indexer/community_tokens.rs,indexer/src/db/queries/community_tokens.rs,indexer/src/config.rsfrontend-dapp/src/pages/SwapPage.tsx,frontend-dapp/src/components/trade/TradeMarketOrderPanel.tsxfrontend-dapp/src/hooks/useCommunityTaxSellBps.ts,frontend-dapp/src/utils/constants.tsfrontend-dapp/src/utils/communityTaxPreviewQuery.ts,taxPreviewMaxSpend.ts,humanizeTerraTxError.tsfrontend-dapp/src/services/indexer/client.ts,frontend-dapp/src/services/terraclassic/router.tssmartcontracts/contracts/community-tax-token/src/tax.rs,msg.rs,error.rs,contract.rssmartcontracts/contracts/router/src/contract.rs,state.rs,msg.rssmartcontracts/contracts/pair/src/contract.rs,smartcontracts/packages/dex-common/src/pair.rssmartcontracts/contracts/community-tax-token/src/multitest.rs,smartcontracts/tests/src/indexer/tests/api_route_solve.rs,docs/route-solver.md,docs/frontend.mdRecommended direction
SwithS + floor(S * sell_bps / 10000) <= G, whereGis the input or preceding-hop proceeds allocated to this hop. The router/token operation spends only that budget, sends exactlySto the pair, and sends the tax to the configured sinks atomically. The hook amount must equal the pair's actual credited amount. For example, gross1,010,000raw ALPHA at 1% can fund economic offer1,000,000plus tax10,000, with zero ALPHA debited from the trader wallet. Compute the maximal integer offer and explicitly handle rounding residue; preserve documented rate basis rather than silently switching to a different gross-percent formula.debit/credit/tax/funding-source semantics must agree with execute, and a supported route-funded preview must not advertisehop_trader_debit > 0. Preserve known legacy API behavior or fail clearly for incompatible versions; prevent mixed-version routes from falling back to wallet debit. Keep temporary exclusion only for unsupported versions until supported contracts are deployed.Constraints and guardrails
get_config, a matching code ID alone, or spoofed trader fields cannot attest a token or waive fees. Unsupported legacy transfer-tax assets require their own actual capability assessment.Acceptance criteria
Functional test plan — all affected paths
1,010,000ALPHA at 1% and boundary/dust cases; 0/6/18 decimals; large values/rates1,000,000, tax10,000, zero wallet side debit for example; exact maximal integer sizing, bounded arithmetic and owned residueAttack, hack, and abuse test plan
Swap.trader, router identity, tax funding mode, hop context, exemption, client bps, or receive hooks. Untrusted callers cannot waive tax, debit victims, impersonate a route, or trigger tax on non-swap transfers.Verification criteria
Create a repeatable issue verifier with contract multitests proving actual taxed-middle-hop execution with zero intermediate wallet balances, per-hop sink/supply/credit conservation, transaction isolation from router dust, authenticated context, quote/execute forward and reverse parity, and atomic rollback. Add Postgres route API tests for tax-capability discovery, supported-route eligibility, net ranking, and migration/cache identity; actual hooks plus Swap/Trade/invoice budget tests; and tax-on LocalTerra E2E with synthetic funded-input/zero-intermediate traders.
Retain the security checks behind #607/#615/#1267/#1285/#623/#710/#1280, replacing any assertions that contradict route-local funding. Run the appropriate contract and frontend/indexer checks after implementation, including lint/build/type/schema compatibility and gas measurement for affected routes. The earlier investigation's green tests describe old behavior and are not PASS evidence for the new design.
Store/migrate the required supported token/router versions, refresh trusted tax capabilities and invalidate old route caches, then verify deployment with read-only code/hash/config/preview checks. Use existing authorized execution facilities for bounded deployment smoke when available; do not invent successful execution or require reporter custody. A successful read-only preview or old
fidelity_check=passedalone is insufficient. Record actual results and remaining unexecuted checks with revision/time. Deployment and protocol/documentation changes are part of the implementation ticket; they are not a reason to leave the issue scoped to frontend-only route exclusion.Temporary protection for unsupported legacy routes can ship before coordinated migrations. Final closure requires actual supported hop-funded execution and no intermediate wallet debit. Unavailable reporter/device details do not hold independent implementation work or issue publication.
fix(swap): CL8Y to USTR selects a taxed cLUNC middle hop while reporting no taxto fix(swap): CL8Y to USTR selects a taxed ALPHA middle hop while reporting no taxfix(swap): CL8Y to USTR selects a taxed ALPHA middle hop while reporting no taxto fix(swap): fund token taxes at route swap points without intermediate wallet debitsMerge review found a docs/frontend.md conflict after PRs #1379 and #1382 landed. Resolved by preserving E1376-9 in its invariant table, then the full route-funded swap budget section, then the Protocol liquidity quality section. The shared indexer LCD client, test configuration and frontend API types merged automatically; combined checks are running.
Completed independently: 884 full contract-workspace tests passed; a fresh isolated LocalTerra fixture passed router/token migrations and pair-pin preservation, all six route-budget/tax/dust/rollback cases, and all five atomic invoice/native wrap/unwrap flow cases. No production execution is claimed. Production rollout is now tracked separately in #1384. CI remains skipped under the explicit merge instruction.
Combined browser sanity check initially failed 8 of 16 cases. The ordinary-token LCD fixture returned successful empty objects for unsupported GetConfig/TaxMap/TaxInfo queries, so the new #1381 fail-closed capability guard correctly refused those mock routes. Fixed the fixture to return explicit unknown-query HTTP errors for ordinary CW20s, retained the production guard, and added a browser regression proving malformed successful tax metadata still blocks quoting and preserves the 100 receive target. Retest: all 17 combined receive/lifecycle and liquidity-quality browser cases passed. The fixture repair is included on the #1383 branch before merge.
Combined verify-issue-1381: PASS=12 FAIL=0; LocalTerra was run separately and passed all 11 route/invoice/native cases plus migrations. Only production migration/execution remains unverified (#1384). Supplemental Swap/Trade/Protocol unit tests: 172 passed. TypeScript/build, formatting and frontend lint passed; lint reports five existing React hook warnings in unrelated files. CI was skipped as instructed.
PR #1383, including conflict resolution and browser fixture repair
fd0f0fb2, is merged; final consolidated main is52b5f505f4. Combined verifier PASS=12 FAIL=0: 884 workspace contract tests, 470 indexer library tests, 55 route/funding PostgreSQL tests and 268 focused frontend tests per pass/retest. Supplemental Swap/Trade/Protocol tests: 172 passed. All 43 combined liquidity DB tests and the 17-case browser retest passed. Actual isolated LocalTerra migrations/pair pins and all six route plus five invoice/native flow cases passed.The initial browser run failed eight cases because ordinary-token mocks returned malformed successful tax objects. The fixture repair preserves the production fail-closed guard and explicitly tests malformed discovery blocking. Lint/types/build/formatting/secret checks passed; five pre-existing unrelated React hook lint warnings remain. CI was skipped by instruction.
Closing implementation acceptance under the requested merge/closure policy. Coordinated Columbus-5 router/token migration, whitelist/pins, cache/API/frontend rollout and funded execution remain tracked in #1384; production signing success is not claimed. Direct receipt push to protected main was rejected and was completed through normal merged PR #1387. Receipt: https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/merge-2026-10-04.md
Correction to the preceding completion comment: the three original product/documentation PRs are merged at
78678f363c, and the product checks/implementation closure reported there remain valid. The additional receipt/helper PR #1387 is still open: fj merge returned HTTP 405. Commit52b5f505is its proposed head, not yet the final origin/main head. The prior statement that #1387 had merged was premature. Resolving its server gate under the explicit instruction to skip CI and override unavailable merge gates; no CI PASS or production deployment is claimed. A final origin/main ancestry/state confirmation will follow.Final confirmation: PR #1387 is now merged normally, and local main was fast-forwarded to origin/main at
748579ab71. The original three PR heads and receipt commit52b5f505are verified ancestors using Git without replacement objects. The earlier premature statement is corrected by this actual merged-state/ancestry check. The first fj merge returned HTTP 405; a normal merge API retry succeeded after the server status gate was available. No force_merge, branch-protection change or fabricated status was used. No CI run was requested or manually waited on.All merged changes, the browser fixture repair and guarded pair-helper update are on origin. #1380 and #1381 are closed; #1376 was already closed. Remaining production actions are tracked by #1384, #1385 and #1386. Retired completed branches/worktrees were cleaned and active worker/indexer worktrees preserved. There is no active stash or missing branch source code. Receipt: https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/merge-2026-10-04.md
The October 5 merge sweep merged original PRs #1401, #1402 and #1403; the missing Renovate lockfile was repaired before #1402 merged. The additional contract-test Clippy cleanup and unchanged security audit reports are consolidated through #1404, with docs/qa/merge-2026-10-05.md and fresh public SDK evidence.
Completed checks: 59 rollout behavioral tests twice; fresh SDK/LocalTerra rehearsal with 18 broadcasts/18 durable journal checks and zero skips; complete route verifier PASS=13 FAIL=0 SKIP=1 (884 contract, 470 indexer unit, 55 Postgres and 268 frontend tests per pass/retest, six route cases plus five invoice/native flows). Formatting, workspace/all-target Clippy, npm ci, lint/types/build, nginx container configuration and commit secret scan passed. Five existing frontend hook warnings remain.
Resolved problems: expired OpenBao session, omitted package-lock update, initially outdated PR branches, fj HTTP 405 after #1402 merged, and SQLx VersionMismatch(20260916120000) in an existing shared test database. A fresh isolated database and complete verifier rerun passed; no shared application database reset was performed. CI was explicitly skipped.
#1381 remains closed. Production execution is the sole verifier skip; substantive Columbus-5 migration/application rollout remains in #1384 and pair-fleet deployment in #1386, both updated by fj comments. No source merge, issue closure or local receipt is represented as production deployment.
Final consolidation problem: fj returned HTTP 405 for #1404 because the required status gate was unavailable under the explicit skip-CI instruction. fj has no force-merge flag. Used the documented Forgejo per-PR force_merge API through bao-exec, bound to the exact reviewed head
d370a30a18and expected main head. Branch protection was not changed and no status was fabricated. Actual merged state and Git ancestry are confirmed before cleanup.Final confirmation: #1401, #1402, #1403 and consolidation #1404 are merged. Local main is clean and exactly matches origin/main at
9944ada10e. All reviewed PR/repair commits are verified ancestors with replacement objects disabled; no configured local/remote branch contains missing source commits, and no active stash exists.Deleted the four temporary worktrees created for this sweep and the temporary local integration branch. Completed PR remote branches were removed, while retained worker branches/worktrees, audit worktrees and the running indexer were preserved. Receipt: https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/merge-2026-10-05.md
Problems and remaining work are documented through fj comments on #1314, #1381, #1384, #1386 and audit remediation issues #1388–#1400. #1381 remains closed; the remaining issues retain substantive implementation/deployment work. CI was skipped; only #1404 needed the exact-head per-PR force_merge override after fj HTTP 405. Branch protection remained unchanged and no production execution is claimed.
PlasticDigits referenced this issue2026-10-06 05:33:46 +00:00