defi-protocols
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDeFi Protocols Skill
DeFi协议开发技能
Master DeFi protocol development including AMM mechanics, lending systems, yield optimization, and oracle integration.
精通DeFi协议开发,包括AMM机制、借贷系统、收益优化和预言机集成。
Quick Start
快速开始
python
undefinedpython
undefinedInvoke this skill for DeFi development
调用此技能进行DeFi开发
Skill("defi-protocols", protocol_type="amm", chain="ethereum")
undefinedSkill("defi-protocols", protocol_type="amm", chain="ethereum")
undefinedTopics Covered
涵盖主题
1. AMM (Automated Market Makers)
1. AMM(自动做市商)
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
构建去中心化交易所:
- 恒定乘积模型:x * y = k(Uniswap V2)
- 集中流动性:基于Tick机制(Uniswap V3)
- 稳定币兑换:Curve不变量模型
- TWAP:时间加权平均价格
2. Lending Protocols
2. 借贷协议
Create lending markets:
- Overcollateralized: Aave/Compound model
- Interest Rates: Utilization-based curves
- Liquidation: Health factor, incentives
- Isolated Markets: Risk segmentation
创建借贷市场:
- 超额抵押:Aave/Compound模型
- 利率机制:基于使用率的利率曲线
- 清算机制:健康系数、激励措施
- 隔离市场:风险隔离
3. Yield Optimization
3. 收益优化
Maximize returns:
- Auto-compounding: Vault strategies
- Liquidity Mining: Reward distribution
- veTokens: Vote-escrowed governance
- Bribes: Gauge voting incentives
最大化收益:
- 自动复投:金库策略
- 流动性挖矿:奖励分配
- veTokens:锁仓投票治理
- 贿赂机制:投票激励
4. Oracle Integration
4. 预言机集成
Secure price feeds:
- Chainlink: Decentralized oracles
- TWAP: Manipulation resistant
- Staleness Checks: Price freshness
- Fallbacks: Multi-oracle setups
安全的价格数据源:
- Chainlink:去中心化预言机
- TWAP:抗操纵
- 时效性检查:价格新鲜度验证
- 备选方案:多预言机配置
Code Examples
代码示例
AMM Swap Calculation
AMM兑换计算
solidity
// 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);
}
}solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
library SwapMath {
uint256 constant FEE_NUMERATOR = 997;
uint256 constant FEE_DENOMINATOR = 1000;
/// @notice 计算恒定乘积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 计算滑点百分比(基点)
function getPriceImpact(
uint256 amountIn,
uint256 reserveIn
) internal pure returns (uint256) {
return (amountIn * 10000) / (reserveIn + amountIn);
}
}Chainlink Oracle
Chainlink预言机
solidity
// 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);
}
}solidity
// 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
闪电贷回调
solidity
// 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;
}
}solidity
// 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) {
// 在此处执行套利逻辑
// 还款:本金 + 溢价
IERC20(asset).approve(address(POOL), amount + premium);
return true;
}
}DeFi Math Formulas
DeFi数学公式
Constant Product AMM
恒定乘积AMM
Invariant: x * y = k
Output: dy = y - k/(x + dx)
Price: p = y/x
Slippage: dx/(x + dx) * 100%不变量:x * y = k
输出金额:dy = y - k/(x + dx)
价格:p = y/x
滑点: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)使用率:U = 借贷额 / (存款额 + 借贷额)
借贷利率:R = 基础利率 + 斜率 * U (当U < 最优使用率时)
存款利率:R_supply = R_borrow * U * (1 - 准备金率)Health Factor
健康系数
HF = (collateral * liquidation_threshold) / debt
Liquidation when HF < 1HF = (抵押品价值 * 清算阈值) / 债务
当HF < 1时触发清算Common Pitfalls
常见陷阱
| Pitfall | Risk | Prevention |
|---|---|---|
| Spot price oracle | Flash loan manipulation | Use TWAP |
| No slippage check | Sandwich attacks | Enforce min output |
| Stale prices | Wrong liquidations | Check updatedAt |
| Reentrancy | Fund drainage | CEI + guards |
| 陷阱 | 风险 | 预防措施 |
|---|---|---|
| 现货价格预言机 | 闪电贷操纵 | 使用TWAP |
| 无滑点检查 | 三明治攻击 | 强制设置最小输出金额 |
| 价格过期 | 错误清算 | 检查更新时间 |
| 重入攻击 | 资金被盗 | CEI模式 + 防护机制 |
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"
"预言机价格偏差"
bash
undefinedbash
undefinedCompare oracle vs DEX price
对比预言机与DEX价格
cast call $ORACLE "latestRoundData()" --rpc-url $RPC
cast call $POOL "slot0()" --rpc-url $RPC
undefinedcast call $ORACLE "latestRoundData()" --rpc-url $RPC
cast call $POOL "slot0()" --rpc-url $RPC
undefined"Sandwich attack detected"
"检测到三明治攻击"
Add minimum output enforcement:
solidity
require(amountOut >= minAmountOut, "Slippage exceeded");添加最小输出金额限制:
solidity
require(amountOut >= minAmountOut, "滑点超出限制");Protocol Addresses (Mainnet)
主网协议地址
| Protocol | Contract |
|---|---|
| Uniswap V3 Router | 0xE592427A0AEce92De3Edee1F18E0157C05861564 |
| Aave V3 Pool | 0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2 |
| Chainlink ETH/USD | 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 |
| 协议 | 合约地址 |
|---|---|
| Uniswap V3 Router | 0xE592427A0AEce92De3Edee1F18E0157C05861564 |
| Aave V3 Pool | 0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2 |
| Chainlink ETH/USD | 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 |
Cross-References
交叉引用
- Bonded Agent:
04-defi-specialist - Related Skills: ,
solidity-developmentsmart-contract-security
- 关联Agent:
04-defi-specialist - 相关技能:,
solidity-developmentsmart-contract-security
Version History
版本历史
| Version | Date | Changes |
|---|---|---|
| 2.0.0 | 2025-01 | Production-grade with math, security |
| 1.0.0 | 2024-12 | Initial release |
| 版本 | 日期 | 更新内容 |
|---|---|---|
| 2.0.0 | 2025-01 | 生产级内容,包含数学模型、安全相关 |
| 1.0.0 | 2024-12 | 初始版本 |