What is a Harvest Function?
A harvest function is a smart contract method that claims accumulated rewards from DeFi protocols and processes them. Typically by selling reward tokens and reinvesting the proceeds. It's the core mechanism enabling auto-compounding in yield aggregator vaults.
How Harvest Works
- Trigger: Keeper bot or user calls harvest()
- Claim: Function claims pending rewards
- Swap: Reward tokens swapped for deposit asset
- Reinvest: Proceeds deposited back into strategy
- Accounting: Vault shares updated to reflect gains
Harvest Function Components
```solidity
function harvest() external {
// 1. Claim rewards from farming contract
farmingPool.getReward();
// 2. Swap rewards to want token
uint256 rewardBalance = rewardToken.balanceOf(address(this));
router.swap(rewardToken, wantToken, rewardBalance);
// 3. Reinvest into strategy
deposit(wantToken.balanceOf(address(this)));
}
```
Harvest Timing
Manual Harvest
- Anyone can call the function
- Often incentivized with small rewards
- May be suboptimal timing
Automated Harvest
- Keeper bots monitor and execute
- Optimized for gas vs reward balance
- Services like Gelato, Chainlink Keepers
Harvest Economics
Profitable harvest when:Reward Value > Gas Cost + Slippage + Caller Incentive
Larger TVL vaults can harvest more frequently because fixed gas costs are spread across more capital.
Caller Incentives
- Gas reimbursement
- Bounty (% of harvest)
- Protocol token rewards
- Priority access to harvest
Security Considerations
- MEV protection for swaps
- Slippage limits
- Price oracle checks
- Access control on sensitive functions
Harvest in Practice
Beefy Finance harvests range from every few minutes (high TVL) to daily (smaller vaults), optimizing the gas cost vs compounding benefit trade-off.