DeFi yield farming pays users, usually in a protocol token, for supplying liquidity or capital to a protocol. This guide explains the reward contracts, vaults, impermanent loss and yield figures behind a farm, and the incentive designs that keep liquidity after rewards drop.
How liquidity mining started
Liquidity mining spread in mid-2020, when Compound began paying its COMP token to lenders and borrowers. Within weeks, other protocols paid their own tokens to anyone who deposited LP tokens, and farmers moved capital between protocols to chase the highest APY.
A DeFi yield farming position has three layers:
- Base yield: trading fees from an AMM LP position, interest from a lending market or staking rewards.
- Incentive yield: extra tokens a protocol emits to attract capital.
- Strategy layer: vaults that claim incentives, sell them and reinvest, so users compound without manual work.
A farming platform can work at any of these layers: a new DEX runs an incentive program on its own pools, while a yield aggregator builds vaults on top of other protocols' farms.
Incentive contracts
MasterChef
SushiSwap introduced the MasterChef contract, and many forks copied it. MasterChef pays a fixed amount of reward token per block and splits it across pools by allocation points. Each pool stores an accRewardPerShare value, and each user stores a rewardDebt. A user's pending reward is amount × accRewardPerShare − rewardDebt, where amount is the user's staked LP balance.
Forks have shipped dangerous changes to MasterChef. Some added owner-callable migrators that can move all staked LP tokens, others added uncapped minting, and some added deposit fees that the owner can raise to 100%. Any inherited MasterChef needs a line-by-line review, and the PancakeSwap clone script guide lists these risks in detail.
Gauges and vote-escrow
Curve's model moves emission decisions away from the core team. Token holders lock CRV to get veCRV, and their votes set the weights of the liquidity gauges that receive emissions. Protocols that want liquidity in their pools then buy voting power or pay holders to vote for those pools, and these payments are called bribes. Convex collected large amounts of veCRV and built a business on these vote payments.
In a gauge system, many token holders decide emissions instead of one owner. Gauge systems are complex, and a holder or group that collects most of the voting power controls the emissions.
Rewards computed off-chain
Some programs compute rewards off-chain from event data: the operator publishes a Merkle root, and users claim against that root. This model supports detailed rules without costly on-chain bookkeeping. For example, a rule can reward a concentrated liquidity position only while the current price sits inside the position's range. Incentive platforms such as Merkl run this model as a service.
Users must trust the operator to compute the root correctly, though publishing the scripts and input data lets anyone check the result.
Vaults and auto-compounders
A vault accepts deposits, issues shares and runs a strategy. The ERC-4626 standard defines the vault interface: deposit, mint, withdraw, redeem, plus functions that preview and convert amounts. Lending markets, aggregators and dashboards already read this interface.
Vaults carry four specific risks:
- Inflation (donation) attack: in an empty vault, the first depositor mints one share and then sends a large amount of the asset straight to the vault. The share price jumps, and the next depositor's shares round down to zero. OpenZeppelin's ERC-4626 implementation uses virtual shares and assets plus a decimal offset, which makes the attack unprofitable. Dead shares minted at deployment or a minimum first deposit also help.
- Harvest sandwiching: when a vault sells reward tokens, MEV bots can trade before and after the swap. Use slippage limits based on an oracle, private transaction submission or smaller, more frequent harvests.
- Share-price manipulation: if
totalAssets()reads a spot price or a balance that one transaction can move, attackers deposit at a low price and withdraw at a high one. Harvest Finance lost tens of millions of dollars this way in October 2020, after an attacker used flash loans to move prices in a Curve pool. - Strategy loss: the underlying protocol can be exploited, lose its peg or freeze withdrawals, and vault depositors carry every risk of the protocols underneath.
The Yearn Finance protocol guide covers aggregator architecture in more depth.
Impermanent loss in DeFi yield farming
Most farms reward LP positions, and LPs in a constant-product pool suffer impermanent loss when the two asset prices move apart. If one asset's price changes by a factor r against the other, the LP position is worth 2√r / (1 + r) of the value of simply holding both assets.
| Relative price change | LP value compared with holding |
|---|---|
| 1.25× (25%) | about −0.6% |
| 1.5× (50%) | about −2.0% |
| 2× | about −5.7% |
| 4× | −20% |
| 5× | about −25.5% |
Concentrated liquidity earns more fees inside the chosen price range, and it also suffers larger impermanent loss there. Most farm APY figures do not subtract impermanent loss, so the interface should show the loss next to the yield.
APR, APY and TVL
Farm dashboards show three figures that readers often confuse, so the interface should define each one:
- APR is the simple yearly rate without compounding: rewards per year divided by the value deposited.
- APY assumes rewards are reinvested. With
ncompounding periods a year,APY = (1 + APR/n)^n − 1. A 100% APR compounded daily becomes about 171.5% APY. That figure holds only if the user compounds daily, the reward token price stays flat and gas costs stay small. An APY shown for a farm without auto-compounding overstates what users receive. - TVL (total value locked) is the market value of assets in the contracts. TVL moves with token prices and can count the same deposit twice when one protocol deposits into another. It measures size, not revenue or safety.
Farms compute APR and APY from the current emission rate, the current reward-token price and the current deposits. All three inputs change constantly: as deposits grow, the reward per dollar falls, and as farmers sell rewards, the token price falls. A rate shown at launch is almost never the rate a farmer earns over a year.
A clearer display splits the APR or APY in two. Base yield comes from fees or interest and is paid in the deposited assets. Incentive yield is paid in the reward token, and the display shows the date the incentive schedule ends.
Mercenary liquidity
Emissions are a cost to the protocol. A farm that pays 200% APY in its own token attracts farmers who deposit, claim and sell. That selling lowers the token price, the lower price cuts the APY, and the lower APY makes farmers leave. Many farms from 2020 to 2022 followed this sequence, and some of their tokens lost almost all their value.
These liquidity mining designs keep more capital:
- Fund rewards from revenue as well as inflation. Fee-based "real yield" is smaller but can continue.
- Measure cost per retained dollar: divide the value of rewards paid by the liquidity that remains 30 and 90 days after a program ends. Peak TVL alone hides this cost.
- Target incentives at the core pairs that need depth, and reduce them on a published schedule.
- Reward commitment with lockups, vesting of rewards or ve-style boosts. Each of these mechanisms adds code to audit, and lockups stop users from exiting in a crash.
- Avoid points programs with vague promises: points that hint at a future token without written terms lead to disputes and regulator attention.
The yield farming development process
- Model the economics: total emissions, schedule, expected TVL and the effect of the token price. Run a scenario in which the token price falls 80%.
- Choose the reward mechanism: MasterChef-style contract, separate staking contracts per pool, gauges or Merkle distribution.
- Write or fork the contracts. Remove owner powers the farm does not need, and put a timelock on the rest.
- Test edge cases: zero total stake, many pools, a low-decimal reward token, fee-on-transfer LP tokens and the end of emissions.
- Audit the farm and any vault strategies. Strategies that call outside protocols need fork tests against those protocols' live mainnet contracts.
- Launch, monitor and reduce emissions on the published schedule.
Cost and timeline drivers
These figures are estimates based on the scope in each row, not quotes.
| Scope | Estimate | Main effort |
|---|---|---|
| Forked MasterChef and interface for your own pools | 3–6 weeks, small team | Removing unsafe owner powers, audit |
| Single-strategy ERC-4626 vault | 4–8 weeks | Strategy integration, safe harvests, fork tests |
| Gauge and ve-token system | 3–6 months | Voting math, decay, fee distribution and governance |
| Multi-strategy aggregator | 6 months or more | Many integrations, a risk framework and ongoing operations |
Audit fees grow with code size and complexity, and they take a large share of each budget. The DEX development guide covers the pools that farms reward, and the DeFi staking platform guide covers single-asset rewards.
Frequently asked questions
What is DeFi yield farming?
DeFi yield farming means depositing tokens or LP positions into a protocol to earn fees, interest and incentive tokens. Liquidity mining is the part where a protocol pays its own token to liquidity providers.
Is yield farming the same as staking?
The two overlap. Farming usually means depositing LP tokens or capital and earning incentive tokens, while staking usually means locking one asset. The reward accounting is often the same, but farming adds impermanent loss and more protocol dependencies.
Why do so many farm tokens lose value?
Farmers sell rewards to take profit, so if the token has no demand beyond farming, constant emissions create constant selling. Tokens that share fee revenue or have a use beyond farming face less constant selling.
What is an auto-compounding vault?
An auto-compounding vault claims farming rewards for its depositors, swaps them for more of the underlying asset and deposits them again. The vault saves users gas and effort but adds swap, strategy and contract risk.
Should a farm contract be upgradeable?
Immutable core contracts with replaceable reward distributors are safer than fully upgradeable farms, because no upgrade can touch staked principal. If a farm needs upgrades, a multisig and a timelock long enough for users to exit should control them.