Under the hood

Every formula.
Documented.

The complete methodology behind all 13 OrnyTools — models, data sources, assumptions, and known limits for every calculator.

Trade Size Optimizer (detailed) 1. Overview 2. Why √(G·TVL) underestimates 3. Exact constant-product solver 4. V3 on-chain liquidity 5. Orny confidence score 6. Known limitations Other tools 7. IL Calculator 8. RedZone 9. Leverage Calculator 10. V3 Range Optimizer 11. Yield Optimizer 12. Stablecoin Analyzer 13. Waste Detector 14. Aave V3 Calculator 15. GMX V2 Calculator 16. Position Dashboard
01 — Overview

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 key insight: the optimal size is not a function of gas alone. It depends on pool depth, fee tier, and — for V3 — the active liquidity at the current price. Two pools with the same TVL can have optimal sizes that differ by 5–10×.

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.


02 — The analytical formula

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:

SituationEffect on R_effectiveFormula 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 V3 problem: A pool showing $50M TVL may have only $2–5M of active liquidity near the current price. Plugging $50M into the formula gives an optimal size 3–5× too large, landing you in the slippage-dominated zone.

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.


03 — Exact solver

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.


04 — V3 on-chain liquidity

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.

1
Read slot0() — selector 0x3850c7bd
Returns a packed tuple. The first 160 bits encode sqrtPriceX96 — the square root of the current price in Q64.96 fixed-point format.
2
Read liquidity() — selector 0x1a686502
Returns 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.
3
Derive virtual reserves
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.

Why this matters: for a pool with $50M TVL but a tight ±1% range, 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.


05 — Orny confidence score

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 ptsPositiveTVL ≥ $10M — deep pool, slippage model is accurate across a wide size range
−5 ptsCautionTVL $500k–$1M — moderate depth, reserve estimate may drift with price
−12 ptsNegativeTVL < $500k — thin pool, constant-product approximation degrades
+4 ptsPositiveV3 depth read on-chain — R_eff is the real active liquidity, not TVL-based
−5 ptsCautionV3 pool with slider estimate — TVL proxy introduces a systematic error
−8 ptsNegativeTrade > 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.

Best-case configuration: V3 pool with on-chain active liquidity read, TVL ≥ $10M, trade size ≤ 5% of depth → confidence 92%. The on-chain read is the single highest-value action the user can take.

06 — Known limitations

What the model does not capture

In summary: OrnyTools gives you the mathematically correct answer for the inputs you provide. The quality of the output is bounded by the quality of the inputs — especially pool depth. On-chain V3 data is always more reliable than TVL-based estimates.

07 — IL Calculator

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.

Source: User inputs only (initial price, new price, range bounds). No external data fetched.

08 — RedZone

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.

Sources: Chainlink price feeds (live, on-chain via public RPC) · Protocol LT parameters (hard-coded from official docs, updated manually).

09 — Leverage Calculator

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).

Limitation: the model assumes constant LTV across all loops. In practice, borrow APY and supply APY fluctuate, and high utilization can raise borrow rates above supply rates mid-loop, eliminating the yield spread.

10 — V3 Range Optimizer

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.

Sources: User inputs (range, capital, fee tier) · GeckoTerminal 24h volume (to estimate base fee APR) · Volatility estimated from recent price history if available.

11 — Yield Optimizer

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.

Sources: User inputs (APR, capital, duration) · CoinGecko for token incentive prices · Protocol fee tiers from documentation.

12 — Stablecoin Analyzer

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.

DimensionWhat is scoredData source
Peg mechanismFiat-backed > crypto-backed > algorithmicHard-coded classification
Market capLiquidity proxy: larger supply = easier to exitCoinGecko live
Volume / Market capTrading velocity: high ratio = active arbitrage keeping peg tightCoinGecko live
Current price deviationDistance 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
Limitation: the analyzer uses current market prices and volumes, not historical depeg episodes. A stablecoin that is currently on-peg may have depegged significantly in the past. Always check DeFiLlama's stablecoin historical charts for UST-type tail risk.

13 — Waste Detector

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.


14 — Aave V3 Calculator

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
Multi-collateral note: the calculator models a single-collateral position. Real Aave V3 positions can have multiple collateral assets with different LTs. In that case, use the Position Dashboard (on-chain read) for accurate values.

15 — GMX V2 Calculator

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)
Approximations: borrow rate is estimated at 0.01%/h (the typical rate). Actual rates fluctuate with pool utilization. Opening fee is modeled at 0.07% (market order rate); limit orders are 0.05%. Verify current rates on GMX V2 before opening large positions.

16 — Position Dashboard

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.

Why this is the most reliable tool in the suite: it reads directly from the protocol's own state, using the same function Aave's UI calls. No modeling — just on-chain truth.
17 — Morpho Blue Calculator

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.
No grace period on Morpho Blue: unlike Aave V3 which has a liquidation bonus and health factor buffer, Morpho Blue liquidates at the exact LLTV boundary. A 1% price move past the liquidation price means full liquidation can be triggered. Keep a wider safety margin than you would on Aave.
Back to all tools
See also: Stablecoin RiskGuidesAbout