T09 · Insecure Skill Coding Practices
Warning
- Location
- scripts/liquidity_optimizer.py:29
- Finding
- Incorrect Impermanent-Loss and TVL Calculations Produce Misleading Financial Risk Reports<![CDATA[ ## Vulnerability Details **File Location**: `scripts/liquidity_optimizer.py:29-31`, `scripts/liquidity_optimizer.py:34-65`, `scripts/liquidity_optimizer.py:91`, `scripts/liquidity_optimizer.py:119-120`, and `scripts/liquidity_optimizer.py:142-144` **Vulnerability Type**: Financial calculation integrity error and insufficient input validation **Risk Level**: Medium ### Vulnerable Code ```python def calculate_impermanent_loss(price_ratio: float) -> float: """Calculate impermanent loss for a given price ratio change.""" return sqrt(price_ratio) - 1 ``` ```python def analyze_pool(pool: dict, investment: float = 1000) -> dict: """Analyze a single pool and estimate returns and IL risk.""" apr = pool["apr"] tvl = pool["tvl"] volume = pool["volume_24h"] # Estimate daily fees earned on $1000 investment daily_rewards = (investment * (apr / 100)) / 365 fee_yield = daily_rewards / investment * 100 # TVL concentration risk (higher TVL = safer pool) tvl_score = min(tvl / 10_000_000, 1.0) # Volume efficiency: fees/volume ratio fee_efficiency = pool["fees_24h"] / volume if volume > 0 else 0 # IL risk simulation (price change scenarios) scenarios = [ ("±10%", calculate_impermanent_loss(1.10), 0.10), ("±25%", calculate_impermanent_loss(1.25), 0.25), ("±50%", calculate_impermanent_loss(1.50), 0.50), ("±100%", calculate_impermanent_loss(2.00), 1.00), ] return { "protocol": pool["protocol"], "pair": pool["pair"], "apr": apr, "daily_rewards": daily_rewards, "fee_yield_daily_pct": fee_yield, "tvl_score": tvl_score, "volume_24h": volume, "fee_efficiency": fee_efficiency, "il_scenarios": scenarios, } ``` ```python print(f" TVL: ${pool['volume_24h']/1e6:.1f}M | Vol: ${pool['volume_24h']/1e6:.1f}M/day") ``` ```python il_from_drift = calculate_impermanent_loss(current_price / ((lower_tick + upp ...[truncated 3619 chars]
- Remediation
- <![CDATA[ ## Remediation Suggestions 1. **Implement the appropriate financial model** - For standard constant-product pools, use a reviewed formula such as: ```python def calculate_constant_product_il(price_ratio: float) -> float: if not math.isfinite(price_ratio) or price_ratio <= 0: raise ValueError("price_ratio must be a finite number greater than zero") return (2 * math.sqrt(price_ratio) / (1 + price_ratio)) - 1 ``` - For concentrated-liquidity pools, implement a range-aware calculation using the current price, entry price, lower bound, upper bound, and token composition. - Do not represent the constant-product approximation as an accurate CLMM calculation. 2. **Calculate upward and downward scenarios independently** - Replace labels such as `±50%` with separate scenarios. - For example, evaluate a 50% increase with `1.50` and a 50% decrease with `0.50`. - Avoid a “100% decrease” scenario because it implies a zero price ratio, which is outside the valid domain of formulas containing division or square roots. 3. **Preserve and display actual TVL** - Add the original TVL to the analysis result: ```python "tvl": tvl, ``` - Display `pool["tvl"]` as TVL and `pool["volume_24h"]` as volume. 4. **Validate all numeric inputs** - Reject non-numeric, non-finite, zero, and negative price ratios. - Validate that `investment` is finite and greater than zero. - Validate that prices and tick bounds are finite and positive. - Require `lower_tick < upper_tick`. - Prevent division by a zero midpoint. - Catch validation errors in the CLI and return a clear message with a nonzero exit status. 5. **Add automated tests** - Test known constant-product IL reference values. - Test reciprocal price ratios where appropriate. - Test upward and downward scenarios separately. - Test malformed, negative, zero, infinite, and NaN inputs. - Test that TVL and volume remain distinct in gener ...[truncated 396 chars]
