Developing a DeFi strategy yield calculator
User sees "APY 45%" on platform and deposits money. Three months later withdraws — got 8% in dollars. The rest was eaten by: entry and exit fees, gas on 12 transactions, impermanent loss in pool, tax on reward tokens that fell 70% by harvest time. Yield calculator is a tool that shows real numbers before decision is made.
What needs to be calculated correctly
APY vs. APR: one of the most common confusions in DeFi
APR (Annual Percentage Rate) — simple interest without reinvestment. APY (Annual Percentage Yield) — with compound interest. Difference is significant:
- APR 50% → APY ≈ 64.8% with daily compounding
- APR 50% → APY ≈ 100% with compounding every block (~12 sec on Ethereum)
Formula for APY from APR: APY = (1 + APR/n)^n - 1, where n is number of compounding periods per year.
Problem: in DeFi APY often displayed assuming constant rate and maximum compounding. In reality rate changes every block, and gas for every compound operation reduces actual returns.
Breakeven on compound frequency: At $5 gas per claim and $1000 position with APR 40% — optimal frequency is compound once every ~7 days. More often — gas costs more than compound earns. Calculator should compute optimal interval.
Impermanent loss for LP positions
For liquidity provider positions, returns cannot be calculated without impermanent loss (IL). Formula for Uniswap v2:
IL = 2 * sqrt(priceRatio) / (1 + priceRatio) - 1
For ETH/USDC pool: ETH entered at $2000, now $3000. priceRatio = 1.5. IL = 2×√1.5/(1+1.5) - 1 ≈ -2.02%.
For Uniswap v3 with concentrated liquidity, IL calculated differently — depends on position range. If price exits range, position becomes 100% one asset (full IL, no fees earned). Math is more complex but implementable: need tickLower, tickUpper, current tick.
Real components of returns for full calculation
interface YieldComponents {
baseApr: number; // Lending APR or trading fees
rewardApr: number; // Emission rewards in protocol tokens
compoundBonus: number; // Gain from reinvestment
impermanentLoss: number; // LP only (negative)
tradingFees: number; // Accumulated fees over period
gasCosts: number; // All on-chain operations in USD
tokenPriceImpact: number; // Change in reward token price
realYield: number; // Total in USD
}
How we build calculator
Data sources
-
Aave v3:
getReserveData()returnscurrentLiquidityRate(RAY = 1e27). Convert to APY:(1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1 -
Compound v3:
getUtilization()→getSupplyRate(utilization)→ linear APR calculation -
Uniswap v3: fees APR calculated via subgraph or
positions()NFT data — 24h volume × fee tier / TVL × 365 -
Curve:
get_virtual_price()for base APY + gauge reward APR via CRV emission schedule -
Balancer: vault API or subgraph for
swapFeeand volume
The Graph subgraph is preferred source for historical data. Direct RPC calls for real-time current rates.
Simulation over time horizon
Calculator should not just calculate current APY, but project to user horizon (30/90/365 days) with several scenarios:
| Scenario | Assumptions | Purpose |
|---|---|---|
| Optimistic | APR unchanged, reward price +50% | Maximum potential |
| Base | APR drops 20% per quarter (TVL growth) | Realistic estimate |
| Conservative | APR -50%, rewards -70% | Protection from wrong expectations |
| Bear market | APR minimum, all assets -50% | Stress test |
Gas cost calculation
Each operation has measurable gas cost:
const GAS_ESTIMATES = {
aaveDeposit: 180_000,
aaveWithdraw: 210_000,
uniswapV3Mint: 450_000,
uniswapV3Collect: 280_000,
curveDeposit: 320_000,
rewardClaim: 150_000,
} as const;
function calcGasCost(operation: keyof typeof GAS_ESTIMATES, gasPriceGwei: number): number {
const gasUnits = GAS_ESTIMATES[operation];
const ethPrice = getCurrentEthPrice();
return (gasUnits * gasPriceGwei * 1e-9) * ethPrice; // USD
}
Historical gas price data from Etherscan API or The Graph — for calculating average costs for given rebalancing/harvesting strategy.
Functionality and UX
Minimum set:
- Input amount and period
- Choose protocol/strategy (search by name)
- Real-time APR fetch from protocols
- Three scenarios (optimistic/base/conservative)
- Breakdown: base yield, rewards, impermanent loss, gas costs, net yield
- Compare multiple strategies side by side
Additionally — ROI breakeven calculator: at what minimum amount and duration does strategy cover gas costs. Especially important for small investors on Ethereum mainnet.
Stack
Frontend: React + TypeScript, Recharts for yield charts, wagmi for wallet connection. Data: The Graph (APR histories), Alchemy/Infura (real-time chain data), CoinGecko API (token prices). Logic: Typescript utility library with pure functions for all financial calculations — easy to test and reuse.
Timeline estimates
Basic calculator for 2-3 protocols — 3-5 days. Multi-protocol with historical data, LP IL and gas optimizer — 1-2 weeks. Cost calculated individually.







