Found Academy useful? A $5 donation by May 14 helps us ship more, faster. Every donor counts (QF matching).

Donate

Section 18 of 18

Final Build
+100 Lynx

Complete Multi-Strategy Vault

Final Build

Submit your complete protocol and run the full test suite. Earn the "yearn-v2-builder" badge on completion.

The Complete Multi-Strategy Vault

You have built the entire Yearn V2 vault system. The deployable artifact is two contracts:

  • Vault (the final link in the Vault inheritance chain, section 17). Inherits everything from sections 2-17. Deploys with a constructor that takes (token, name, symbol, governance, management, guardian, rewards).
  • A concrete strategy that inherits from StrategyHarvest (section 15), which inherits from BaseStrategy (section 8). Section 15's example showed an Aave lender; you can write Curve, Compound, or any other underlying-protocol adapter on the same template.

What You Built

A multi-strategy vault aggregator with:

  • ERC-20 share token with EIP-2612 permit (sections 2, 3).
  • Share-price math with first-depositor (virtual offset) defense (sections 4, 5).
  • Donation-attack defense via the totalIdle accumulator (section 6).
  • Strategy registry with bounded withdrawal queue (section 9).
  • Dynamic capital allocation via creditAvailable and debtOutstanding (section 10).
  • Central report cycle with anti-fake-gain validation, proportional debtRatio loss accounting, and fee assessment (section 11).
  • Locked-profit degradation (Yearn's signature MEV defense, section 13).
  • Multi-strategy withdraw with queue iteration and loss accounting (section 14).
  • Strategy harvest cycle with realize/report/reinvest pattern (section 15).
  • Performance + management fees paid via share dilution (section 16).
  • Emergency shutdown, 2-step governance transfer, and sweep (section 17).

About 1,700 lines of Solidity across 15 reference files. The same code, in the same shape, is what the Yearn V2 vaults on mainnet are running today (translated from Vyper).

How the Tests Verify the Whole System

tests/18-complete-vault.json checks structural integrity end-to-end:

  • The full Vault inheritance chain is intact: VaultStorage → VaultShareToken → VaultShareMath → VaultDeposit → VaultTotalAssets → VaultAddStrategy → VaultCreditDebt → VaultReport → VaultLockedProfit → VaultWithdraw → VaultFees → Vault.
  • The Strategy chain is intact: BaseStrategy → StrategyHarvest.
  • The Vault constructor exists with the 7-argument signature.
  • All major user-facing functions are present: deposit, withdraw, addStrategy, report, harvest, setEmergencyShutdown.
  • Both defenses are baked in: DECIMALS_OFFSET (first-depositor) and _calculateLockedProfit (JIT extraction).
  • Donation defense (totalIdle) is in storage.

A behavioral test (which the Academy runner doesn't execute, but you should run locally if you have Foundry installed) would walk:

  1. Deploy USDC mock + Vault + StrategyAaveLender.
  2. Deposit $1M USDC. Verify shares minted, totalIdle increased.
  3. addStrategy with debtRatio = 5_000 (50%).
  4. Strategy harvests. Vault transfers $500k credit to strategy. Strategy supplies to Aave.
  5. Skip 30 days. Aave has accrued ~$2k interest.
  6. Strategy harvests. Reports $2k gain. Vault charges 2% management fee on the deployed $500k for 30 days (~$821, computed as 500_000 * 200 / 10_000 * 30 / 365.25) plus 10% performance fee on the $2k gain ($200). Total ~$1,021 in fees minted as shares to rewards/strategist. lockedProfit jumps to ~$979 (gain minus fees). Strategy redeposits credit if any.
  7. Immediately withdraw 100% of shares. Without locked profit defense, you'd extract a fraction of the $979. With it, _freeFunds() excludes the locked portion, so you get only your principal back (give or take). Wait 6 hours, withdraw again. Locked profit is fully released.
  8. Governance triggers setEmergencyShutdown(true). Strategy harvests; debtOutstanding is now full debt; strategy liquidates everything and returns to vault.
  9. Final user withdraws everything; vault wraps up clean.

Every step exercises a different chunk of what you built.

What This Module Did Not Cover

ERC-4626 conformance overlay. Yearn V3 inherits from OpenZeppelin's ERC-4626 implementation, which is the same vault math you wrote here plus a standardized external interface (previewDeposit, previewMint, previewWithdraw, previewRedeem, the asymmetric rounding rules). Adding the ERC-4626 surface on top of your Vault is an exercise in renaming and adding a few view functions. The math doesn't change.

Concrete strategy implementations. Section 15 showed a sketch of StrategyAaveLender. Real strategies are 200-500 lines each, protocol-specific, and live in the yearn/strategies repository. Writing one is its own project.

Multi-token vaults. Yearn V3 supports a single vault holding multiple underlying tokens. Yearn V2 (this module) is single-asset.

Restaking (EigenLayer-era). Restaked-collateral protocols (EigenLayer, Karak, Symbiotic) are a separate vault class entirely, they let users stake the SAME underlying for multiple protocols simultaneously. The accounting model is different from a yield aggregator.

Cross-chain vaults. Single-chain only. Cross-chain vaults are a separate design problem.

Where to Go Next

  • The other Build modules: Uniswap V2 if you haven't built it (foundational), Compound V2 if you haven't built it (lending mechanics that complement vault patterns).
  • The eMBA tracks: Module 4 (Tokenomics) covers vault token design at the strategic level, when vault tokens like yvUSDC make sense as collateral, as governance, as reward currency.
  • Real Yearn code: clone yearn/yearn-vaults and read Vault.vy end-to-end. You will recognize every function. The Vyper syntax is foreign but the design is identical to what you just built.

The contracts you wrote across these 17 sections are the lineage that became ERC-4626. Every modern vault, Maker's Smart Burn Engine treasury wrapper, Aave's Umbrella safety module, dYdX V4's staking vault, Sky's USDS vault, descends from this design.

You can now read any of those audits.

Your Complete Protocol

Solution.sol
Solidity
Loading editor...