The foundational mechanisms and strategies that enable yield optimizers to automatically reinvest rewards to maximize returns.
How Yield Optimizers Compound Rewards Automatically
Core Concepts of Automated Compounding
Harvesting and Gas Optimization
Harvesting is the process of claiming accrued rewards from a liquidity pool or farm. Optimizers batch transactions across many users to amortize gas costs.
- Uses keeper bots or MEV strategies to trigger harvests at optimal times.
- Aggregates small rewards into large sums before claiming to improve cost efficiency.
- This reduces the individual gas burden, making small-yield positions viable.
Reward Conversion and Swapping
Reward Tokens earned (e.g., SUSHI, CRV) are often not the same as the principal tokens. Optimizers automatically swap them.
- Uses decentralized exchanges (DEXs) or internal liquidity to convert rewards to the base asset.
- Implements slippage control and route optimization to maximize swap value.
- This ensures all value is consolidated into compoundable assets, removing manual steps.
Reinvestment and Compounding
Reinvestment is the core action where swapped assets are added back to the principal stake. This exploits compound interest.
- Automatically stakes the newly acquired tokens back into the original vault or strategy.
- Frequency of compounding (daily, weekly) is a key performance variable.
- This automated loop turns linear yield growth into exponential growth over time.
Vault Strategy and Risk Management
A Vault Strategy is the smart contract logic dictating where and how funds are deployed. It manages underlying risks.
- Continuously monitors for safer or higher-yielding opportunities (yield farming).
- May implement emergency exits or de-risking in case of protocol exploits.
- This abstracts complexity from users, who deposit a single token while the strategy handles the rest.
Performance Fees and Incentives
Performance Fees are how optimizer protocols generate revenue, typically a percentage of yield earned.
- Fees are often taken in the harvested reward tokens upon each compounding cycle.
- Aligns protocol incentives with user success; the protocol earns more when users do.
- This sustainable model funds further development, security audits, and keeper networks.
APY Calculation and Reporting
APY (Annual Percentage Yield) displayed includes the projected effect of automated compounding. It's a forward-looking metric.
- Calculated based on current reward rates and the optimizer's compounding frequency.
- Can be volatile as it depends on fluctuating token prices and farm emissions.
- Users must understand this is an estimate, not a guarantee, based on current conditions.
The Automated Compounding Workflow
Process overview
Monitor and Harvest Rewards
The optimizer contract checks for claimable rewards on the underlying protocol.
Detailed Instructions
The keeper bot or automated script calls the optimizer's harvest() function on a predetermined schedule, typically via a cron job or Gelato Network task. This function interacts with the underlying yield source, such as a Curve Gauge or Aave aToken pool, to claim accrued rewards like CRV or stkAAVE.
- Sub-step 1: The contract checks the pending reward balance by calling the source protocol's reward function (e.g.,
claimable_reward(address)). - Sub-step 2: If the reward value exceeds a predefined gas cost threshold (e.g., $50 worth of tokens), the harvest transaction is executed.
- Sub-step 3: The claimed reward tokens are transferred to the optimizer's contract address for processing.
solidity// Example harvest function snippet function harvest() external onlyKeeper { uint256 pending = gauge.claimable_reward(address(this), rewardToken); require(pending > minHarvestThreshold, "Rewards below threshold"); gauge.get_reward(); emit Harvested(rewardToken, pending); }
Tip: The gas threshold is crucial for profitability; it's often dynamically adjusted based on current network gas prices and token value.
Swap Rewards for Vault Assets
Harvested reward tokens are converted into the vault's primary deposit asset.
Detailed Instructions
After harvesting, the optimizer holds reward tokens (e.g., CRV) that are not the vault's base asset (e.g., USDC). The contract uses a DEX aggregator like 1inch or a direct pool on Uniswap V3 to swap these tokens efficiently. The goal is to minimize slippage and maximize the amount of base asset obtained.
- Sub-step 1: The contract approves the DEX router to spend the harvested reward tokens.
- Sub-step 2: It executes a swap, often using a minimum amount out parameter to protect against front-running and excessive slippage. This is calculated based on a current oracle price and a allowed slippage tolerance (e.g., 0.5%).
- Sub-step 3: The received base assets (e.g., USDC, ETH) are now held in the optimizer's contract balance.
solidity// Example swap call to a DEX aggregator IERC20(rewardToken).approve(address(oneInchRouter), amount); (uint256 returnAmount, ) = oneInchRouter.swap( IERC20(rewardToken), IERC20(wantToken), amount, minReturnAmount, address(this), new bytes(0) );
Tip: Optimizers often split large swaps across multiple DEXs or use on-chain liquidity pools to achieve better rates than a single venue.
Re-deposit Compounded Assets
The newly acquired base assets are staked back into the underlying yield-bearing position.
Detailed Instructions
The swapped base assets are now re-deposited into the core yield strategy. This increases the user's share of the vault without requiring new capital. The contract calls the deposit function of the underlying protocol (e.g., Curve's add_liquidity or Aave's deposit).
- Sub-step 1: The contract approves the underlying protocol to spend the base assets.
- Sub-step 2: It deposits the assets, receiving LP tokens or aTokens in return. For complex strategies, this may involve adding liquidity to a specific Curve pool metapool.
- Sub-step 3: The newly received yield-bearing tokens are added to the optimizer's total staked balance, increasing the underlying principal for all vault shareholders proportionally.
solidity// Example deposit into a Curve pool IERC20(wantToken).approve(address(curvePool), depositAmount); uint256 lpReceived = curvePool.add_liquidity([depositAmount, 0], minLpAmount); // Then stake the LP tokens gauge.deposit(lpReceived);
Tip: The
minLpAmountparameter is vital to prevent sandwich attacks during the deposit transaction, ensuring a minimum quantity of LP tokens is received.
Update Vault Share Accounting
The vault's total assets and exchange rate are recalculated to reflect the compounded growth.
Detailed Instructions
After the deposit, the optimizer must update its internal accounting. The key metric is the vault share price or price per share (PPS), which increases slightly due to the compounded rewards. This is calculated as totalAssets() / totalSupply().
- Sub-step 1: The contract calls a function to calculate the total value of assets it controls, including the newly deposited amount. This often involves querying the price of LP tokens from an oracle.
- Sub-step 2: It emits an event (e.g.,
StrategyReported) logging the harvest details: profit generated, total assets, and new PPS. - Sub-step 3: Users can now see their vault token balance is worth more underlying assets, as the redeemable value per share has increased.
solidity// Example function to update and report state function _updateVaultState() internal { uint256 totalAssetsBefore = lastReportedAssets; uint256 totalAssetsNow = estimatedTotalAssets(); // Sums all staked positions uint256 profit = totalAssetsNow - totalAssetsBefore; // Increase the vault's recorded total assets vault.report(profit, 0); emit HarvestReported( block.timestamp, profit, totalAssetsNow, vault.pricePerShare() ); }
Tip: The
estimatedTotalAssets()function is a critical piece of on-chain logic that must accurately value often illiquid LP positions, sometimes using time-weighted average price oracles (TWAPs).
Common Compounding Strategies
Comparison of automated reward compounding approaches used by yield optimizers.
| Strategy Parameter | Time-Based | Gas-Optimized | Yield-Threshold |
|---|---|---|---|
Primary Trigger | Fixed interval (e.g., every 6 hours) | Gas price below 30 Gwei | Accrued rewards > 0.5% of position |
Gas Efficiency | Low (can compound at high gas) | High (waits for cheap txs) | Medium (depends on yield accrual speed) |
Capital Efficiency | High (frequent compounding) | Variable (delays during high gas) | Very High (compounds only when profitable) |
Typical Protocol Fee | 20% performance fee on yield | 15% performance fee on yield | 10% performance fee + 0.5% harvest fee |
Best For | High APR pools (>50% APY) | Users sensitive to gas costs | Large TVL positions (>$100k) |
Rebalance Frequency | Predictable, scheduled | Opportunistic, irregular | Irregular, yield-dependent |
Example Optimizer | Yearn Finance vaults | Beefy Finance on L2s | Idle Finance tranches |
Smart Contract Complexity | Medium (requires keeper network) | Low (simple gas oracle check) | High (requires yield oracle and math) |
Protocol-Specific Implementations
How Major Protocols Handle Auto-Compounding
Auto-compounding is the process where a yield optimizer automatically reinvests your earned rewards to generate more rewards. Different protocols implement this core mechanism in distinct ways, affecting your returns and risk.
Key Implementation Styles
- Vault-Based (Yearn Finance): Your deposited assets are pooled into a single, automated strategy vault. The protocol's keepers harvest rewards, swap them for more of the underlying asset, and redeposit them on a regular schedule, increasing your share of the vault.
- Gauge Voting (Convex Finance): Users deposit liquidity provider (LP) tokens like Curve's crvUSD/FRAX. Convex collects CRV and CVX rewards, converts a portion to the underlying LP tokens, and automatically stakes them back into the gauge, compounding your position.
- Rebasing (Lido Finance): While not a traditional optimizer, stETH demonstrates a passive compounding effect. Your stETH balance increases daily as staking rewards are automatically minted and distributed, representing your growing share of the pooled ETH stake.
Practical Outcome
When you deposit DAI into a Yearn vault, you receive yvDAI tokens. Over time, the value of each yvDAI token increases relative to DAI as rewards are harvested and compounded, without you taking any action.
The Math of Compounding
Understanding the exponential growth mechanics and key variables that determine final yield in automated compounding strategies.
Compounding Frequency
Compounding frequency refers to how often earned rewards are harvested and reinvested. Common intervals are daily, hourly, or per-block.
- More frequent compounding accelerates APY growth due to earning on previously earned rewards.
- Example: A 100% APR compounded daily yields ~171% APY, while compounded hourly yields ~171.5% APY.
- This matters as it directly impacts the effective yield, making frequency a critical protocol design choice.
APR vs. APY
APR (Annual Percentage Rate) is the simple interest rate without compounding. APY (Annual Percentage Yield) includes the effect of compounding.
- APY = (1 + (APR / n))^n - 1, where 'n' is compounding periods per year.
- Example: A 10% APR compounded monthly (n=12) results in a 10.47% APY.
- Users must distinguish between the two to accurately compare yields across different optimizer strategies.
Gas Cost Optimization
Gas optimization is the process of minimizing transaction fees incurred during harvest and compound operations.
- Optimizers batch user transactions or wait for optimal gas prices to compound.
- Example: A strategy may compound only when the expected yield increase outweighs the gas cost.
- This matters because high gas costs can negate the benefits of frequent compounding, especially on Ethereum L1.
Time Value of Assets (TVL Impact)
The Time Value of Assets principle states that the total value locked (TVL) and its growth rate affect individual returns.
- In liquidity pools, larger TVL can dilute rewards per depositor if emissions are fixed.
- Example: Early depositors in a new vault may see higher yields before TVL scales.
- This highlights why monitoring a protocol's TVL growth is essential for yield forecasting.
Impermanent Loss Consideration
Impermanent Loss (IL) is the potential loss compared to holding assets, experienced by liquidity providers in automated market maker (AMM) pools.
- Yield optimizers farming LP tokens must weigh high yields against IL risk.
- Example: A pool with 50% APY may still result in a net loss if token prices diverge significantly.
- This matters for users to assess the true, risk-adjusted return of a compounding strategy.
Reward Token Volatility
Reward token volatility refers to the price fluctuation of the tokens earned as yield, which impacts the real USD value of compounded rewards.
- High volatility can lead to significant value changes between harvest cycles.
- Example: Compounding a volatile token during a market downturn locks in lower-value assets.
- This is a key risk factor, as the nominal APY may not reflect the realized USD return.
Risks and Considerations
Further Resources
Ready to Start Building?
Let's bring your Web3 vision to life.
From concept to deployment, ChainScore helps you architect, build, and scale secure blockchain solutions.