fix(swap): validate offline gas budgets for USTR routes and align fee readiness with signing #1480

Closed
opened 2026-10-12 00:33:50 +00:00 by PlasticDigits · 2 comments
Owner

Problem and scope

Mainnet feedback indicates that LUNC → USTR and CL8Y → USTR can remain unusable at small amounts, and that USTC → USTR can require increasing gas manually in the wallet. A short-estimate out-of-gas message was observed. High-price-impact confirmation was also observed on LUNC → cLUNC → UST1 → USTR and CL8Y → cUSTC → UST1 → USTR.

Bundle the related execution work into this issue: measured gas coverage for locally prepared routes, one consistent fee budget across display/balance reserve/signing, wallet fee handling, and accurate separation of price protection from gas failure. A high-impact confirmation alone is not proof of a pricing bug. Do not remove it to make the trade appear successful.

This is an anonymized technical summary. No conversations, screenshots, reporter identifiers, wallet balances, actor addresses, or reporter-linked transaction history are published. Wallet/app version, exact original input amounts, deployed frontend revision, and included transaction gas fields were unavailable for the reported attempts. The investigation establishes a source-level coverage gap and public quote observations, not the exact root cause of each original transaction.

Current codebase and investigation

Source reviewed: 2d1627ffa33eb3e08199acfff574a5b63fcfbd39 (2026-10-12). Public read-only probes used https://indexer.dex.cl8y.com; its /health advertised backend SHA ea627f7b0e8d5ebc9fde2bb5b243f451cf159f4d. This does not attest the frontend artifact.

  1. SwapPage.tsx passes local execution metadata to executeMultiHopSwap or executeLocalNativeRoute. In router.ts, these reviewed-route paths explicitly pass gasEstimation: 'offline' (including protected direct wrap/unwrap). terraBroadcast.ts consequently uses totalGasLimitForExecuteMsgs and does not call resolveBroadcastGasLimit/resolveSwapAutoGas. This is intentional network isolation introduced by #1452, but it restores static gas as the primary budget for these paths.
  2. #1360 implemented bounded LCD auto-gas (ceil(gas_used × 1.2)) for other swap-shaped executes, plus a static fallback. Its helper remains present; it does not protect the reviewed local routes above. terraBroadcast.autoGas.test.ts explicitly asserts that the offline path never calls the gas reader and signs the static sum. The old auto-gas documentation therefore does not describe every current retail signing path.
  3. Legacy execute_swap_operations uses the global router hop formula: two hops 1,910,000, three hops 2,860,000. Wrap + two legacy hops adds 400,000 wrap gas and 400,000 combination overhead: 2,710,000. At 28.325 uluna/gas these last two shapes cost approximately 81.01 and 76.76 LUNC, matching the observed UI fee classes. This agreement identifies an envelope, not an actual signed gas limit or proof that the wallet honored it.
  4. execute_route_swap_operations has a distinct measured route-local-v1 budget, 600,000 + 1,700,000 × hops, plus applicable hybrid/unwrap/combination costs. Do not conflate this funding protocol with legacy execute_swap_operations. The live quote probes below returned tax_funding_version: null, so legacy coverage is still relevant.
  5. SwapPage.tsx currently assigns swapNetworkFeeEstimate = swapNetworkFeeFallback. It does not use useAutoGasFeeEstimate. The #1360 fee-row tests render a standalone test component using that hook; they do not establish actual Swap-page hint/signing parity or the adequacy of offline budgets. The #1264 runner also reports its filtered SwapPage invocation as passing despite matching no tests; restore meaningful entry-path assertions. Preview construction in swapNetworkFee.ts also needs review against the actual serialized submit message, including protected wrappers and hybrid execution modes.
  6. local_quote.rs reports symmetric deviation of delivered net output from an independently priced fair output. local_reference_quote.rs binds references to execution identities, decimals and freshness; wrapper composition includes native funding economics. swapRouteSlippage.ts prefers route-level deviation. Confirmation above 5%, Expert requirements above 30%, and nonwaivable ≥99% protection are separate from network gas. A small trade can retain a nonzero deviation because fees or the market/reference relationship are not exclusively amount-dependent AMM impact.
  7. humanizeTerraTxError.ts maps recognized out-of-gas logs to fixed retail copy. That copy does not establish whether the dApp budget, a wallet rewrite, changing execution work, or a provider estimate caused the original failure.

Public quote observations

Read-only GET /api/v1/route/solve on 2026-10-12, exact entered raw amounts, max_spread=0.05, protection_policy=quote_relative_v1, native paths pool-only, no trader context, signatures or broadcasts:

Input → USTR Human input HTTP Reported fair-reference deviation Path class
LUNC 1 / 100 / 1000 200 each 2.2577% / 3.1976% / 5.7635% wrap + cLUNC → UST1 → USTR
CL8Y 0.01 / 0.1 200 each 4.9182% / 4.9689% four pool hops through cLUNC/cUSTC/UST1
CL8Y 1 200 5.3448% CL8Y → cUSTC → UST1 → USTR
USTC 1 / 100 200 each 5.4844% / 5.4998% wrap + cUSTC → UST1 → USTR

All eight returned local_v1, quote_relative_v1, and null tax-funding version. These are observations at their respective request times, not same-generation route comparisons or funded execution proof. They did not reproduce the originally observed impact percentages. Normal new HTTPS request elapsed times were approximately 847–1171 ms; these are not initialized browser latency measurements and do not replace #1473 acceptance.

Why an implementation is needed

Reducing the input or raising slippage does not repair an inadequate gas envelope. Repeated included out-of-gas transactions can charge fees without delivering output. Closed #1360/#1264 receipts measured different source, execution shapes or wallet paths and do not certify current locally prepared legacy routes. The architecture now needs evidence-backed offline gas coverage rather than relying on helper-only simulation tests or requiring users to discover a multiplier.

The fix must address the actual deficient layer. If a measured route fits the dApp envelope but the wallet lowers signed gas, fix wallet handling; if signed gas honors the dApp budget and execution exceeds it, repair the applicable global execution-family budget. Raising fee amount/gas price alone is not raising Fee.gas.

Relevant files

  • frontend-dapp/src/pages/SwapPage.tsx; components/trade/TradeMarketOrderPanel.tsx; hooks/useAutoGasFeeEstimate.ts; utils/swapNativeGasBalanceGate.ts; utils/maxSpendableAmount.ts — real fee display, native balance reservation and entry flows.
  • frontend-dapp/src/services/terraclassic/router.ts, transactions.ts, terraBroadcast.ts, terraBroadcastScope.ts — exact message assembly, local/offline option propagation, canonical signing and recovery.
  • frontend-dapp/src/services/terraclassic/terraGas.ts, swapNetworkFee.ts, terraClassicFeeEstimate.ts, hybridSwapGas.ts, terraGasRetailInventory.ts; frontend-dapp/src/utils/constants.ts — execution-family budgets and combined-message costs.
  • frontend-dapp/src/services/terraclassic/swapAutoGas.ts, terraSimulateTx.ts, terraWalletSignTxRaw.ts; frontend-dapp/src/utils/extensionSignedFeeGuard.ts; frontend-dapp/patches/@goblinhunt+cosmes+0.0.71-ghunt.22.patch — remaining auto-gas paths, wallet behavior and existing chain-scoped guards.
  • frontend-dapp/src/utils/swapRouteSlippage.ts, swapPayAcquireGuidance.ts, humanizeTerraTxError.ts, localRouteQuote.ts; indexer/src/api/local_quote.rs, local_reference_quote.rs, local_quote/protection.rs — independent fairness, execution protection, stale-intent and expiry boundaries.
  • frontend-dapp/src/services/terraclassic/__tests__/terraBroadcast.autoGas.test.ts, swapAutoGasFeeHint.test.tsx, swapNetworkFee.test.ts, terraGas.retailShapes.test.ts, terraGas.mixedHybrid.test.ts; frontend-dapp/src/pages/SwapPage*.test.tsx; frontend-dapp/e2e/wrap-swap.spec.ts — extend actual path coverage.
  • smartcontracts/contracts/pair/src/contract.rs, hook_bounds_tests.rs; smartcontracts/contracts/router/src/contract.rs, route_tax.rs; treasury/wrap-mapper dependency pins — benchmark the current compiled settlement and wrapper implementations, with rejection rollback checks.
  • docs/adr/0014-swap-auto-gas.md, docs/adr/0004-terraclassic-retail-gas-census.md, docs/frontend.md, docs/route-solver.md; applicable gas/local-quote playbooks; packages/localnet-trading-swarm/src/gas.ts — policy reconciliation and shared constants.
  1. Add a reproducible, owned funded fixture for each reported execution family and capture the exact submitted messages, requested/signed gas and fee, included code/gas usage, output and balance deltas. Compare legacy and funding-v1 paths separately. Use synthetic actors in public fixtures and receipts.
  2. Calibrate generic offline execution-family budgets from current contract artifacts and bounded worst-case work. Include wrap/unwrap, router bookkeeping, pair work, tax/hook settlement, makers/scans/parks and combined-message overhead. Prefer a measured global model; do not add CL8Y/USTR address exceptions or a blind ×3 multiplier. If a family cannot be covered safely within chain limits, retain its quote but block signing with a truthful fee-readiness outcome. Any background calibration must be independently scheduled and bounded; requests cannot trigger it.
  3. Reuse one submit-plan budget for the actual Swap/Trade fee row, Max/native balance reserve and signed Fee. Verify all message fields used to choose the family. Handle legitimate changes by refreshing the review; never silently swap operations or weaken receive floors.
  4. Inspect extension and WalletConnect requested-versus-signed gas where the wallet API permits this. Preserve existing preferNoSetFee and guard scope; do not turn on a global mainnet fee guard without explicit evidence and wallet compatibility tests. Keep unsupported atomic-post behavior truthful.
  5. Treat price-impact confirmation independently. Recompute the displayed percent from compatible net output/reference observations, show one consistent percentage, and verify real fee/reference divergence versus size-dependent effects. A verified legitimate warning stays. Actual failures must never suggest increasing gas as a remedy for price protection or increasing slippage as a remedy for out-of-gas.
  6. Update the historical auto-gas/fallback documentation and verifier assumptions to describe the local/offline boundary. Test production entry components through real builders and the broadcast boundary, not only a helper-shaped harness.

Constraints and guardrails

  • Preserve #1452 zero request-triggered RPC/LCD/network validation during quote, refresh, preflight and reviewed-route preparation. Removing gasEstimation: 'offline' to reintroduce user-triggered simulation is not an acceptable fix. Non-local existing auto-gas paths remain a separate policy.
  • Apply generic economics and execution-family handling to every supported asset identity/amount; USTR routes are regression examples, not an admission whitelist.
  • Fee denom is always uluna, including native uusd offers. Keep configured gas-price minima, checked fee arithmetic, native pay+fee reservation and chain gas/transaction limits. Bound the final signed budget, not only a simulated gas_used field.
  • Preserve exact gross route funding, tax parity, positive per-hop/post-hook and final floors, quote-relative protection, original expiry, actor/context binding, supported mode limits, native pool-only behavior, pause/blacklist/freeze/launch guards, 30% Expert and nonwaivable ≥99% protection.
  • One intentional signing/broadcast flow per submission; no automatic resend of an included out-of-gas failure or a transaction with unknown inclusion. Preserve existing sequence-mismatch handling and recovery semantics.
  • No shared/production database mutation or chain reset. Credential injection uses openbao-tools; credentials and actor-correlating evidence never enter issues, browser bundles or public logs.

Acceptance criteria

  • AC1: Classify all three reported input families as dApp underbudget, wallet gas rewrite, provider/legacy-path issue, or genuine protection rejection using funded controlled evidence. Record missing original-report details explicitly; a quote HTTP 200 cannot satisfy execution acceptance.
  • AC2: For supported eligible LUNC/USTC/CL8Y → USTR fixtures, small and typical offers settle at the dApp-selected gas without manual wallet edits, with code 0, gas_used < gas_wanted, expected delivered net amount and all floors respected. Cover applicable legacy/v1 modes and non-USTR control assets. Unsupported or over-limit families block before signing.
  • AC3: Actual Swap and Trade fee rows, Max/native balance reserve and requested/signed fees derive from the same execution budget. Test native pay+fee and CW20 pay+LUNC fee separately, including low balances and rounding boundaries. Document unavoidable wallet behavior explicitly.
  • AC4: All quote/refresh/confirmation/preparation provider counters remain zero. Calibration cannot be requested by input changes, cache misses, manual retry or malicious traffic. Preserve quote generation/expiry through the complete review/sign flow.
  • AC5: Legitimate >5% confirmation remains functional; ≤5%, >30% and ≥99% paths preserve their existing behavior. One consistent fair-reference percent is shown. Missing/stale/malformed references cannot become zero-impact approval. Gas failures and protection outcomes remain distinct.
  • AC6: No double-spend/resend or fee charged by an automatic retry after included code 11; unknown inclusion follows recovery. Wallet rejection, disconnect, sequence mismatch and concurrent submit paths terminate or recover correctly.
  • AC7: Updated docs/inventories/verifiers cover the current local/offline contract. Run first/retest on stable source and publish sanitized exact-revision receipts with executable checks, failures and skips separated. Attest deployed frontend/backend and contract artifacts independently before claiming production resolution.

Test plan: functional and failure paths

Area Required coverage
Inputs and sizing LUNC/USTC/CL8Y → USTR; reverse USTR → native/wrapped/CW20; cLUNC/cUSTC controls; at least one unrelated/custom asset. One raw unit, dust ±1, 0.01/0.1/1/10/100/1000 and liquidity-limited amounts, both six/eighteen decimals; exact-input and supported receive sizing.
Execution shapes Direct pair, locally prepared router with one/two/three/four permitted hops, legacy/v1 funding, wrap-only/unwrap-only and combined native routes, tax-off/on, supported hook/tier states, hybrid/manual/greedy within their own caps, empty/populated/expired books. Native wrap routes stay pool-only.
Fee and wallet Actual production components/builders; extension split signing and supported atomic WalletConnect; requested vs signed gas/fee; lower/higher wallet rewrite; fee amount changed without gas-limit change; fresh/no-pubkey accounts; balances exactly at pay+fee ±1 uluna; Max; fee rounding and overflow.
State and failure Missing/stale/unsupported quote, reference or gas coverage; expired deadline/observation/config; input/asset/mode/tier/account changes during review; balance/state changes; revert by min_return/minimum_receive, tax, pause/freeze/blacklist; transport timeout, non-success provider response and bad simulation bodies on remaining auto-gas paths.
Confirmation/recovery High-impact first/second click, cancel/requote, Expert transition, double click, disconnected wallet, rejected/stalled signing, sequence mismatch, broadcast timeout/unknown inclusion, included code 11 and other nonzero codes. Assert broadcast counts and terminal balance/output effects.

Use independently calculated expected outputs and decoded signed Fee, not assertions that simply restate a constant. Fund owned LocalTerra fixtures and compare net balance/reserve/LP effects; rejection by settlement floors must roll back economics. Device/wallet acceptance is separate from mocks and chain simulation.

Test plan: attack, hack and abuse vectors

  • Budget/fee manipulation: forged route metadata, shortened hop counts, spoofed token symbols/decimals, arbitrary gas fields, unknown protocol variants, malformed/base64/oversized CW20 hooks, negative/fractional/nonfinite/unsafe gas and fee values, multiplication overflow, chain-cap overflow and downgrade from v1 to legacy. Reject before signing; never fall through to a cheap BASE_GAS_LIMIT.
  • State/cache poisoning: tamper amount, funds, recipient, actor/tier, route identity, mode, floors, generation, original observation time, expiry or cached gas coverage. No reuse across incompatible plans/artifacts/chains; altered or expired intent cannot sign.
  • Economic attacks: manipulated thin pools or fair marks, future/stale references, gross/net tax confusion, extra-debit balance shortfall, malicious/expensive hooks and launch-guard bypass. Preserve independent reference eligibility and all signed floors; no higher gas budget authorizes additional principal or bypasses protection.
  • Resource exhaustion: maximum supported hops/makers/scans/expired parks, oversized/dense/cyclic routes, bursts and rapidly changing inputs. Bound work, memory, calibration jobs, cancellation and provider traffic. No user-driven calibration or unbounded estimator retry loop.
  • Wallet/replay attacks: malicious signer reducing gas/changing funds or recipient, concurrent requests/signature reuse, sequence races and misleading unknown-inclusion results. Inspect signed fields where available, preserve existing wallet trust boundaries and never automatically rebroadcast a deterministically failed or potentially included transaction.
  • Disclosure/injection: provider/contract/wallet errors containing HTML, secrets, arbitrary prose or actor details. Fixed bounded retail errors; sanitized receipts; no credentials, reporter identities or conversations in public artifacts.

This is a follow-up after closed #1360 (auto-gas), #1264/#587 (native wrap gas), and #1452 (local quotes), with #1459/#1473 defining current local execution/protection semantics. Coordinate deployed acceptance with #1456 rather than claiming that old closures certify this regression. #1222's historical census “Stay” is not a hold on this measured-execution follow-up.

Baseline investigation checks (2026-10-12; no implementation changes):

  • make verify-issue-1360: 82 tests passed; optional funded-account mainnet simulation and signed-wallet checks unavailable.
  • make verify-issue-1328: 103 tests passed; optional funded-account mainnet simulation/signing unverified.
  • make verify-issue-1222: nine groups passed, including 83 gas/network-fee/inventory tests on first/retest. This verifies existing assumptions, not their production adequacy.
  • make verify-issue-1264: four groups passed; 123 source tests passed on first/retest. The runner's filtered SwapPage.test.tsx -t #1264 invocation matched no tests (25 skipped per run); original included-transaction acceptance was not exercised.
  • make verify-issue-1452: overall FAIL, retained. The library passed 774 tests on first/retest (one ignored); frontend passed 471 tests on first/retest; types/format/crosslinks passed. Disposable socket checks could not run without dedicated QA credentials and the runner counted those as failures. Controlled browser first passed, retest failed the 500 ms bound: Swap maxima approximately 1524 ms desktop / 1046 ms phone, with zero quote-triggered provider calls. This is not a gas-execution receipt and not deployment acceptance.
  • make verify-issue-1257: overall FAIL, retained. Targeted Rust scale tests passed. A frontend mainnet-identity fixture failed under this checkout's LocalTerra token configuration; a canonical-identity retest of the affected registry/default suites passed all 39 tests. Historical source-grep and old top-five-solver documentation assertions also failed and remain unresolved; do not classify them as a reproduced gas failure.
  • make verify-issue-1473: overall FAIL (12 passed groups, five failed, two explicit skips), retained. The library passed 774 tests on first/retest (one ignored). Frontend had 425 passed/two mainnet-default fixture failures per run under LocalTerra configuration; the isolated canonical-identity retest passed 39 tests as above. Disposable socket credentials were unavailable. The complete controlled desktop/phone browser matrix recorded 4250 cases, 3948 useful-output samples and 3 failures; useful p50/p95/p99/max approximately 89.8/148.6/166.1/3564.6 ms against 750 ms, zero provider requests. It is controlled fixture evidence, not deployed or funded gas acceptance.
  • Original-report wallet/version/amount details and included gas evidence unavailable; no mainnet signing/broadcast attempted. Owned funded route-budget and physical-wallet acceptance remain unverified. Source tests are not proof of deployed execution.

Implementation verification must rerun make verify-issue-1360, make verify-issue-1328, make verify-issue-1264, make verify-issue-1222, make verify-issue-1452, make verify-issue-1473, and applicable tax/net-floor/launch-guard checks (1381, 1398, 1390), alongside the new actual-entry/funded matrix. Keep unrelated pre-existing failures visible and update stale assertions only with equivalent functional protection coverage.

Unavailable workflow holds/device/signing/deployment capabilities do not block filing or a reviewable implementation. Record explicit SKIP reasons and keep corresponding acceptance unchecked; executed failures remain FAIL. Production completion requires exact artifact provenance and funded/wallet receipts, not passing helper tests alone.

Published implementation and evidence (2026-10-12)

Implementation PR #1481 is deployed at 0395459971312c31f87d502ef7822733a7250238; evidence/QA #1482 publishes bounded live outcomes and retained failures. Current results and agent checklist distinguish completed subsets from incomplete whole criteria.

All whole criteria remain incomplete despite passing source, funded plain-core and live-quote subsets. Physical/atomic-wallet, reported native/USTR/hook/book gas and production contract provenance remain incomplete. This issue remains open.

## Problem and scope Mainnet feedback indicates that LUNC → USTR and CL8Y → USTR can remain unusable at small amounts, and that USTC → USTR can require increasing gas manually in the wallet. A short-estimate out-of-gas message was observed. High-price-impact confirmation was also observed on LUNC → cLUNC → UST1 → USTR and CL8Y → cUSTC → UST1 → USTR. Bundle the related execution work into this issue: measured gas coverage for locally prepared routes, one consistent fee budget across display/balance reserve/signing, wallet fee handling, and accurate separation of price protection from gas failure. **A high-impact confirmation alone is not proof of a pricing bug.** Do not remove it to make the trade appear successful. This is an anonymized technical summary. No conversations, screenshots, reporter identifiers, wallet balances, actor addresses, or reporter-linked transaction history are published. Wallet/app version, exact original input amounts, deployed frontend revision, and included transaction gas fields were unavailable for the reported attempts. The investigation establishes a source-level coverage gap and public quote observations, not the exact root cause of each original transaction. ## Current codebase and investigation Source reviewed: `2d1627ffa33eb3e08199acfff574a5b63fcfbd39` (2026-10-12). Public read-only probes used `https://indexer.dex.cl8y.com`; its `/health` advertised backend SHA `ea627f7b0e8d5ebc9fde2bb5b243f451cf159f4d`. This does not attest the frontend artifact. 1. `SwapPage.tsx` passes local execution metadata to `executeMultiHopSwap` or `executeLocalNativeRoute`. In `router.ts`, these reviewed-route paths explicitly pass `gasEstimation: 'offline'` (including protected direct wrap/unwrap). `terraBroadcast.ts` consequently uses `totalGasLimitForExecuteMsgs` and does **not** call `resolveBroadcastGasLimit`/`resolveSwapAutoGas`. This is intentional network isolation introduced by #1452, but it restores static gas as the primary budget for these paths. 2. #1360 implemented bounded LCD auto-gas (`ceil(gas_used × 1.2)`) for other swap-shaped executes, plus a static fallback. Its helper remains present; it does not protect the reviewed local routes above. `terraBroadcast.autoGas.test.ts` explicitly asserts that the offline path never calls the gas reader and signs the static sum. The old auto-gas documentation therefore does not describe every current retail signing path. 3. Legacy `execute_swap_operations` uses the global router hop formula: two hops **1,910,000**, three hops **2,860,000**. Wrap + two legacy hops adds 400,000 wrap gas and 400,000 combination overhead: **2,710,000**. At 28.325 uluna/gas these last two shapes cost approximately **81.01** and **76.76 LUNC**, matching the observed UI fee classes. This agreement identifies an envelope, not an actual signed gas limit or proof that the wallet honored it. 4. `execute_route_swap_operations` has a distinct measured route-local-v1 budget, `600,000 + 1,700,000 × hops`, plus applicable hybrid/unwrap/combination costs. Do not conflate this funding protocol with legacy `execute_swap_operations`. The live quote probes below returned `tax_funding_version: null`, so legacy coverage is still relevant. 5. `SwapPage.tsx` currently assigns `swapNetworkFeeEstimate = swapNetworkFeeFallback`. It does not use `useAutoGasFeeEstimate`. The #1360 fee-row tests render a standalone test component using that hook; they do not establish actual Swap-page hint/signing parity or the adequacy of offline budgets. The #1264 runner also reports its filtered SwapPage invocation as passing despite matching no tests; restore meaningful entry-path assertions. Preview construction in `swapNetworkFee.ts` also needs review against the actual serialized submit message, including protected wrappers and hybrid execution modes. 6. `local_quote.rs` reports symmetric deviation of delivered net output from an independently priced fair output. `local_reference_quote.rs` binds references to execution identities, decimals and freshness; wrapper composition includes native funding economics. `swapRouteSlippage.ts` prefers route-level deviation. Confirmation above 5%, Expert requirements above 30%, and nonwaivable ≥99% protection are separate from network gas. A small trade can retain a nonzero deviation because fees or the market/reference relationship are not exclusively amount-dependent AMM impact. 7. `humanizeTerraTxError.ts` maps recognized out-of-gas logs to fixed retail copy. That copy does not establish whether the dApp budget, a wallet rewrite, changing execution work, or a provider estimate caused the original failure. ### Public quote observations Read-only GET `/api/v1/route/solve` on 2026-10-12, exact entered raw amounts, `max_spread=0.05`, `protection_policy=quote_relative_v1`, native paths pool-only, no trader context, signatures or broadcasts: | Input → USTR | Human input | HTTP | Reported fair-reference deviation | Path class | | --- | ---: | ---: | ---: | --- | | LUNC | 1 / 100 / 1000 | 200 each | 2.2577% / 3.1976% / 5.7635% | wrap + cLUNC → UST1 → USTR | | CL8Y | 0.01 / 0.1 | 200 each | 4.9182% / 4.9689% | four pool hops through cLUNC/cUSTC/UST1 | | CL8Y | 1 | 200 | 5.3448% | CL8Y → cUSTC → UST1 → USTR | | USTC | 1 / 100 | 200 each | 5.4844% / 5.4998% | wrap + cUSTC → UST1 → USTR | All eight returned `local_v1`, `quote_relative_v1`, and null tax-funding version. These are observations at their respective request times, not same-generation route comparisons or funded execution proof. They did not reproduce the originally observed impact percentages. Normal new HTTPS request elapsed times were approximately 847–1171 ms; these are not initialized browser latency measurements and do not replace #1473 acceptance. ## Why an implementation is needed Reducing the input or raising slippage does not repair an inadequate gas envelope. Repeated included out-of-gas transactions can charge fees without delivering output. Closed #1360/#1264 receipts measured different source, execution shapes or wallet paths and do not certify current locally prepared legacy routes. The architecture now needs evidence-backed offline gas coverage rather than relying on helper-only simulation tests or requiring users to discover a multiplier. The fix must address the actual deficient layer. If a measured route fits the dApp envelope but the wallet lowers signed gas, fix wallet handling; if signed gas honors the dApp budget and execution exceeds it, repair the applicable global execution-family budget. Raising fee amount/gas price alone is not raising `Fee.gas`. ## Relevant files - `frontend-dapp/src/pages/SwapPage.tsx`; `components/trade/TradeMarketOrderPanel.tsx`; `hooks/useAutoGasFeeEstimate.ts`; `utils/swapNativeGasBalanceGate.ts`; `utils/maxSpendableAmount.ts` — real fee display, native balance reservation and entry flows. - `frontend-dapp/src/services/terraclassic/router.ts`, `transactions.ts`, `terraBroadcast.ts`, `terraBroadcastScope.ts` — exact message assembly, local/offline option propagation, canonical signing and recovery. - `frontend-dapp/src/services/terraclassic/terraGas.ts`, `swapNetworkFee.ts`, `terraClassicFeeEstimate.ts`, `hybridSwapGas.ts`, `terraGasRetailInventory.ts`; `frontend-dapp/src/utils/constants.ts` — execution-family budgets and combined-message costs. - `frontend-dapp/src/services/terraclassic/swapAutoGas.ts`, `terraSimulateTx.ts`, `terraWalletSignTxRaw.ts`; `frontend-dapp/src/utils/extensionSignedFeeGuard.ts`; `frontend-dapp/patches/@goblinhunt+cosmes+0.0.71-ghunt.22.patch` — remaining auto-gas paths, wallet behavior and existing chain-scoped guards. - `frontend-dapp/src/utils/swapRouteSlippage.ts`, `swapPayAcquireGuidance.ts`, `humanizeTerraTxError.ts`, `localRouteQuote.ts`; `indexer/src/api/local_quote.rs`, `local_reference_quote.rs`, `local_quote/protection.rs` — independent fairness, execution protection, stale-intent and expiry boundaries. - `frontend-dapp/src/services/terraclassic/__tests__/terraBroadcast.autoGas.test.ts`, `swapAutoGasFeeHint.test.tsx`, `swapNetworkFee.test.ts`, `terraGas.retailShapes.test.ts`, `terraGas.mixedHybrid.test.ts`; `frontend-dapp/src/pages/SwapPage*.test.tsx`; `frontend-dapp/e2e/wrap-swap.spec.ts` — extend actual path coverage. - `smartcontracts/contracts/pair/src/contract.rs`, `hook_bounds_tests.rs`; `smartcontracts/contracts/router/src/contract.rs`, `route_tax.rs`; treasury/wrap-mapper dependency pins — benchmark the current compiled settlement and wrapper implementations, with rejection rollback checks. - `docs/adr/0014-swap-auto-gas.md`, `docs/adr/0004-terraclassic-retail-gas-census.md`, `docs/frontend.md`, `docs/route-solver.md`; applicable gas/local-quote playbooks; `packages/localnet-trading-swarm/src/gas.ts` — policy reconciliation and shared constants. ## Recommended direction 1. Add a reproducible, owned funded fixture for each reported execution family and capture the **exact** submitted messages, requested/signed gas and fee, included code/gas usage, output and balance deltas. Compare legacy and funding-v1 paths separately. Use synthetic actors in public fixtures and receipts. 2. Calibrate generic offline execution-family budgets from current contract artifacts and bounded worst-case work. Include wrap/unwrap, router bookkeeping, pair work, tax/hook settlement, makers/scans/parks and combined-message overhead. Prefer a measured global model; do not add CL8Y/USTR address exceptions or a blind ×3 multiplier. If a family cannot be covered safely within chain limits, retain its quote but block signing with a truthful fee-readiness outcome. Any background calibration must be independently scheduled and bounded; requests cannot trigger it. 3. Reuse one submit-plan budget for the actual Swap/Trade fee row, Max/native balance reserve and signed Fee. Verify all message fields used to choose the family. Handle legitimate changes by refreshing the review; never silently swap operations or weaken receive floors. 4. Inspect extension and WalletConnect requested-versus-signed gas where the wallet API permits this. Preserve existing `preferNoSetFee` and guard scope; do not turn on a global mainnet fee guard without explicit evidence and wallet compatibility tests. Keep unsupported atomic-post behavior truthful. 5. Treat price-impact confirmation independently. Recompute the displayed percent from compatible net output/reference observations, show one consistent percentage, and verify real fee/reference divergence versus size-dependent effects. A verified legitimate warning stays. Actual failures must never suggest increasing gas as a remedy for price protection or increasing slippage as a remedy for out-of-gas. 6. Update the historical auto-gas/fallback documentation and verifier assumptions to describe the local/offline boundary. Test production entry components through real builders and the broadcast boundary, not only a helper-shaped harness. ## Constraints and guardrails - Preserve #1452 zero request-triggered RPC/LCD/network validation during quote, refresh, preflight and reviewed-route preparation. **Removing `gasEstimation: 'offline'` to reintroduce user-triggered simulation is not an acceptable fix.** Non-local existing auto-gas paths remain a separate policy. - Apply generic economics and execution-family handling to every supported asset identity/amount; USTR routes are regression examples, not an admission whitelist. - Fee denom is always `uluna`, including native `uusd` offers. Keep configured gas-price minima, checked fee arithmetic, native pay+fee reservation and chain gas/transaction limits. Bound the final signed budget, not only a simulated `gas_used` field. - Preserve exact gross route funding, tax parity, positive per-hop/post-hook and final floors, quote-relative protection, original expiry, actor/context binding, supported mode limits, native pool-only behavior, pause/blacklist/freeze/launch guards, 30% Expert and nonwaivable ≥99% protection. - One intentional signing/broadcast flow per submission; no automatic resend of an included out-of-gas failure or a transaction with unknown inclusion. Preserve existing sequence-mismatch handling and recovery semantics. - No shared/production database mutation or chain reset. Credential injection uses openbao-tools; credentials and actor-correlating evidence never enter issues, browser bundles or public logs. ## Acceptance criteria - [ ] AC1: Classify all three reported input families as dApp underbudget, wallet gas rewrite, provider/legacy-path issue, or genuine protection rejection using funded controlled evidence. Record missing original-report details explicitly; a quote HTTP 200 cannot satisfy execution acceptance. - [ ] AC2: For supported eligible LUNC/USTC/CL8Y → USTR fixtures, small and typical offers settle at the dApp-selected gas without manual wallet edits, with code 0, `gas_used < gas_wanted`, expected delivered net amount and all floors respected. Cover applicable legacy/v1 modes and non-USTR control assets. Unsupported or over-limit families block before signing. - [ ] AC3: Actual Swap and Trade fee rows, Max/native balance reserve and requested/signed fees derive from the same execution budget. Test native pay+fee and CW20 pay+LUNC fee separately, including low balances and rounding boundaries. Document unavoidable wallet behavior explicitly. - [ ] AC4: All quote/refresh/confirmation/preparation provider counters remain zero. Calibration cannot be requested by input changes, cache misses, manual retry or malicious traffic. Preserve quote generation/expiry through the complete review/sign flow. - [ ] AC5: Legitimate >5% confirmation remains functional; ≤5%, >30% and ≥99% paths preserve their existing behavior. One consistent fair-reference percent is shown. Missing/stale/malformed references cannot become zero-impact approval. Gas failures and protection outcomes remain distinct. - [ ] AC6: No double-spend/resend or fee charged by an automatic retry after included code 11; unknown inclusion follows recovery. Wallet rejection, disconnect, sequence mismatch and concurrent submit paths terminate or recover correctly. - [ ] AC7: Updated docs/inventories/verifiers cover the current local/offline contract. Run first/retest on stable source and publish sanitized exact-revision receipts with executable checks, failures and skips separated. Attest deployed frontend/backend and contract artifacts independently before claiming production resolution. ## Test plan: functional and failure paths | Area | Required coverage | | --- | --- | | Inputs and sizing | LUNC/USTC/CL8Y → USTR; reverse USTR → native/wrapped/CW20; cLUNC/cUSTC controls; at least one unrelated/custom asset. One raw unit, dust ±1, 0.01/0.1/1/10/100/1000 and liquidity-limited amounts, both six/eighteen decimals; exact-input and supported receive sizing. | | Execution shapes | Direct pair, locally prepared router with one/two/three/four permitted hops, legacy/v1 funding, wrap-only/unwrap-only and combined native routes, tax-off/on, supported hook/tier states, hybrid/manual/greedy within their own caps, empty/populated/expired books. Native wrap routes stay pool-only. | | Fee and wallet | Actual production components/builders; extension split signing and supported atomic WalletConnect; requested vs signed gas/fee; lower/higher wallet rewrite; fee amount changed without gas-limit change; fresh/no-pubkey accounts; balances exactly at pay+fee ±1 uluna; Max; fee rounding and overflow. | | State and failure | Missing/stale/unsupported quote, reference or gas coverage; expired deadline/observation/config; input/asset/mode/tier/account changes during review; balance/state changes; revert by min_return/minimum_receive, tax, pause/freeze/blacklist; transport timeout, non-success provider response and bad simulation bodies on remaining auto-gas paths. | | Confirmation/recovery | High-impact first/second click, cancel/requote, Expert transition, double click, disconnected wallet, rejected/stalled signing, sequence mismatch, broadcast timeout/unknown inclusion, included code 11 and other nonzero codes. Assert broadcast counts and terminal balance/output effects. | Use independently calculated expected outputs and decoded signed Fee, not assertions that simply restate a constant. Fund owned LocalTerra fixtures and compare net balance/reserve/LP effects; rejection by settlement floors must roll back economics. Device/wallet acceptance is separate from mocks and chain simulation. ## Test plan: attack, hack and abuse vectors - **Budget/fee manipulation:** forged route metadata, shortened hop counts, spoofed token symbols/decimals, arbitrary gas fields, unknown protocol variants, malformed/base64/oversized CW20 hooks, negative/fractional/nonfinite/unsafe gas and fee values, multiplication overflow, chain-cap overflow and downgrade from v1 to legacy. Reject before signing; never fall through to a cheap BASE_GAS_LIMIT. - **State/cache poisoning:** tamper amount, funds, recipient, actor/tier, route identity, mode, floors, generation, original observation time, expiry or cached gas coverage. No reuse across incompatible plans/artifacts/chains; altered or expired intent cannot sign. - **Economic attacks:** manipulated thin pools or fair marks, future/stale references, gross/net tax confusion, extra-debit balance shortfall, malicious/expensive hooks and launch-guard bypass. Preserve independent reference eligibility and all signed floors; no higher gas budget authorizes additional principal or bypasses protection. - **Resource exhaustion:** maximum supported hops/makers/scans/expired parks, oversized/dense/cyclic routes, bursts and rapidly changing inputs. Bound work, memory, calibration jobs, cancellation and provider traffic. No user-driven calibration or unbounded estimator retry loop. - **Wallet/replay attacks:** malicious signer reducing gas/changing funds or recipient, concurrent requests/signature reuse, sequence races and misleading unknown-inclusion results. Inspect signed fields where available, preserve existing wallet trust boundaries and never automatically rebroadcast a deterministically failed or potentially included transaction. - **Disclosure/injection:** provider/contract/wallet errors containing HTML, secrets, arbitrary prose or actor details. Fixed bounded retail errors; sanitized receipts; no credentials, reporter identities or conversations in public artifacts. ## Verification and related work This is a follow-up after closed #1360 (auto-gas), #1264/#587 (native wrap gas), and #1452 (local quotes), with #1459/#1473 defining current local execution/protection semantics. Coordinate deployed acceptance with #1456 rather than claiming that old closures certify this regression. #1222's historical census “Stay” is not a hold on this measured-execution follow-up. Baseline investigation checks (2026-10-12; no implementation changes): - `make verify-issue-1360`: 82 tests passed; optional funded-account mainnet simulation and signed-wallet checks unavailable. - `make verify-issue-1328`: 103 tests passed; optional funded-account mainnet simulation/signing unverified. - `make verify-issue-1222`: nine groups passed, including 83 gas/network-fee/inventory tests on first/retest. This verifies existing assumptions, not their production adequacy. - `make verify-issue-1264`: four groups passed; 123 source tests passed on first/retest. The runner's filtered `SwapPage.test.tsx -t #1264` invocation matched no tests (25 skipped per run); original included-transaction acceptance was not exercised. - `make verify-issue-1452`: **overall FAIL**, retained. The library passed 774 tests on first/retest (one ignored); frontend passed 471 tests on first/retest; types/format/crosslinks passed. Disposable socket checks could not run without dedicated QA credentials and the runner counted those as failures. Controlled browser first passed, retest failed the 500 ms bound: Swap maxima approximately 1524 ms desktop / 1046 ms phone, with zero quote-triggered provider calls. This is not a gas-execution receipt and not deployment acceptance. - `make verify-issue-1257`: **overall FAIL**, retained. Targeted Rust scale tests passed. A frontend mainnet-identity fixture failed under this checkout's LocalTerra token configuration; a canonical-identity retest of the affected registry/default suites passed all 39 tests. Historical source-grep and old top-five-solver documentation assertions also failed and remain unresolved; do not classify them as a reproduced gas failure. - `make verify-issue-1473`: **overall FAIL** (12 passed groups, five failed, two explicit skips), retained. The library passed 774 tests on first/retest (one ignored). Frontend had 425 passed/two mainnet-default fixture failures per run under LocalTerra configuration; the isolated canonical-identity retest passed 39 tests as above. Disposable socket credentials were unavailable. The complete controlled desktop/phone browser matrix recorded 4250 cases, 3948 useful-output samples and 3 failures; useful p50/p95/p99/max approximately 89.8/148.6/166.1/3564.6 ms against 750 ms, zero provider requests. It is controlled fixture evidence, not deployed or funded gas acceptance. - Original-report wallet/version/amount details and included gas evidence unavailable; no mainnet signing/broadcast attempted. Owned funded route-budget and physical-wallet acceptance remain unverified. Source tests are not proof of deployed execution. Implementation verification must rerun `make verify-issue-1360`, `make verify-issue-1328`, `make verify-issue-1264`, `make verify-issue-1222`, `make verify-issue-1452`, `make verify-issue-1473`, and applicable tax/net-floor/launch-guard checks (`1381`, `1398`, `1390`), alongside the new actual-entry/funded matrix. Keep unrelated pre-existing failures visible and update stale assertions only with equivalent functional protection coverage. Unavailable workflow holds/device/signing/deployment capabilities do not block filing or a reviewable implementation. Record explicit SKIP reasons and keep corresponding acceptance unchecked; executed failures remain FAIL. Production completion requires exact artifact provenance and funded/wallet receipts, not passing helper tests alone. ## Published implementation and evidence (2026-10-12) Implementation [PR #1481](https://git.cl8y.com/code/cl8y-dex-terraclassic/pulls/1481) is deployed at `0395459971312c31f87d502ef7822733a7250238`; [evidence/QA #1482](https://git.cl8y.com/code/cl8y-dex-terraclassic/pulls/1482) publishes bounded live outcomes and retained failures. [Current results](https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/issue-1480/RESULTS.md) and [agent checklist](https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/issue-1480/README.md) distinguish completed subsets from incomplete whole criteria. All whole criteria remain incomplete despite passing source, funded plain-core and live-quote subsets. Physical/atomic-wallet, reported native/USTR/hook/book gas and production contract provenance remain incomplete. This issue remains open.
Author
Owner

Implementation #1481 and evidence/QA #1482 are merged. Backend/frontend/root assets are separately attested at 0395459971312c31f87d502ef7822733a7250238; evidence main d65228c2 keeps identical application inputs.

Reviewed local budgets use generic 800k+2.4M/hop legacy and 800k+1.8M/hop funding-v1, applicable work overhead and a 15M final cap. Fee display, Max/native reserve and signing share the plan; queued Swap submissions recheck cached principal+fee coverage. Exact requested/signed fee and original expiry guards remain. Owned first/retest each delivered 24 settlements plus 48 intentional floor rejections, with independently calculated net, decoded fees, rollback and ≥20% measured core gas headroom. Mixed 6/18/9-decimal 1%/5%/30% and tax/invoice subsets passed. Final source entrypoint passed 351 frontend tests per round; hosted implementation CI422 passed all required steps.

Live browser shards completed 840 unique cases, zero failures and 558 useful quotes (max467.3 ms against750 ms). Earlier browser timing/wall-cap, one unproved API validation and cold883.045 ms failures remain FAIL. Live quotes do not certify funded production gas or physical wallet behavior.

All whole acceptance criteria remain incomplete: original reported wallet/amount details, native/USTR/wrapper/tax/hook/book worst-case calibrated settlement, atomic WalletConnect/signed-device inspection and deployed contract provenance. Results, checklist/skip policy, and OB1480 instructions record those limits. This issue remains open.

Physical mobile fee approval is pending in the PM inbox, task f2041acd-86a0-4a86-9b90-469196638b90, linked through PM #143. Its one action compares fee approval and cancels without signing; it is not funded/device acceptance.

Implementation [#1481](https://git.cl8y.com/code/cl8y-dex-terraclassic/pulls/1481) and evidence/QA [#1482](https://git.cl8y.com/code/cl8y-dex-terraclassic/pulls/1482) are merged. Backend/frontend/root assets are separately attested at `0395459971312c31f87d502ef7822733a7250238`; evidence main `d65228c2` keeps identical application inputs. Reviewed local budgets use generic 800k+2.4M/hop legacy and 800k+1.8M/hop funding-v1, applicable work overhead and a 15M final cap. Fee display, Max/native reserve and signing share the plan; queued Swap submissions recheck cached principal+fee coverage. Exact requested/signed fee and original expiry guards remain. Owned first/retest each delivered 24 settlements plus 48 intentional floor rejections, with independently calculated net, decoded fees, rollback and ≥20% measured core gas headroom. Mixed 6/18/9-decimal 1%/5%/30% and tax/invoice subsets passed. Final source entrypoint passed 351 frontend tests per round; hosted implementation CI422 passed all required steps. Live browser shards completed 840 unique cases, zero failures and 558 useful quotes (max467.3 ms against750 ms). Earlier browser timing/wall-cap, one unproved API validation and cold883.045 ms failures remain FAIL. Live quotes do not certify funded production gas or physical wallet behavior. All whole acceptance criteria remain incomplete: original reported wallet/amount details, native/USTR/wrapper/tax/hook/book worst-case calibrated settlement, atomic WalletConnect/signed-device inspection and deployed contract provenance. [Results](https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/issue-1480/RESULTS.md), [checklist/skip policy](https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/docs/qa/issue-1480/README.md), and [OB1480 instructions](https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/main/skills/AGENTS_OFFLINE_SWAP_BUDGET.md) record those limits. This issue remains open. Physical mobile fee approval is pending in [the PM inbox](https://pm.cl8y.com/inbox), task `f2041acd-86a0-4a86-9b90-469196638b90`, linked through [PM #143](https://git.cl8y.com/PlasticDigits/cl8y-pm/issues/143). Its one action compares fee approval and cancels without signing; it is not funded/device acceptance.
Author
Owner

Closed at the user's request as part of consolidating issues #1449–#1500.

Offline gas budgets, fee readiness, Max and signing consistency fixes are implemented. Physical wallet review and broad verification-only acceptance are not carried forward; actual remaining native/protected-wrapper work is tracked by #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.

Closed at the user's request as part of consolidating issues #1449–#1500. Offline gas budgets, fee readiness, Max and signing consistency fixes are implemented. Physical wallet review and broad verification-only acceptance are not carried forward; actual remaining native/protected-wrapper work is tracked by #1504. Replacement: https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/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.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
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#1480
No description provided.