What the optimizer solves
Every swap on an AMM carries two competing costs: a fixed gas cost that dominates small trades, and a slippage cost that grows with trade size. Plotted against trade size, their sum forms a U-curve with a minimum — the optimal trade size.
The optimizer finds the exact bottom of that U-curve for any pool, using the full constant-product math rather than a linearized approximation.
The total cost function minimized is:
C(A) = G/A + A/(R+A) + fee ↑ ↑ ↑ gas % slippage % pool fee %
where A is the trade size (USD), G is the gas cost (USD, fixed), R is the effective one-sided reserve (USD), and fee is the pool fee as a fraction.
Why √(G·TVL) underestimates
A commonly cited shortcut for the optimal trade size is the closed-form solution derived by linearizing slippage. Assuming A ≪ R (trade size much smaller than pool depth):
Approximate slippage: A/(R+A) ≈ A/R (when A ≪ R)
C(A) ≈ G/A + A/R + fee
dC/dA = −G/A² + 1/R = 0
A_opt ≈ √(G·R) = √(G · TVL/2)
For example, with G = $2.50 and TVL = $5M:
A_opt = √(2.50 × 2,500,000) = √6,250,000 ≈ $2,500
Where the approximation breaks down
The formula uses A/R for slippage. The exact constant-product formula is A/(R+A). These diverge as A approaches R — which happens in three real-world situations:
| Situation | Effect on R_effective | Formula error |
|---|---|---|
| Unbalanced pool (price has moved) | R < TVL/2 | Overestimates A_opt |
| V3 concentrated liquidity | R_active ≪ TVL/2 (5–20% typical) | Overestimates A_opt by 3–10× |
| Deep pool, tiny trade | A/R → 0 | Formula is accurate |
The formula also assumes a balanced pool (50/50 token split). Any price movement creates an imbalanced pool where the effective one-sided depth R differs from TVL/2. These compounding errors are why empirical measurements show the analytical formula can underestimate slippage by a factor of 3–5× on live V3 pools.
Constant-product ternary search
Rather than approximating, OrnyTools minimizes the exact cost function numerically via ternary search — a derivative-free method for unimodal functions that converges in O(log n) iterations.
The exact cost model
// Exact slippage from constant-product AMM (x·y = k) // One-sided reserve R = effective depth (USD) // Trade of size A pushes the pool by A tokens slippage_USD(A, R) = A² / (R + A) gas_share(A) = G / A fee_cost(A) = fee × A C(A) = G/A + A/(R+A) + fee ← cost per dollar traded
Ternary search
The cost function C(A) is strictly unimodal on (0, ∞): it decreases from infinity as gas dominates at small A, reaches a minimum, then increases as slippage dominates at large A. This guarantees ternary search converges to the global minimum.
// Ternary search on [lo, hi] — O(log n) evaluations lo = 0.01, hi = R × 0.5 while hi − lo > 0.01: m1 = lo + (hi − lo) / 3 m2 = hi − (hi − lo) / 3 if C(m1) < C(m2): hi = m2 else: lo = m1 A_opt = (lo + hi) / 2
The search converges to $0.01 precision in under 50 iterations. There is no closed-form derivative required, and the result is exact for any R value — including the small active-liquidity values typical of tight V3 ranges.
Fee tier inclusion
The pool fee fee × A is a linear term in total cost. Its derivative is constant, so it does not shift the minimum of the cost-per-dollar curve — it only raises the floor uniformly. The fee is included in the displayed total cost but does not change A_opt. This is a known property of proportional fee models and applies equally to 0.05%, 0.3% and 1% fee tiers.
From slot0() to virtual reserves
For Uniswap V3 pools, TVL shown on GeckoTerminal or DefiLlama includes all liquidity across all price ranges — most of which is inactive. The engine reads the real active liquidity directly from the contract via raw eth_call, without any third-party library.
0x3850c7bdReturns a packed tuple. The first 160 bits encode
sqrtPriceX96 — the square root of the current price in Q64.96 fixed-point format.0x1a686502Returns the active liquidity
L at the current price. This is the liquidity that earns fees on the next swap — a real-time measure of depth, not a TVL proxy.The V3 virtual reserve model gives the amount of each token providing the active liquidity
L:// Q96 = 2^96 (fixed-point denominator) sqrtP = sqrtPriceX96 / 2^96 // Virtual reserves from active liquidity L and current sqrt-price x_virtual = L / sqrtP (token0 amount, in token0 units) y_virtual = L × sqrtP (token1 amount, in token1 units) // Convert to USD using GeckoTerminal spot prices p0, p1 R_eff = (x_virtual × p0 + y_virtual × p1) / 2
R_eff is the effective one-sided depth — the value used in the cost function. It directly represents the pool's capacity to absorb a swap near the current price, accounting for tick concentration.
R_eff may be $3–8M. Using TVL directly overestimates depth by 6–15× and produces an optimal size far into the slippage-heavy zone.
RPC fallback chain
All on-chain reads go through a fallback RPC array per chain. If the primary endpoint fails or returns 0x, the engine retries on the next endpoint. Ethereum uses three public nodes (publicnode, llamarpc, cloudflare). Arbitrum and Base each use two. If all endpoints fail, the engine falls back to the TVL-based slider estimate and flags the lower confidence accordingly.
How the confidence score is computed
The score reflects the engine's certainty that the recommended size is close to the true optimum, given the quality of the inputs. It starts at a base of 88% and adjusts for known error sources:
| +4 pts | Positive | TVL ≥ $10M — deep pool, slippage model is accurate across a wide size range |
| −5 pts | Caution | TVL $500k–$1M — moderate depth, reserve estimate may drift with price |
| −12 pts | Negative | TVL < $500k — thin pool, constant-product approximation degrades |
| +4 pts | Positive | V3 depth read on-chain — R_eff is the real active liquidity, not TVL-based |
| −5 pts | Caution | V3 pool with slider estimate — TVL proxy introduces a systematic error |
| −8 pts | Negative | Trade > 8% of pool depth — the first-order constant-product model degrades at high price impact; tick boundaries become relevant |
The score is clamped to [52%, 97%]. A score of 97% is never reached — the remaining 3% accounts for unknowable factors (pool imbalance at execution time, MEV, network latency). A score below 65% triggers a Orny Warning and a recommendation to use a deeper pool or on-chain data.
What the model does not capture
- Single-hop only. The optimizer models a direct swap on one pool. Aggregators (1inch, Paraswap) split volume across multiple pools, reducing effective slippage for large trades. For sizes where splitting is optimal, the simulator's "split recommendation" tab provides an estimate.
- Balanced reserve assumption. The model assumes
R = TVL / 2for V2 pools (equal token values). Pools that have drifted from 50/50 due to price movement have different effective depths per side. The on-chain V3 read corrects for this; V2 remains approximate. - Static tick range. V3 liquidity is distributed across price ticks. The
liquidity()call returns the active liquidity at the current tick only. For large trades that cross multiple ticks, the real average depth is lower. The −8pt confidence penalty at high price-impact sizes partially accounts for this. - No MEV model. Sandwich attacks and backrunning add an effective cost that depends on mempool conditions and block builder behavior. This is not modelable from on-chain data alone. Use private mempools (Flashbots Protect, MEV Blocker) for sensitive trades.
- Gas price is user-supplied. The model uses the gas cost entered by the user. On Ethereum mainnet, the actual gas cost varies with block congestion. On Arbitrum and Base, gas costs are near-deterministic and the defaults ($0.05 and $0.02 respectively) are reliable.
- Token prices via GeckoTerminal. The USD conversion for V3 reserve calculation uses GeckoTerminal spot prices fetched at load time. Rapid price movements between fetch and execution introduce a small reserve estimation error.
Impermanent Loss
Impermanent loss is the difference in value between holding tokens in a liquidity pool vs holding them in a wallet, caused by the pool rebalancing against price movements.
V2 constant-product formula
// r = price_new / price_initial (price ratio) IL = 2 × √r / (1 + r) − 1 // Examples: r = 2.0 (price doubled) → IL = −5.72% r = 4.0 (price 4×) → IL = −20.0% r = 0.5 (price halved) → IL = −5.72% r = 0.25 (price down 75%) → IL = −20.0%
IL is symmetric around the initial price: a 2× increase causes the same IL as a 50% decrease. It only becomes realized when you withdraw — if the price returns to its initial value before you exit, IL is zero.
V3 concentrated range adjustment
In Uniswap V3, IL only applies when the price is within the LP's range. Outside the range, the position is 100% in one token and earns no fees. The effective IL is scaled by the fraction of time the position spends in range. The calculator uses user-specified price bounds to compute the range-adjusted IL.
Multi-chain Liquidation Calculator
RedZone computes the liquidation price and safe collateral floor for any asset on Aave V3, Compound, Morpho and equivalent protocols — across 6 chains. It uses Chainlink price feeds as the primary oracle, replicating the exact calculation the protocol runs on-chain.
Health Factor and liquidation condition
// Aave V3 Health Factor (multi-collateral, multi-debt) HF = Σ(collateral_i × price_i × LT_i) / Σ(debt_j × price_j) // Liquidation triggers when HF < 1 // Single-collateral simplification (RedZone default): P_liq = debt_USD / (collateral_qty × LT) // Drop to liquidation (% from current price): Δ% = (P_current − P_liq) / P_current × 100
LT (Liquidation Threshold) is the protocol parameter above the LTV: it defines the maximum debt-to-collateral ratio before liquidation. Values are hard-coded per asset per protocol and updated when protocols upgrade their risk parameters.
Recursive Loop Leverage
The Leverage Calculator models the supply-borrow loop strategy: deposit collateral → borrow stablecoin → swap to collateral asset → re-deposit → repeat. This recursion amplifies both gains and exposure.
// After n loops with LTV ratio: final_collateral = initial × (1 − LTV^(n+1)) / (1 − LTV) // Limit as n → ∞ (geometric series): max_collateral = initial / (1 − LTV) leverage_ratio = 1 / (1 − LTV) // Example: LTV = 0.80, $1,000 initial max_collateral = 1,000 / 0.20 = $5,000 (5× leverage) // Liquidation price (single-collateral loop): P_liq = P0 × (debt_total / (collateral_total × LT))
Each loop cycle also costs gas (1 approval + 1 deposit + 1 borrow + 1 swap). The calculator displays the cumulative gas cost and the break-even time (how many days of yield to recover loop gas).
Concentrated Liquidity Range
Uniswap V3 LPs concentrate capital between a lower and upper price bound. The tool finds the range that maximizes fee revenue per dollar of capital, given an estimate of time spent in range.
// Capital efficiency vs a V2 position: CE = 1 / (1 − √(P_lower/P_upper)) // For a ±10% range (P_lower=0.9×P, P_upper=1.1×P): CE = 1 / (1 − √(0.9/1.1)) ≈ 10.5× // Expected fees accounting for % time in range: fee_APR = V2_fee_APR × CE × time_in_range // Impermanent loss risk at range boundary: // When price exits range, position becomes 100% in one token. // Effective IL if price exits and stays out: IL_at_exit = IL(P_boundary / P_entry)
The time_in_range estimate uses a log-normal price model: given current price volatility (σ, annualized), the probability that the price stays within [P_lower, P_upper] after T days is derived from the normal CDF applied to log returns.
APR / APY Compound Model
The Yield Optimizer compares DeFi yield sources on a normalized basis: same capital, same duration, after compounding frequency and protocol fees.
// APR → APY (n = compoundings per year) APY = (1 + APR/n)^n − 1 // Continuous compounding limit: APY_continuous = e^APR − 1 // Net yield after protocol fees and gas (annualized): net_APY = gross_APY × (1 − protocol_fee_rate) − (gas_per_compound × compounds_per_year) / capital // Break-even compounding frequency (minimizes gas drag): // Compound when earned_yield > gas_cost_of_compound compound_when: capital × APR × Δt > gas_cost
Token incentives (liquidity mining rewards) are treated separately: their USD value is computed at current market price and added to the base APY. The tool flags when token incentive APY exceeds base APY by more than 3× — a sign of unsustainable yield that typically resets when emissions slow.
Peg Stability Scoring
The Stablecoin Analyzer scores each stablecoin on four dimensions and produces a composite risk/yield rating. The goal is to surface the trade-off between yield and peg stability — two variables that are often inversely correlated.
| Dimension | What is scored | Data source |
|---|---|---|
| Peg mechanism | Fiat-backed > crypto-backed > algorithmic | Hard-coded classification |
| Market cap | Liquidity proxy: larger supply = easier to exit | CoinGecko live |
| Volume / Market cap | Trading velocity: high ratio = active arbitrage keeping peg tight | CoinGecko live |
| Current price deviation | Distance from $1.00 — penalized exponentially above 0.2% | CoinGecko live |
// Liquidity score (0–100) composite: mech_score = {fiat:40, crypto:25, algo:10}[mechanism] mcap_score = log10(mcap_usd) × 6 // capped at 30 vel_score = min(30, vol_mcap_ratio × 150) peg_score = max(0, 30 × (1 − |price−1| / 0.005)) liquidity_score = mech_score + mcap_score + vel_score + peg_score
Quantifying DeFi Inefficiency
The Waste Detector runs the Trade Optimizer in reverse: given your actual trade history (size, pool, gas paid), it computes what the optimal size would have been and quantifies the excess cost.
// For each historical trade of size A_actual: A_opt = ternary_search(gas, R, fee) ← exact solver // Excess cost per trade: excess_pct = C(A_actual) − C(A_opt) ← cost per dollar excess_usd = excess_pct × A_actual // Annual projection (from weekly trades): waste_annual = excess_usd × 52 // Category labels: excess < 0.1% → "Efficient" excess 0.1–0.5% → "Moderate waste" excess > 0.5% → "Significant waste — consider splitting"
The tool also flags gas waste separately: trades where the gas cost represented more than 1% of trade value are labeled "gas-dominated" — these should either be batched or made larger.
Health Factor & Borrow Power
The Aave V3 Calculator is a simulation tool: it takes your current or hypothetical position and projects HF, liquidation price, maximum borrow, and stress scenarios. Unlike the Position Dashboard, it does not read on-chain state — it takes user inputs and applies Aave's formulas.
// Health Factor: HF = collateral_USD × LT / debt_USD // Maximum borrow (LTV constraint): max_borrow = collateral_USD × LTV − debt_existing // Borrow power used (%): borrow_pct = debt_USD / (collateral_USD × LTV) × 100 // Price at liquidation (uniform price drop on collateral): P_liq = P_current × debt_USD / (collateral_USD × LT) // Stress test (−30% price shock): HF_stressed = collateral_USD × 0.70 × LT / debt_USD
Perpetual Position Fees & Liquidation
The GMX V2 Calculator models the full cost of a perpetual position on GMX V2 (Arbitrum): opening fee, borrowing fee, and the exact liquidation price for both long and short positions. Entry price is fetched live from CoinGecko.
// Position sizing: size = collateral × leverage borrowed = size − collateral // Fees (GMX V2 standard parameters): fee_open = size × 0.0007 × 2 ← open + close (0.07% each) fee_borrow = borrowed × 0.0001 × hours ← ~0.01%/h on borrowed fee_total = fee_open + fee_borrow // Liquidation price: // Triggered when (collateral − fees) < maintenance_margin × size // maintenance_margin = 1% LONG: P_liq = P0 × (1 − (collateral − fee_total − 0.01×size) / size) SHORT: P_liq = P0 × (1 + (collateral − fee_total − 0.01×size) / size) // Break-even price (minimum move to cover fees): LONG: P_break = P0 + fee_total / (size / P0) SHORT: P_break = P0 − fee_total / (size / P0)
On-chain Aave V3 State Reader
The Position Dashboard fetches live Aave V3 account data for any Arbitrum address by calling getUserAccountData(address) directly on the Aave Pool contract — no API key, no third-party indexer, no wallet connection.
// Contract: Aave V3 Pool on Arbitrum // 0x794a61358D6845594F94dc1DB02A252b5b4814aD // Selector: 0xbf92857c (getUserAccountData) // Returns 6 × uint256 (ABI-encoded, 32 bytes each): [0] totalCollateralBase / 1e8 → USD [1] totalDebtBase / 1e8 → USD [2] availableBorrowsBase / 1e8 → USD [3] currentLiquidationThreshold / 1e4 → fraction (e.g. 0.82) [4] ltv / 1e4 → fraction (e.g. 0.80) [5] healthFactor / 1e18 → HF (e.g. 1.87) // Margin to liquidation (uniform price drop estimate): liq_factor = debt / (collateral × liq_threshold) drop_to_liq = (1 − liq_factor) × 100%
The drop_to_liq value assumes a uniform price movement across all collateral assets. In reality, a position with mixed collateral (e.g. WBTC + ETH) has a liquidation price that depends on the correlation of those assets — a correlated drop is more dangerous than the uniform estimate suggests.
Isolated Market Health Factor & Loop Simulator
Morpho Blue has no global pool — each market is a standalone pair (collateral / loan token) with its own fixed LLTV. Unlike Aave, there is no grace period: liquidation triggers the instant LTV exceeds LLTV.
// Per-market inputs: collateral amount, borrow amount, price, LLTV LTV = borrow / (collateral × price) HF = (collateral × price × LLTV) / borrow liqPrice = borrow / (collateral × LLTV) // Drop to liquidation (% collateral price decline): dropToLiq = (1 − LTV / LLTV) × 100% // HF = LLTV / LTV → HF > 1 = safe, HF ≤ 1 = liquidatable
Loop simulator: each loop borrows a fraction r of remaining LLTV capacity and buys more collateral. After N loops:
// r = LLTV × (utilization% / 100) e.g. 86% × 80% = 0.688 // Each loop adds r × current_collateral to collateral and debt: col_n = col_0 × (1 + r + r² + … + rⁿ) = col_0 × (1 − rⁿ⁺¹) / (1 − r) debt_n = col_0 × (r + r² + … + rⁿ) = col_0 × r × (1 − rⁿ) / (1 − r) // Effective leverage after N loops: leverage = col_n / col_0 → converges to 1/(1−r) as N→∞ // Final HF is computed identically to the single-position formula.