AgentSkillsCN

building-blocks

Ethereum 上的 DeFi 积木与协议可组合性。深入了解各大协议(Uniswap、Aave、Compound、MakerDAO、Yearn、Curve)的工作原理、如何在其基础上构建,以及如何将它们巧妙组合,打造出全新的产品。适用于构建 DeFi 集成、设计代币经济学,或当用户希望将现有协议融合创新,打造全新应用时使用。

SKILL.md
--- frontmatter
name: building-blocks
description: DeFi legos and protocol composability on Ethereum. Major protocols (Uniswap, Aave, Compound, MakerDAO, Yearn, Curve), how they work, how to build on them, and how to combine them into novel products. Use when building DeFi integrations, designing tokenomics, or when a user wants to compose existing protocols into something new.

Building Blocks (DeFi Legos)

What You Probably Got Wrong

DeFi TVL: Ethereum DeFi TVL is $50B+ (Feb 2026). If you're quoting numbers from 2023-2024, they're stale.

Uniswap V4: V4 introduced a hooks system — custom logic attached to pools (dynamic fees, TWAMM, limit orders, custom oracles). This is a major composability upgrade.

<!-- VERIFICATION NEEDED: V4 deployment status and mainnet addresses -->

Costs changed everything: A flash loan arbitrage on mainnet costs ~$0.05-0.50 in gas now (was $5-50). This opens composability patterns that were previously uneconomical.

Key Protocol Addresses (Verified Feb 2026)

ProtocolContractMainnet Address
Uniswap V2 RouterRouter0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
Uniswap V2 FactoryFactory0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
Uniswap V3 FactoryFactory0x1F98431c8aD98523631AE4a59f267346ea31F984
Uniswap V3 SwapRouter02Router0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45
Uniswap Universal RouterRouter0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD
Aave V3 PoolPool0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2

See addresses/SKILL.md for complete multi-chain address list.

Uniswap V4 Hooks (New)

Hooks let you add custom logic that runs before/after swaps, liquidity changes, and donations. This is the biggest composability upgrade since flash loans.

Hook Interface (Solidity)

solidity
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";

contract DynamicFeeHook is BaseHook {
    constructor(IPoolManager _manager) BaseHook(_manager) {}

    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: false,
            afterInitialize: false,
            beforeAddLiquidity: false,
            afterAddLiquidity: false,
            beforeRemoveLiquidity: false,
            afterRemoveLiquidity: false,
            beforeSwap: true,           // ← We hook here
            afterSwap: false,
            beforeDonate: false,
            afterDonate: false,
            beforeSwapReturnDelta: false,
            afterSwapReturnDelta: false,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    // Dynamic fee: higher fee during high-volume periods
    function beforeSwap(
        address,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata
    ) external override returns (bytes4, BeforeSwapDelta, uint24) {
        // Return dynamic fee override (e.g., 0.05% normally, 0.30% during volatility)
        uint24 fee = _isHighVolatility() ? 3000 : 500;
        return (this.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, fee | 0x800000);
    }
}

Hook use cases with real code patterns:

  • Dynamic fees — adjust based on volatility, time-of-day, or oracle data
  • TWAMM — split large orders over time to reduce price impact
  • Limit orders — execute when price crosses a threshold
  • MEV protection — auction swap ordering rights to searchers
  • Custom oracles — TWAP updated on every swap

Composability Patterns (Updated for 2026 Gas)

These patterns are now economically viable even for small amounts due to sub-dollar gas:

Flash Loan Arbitrage

Borrow from Aave → swap on Uniswap for profit → repay Aave. All in one transaction. If unprofitable, reverts (lose only gas: ~$0.05-0.50).

Leveraged Yield Farming

Deposit ETH on Aave → borrow stablecoin → swap for more ETH → deposit again → repeat. Gas cost per loop: ~$0.02 on mainnet, negligible on L2.

Meta-Aggregation

Route swaps across multiple DEXs for best execution. 1inch and Paraswap check Uniswap, Curve, Sushi simultaneously.

ERC-4626 Yield Vaults

Standard vault interface — the "ERC-20 of yield." Every vault exposes the same functions regardless of strategy.

solidity
import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {ERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract SimpleYieldVault is ERC4626 {
    constructor(IERC20 asset_) 
        ERC4626(asset_) 
        ERC20("Vault Shares", "vSHARE") 
    {}

    // totalAssets() drives the share price
    // As yield accrues, totalAssets grows → shares worth more
    function totalAssets() public view override returns (uint256) {
        return IERC20(asset()).balanceOf(address(this)) + _getAccruedYield();
    }
}

// Usage: deposit/withdraw are standardized
// vault.deposit(1000e6, msg.sender);  // deposit 1000 USDC, get shares
// vault.redeem(shares, msg.sender, msg.sender);  // burn shares, get USDC back
// vault.convertToAssets(shares);  // how much USDC are my shares worth?

Why ERC-4626 matters: Composability. Any protocol can integrate any vault without custom adapters. Yearn V3, Aave's wrapped tokens, Morpho vaults, Pendle yield tokens — all ERC-4626.

Flash Loan (Aave V3 — Complete Pattern)

solidity
import {FlashLoanSimpleReceiverBase} from 
    "@aave/v3-core/contracts/flashloan-v3/base/FlashLoanSimpleReceiverBase.sol";
import {IPoolAddressesProvider} from 
    "@aave/v3-core/contracts/interfaces/IPoolAddressesProvider.sol";

contract FlashLoanArb is FlashLoanSimpleReceiverBase {
    constructor(IPoolAddressesProvider provider) 
        FlashLoanSimpleReceiverBase(provider) {}

    function executeArb(address token, uint256 amount) external {
        // Borrow `amount` of `token` — must repay + 0.05% fee in same tx
        POOL.flashLoanSimple(address(this), token, amount, "", 0);
    }

    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,  // 0.05% fee
        address,
        bytes calldata
    ) external override returns (bool) {
        // --- Your arbitrage logic here ---
        // Buy cheap on DEX A, sell expensive on DEX B
        // Must end with at least `amount + premium` of `asset`
        
        uint256 owed = amount + premium;
        IERC20(asset).approve(address(POOL), owed);
        return true;  // If unprofitable, revert here — lose only gas (~$0.05-0.50)
    }
}

Aave V3 Pool (mainnet): 0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2 Flash loan fee: 0.05% (5 basis points). Free if you repay to an Aave debt position.

Building on Arbitrum (Highest DeFi Liquidity L2)

Key protocols on Arbitrum:

  • GMX — perps DEX, $500M+ TVL
  • Uniswap, Curve, Balancer — DEXs
  • Radiant, Aave — lending
  • Pendle — yield trading

Discovery Resources

  • DeFi Llama: https://defillama.com — TVL rankings, yield rankings, all chains
  • Dune Analytics: https://dune.com — query on-chain data
  • ethereum.org/en/dapps/ — curated list

Guardrails for Composability

  • Every protocol you compose with is a dependency. If Aave gets hacked, your vault depending on Aave is affected.
  • Oracle manipulation = exploits. Verify oracle sources.
  • Impermanent loss is real for AMM LPs. Quantify it before providing liquidity.
  • The interaction between two safe contracts can create unsafe behavior. Audit compositions.
  • Start with small amounts. Test with minimal value before scaling.
  • Flash loan attacks can manipulate prices within a single transaction. Design for this.