Skip to content

[OPTIMIZATION] UniswapV3SwapConnectors.getMaxAmount() hits computation limits - optimize with price impact heuristic #60

@liobrasil

Description

@liobrasil

Issue to be solved

The current getMaxAmount() implementation in UniswapV3SwapConnectors is hitting Cadence computation limits due to expensive tick bitmap scanning, requiring 20-30+ EVM calls per transaction.

Current approach:

  • Scans tick bitmap in a radius around current tick
  • Queries tickBitmap() and ticks() for each word
  • Simulates swap step-by-step through initialized ticks
  • Computationally expensive and causes transaction failures

Impact:

  • Transactions failing with computation limit errors
  • Poor user experience
  • Blocks swap functionality in production

In-scope: Optimize getMaxAmount() calculation to reduce EVM calls and prevent computation limits

Suggest A Solution

Replace tick-scanning with a lightweight price impact heuristic:

Technical implementation:

  • Uses only 2 EVM calls (slot0 + liquidity) instead of 20-30+
  • Calculates max amount based on configurable price impact tolerance
  • Uses mathematical approximation: sqrt(1 ± x) ≈ 1 ± x/2 for small x
  • Applies 80% safety margin for additional protection

Details:

  1. Add maxPriceImpactBps parameter (default: 500 = 5%, range: 1-5000 bps)
  2. Remove all tick bitmap scanning functions (~250 lines)
  3. Calculate max based on price impact formula:
    • For token0 → token1: maxAmount = (L × ΔsqrtP × Q96) / (sqrtP₀ × sqrtP₁)
    • For token1 → token0: maxAmount = (L × ΔsqrtP) / Q96

Trade-offs:

  • ⚠️ Less precise than full simulation (acceptable for protecting against oversized swaps)

Implementation: Already developed in PR #54

Caveats:

  • Approximation-based rather than exact calculation
  • May underestimate max in some edge cases
  • Requires testing across various pool states before production deployment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions