defi-protocols

Master DeFi protocol development including AMMs, lending, yield, and oracles

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "defi-protocols" with this command: npx skills add pluginagentmarketplace/custom-plugin-blockchain/pluginagentmarketplace-custom-plugin-blockchain-defi-protocols

DeFi Protocols Skill

Master DeFi protocol development including AMM mechanics, lending systems, yield optimization, and oracle integration.

Quick Start

# Invoke this skill for DeFi development
Skill("defi-protocols", protocol_type="amm", chain="ethereum")

Topics Covered

1. AMM (Automated Market Makers)

Build decentralized exchanges:

  • Constant Product: x * y = k (Uniswap V2)
  • Concentrated Liquidity: Tick-based (Uniswap V3)
  • Stable Swaps: Curve invariant
  • TWAP: Time-weighted average price

2. Lending Protocols

Create lending markets:

  • Overcollateralized: Aave/Compound model
  • Interest Rates: Utilization-based curves
  • Liquidation: Health factor, incentives
  • Isolated Markets: Risk segmentation

3. Yield Optimization

Maximize returns:

  • Auto-compounding: Vault strategies
  • Liquidity Mining: Reward distribution
  • veTokens: Vote-escrowed governance
  • Bribes: Gauge voting incentives

4. Oracle Integration

Secure price feeds:

  • Chainlink: Decentralized oracles
  • TWAP: Manipulation resistant
  • Staleness Checks: Price freshness
  • Fallbacks: Multi-oracle setups

Code Examples

AMM Swap Calculation

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

library SwapMath {
    uint256 constant FEE_NUMERATOR = 997;
    uint256 constant FEE_DENOMINATOR = 1000;

    /// @notice Calculate output amount for constant product AMM
    function getAmountOut(
        uint256 amountIn,
        uint256 reserveIn,
        uint256 reserveOut
    ) internal pure returns (uint256) {
        uint256 amountInWithFee = amountIn * FEE_NUMERATOR;
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = reserveIn * FEE_DENOMINATOR + amountInWithFee;
        return numerator / denominator;
    }

    /// @notice Calculate price impact percentage (basis points)
    function getPriceImpact(
        uint256 amountIn,
        uint256 reserveIn
    ) internal pure returns (uint256) {
        return (amountIn * 10000) / (reserveIn + amountIn);
    }
}

Chainlink Oracle

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceOracle {
    AggregatorV3Interface public immutable priceFeed;
    uint256 public constant STALENESS_THRESHOLD = 1 hours;

    error StalePrice();
    error InvalidPrice();

    constructor(address feed) {
        priceFeed = AggregatorV3Interface(feed);
    }

    function getPrice() external view returns (uint256) {
        (, int256 price,, uint256 updatedAt,) = priceFeed.latestRoundData();

        if (block.timestamp - updatedAt > STALENESS_THRESHOLD) {
            revert StalePrice();
        }
        if (price <= 0) revert InvalidPrice();

        return uint256(price);
    }
}

Flash Loan Callback

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "@aave/v3-core/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";

contract Arbitrage is FlashLoanSimpleReceiverBase {
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address,
        bytes calldata
    ) external override returns (bool) {
        // Execute arbitrage logic here

        // Repay: amount + premium
        IERC20(asset).approve(address(POOL), amount + premium);
        return true;
    }
}

DeFi Math Formulas

Constant Product AMM

Invariant: x * y = k
Output: dy = y - k/(x + dx)
Price: p = y/x
Slippage: dx/(x + dx) * 100%

Interest Rates

Utilization: U = borrows / (deposits + borrows)
Borrow Rate: R = base + slope * U  (when U < optimal)
Supply Rate: R_supply = R_borrow * U * (1 - reserve_factor)

Health Factor

HF = (collateral * liquidation_threshold) / debt
Liquidation when HF < 1

Common Pitfalls

PitfallRiskPrevention
Spot price oracleFlash loan manipulationUse TWAP
No slippage checkSandwich attacksEnforce min output
Stale pricesWrong liquidationsCheck updatedAt
ReentrancyFund drainageCEI + guards

Security Checklist

  • Oracle staleness validation
  • Slippage protection
  • Flash loan attack resistance
  • Reentrancy guards
  • Access control on admin
  • Emergency pause mechanism
  • Timelock on parameters

Troubleshooting

"Oracle price deviation"

# Compare oracle vs DEX price
cast call $ORACLE "latestRoundData()" --rpc-url $RPC
cast call $POOL "slot0()" --rpc-url $RPC

"Sandwich attack detected"

Add minimum output enforcement:

require(amountOut >= minAmountOut, "Slippage exceeded");

Protocol Addresses (Mainnet)

ProtocolContract
Uniswap V3 Router0xE592427A0AEce92De3Edee1F18E0157C05861564
Aave V3 Pool0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2
Chainlink ETH/USD0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419

Cross-References

  • Bonded Agent: 04-defi-specialist
  • Related Skills: solidity-development, smart-contract-security

Version History

VersionDateChanges
2.0.02025-01Production-grade with math, security
1.0.02024-12Initial release

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Web3

web3-frontend

No summary provided by upstream source.

Repository SourceNeeds Review
Web3

solidity-development

No summary provided by upstream source.

Repository SourceNeeds Review
Web3

blockchain-basics

No summary provided by upstream source.

Repository SourceNeeds Review