DeFi协议集成专家 defi-protocols

DeFi协议集成技能专注于为开发者提供主流去中心化金融协议的技术集成解决方案。该技能涵盖Uniswap、Aave、Compound、Chainlink、Curve、Balancer等核心DeFi协议的智能合约开发、流动性管理、借贷系统、预言机集成、闪电贷执行和MEV保护。适用于构建去中心化交易所、借贷平台、收益聚合器、自动化交易策略等Web3金融应用。关键词:DeFi集成、智能合约开发、区块链金融、Web3开发、去中心化金融、协议交互、Solidity编程、链上交易、流动性挖矿、预言机服务。

DeFi 0 次安装 0 次浏览 更新于 2/23/2026

名称:defi-protocols 描述:集成主要DeFi协议的专业知识,包括Uniswap、Aave、Compound、Chainlink、Curve和Balancer。支持交换、流动性提供、借贷、预言机和闪电贷。 允许工具:读取、搜索、写入、Bash、编辑、全局、网络获取

DeFi协议集成技能

与主要DeFi协议的专业集成,用于构建可组合的金融应用程序。

能力

  • Uniswap集成:V2/V3交换、流动性、头寸管理
  • Aave/Compound:供应、借贷、清算
  • Chainlink预言机:价格馈送、VRF、自动化
  • Curve Finance:池交互、计量器
  • Balancer:加权池、加入/退出
  • 闪电贷:Aave、dYdX闪电贷执行
  • MEV保护:Flashbots集成

Uniswap集成

V2交换

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

import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract UniswapV2Swap {
    IUniswapV2Router02 public immutable router;

    constructor(address _router) {
        router = IUniswapV2Router02(_router);
    }

    function swapExactTokensForTokens(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOutMin,
        address to
    ) external returns (uint256 amountOut) {
        IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);
        IERC20(tokenIn).approve(address(router), amountIn);

        address[] memory path = new address[](2);
        path[0] = tokenIn;
        path[1] = tokenOut;

        uint256[] memory amounts = router.swapExactTokensForTokens(
            amountIn,
            amountOutMin,
            path,
            to,
            block.timestamp
        );

        return amounts[1];
    }
}

V3交换

import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";

contract UniswapV3Swap {
    ISwapRouter public immutable router;

    constructor(address _router) {
        router = ISwapRouter(_router);
    }

    function swapExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountIn,
        uint256 amountOutMinimum
    ) external returns (uint256 amountOut) {
        IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);
        IERC20(tokenIn).approve(address(router), amountIn);

        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: tokenIn,
                tokenOut: tokenOut,
                fee: fee,
                recipient: msg.sender,
                deadline: block.timestamp,
                amountIn: amountIn,
                amountOutMinimum: amountOutMinimum,
                sqrtPriceLimitX96: 0
            });

        return router.exactInputSingle(params);
    }
}

V3流动性头寸

import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";

contract UniswapV3LP {
    INonfungiblePositionManager public immutable nfpm;

    function mintPosition(
        address token0,
        address token1,
        uint24 fee,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) external returns (uint256 tokenId) {
        IERC20(token0).approve(address(nfpm), amount0Desired);
        IERC20(token1).approve(address(nfpm), amount1Desired);

        INonfungiblePositionManager.MintParams memory params =
            INonfungiblePositionManager.MintParams({
                token0: token0,
                token1: token1,
                fee: fee,
                tickLower: tickLower,
                tickUpper: tickUpper,
                amount0Desired: amount0Desired,
                amount1Desired: amount1Desired,
                amount0Min: 0,
                amount1Min: 0,
                recipient: msg.sender,
                deadline: block.timestamp
            });

        (tokenId, , , ) = nfpm.mint(params);
    }
}

Aave集成

供应和借贷

import {IPool} from "@aave/v3-core/contracts/interfaces/IPool.sol";
import {IPoolAddressesProvider} from "@aave/v3-core/contracts/interfaces/IPoolAddressesProvider.sol";

contract AaveIntegration {
    IPool public immutable pool;

    constructor(address _poolProvider) {
        pool = IPool(IPoolAddressesProvider(_poolProvider).getPool());
    }

    function supply(address asset, uint256 amount) external {
        IERC20(asset).transferFrom(msg.sender, address(this), amount);
        IERC20(asset).approve(address(pool), amount);

        pool.supply(asset, amount, msg.sender, 0);
    }

    function borrow(
        address asset,
        uint256 amount,
        uint256 interestRateMode // 1 = 稳定, 2 = 可变
    ) external {
        pool.borrow(asset, amount, interestRateMode, 0, msg.sender);
    }

    function repay(
        address asset,
        uint256 amount,
        uint256 interestRateMode
    ) external {
        IERC20(asset).transferFrom(msg.sender, address(this), amount);
        IERC20(asset).approve(address(pool), amount);

        pool.repay(asset, amount, interestRateMode, msg.sender);
    }

    function withdraw(address asset, uint256 amount) external {
        pool.withdraw(asset, amount, msg.sender);
    }
}

闪电贷

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

contract AaveFlashLoan is IFlashLoanSimpleReceiver {
    IPool public immutable POOL;

    constructor(address _pool) {
        POOL = IPool(_pool);
    }

    function executeFlashLoan(address asset, uint256 amount) external {
        POOL.flashLoanSimple(
            address(this),
            asset,
            amount,
            abi.encode(msg.sender),
            0
        );
    }

    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external override returns (bool) {
        require(msg.sender == address(POOL), "调用者必须是池");
        require(initiator == address(this), "发起者必须是本合约");

        // 自定义逻辑
        // 例如:套利、清算、抵押品交换

        // 偿还闪电贷
        uint256 amountOwed = amount + premium;
        IERC20(asset).approve(address(POOL), amountOwed);

        return true;
    }
}

Chainlink集成

价格馈送

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

contract PriceConsumer {
    AggregatorV3Interface internal priceFeed;

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

    function getLatestPrice() public view returns (int256) {
        (
            uint80 roundId,
            int256 price,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();

        // 陈旧价格检查
        require(updatedAt > block.timestamp - 1 hours, "价格陈旧");
        require(price > 0, "无效价格");

        return price;
    }

    function getDecimals() public view returns (uint8) {
        return priceFeed.decimals();
    }
}

VRF(随机性)

import "@chainlink/contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol";
import "@chainlink/contracts/src/v0.8/vrf/interfaces/VRFCoordinatorV2Interface.sol";

contract VRFConsumer is VRFConsumerBaseV2 {
    VRFCoordinatorV2Interface COORDINATOR;
    uint64 s_subscriptionId;
    bytes32 keyHash;
    uint32 callbackGasLimit = 100000;
    uint16 requestConfirmations = 3;
    uint32 numWords = 2;

    uint256[] public s_randomWords;
    uint256 public s_requestId;

    constructor(
        uint64 subscriptionId,
        address vrfCoordinator,
        bytes32 _keyHash
    ) VRFConsumerBaseV2(vrfCoordinator) {
        COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
        s_subscriptionId = subscriptionId;
        keyHash = _keyHash;
    }

    function requestRandomWords() external returns (uint256 requestId) {
        requestId = COORDINATOR.requestRandomWords(
            keyHash,
            s_subscriptionId,
            requestConfirmations,
            callbackGasLimit,
            numWords
        );
        s_requestId = requestId;
    }

    function fulfillRandomWords(
        uint256 requestId,
        uint256[] memory randomWords
    ) internal override {
        s_randomWords = randomWords;
    }
}

Curve集成

interface ICurvePool {
    function exchange(
        int128 i,
        int128 j,
        uint256 dx,
        uint256 min_dy
    ) external returns (uint256);

    function add_liquidity(
        uint256[3] calldata amounts,
        uint256 min_mint_amount
    ) external returns (uint256);

    function remove_liquidity(
        uint256 amount,
        uint256[3] calldata min_amounts
    ) external returns (uint256[3] memory);
}

contract CurveSwap {
    ICurvePool public pool;

    function swap(
        int128 tokenIn,
        int128 tokenOut,
        uint256 amountIn,
        uint256 minAmountOut
    ) external returns (uint256) {
        return pool.exchange(tokenIn, tokenOut, amountIn, minAmountOut);
    }
}

MEV保护(Flashbots)

// TypeScript/ethers.js 示例
import { FlashbotsBundleProvider } from "@flashbots/ethers-provider-bundle";

async function sendPrivateTransaction() {
  const flashbotsProvider = await FlashbotsBundleProvider.create(
    provider,
    wallet,
    "https://relay.flashbots.net"
  );

  const signedTransactions = await flashbotsProvider.signBundle([
    {
      signer: wallet,
      transaction: {
        to: targetContract,
        data: encodedFunctionData,
        gasLimit: 500000,
      },
    },
  ]);

  const bundleSubmission = await flashbotsProvider.sendRawBundle(
    signedTransactions,
    targetBlockNumber
  );

  const waitResponse = await bundleSubmission.wait();
  console.log("包含的捆绑包:", waitResponse);
}

流程集成

流程 目的
amm-pool-development.js AMM构建
lending-protocol.js 借贷协议
yield-aggregator.js 收益策略
economic-simulation.js 协议建模

最佳实践

  1. 始终验证预言机数据的新鲜度
  2. 实施滑点保护
  3. 安全使用闪电贷回调
  4. 处理敏感交易的MEV
  5. 使用主网分叉进行测试

另请参阅

  • skills/solidity-dev/SKILL.md - Solidity开发
  • agents/defi-architect/AGENT.md - DeFi专家
  • DeFiLlama - 协议TVL